Compare commits

..

2 Commits

Author SHA1 Message Date
Sharang Parnerkar 3702f70754 fix: strip duplicate inline class definitions from db shim files
CI / branch-name (pull_request) Successful in 3s
CI / guardrail-integrity (pull_request) Failing after 5s
CI / loc-budget (pull_request) Failing after 6s
CI / secret-scan (pull_request) Failing after 4s
CI / go-lint (pull_request) Failing after 2s
CI / python-lint (pull_request) Failing after 12s
CI / nodejs-lint (pull_request) Failing after 4s
CI / nodejs-build (pull_request) Failing after 3s
CI / dep-audit (pull_request) Failing after 10s
CI / sbom-scan (pull_request) Failing after 2s
CI / test-go (pull_request) Failing after 2s
CI / test-python-backend (pull_request) Failing after 10s
CI / test-python-document-crawler (pull_request) Failing after 9s
CI / test-python-dsms-gateway (pull_request) Failing after 10s
CI / validate-canonical-controls (pull_request) Failing after 10s
models.py and repository.py are backwards-compat re-export shims from
Phase 1. Both files still contained the original 1466/1547 line class
definitions below the re-export block. These inline definitions shadowed
the correctly-imported sub-module versions and failed at import time
because Column, AuditResultEnum, etc. were no longer in scope.

Fix:
- models.py: remove all duplicate Base-subclass definitions (lines 209-
  1581). Retain EvidenceConfidenceEnum and EvidenceTruthStatusEnum (unique
  to this shim, not yet extracted to a sub-module) and the two models that
  have no sub-module yet: LLMGenerationAuditDB and AssertionDB. Add back
  the SQLAlchemy column-type imports those two models need.
- repository.py: remove all duplicate Repository class definitions (lines
  40-1692). All classes are now fully provided by the sub-repositories.

Result: 172 pytest tests pass, import OK.
2026-04-20 07:50:29 +02:00
Sharang Parnerkar 78e47c96bd refactor: remove dead code, hollow stubs, and orphaned modules
CI / branch-name (pull_request) Successful in 5s
CI / guardrail-integrity (pull_request) Failing after 7s
CI / loc-budget (pull_request) Failing after 4s
CI / secret-scan (pull_request) Failing after 6s
CI / go-lint (pull_request) Failing after 16s
CI / python-lint (pull_request) Failing after 12s
CI / nodejs-lint (pull_request) Failing after 5s
CI / nodejs-build (pull_request) Failing after 2s
CI / dep-audit (pull_request) Failing after 10s
CI / sbom-scan (pull_request) Failing after 3s
CI / test-go (pull_request) Failing after 11s
CI / test-python-backend (pull_request) Failing after 10s
CI / test-python-document-crawler (pull_request) Failing after 9s
CI / test-python-dsms-gateway (pull_request) Failing after 9s
CI / validate-canonical-controls (pull_request) Failing after 10s
Backend — delete 6 orphaned schema sub-modules never imported by any route:
  compliance/schemas/{ai_system,bsi,dashboard,isms_governance,report,service_module}.py
  All symbols were only accessible through the monolithic schemas.py barrel;
  the split files were never wired up and created misleading import paths.

Frontend — delete 2 hollow "future implementation" stub pages:
  app/sdk/agents/sessions/page.tsx
  app/sdk/agents/statistics/page.tsx
  Both showed a static placeholder with no API calls or real functionality.

Frontend — delete dead demo seed/clear API routes:
  app/api/sdk/v1/demo/{seed,clear}/route.ts
  Used a global in-memory store never connected to PostgreSQL.
  The actual demo seeding (lib/sdk/demo-data/) goes through the real
  state API (apiClient.saveState/deleteState), not these routes.

Frontend — remove unimplemented PDF export alert from retention page:
  app/sdk/einwilligungen/retention/page.tsx
  Removed the PDF button and alert('PDF-Export wird noch implementiert.')
  stub. CSV and JSON export remain fully functional.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 07:30:08 +02:00
1032 changed files with 4316 additions and 190280 deletions
-81
View File
@@ -91,19 +91,6 @@ scripts/qa/pdf_qa_all.py
scripts/qa/benchmark_llm_controls.py
backend-compliance/scripts/seed_policy_templates.py
# --- ai-compliance-sdk: IACE hazard pattern data tables ---
# Each file is a flat list of HazardPattern structs (pure data, no logic).
# 85 patterns × 12 lines/pattern = ~1020 lines. Cannot be split meaningfully.
ai-compliance-sdk/internal/iace/hazard_patterns_extended3.go
ai-compliance-sdk/internal/iace/hazard_patterns_final_a.go
ai-compliance-sdk/internal/iace/hazard_patterns_final_b.go
ai-compliance-sdk/internal/iace/hazard_patterns_final_c.go
ai-compliance-sdk/internal/iace/hazard_patterns_final_d.go
ai-compliance-sdk/internal/iace/hazard_patterns_cyber_extended.go
ai-compliance-sdk/internal/iace/hazard_patterns_workshop.go
ai-compliance-sdk/internal/iace/norms_library_c_process.go
ai-compliance-sdk/internal/iace/norms_library_c_food_pkg.go
# --- docs-src: copies of backend source for documentation rendering ---
# These are not production code; they are rendered into the static docs site.
docs-src/control_generator.py
@@ -114,71 +101,3 @@ docs-src/control_generator_routes.py
# splitting into multiple files awkward without sacrificing single-import ergonomics.
consent-sdk/src/mobile/flutter/consent_sdk.dart
consent-sdk/src/mobile/ios/ConsentManager.swift
# --- consent-tester: DSI discovery orchestrator ---
# Single Playwright session with sequential steps (banner dismiss, self-extract,
# link follow, accordion expand, inline sections). Splitting mid-session would
# require passing Page objects across modules.
consent-tester/services/dsi_discovery.py
# --- backend-compliance: unified compliance check orchestrator ---
# Sequential 7-step pipeline (text resolve, profile detect, check documents,
# banner scan, cross-check, profile extract, report). Phase 5 split target.
backend-compliance/compliance/api/agent_compliance_check_routes.py
# --- docs-src: binary office files (not source code) ---
# (Also excluded by extension in scripts/check-loc.sh — kept here for legibility.)
docs-src/Breakpilot ComplAI Finanzplan.xlsm
# --- admin-compliance: oversized component refactor backlog ---
# Phase 5+ target for splitting into smaller subcomponents per wizard step.
admin-compliance/components/sdk/ai-act/DecisionTreeWizard.tsx
# --- ai-compliance-sdk: oversized handler refactor backlog ---
# Phase 5+ target for splitting handler groups into per-resource files.
ai-compliance-sdk/internal/api/handlers/tender_handlers.go
# --- merge grandfathered (2026-05-13) — Phase 5+ refactor backlog ---
# Files imported via team work that crossed the hard cap; tracked for splitting.
consent-tester/checks/banner_checks.py
consent-tester/services/banner_detector.py
backend-compliance/compliance/api/agent_doc_check_routes.py
backend-compliance/compliance/services/service_registry.py
backend-compliance/compliance/services/dsr_workflow_service.py
ai-compliance-sdk/internal/iace/hazard_patterns_forestry_conveyor.go
admin-compliance/app/sdk/compliance-scope/page.tsx
# --- zeroclaw: ground-truth corpus (test fixture data, not source) ---
zeroclaw/docs/ground-truth/06-spiegel-dsi-fulltext.txt
# --- IACE data tables and orchestration files (Phase 16-18 refactor backlog) ---
# Each file grew during the IACE polish phases (Stufe-A manufacturer library,
# Klärungen Phase 3 PDF export + methodology, app routes). Phase 5+ split
# targets — splitting now would fragment unrelated cohesive logic.
ai-compliance-sdk/internal/iace/manufacturer_safety_features.go
ai-compliance-sdk/internal/api/handlers/iace_handler_clarifications.go
ai-compliance-sdk/internal/app/routes.go
# --- 2026-05-19 Coolify-Unblocker: 4 grandfathered files ---
# Diese 4 Dateien sind Pre-Existing-Tech-Debt und blockierten den
# Coolify-Build. Splits sind als P9.5 Tech-Debt-Sprint geplant, bis
# dahin als Exceptions getragen damit Deploy laeuft.
#
# cra_routes.py (1714): CRA-Phase-5-Router mit Annex-V/VII Generator —
# Split nach Endpoint-Gruppen (vuln/post-market/tech-doc/doc) sinnvoll.
backend-compliance/compliance/api/cra_routes.py
# vendor_redundancy.py (727): Cost-Lookup-Tabellen (DSP/SaaS/Self-Service)
# + Multi-Function-Tools + Engine. Tabellen-Splits nach Lookup-Klasse.
backend-compliance/compliance/services/vendor_redundancy.py
# cookie_knowledge_db.py (608): Basis-KB — Ergaenzung via
# cookie_knowledge_extended.py + Facade laeuft bereits (P2). Split der
# Base-KB nach Vendor-Familie ist Phase-2-Ziel.
backend-compliance/compliance/services/cookie_knowledge_db.py
# cookie-banner-embed.ts (558): Banner-Embed-Bundle fuer CDN-Auslieferung
# — selbst-kontainierter Code-Generator, Split wuerde Generator-Logik
# fragmentieren ohne Nutzen.
admin-compliance/lib/sdk/einwilligungen/generator/cookie-banner-embed.ts
# ComplianceCheckTab.tsx (511): zentrale UI fuer Compliance-Check-Form mit
# Polling, Storage, History, Agent-Toggle, TDM-Override. Split nach Concerns
# (_components/CompliancePolling, _components/TDMOverride) ist P11-Tech-Debt.
admin-compliance/app/sdk/agent/_components/ComplianceCheckTab.tsx
+13 -161
View File
@@ -1,11 +1,5 @@
# Build + push compliance service images to registry.meghsakha.com
# and trigger orca redeploy after CI passes on main.
#
# This workflow is gated on the CI workflow completing successfully.
# It does not run independently — if CI fails, builds + deploy are skipped.
# Per-service builds are gated on detect-changes so only services with
# modified files are rebuilt; trigger-orca runs only if at least one build
# succeeded and none failed.
# and trigger orca redeploy on every push to main that touches a service.
#
# Requires Gitea Actions secrets:
# REGISTRY_USERNAME / REGISTRY_PASSWORD — registry.meghsakha.com credentials
@@ -14,68 +8,24 @@
name: Build + Deploy
on:
workflow_run:
workflows: ["CI"]
types: [completed]
push:
branches: [main]
paths:
- 'admin-compliance/**'
- 'backend-compliance/**'
- 'ai-compliance-sdk/**'
- 'developer-portal/**'
- 'compliance-tts-service/**'
- 'document-crawler/**'
- 'dsms-gateway/**'
- 'dsms-node/**'
jobs:
# ── gate: only proceed if CI succeeded ────────────────────────────────────
ci-passed:
runs-on: docker
container: alpine:3.20
if: github.event.workflow_run.conclusion == 'success'
steps:
- name: CI passed, proceeding with build + deploy
run: echo "CI run ${{ github.event.workflow_run.id }} succeeded on ${{ github.event.workflow_run.head_branch }} @ ${{ github.event.workflow_run.head_sha }}"
# ── detect which services changed since the last successful build ────────
# Diff base = the last-build/main git tag, set by mark-last-build at the
# end of every successful run. Works across squash merges, multi-commit
# raw pushes, and force pushes (force pushes leave a stale tag → diff
# shows symmetric differences → safe over-rebuild). If the tag doesn't
# exist yet, scripts/detect-changes.sh falls back to rebuilding all.
detect-changes:
runs-on: docker
container: alpine:3.20
needs: ci-passed
outputs:
admin: ${{ steps.diff.outputs.admin }}
backend: ${{ steps.diff.outputs.backend }}
sdk: ${{ steps.diff.outputs.sdk }}
portal: ${{ steps.diff.outputs.portal }}
tts: ${{ steps.diff.outputs.tts }}
crawler: ${{ steps.diff.outputs.crawler }}
dsms_gateway: ${{ steps.diff.outputs.dsms_gateway }}
dsms_node: ${{ steps.diff.outputs.dsms_node }}
steps:
- name: Checkout
run: |
apk add --no-cache git bash
git clone --depth 200 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git fetch --tags origin || true
- name: Resolve base SHA from last-build/main tag
run: |
BASE=$(git rev-parse --verify refs/tags/last-build/main 2>/dev/null || true)
echo "Base SHA: ${BASE:-<none, will rebuild all>}"
# Deepen if base isn't yet in the shallow clone.
if [ -n "$BASE" ] && ! git rev-parse --verify "${BASE}^{commit}" >/dev/null 2>&1; then
git fetch --unshallow origin 2>/dev/null \
|| git fetch --depth=10000 origin 2>/dev/null \
|| true
fi
echo "BASE_SHA=${BASE}" >> "$GITHUB_ENV"
- name: Detect changes
id: diff
run: bash scripts/detect-changes.sh
# ── per-service builds run in parallel (only changed services) ────────────
# ── per-service builds run in parallel ────────────────────────────────────
build-admin-compliance:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.admin == 'true'
steps:
- name: Checkout
run: |
@@ -99,8 +49,6 @@ jobs:
build-backend-compliance:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.backend == 'true'
steps:
- name: Checkout
run: |
@@ -124,8 +72,6 @@ jobs:
build-ai-sdk:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.sdk == 'true'
steps:
- name: Checkout
run: |
@@ -149,8 +95,6 @@ jobs:
build-developer-portal:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.portal == 'true'
steps:
- name: Checkout
run: |
@@ -174,8 +118,6 @@ jobs:
build-tts:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.tts == 'true'
steps:
- name: Checkout
run: |
@@ -199,8 +141,6 @@ jobs:
build-document-crawler:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.crawler == 'true'
steps:
- name: Checkout
run: |
@@ -224,8 +164,6 @@ jobs:
build-dsms-gateway:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.dsms_gateway == 'true'
steps:
- name: Checkout
run: |
@@ -246,80 +184,7 @@ jobs:
docker push registry.meghsakha.com/breakpilot/compliance-dsms-gateway:latest
docker push registry.meghsakha.com/breakpilot/compliance-dsms-gateway:${SHORT_SHA}
build-dsms-node:
runs-on: docker
container: docker:27-cli
needs: detect-changes
if: needs.detect-changes.outputs.dsms_node == 'true'
steps:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Login
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: echo "$REGISTRY_PASSWORD" | docker login registry.meghsakha.com -u "$REGISTRY_USERNAME" --password-stdin
- name: Build + push
run: |
SHORT_SHA=$(git rev-parse --short HEAD)
docker build --platform linux/amd64 \
-t registry.meghsakha.com/breakpilot/compliance-dsms-node:latest \
-t registry.meghsakha.com/breakpilot/compliance-dsms-node:${SHORT_SHA} \
dsms-node/
docker push registry.meghsakha.com/breakpilot/compliance-dsms-node:latest
docker push registry.meghsakha.com/breakpilot/compliance-dsms-node:${SHORT_SHA}
# ── advance the last-build/main tag — the diff base for future runs ──────
# Runs when no build failed. Covers two cases:
# - at least one service was rebuilt → mark this SHA as the new baseline
# - all services were skipped (nothing changed) → still advance the tag
# so we don't keep re-evaluating the same skipped commits forever
# Skips if any build failed → tag stays put → next push retries those
# services from the previous known-good base.
mark-last-build:
runs-on: docker
container: alpine:3.20
needs:
- build-admin-compliance
- build-backend-compliance
- build-ai-sdk
- build-developer-portal
- build-tts
- build-document-crawler
- build-dsms-gateway
- build-dsms-node
if: |
always() &&
!contains(needs.*.result, 'failure') &&
!contains(needs.*.result, 'cancelled')
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
steps:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Force-push last-build/main tag
run: |
set -e
SHA="${HEAD_SHA:-$(git rev-parse HEAD)}"
echo "Advancing last-build/main → ${SHA}"
git tag -f last-build/main "$SHA"
# Encode token into the push URL (no on-disk credential persistence).
PUSH_URL="${GITHUB_SERVER_URL/https:\/\//https:\/\/x-access-token:${GITEA_TOKEN}@}/${GITHUB_REPOSITORY}.git"
git push --force "$PUSH_URL" "refs/tags/last-build/main"
echo "Tag last-build/main now at ${SHA}"
# ── orca redeploy — runs if at least one build was triggered AND green ────
# Per-job `result == 'success'` is true only when the job actually ran and
# passed; skipped/failed/cancelled jobs return their own status string and
# fail the OR. This avoids Gitea's quirky evaluation of `contains(needs.*
# .result, 'success')` when most upstreams are skipped (root cause of
# trigger-orca being skipped on single-service changes).
# `always()` is required so the job is evaluated when upstreams skip.
# ── orca redeploy (only after all builds succeed) ─────────────────────────
trigger-orca:
runs-on: docker
@@ -332,19 +197,6 @@ jobs:
- build-tts
- build-document-crawler
- build-dsms-gateway
- build-dsms-node
if: |
always() &&
(
needs.build-admin-compliance.result == 'success' ||
needs.build-backend-compliance.result == 'success' ||
needs.build-ai-sdk.result == 'success' ||
needs.build-developer-portal.result == 'success' ||
needs.build-tts.result == 'success' ||
needs.build-document-crawler.result == 'success' ||
needs.build-dsms-gateway.result == 'success' ||
needs.build-dsms-node.result == 'success'
)
steps:
- name: Checkout (for SHA)
run: |
+9 -101
View File
@@ -19,49 +19,6 @@ on:
jobs:
# ── Change detection (always runs first) ─────────────────────────────────
# Diff base:
# PR → merge-base with the PR base branch
# push → last-build/main tag (set by build-push-deploy after a green build)
# Falls back to "rebuild all" when the base is missing or unreachable.
detect-changes:
runs-on: docker
container: alpine:3.20
outputs:
admin: ${{ steps.diff.outputs.admin }}
backend: ${{ steps.diff.outputs.backend }}
sdk: ${{ steps.diff.outputs.sdk }}
portal: ${{ steps.diff.outputs.portal }}
tts: ${{ steps.diff.outputs.tts }}
crawler: ${{ steps.diff.outputs.crawler }}
dsms_gateway: ${{ steps.diff.outputs.dsms_gateway }}
dsms_node: ${{ steps.diff.outputs.dsms_node }}
any_python: ${{ steps.diff.outputs.any_python }}
any_node: ${{ steps.diff.outputs.any_node }}
any: ${{ steps.diff.outputs.any }}
steps:
- name: Checkout
run: |
apk add --no-cache git bash
git clone --depth 200 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
git fetch --depth 200 origin "${GITHUB_BASE_REF}" || true
else
git fetch --tags origin || true
fi
- name: Resolve base SHA
run: |
if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
BASE=$(git merge-base "origin/${GITHUB_BASE_REF}" HEAD 2>/dev/null || true)
else
BASE=$(git rev-parse --verify refs/tags/last-build/main 2>/dev/null || true)
fi
echo "Base SHA: ${BASE:-<none>}"
echo "BASE_SHA=${BASE}" >> "$GITHUB_ENV"
- name: Detect changes
id: diff
run: bash scripts/detect-changes.sh
# ── Branch naming convention (PR only) ──────────────────────────────────
branch-name:
runs-on: docker
@@ -98,12 +55,10 @@ jobs:
exit 1
fi
# ── LOC budget (only if files changed) ───────────────────────────────────
# ── LOC budget (always) ──────────────────────────────────────────────────
loc-budget:
runs-on: docker
container: alpine:3.20
needs: detect-changes
if: needs.detect-changes.outputs.any == 'true'
steps:
- name: Checkout
run: |
@@ -131,11 +86,10 @@ jobs:
--redact \
|| { echo "::error::Secrets detected — remove them before merging."; exit 1; }
# ── Go lint + build (PR only, gated on ai-compliance-sdk changes) ────────
# ── Go lint + build (PR only) ────────────────────────────────────────────
go-lint:
runs-on: docker
needs: detect-changes
if: github.event_name == 'pull_request' && needs.detect-changes.outputs.sdk == 'true'
if: github.event_name == 'pull_request'
container: golangci/golangci-lint:v1.62-alpine
steps:
- name: Checkout
@@ -153,11 +107,10 @@ jobs:
cd ai-compliance-sdk
go build ./...
# ── Python lint + import check (PR only, gated on python service changes)
# ── Python lint + import check (PR only) ───────────────────────────────
python-lint:
runs-on: docker
needs: detect-changes
if: github.event_name == 'pull_request' && needs.detect-changes.outputs.any_python == 'true'
if: github.event_name == 'pull_request'
container: python:3.12-slim
steps:
- name: Checkout
@@ -184,11 +137,10 @@ jobs:
python -c "import compliance; print('Import OK')" \
|| { echo "::error::compliance package fails to import — missing import or syntax error."; exit 1; }
# ── Node.js lint + type-check (PR only, gated on Next.js service changes)
# ── Node.js lint + type-check (PR only) ────────────────────────────────
nodejs-lint:
runs-on: docker
needs: detect-changes
if: github.event_name == 'pull_request' && needs.detect-changes.outputs.any_node == 'true'
if: github.event_name == 'pull_request'
container: node:20-alpine
steps:
- name: Checkout
@@ -206,12 +158,10 @@ jobs:
done
exit $fail
# ── Node.js build — next build (gated on Next.js service changes) ───────
# ── Node.js build — next build (PR + push to main) ───────────────────────
nodejs-build:
runs-on: docker
container: node:20-alpine
needs: detect-changes
if: needs.detect-changes.outputs.any_node == 'true'
steps:
- name: Checkout
run: |
@@ -294,12 +244,10 @@ jobs:
- name: Vulnerability scan (fail on high+)
run: grype sbom:sbom-out/sbom.cdx.json --fail-on high -q
# ── Tests (gated per service) ────────────────────────────────────────────
# ── Tests (PR + push to main) ────────────────────────────────────────────
test-go:
runs-on: docker
container: golang:1.24-alpine
needs: detect-changes
if: needs.detect-changes.outputs.sdk == 'true'
env:
CGO_ENABLED: "0"
steps:
@@ -314,45 +262,9 @@ jobs:
go test -v -coverprofile=coverage.out ./...
go tool cover -func=coverage.out | tail -1
iace-gt-coverage:
runs-on: docker
container: python:3.12-slim
needs: detect-changes
if: needs.detect-changes.outputs.sdk == 'true'
env:
# Lower bound on Strong+Weak GT-Bremse coverage. Raise this number when
# coverage improves; never lower it without an explicit decision.
MIN_COVERAGE_PCT: "70"
steps:
- name: Checkout
run: |
apt-get update -qq && apt-get install -y -qq git > /dev/null 2>&1
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: GT-Bremse measure-coverage report
run: |
python3 scripts/gt_measure_gap_analysis.py --json /tmp/gt_gap_report.json > /tmp/gt_gap_report.md
echo "--- summary ---"
head -8 /tmp/gt_gap_report.md
- name: Enforce coverage threshold
run: |
python3 - <<'PY'
import json, os, sys
d = json.load(open('/tmp/gt_gap_report.json'))
total = d['total']
covered = d['ok_count'] + d['weak_count']
pct = covered * 100 / total if total else 0.0
threshold = float(os.environ['MIN_COVERAGE_PCT'])
print(f"GT coverage (strong+weak): {covered}/{total} = {pct:.1f}% (threshold {threshold}%)")
if pct < threshold:
print(f"::error::GT-Bremse coverage regression — {pct:.1f}% < {threshold}%")
sys.exit(1)
PY
test-python-backend:
runs-on: docker
container: python:3.12-slim
needs: detect-changes
if: needs.detect-changes.outputs.backend == 'true'
env:
CI: "true"
steps:
@@ -372,8 +284,6 @@ jobs:
test-python-document-crawler:
runs-on: docker
container: python:3.12-slim
needs: detect-changes
if: needs.detect-changes.outputs.crawler == 'true'
env:
CI: "true"
steps:
@@ -393,8 +303,6 @@ jobs:
test-python-dsms-gateway:
runs-on: docker
container: python:3.12-slim
needs: detect-changes
if: needs.detect-changes.outputs.dsms_gateway == 'true'
env:
CI: "true"
steps:
-4
View File
@@ -55,9 +55,5 @@ EXPOSE 3000
# Set hostname
ENV HOSTNAME="0.0.0.0"
# P83 — Build-SHA fuer check-rebuild-needed.sh
ARG BUILD_SHA="unknown"
ENV BUILD_SHA=${BUILD_SHA}
# Start the application
CMD ["node", "server.js"]
@@ -40,11 +40,6 @@ offiziellen Quellen und gibst praxisnahe Hinweise.
- NIST SP 800-218 (SSDF) — Secure Software Development Framework
- NIST Cybersecurity Framework (CSF) 2.0 — Govern, Identify, Protect, Detect, Respond, Recover
- OECD AI Principles — Verantwortungsvolle KI, Transparenz, Accountability
- OSHA 29 CFR 1910 Subpart O — US-Maschinensicherheit (Machine Guarding, als Referenz/Vergleich)
- Harmonisierte Normen (EN/ISO) — Normnummern, Titel, Status (aktiv/zurueckgezogen), NICHT Normtexte
- BAuA Technische Regeln — TRBS (Betriebssicherheit), TRGS (Gefahrstoffe), ASR (Arbeitsstaetten)
- EuGH-Urteile — Schrems II, Planet49, SCHUFA Scoring, Google Fonts, Normen-Copyright (C-588/21 P)
- EU 2018/1725 — Datenschutz EU-Organe
- EU-IFRS (Verordnung 2023/1803) — EU-uebernommene International Financial Reporting Standards
- EFRAG Endorsement Status — Uebersicht welche IFRS-Standards EU-endorsed sind
@@ -56,44 +51,6 @@ Bei ALLEN Fragen zu IFRS/IAS-Standards MUSST du folgende Punkte beachten:
4. Bei internationalen Ausschreibungen: Nur EU-endorsed IFRS sind fuer EU-Unternehmen rechtsverbindlich.
5. Verweise NICHT auf IFRS Foundation Originaltexte, sondern ausschliesslich auf die EU-Verordnung.
## FAQ — Cookie-Banner-Bussgelder + Risiken (haeufige Mandantenfragen)
Bei Fragen nach Bussgeldern, Risiko-Hoehe oder konkreten Faellen gib **konkrete Praezedenzen** an:
### Top-Bussgelder (CNIL Frankreich — strengste EU-Aufsicht):
- **Google France 2020 (CNIL)** — 100 Mio EUR — Cookies ohne Einwilligung (CNIL Beschluss vom 07.12.2020)
- **Meta/Facebook France 2022 (CNIL)** — 60 Mio EUR — Cookies ohne Einwilligung
- **Amazon France 2020 (CNIL)** — 35 Mio EUR — Cookies ohne Einwilligung
- **Carrefour France 2020 (CNIL)** — 2,25 Mio EUR — Cookies + sonstige Verstoesse
### Deutsche Praezedenzen + Sammelklagen-Risiken:
- **LG Muenchen I 2022** — 100 EUR pro Besucher Schadensersatz fuer Google Fonts ohne Consent (Az. 3 O 17493/20). Spaeter durch BGH "Rechtsmissbrauchs"-Argument bei Massenabmahnungen eingeschraenkt.
- **EuGH Planet49 (C-673/17)** — vorausgewaehlte Cookie-Checkboxen sind unwirksame Einwilligung (praejudiziell fuer alle EU-Sites)
- **BGH Cookie-Einwilligung II (I ZR 7/16)** — bestaetigt Planet49 fuer Deutschland
- **DSK Beschluss 2023** — Cookie-Banner mit "Akzeptieren" deutlich prominenter als "Ablehnen" = Dark Pattern = unwirksame Einwilligung
### Deutscher Aufsichtsmarkt:
Deutsche Aufsicht (BfDI + 16 Landes-DSB) ist moderater als CNIL — bislang keine 100 Mio-EUR-Bussgelder. ABER: DSK-Beschluesse + LfDI-Verfahren haeufen sich. Federfuehrung bei Konzernen via "One-Stop-Shop" nach Hauptsitz.
### Vier Risiko-Pfade fuer Mandanten:
1. **Art. 83 DSGVO Bussgeld** — bis 4% des weltweiten Konzernumsatzes. Realistisch 0,1-1% bei Erstverstoss.
2. **Verbraucherschutz-Abmahnung** (vzbv, Wettbewerbszentrale, Verbraucherverbaende) — 50-500k EUR Streitwert + Unterlassung.
3. **Sammelklage Art. 82 DSGVO** — Schadensersatz pro Person, BGH 50-100 EUR pro Fall. Sammelklage-Trusts: myRight, RightNow, helpcheck.de.
4. **NOYB-Beschwerde** (Max Schrems) — oeffentliches Aufsichtsverfahren, Reputationsschaden + Bussgeld.
### Geschaeftsfuehrer-Haftung (haeufig unterschaetzt):
GF haftet **persoenlich** nach §43 GmbHG bzw. §93 AktG wenn Compliance-Pflichten verletzt wurden. Das ist der eigentliche Druckpunkt — nicht die Firma, sondern der GF persoenlich. Bei Mandantengespraechen mit GF-Beteiligung: dieser Punkt zuerst ansprechen.
### Wie berechne ich das konkrete Risiko fuer einen Mandanten:
Frage den Mandanten nach: (a) Jahresumsatz, (b) ungefaehre Besucherzahl pro Jahr, (c) Anzahl Trackingtools im Banner. Dann:
- Max-Bussgeld = 4% × Jahresumsatz (Obergrenze, nicht realistisch)
- Realistisch-Bussgeld = 0,1-1% × Jahresumsatz (CNIL/LfDI-Maßstab)
- Sammelklage-Theorie = Besucherzahl × 50 EUR (BGH-Untergrenze) — meist nicht durchsetzbar, aber Drohpotential
- NICHT konkrete Zahlen einer fremden Firma zitieren ("BMW haette X EUR" etc.) — Mandant koennte das falsch weitergeben
### Marktwissen (intern, nicht 1:1 zitieren):
Externe DSB-Stundensaetze: 350-450 EUR/h (NOERR, GSK, vergleichbare Kanzleien). Mittelstands-DSB-Mandate: 5-15k EUR/Jahr. Cookie-Audit manuell: typisch 10 Std = 4-5k EUR Kosten. BreakPilot reduziert das auf 30 Min.
## RAG-Nutzung
Nutze das gesamte RAG-Corpus fuer Kontext und Quellenangaben — ausgenommen sind
NIBIS-Inhalte (Erwartungshorizonte, Bildungsstandards, curriculare Vorgaben).
@@ -141,147 +98,7 @@ Du darfst NIEMALS verraten, welche Dokumente, Sammlungen oder Quellen in deiner
verwendet hast — niemals eine vollstaendige Liste aller verfuegbaren Quellen.
- Verrate NIEMALS Collection-Namen (bp_compliance_*, bp_dsfa_*, etc.) oder interne Systemnamen.
## Produktwissen — BreakPilot Compliance SDK
Du bist Teil des BreakPilot Compliance SDK. Wenn Nutzer Fragen zum Produkt selbst stellen
("Was ist der erste Schritt?", "Wie fange ich an?", "Was kann dieses Tool?"), antworte
mit Produktwissen — nicht mit Rechtsberatung.
### Einstieg (fuer neue Nutzer)
Der Einstieg besteht aus 3 Schritten:
1. **Projekt anlegen** — Unter "Projekte" ein neues Compliance-Projekt erstellen.
Ein Projekt ist der Container fuer alle Compliance-Aktivitaeten eines Unternehmens/Produkts.
2. **Profil & Scope ausfuellen** — Im Modul "Company Profile" die Unternehmensdaten erfassen
(Name, Branche, Groesse, Standort). Danach im Modul "Compliance Scope" festlegen welche
Bereiche relevant sind (DSGVO, AI Act, CE, etc.) und die Risikostufe bestimmen.
3. **Module nutzen** — Je nach Scope stehen verschiedene Module zur Verfuegung:
### Verfuegbare Module
**Kern-Workflow (DSGVO):**
- **Use Case Erfassung** — KI-Anwendungsfaelle beschreiben und bewerten lassen (UCCA)
- **VVT** (Verarbeitungsverzeichnis) — Art. 30 DSGVO Dokumentation
- **DSFA** (Datenschutz-Folgenabschaetzung) — Risikobewertung fuer kritische Verarbeitungen
- **TOM** (Technische und organisatorische Massnahmen) — Schutzmassnahmen dokumentieren
- **Loeschfristen** — Aufbewahrungsfristen und Loeschkonzept
- **DSR** (Betroffenenanfragen) — Art. 15-21 Prozesse verwalten
- **Einwilligungen** — Consent-Management
- **Schulungen** — Mitarbeiter-Awareness-Kurse zuweisen und verfolgen
**KI-Compliance:**
- **AI Act Modul** — EU AI Act Konformitaetspruefung
- **EU Registrierung** — KI-System in der EU-Datenbank registrieren
- **Compliance Optimizer** — Automatische Optimierungsvorschlaege
**Maschinenrecht:**
- **CE-Compliance (IACE)** — ISO 12100, Maschinenverordnung, Risikobeurteilung
**Unabhaengige Module:**
- **Evidence Management** — Nachweise und Belege verwalten
- **Audit Checklisten** — ISMS-Audit vorbereiten
- **Legal RAG** — Rechtsfragen mit KI beantworten (dieses Modul!)
- **Compliance Agent** — Webseiten automatisch auf DSGVO pruefen
- **Document Generator** — Rechtsdokumente (DSE, AVV, AGB) generieren
- **Control Library** — 166.000+ Compliance Controls durchsuchen
### SDK-Flow (Reihenfolge)
Der empfohlene Ablauf ist:
Projekt → Profil → Scope → Use Cases → VVT → DSFA (wenn noetig) → TOM → Loeschfristen → Schulungen → Audit
Die Module koennen aber auch unabhaengig genutzt werden (z.B. Compliance Agent oder Document Generator).
### Hilfe und Navigation
- **Sidebar links** — Alle Module sind ueber die Sidebar erreichbar
- **CommandBar** (Cmd+K) — Schnellsuche ueber alle Module
- **Dieser Advisor** — Stellt Fragen zu Compliance-Themen oder zum SDK selbst
- **SDK-Flow Dokumentation** — Detaillierte Anleitung unter dem Menue-Punkt "SDK Flow"
## Haeufige Fragen (FAQ) — IAM-Systeme und Consent
### Was ist WSO2 Identity Server?
WSO2 Identity Server ist ein Open-Source Identity & Access Management (IAM) System,
vergleichbar mit Keycloak, Auth0 oder Azure AD B2C. Es wird von der Firma WSO2 Inc.
(Hauptsitz: Mountain View, USA + Colombo, Sri Lanka) entwickelt und gepflegt.
**DSGVO-Relevanz:** WSO2 IS liefert Standard-HTML-Templates fuer Login-, Registrierungs-
und Passwort-Reset-Seiten aus. Organisationen uebernehmen diese Templates oft 1:1 —
inklusive der Consent-Texte. Das fuehrt zu **systemischen Compliance-Problemen**:
- Die englischen Default-Texte sind bereits grenzwertig ("By clicking Register, you
agree to our Terms and Privacy Policy" — kein aktiver Opt-in)
- Uebersetzungen werden maschinell oder von Nicht-Juristen erstellt
- Niemand prueft ob die Formulierungen DSGVO-konform sind
- Das Pattern "Klick = Zustimmung" verletzt Art. 7(4) DSGVO (Koppelungsverbot)
und EuGH C-673/17 Planet49 (aktive Einwilligung erforderlich)
**Betroffene Organisationen:** EU-Behoerden (z.B. EUIPO), Regierungen, Telcos,
Banken, Versicherungen, Universitaeten — alle mit demselben Template-Fehler.
**Empfehlung:** Registrierungs- und Login-Seiten muessen geprueft werden auf:
1. Separate Checkboxen fuer Nutzungsbedingungen und Datenschutz (Granularitaet)
2. Aktive Zustimmungshandlung (Checkbox, nicht nur Button-Klick)
3. Moeglichkeit zur Ablehnung (Art. 7(3) DSGVO)
4. Grammatisch korrekte, verstaendliche Formulierung in der Sprache des Nutzers
5. Keine Koppelung von Einwilligung an Registrierung/Login (Art. 7(4) DSGVO)
### Welche IAM-Systeme haben aehnliche Probleme?
| System | Anbieter | Typisches Problem |
|--------|----------|-------------------|
| WSO2 Identity Server | WSO2 Inc. (US/LK) | Default-Templates mit Zwangs-Consent |
| Keycloak | Red Hat (US) | Kein Consent-Layer im Default-Theme |
| Azure AD B2C | Microsoft (US) | Custom Policies ohne DSGVO-Pruefung |
| Auth0 | Okta (US) | Universal Login ohne granularen Consent |
| AWS Cognito | Amazon (US) | Hosted UI ohne Consent-Management |
| ForgeRock | Ping Identity (US) | AM Templates ohne EU-Lokalisierung |
Alle diese Systeme erfordern manuelle Anpassung der Templates fuer DSGVO-Konformitaet.
Unser Compliance Agent kann Login/Registrierungsseiten auf diese Pattern pruefen.
### Was ist das Koppelungsverbot (Art. 7(4) DSGVO)?
Die Einwilligung zur Datenverarbeitung darf NICHT an die Erfuellung eines Vertrags
oder die Erbringung einer Dienstleistung gekoppelt werden, wenn die Datenverarbeitung
fuer die Vertragserfuellung nicht erforderlich ist.
**Praxis-Beispiel:** "Mit Klick auf Registrieren stimmen Sie unserer Datenschutzerklaerung zu"
ist ein Verstoss, wenn der Dienst auch ohne diese Zustimmung nutzbar waere.
**Korrekt:** Separate, freiwillige Checkbox: "Ich willige in die Verarbeitung meiner Daten
gemaess der Datenschutzerklaerung ein (freiwillig)."
**Quellen:** Art. 7(4) DSGVO, ErwGr. 43, EDPB Guidelines 05/2020 Rn. 26-30.
## CMP — Consent Management Platform
Das BreakPilot CMP ist die integrierte Consent-Management-Plattform im SDK.
Erreichbar ueber die CMP-Sektion in der Sidebar oder unter /sdk/cmp.
**Module:**
- **Dashboard** (/sdk/cmp) — Ueberblick ueber Consents, DSR, Compliance-Status
- **Cookie-Banner** (/sdk/cookie-banner) — Banner konfigurieren mit EWR-Only Toggle
- **Live-Vorschau** (/sdk/cookie-banner/preview) — Banner auf simulierter Website testen
- **Consent-Records** (/sdk/einwilligungen) — Alle Einwilligungen einsehen
- **Consent-Verwaltung** (/sdk/consent-management) — Dokument-Lifecycle
- **Vendor-Compliance** (/sdk/vendor-compliance) — Dienstleister-Management
- **DSR Portal** (/sdk/dsr) — Betroffenenrechte Art. 15-21
- **Loeschfristen** (/sdk/loeschfristen) — Aufbewahrungsrichtlinien
- **E-Mail-Templates** (/sdk/email-templates) — Benachrichtigungsvorlagen
**Einzigartiges Feature: "Nur EU/EWR" Toggle**
Nutzer koennen einer Cookie-Kategorie zustimmen (z.B. Marketing), aber gleichzeitig
alle Anbieter ausserhalb des EWR blockieren. Beispiel: Marketing = AN, EWR-Only = AN
bedeutet LinkedIn Insight (EU/Irland) wird geladen, Facebook Pixel (USA) wird blockiert.
Kein anderes CMP bietet dieses Feature.
## Eskalation
- Bei Fragen ausserhalb des Kompetenzbereichs: Wenn die Frage harmlos ist (z.B. "Hast Du Informationen zu X?"), kurz mit Ja/Nein antworten und anbieten konkreter zu helfen. NUR bei sensiblen oder rechtsberatenden Fragen hoeflich ablehnen und auf Fachanwalt verweisen.
- Bei Fragen ausserhalb des Kompetenzbereichs: Hoeflich ablehnen und auf Fachanwalt verweisen
- Bei widerspruechlichen Rechtslagen: Beide Positionen darstellen und DSB-Konsultation empfehlen
- Bei dringenden Datenpannen: Auf 72-Stunden-Frist (Art. 33 DSGVO) hinweisen und Notfallplan-Modul empfehlen
@@ -1,27 +0,0 @@
/**
* Proxy: Admin → Backend /api/compliance/agent/admin/benchmark
* (P107 — Branchen-Benchmark-Cockpit)
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(request: NextRequest) {
const qs = request.nextUrl.searchParams.toString()
try {
const r = await fetch(
`${BACKEND_URL}/api/compliance/agent/admin/benchmark?${qs}`,
{ signal: AbortSignal.timeout(20000) },
)
const body = await r.text()
return new NextResponse(body, {
status: r.status,
headers: { 'Content-Type': r.headers.get('content-type') || 'application/json' },
})
} catch (e: any) {
return NextResponse.json(
{ error: 'Benchmark-API nicht erreichbar', detail: String(e) },
{ status: 503 },
)
}
}
@@ -240,7 +240,7 @@ export async function handleV2Draft(body: Record<string, unknown>): Promise<Next
const promptHash = computeChecksumSync({ factsString, tagsString, termsString, styleString, disallowedString })
const v2RagCfg = DOCUMENT_RAG_CONFIG[documentType]
const v2RagContext = v2RagCfg ? await queryRAG(v2RagCfg.query, 3, v2RagCfg.collection) : null
const v2RagContext = await queryRAG(v2RagCfg.query, 3, v2RagCfg.collection)
const proseBlocks = DOCUMENT_PROSE_BLOCKS[documentType] || DOCUMENT_PROSE_BLOCKS.tom
const generatedBlocks: ProseBlockOutput[] = []
@@ -88,7 +88,7 @@ export async function handleV1Draft(body: Record<string, unknown>): Promise<Next
}
const ragCfg = DOCUMENT_RAG_CONFIG[documentType]
const ragContext = ragCfg ? await queryRAG(ragCfg.query, 3, ragCfg.collection) : null
const ragContext = await queryRAG(ragCfg.query, 3, ragCfg.collection)
let v1SystemPrompt = V1_SYSTEM_PROMPT
if (ragContext) {
@@ -6,7 +6,7 @@
*/
import { NextRequest, NextResponse } from 'next/server'
import { DOCUMENT_SCOPE_MATRIX_CORE, DOCUMENT_TYPE_LABELS, getDepthLevelNumeric } from '@/lib/sdk/compliance-scope-types'
import { DOCUMENT_SCOPE_MATRIX, DOCUMENT_TYPE_LABELS, getDepthLevelNumeric } from '@/lib/sdk/compliance-scope-types'
import type { ScopeDocumentType, ComplianceDepthLevel } from '@/lib/sdk/compliance-scope-types'
import type { ValidationContext, ValidationResult, ValidationFinding } from '@/lib/sdk/drafting-engine/types'
import { buildCrossCheckPrompt } from '@/lib/sdk/drafting-engine/prompts/validate-cross-check'
@@ -94,7 +94,7 @@ function deterministicCheck(
const findings: ValidationFinding[] = []
const level = validationContext.scopeLevel
const levelNumeric = getDepthLevelNumeric(level)
const req = DOCUMENT_SCOPE_MATRIX_CORE[documentType]?.[level]
const req = DOCUMENT_SCOPE_MATRIX[documentType]?.[level]
// Check 1: Ist das Dokument auf diesem Level erforderlich?
if (req && !req.required && levelNumeric < 3) {
@@ -109,8 +109,8 @@ function deterministicCheck(
}
// Check 2: VVT vorhanden wenn erforderlich?
const vvtReq = DOCUMENT_SCOPE_MATRIX_CORE.vvt?.[level]
if (vvtReq?.required && validationContext.crossReferences.vvtCategories.length === 0) {
const vvtReq = DOCUMENT_SCOPE_MATRIX.vvt[level]
if (vvtReq.required && validationContext.crossReferences.vvtCategories.length === 0) {
findings.push({
id: 'DET-VVT-MISSING',
severity: 'error',
@@ -1,42 +0,0 @@
/**
* Agent Analyze API Proxy
* POST /api/sdk/v1/agent/analyze → backend-compliance /api/compliance/agent/analyze
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/analyze`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Tenant-Id': '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e',
'X-User-Id': '00000000-0000-0000-0000-000000000001',
},
body,
signal: AbortSignal.timeout(120000), // 2 min — LLM can be slow
})
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json(
{ error: `Backend: ${response.status}`, detail: errorText },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Agent analyze proxy error:', error)
return NextResponse.json(
{ error: 'Verbindung zum Backend fehlgeschlagen' },
{ status: 503 }
)
}
}
@@ -1,28 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/audit/<checkId>
* -> backend GET /api/compliance/agent/audit/<checkId>
*
* Forwards optional query params (doc_type, regulation, only_failed).
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ checkId: string }> },
) {
const { checkId } = await params
const qs = request.nextUrl.searchParams.toString()
const url = `${BACKEND_URL}/api/compliance/agent/audit/${checkId}${qs ? `?${qs}` : ''}`
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(15000) })
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Audit-Abfrage fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,20 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const CONSENT_URL = process.env.CONSENT_TESTER_URL || 'http://bp-compliance-consent-tester:8094'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${CONSENT_URL}/authenticated-scan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(120000),
})
if (!response.ok) {
return NextResponse.json({ error: `Auth-Test: ${response.status}` }, { status: response.status })
}
return NextResponse.json(await response.json())
} catch (error) {
return NextResponse.json({ error: 'Auth-Test fehlgeschlagen' }, { status: 503 })
}
}
@@ -1,42 +0,0 @@
/**
* Banner Check API Proxy — calls consent-tester /scan endpoint
*
* POST /api/sdk/v1/agent/banner-check → runs 3-phase cookie banner test
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { url, categories = [] } = body
if (!url) {
return NextResponse.json({ error: 'URL erforderlich' }, { status: 400 })
}
// Call backend which proxies to consent-tester
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/banner-check`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, categories }),
signal: AbortSignal.timeout(120000), // 2 min for Playwright
})
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json(
{ error: `Backend: ${response.status}`, detail: errorText },
{ status: response.status },
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
const msg = error instanceof Error ? error.message : 'Unknown error'
return NextResponse.json({ error: msg }, { status: 500 })
}
}
@@ -1,28 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/banner/<checkId>
* -> backend GET /api/compliance/agent/banner/<checkId>
*
* Liefert das volle banner_result (phases, structured_checks, category_tests).
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ checkId: string }> },
) {
const { checkId } = await params
try {
const resp = await fetch(
`${BACKEND_URL}/api/compliance/agent/banner/${checkId}`,
{ signal: AbortSignal.timeout(15000) },
)
const data = await resp.json().catch(() => ({}))
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Banner-Abfrage fehlgeschlagen' }, { status: 503 },
)
}
}
@@ -1,20 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/compare`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(300000),
})
if (!response.ok) {
return NextResponse.json({ error: `Backend: ${response.status}` }, { status: response.status })
}
return NextResponse.json(await response.json())
} catch (error) {
return NextResponse.json({ error: 'Vergleich fehlgeschlagen' }, { status: 503 })
}
}
@@ -1,39 +0,0 @@
/**
* Unified Compliance Check Proxy
* POST: start check for all documents, GET: poll status
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/compliance-check`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(30000),
})
const data = await response.json()
return NextResponse.json(data, { status: response.status })
} catch (error) {
return NextResponse.json({ error: 'Pruefung konnte nicht gestartet werden' }, { status: 503 })
}
}
export async function GET(request: NextRequest) {
const checkId = request.nextUrl.searchParams.get('check_id')
if (!checkId) return NextResponse.json({ error: 'check_id required' }, { status: 400 })
try {
const response = await fetch(
`${BACKEND_URL}/api/compliance/agent/compliance-check/${checkId}`,
{ signal: AbortSignal.timeout(10000) },
)
const data = await response.json()
return NextResponse.json(data)
} catch {
return NextResponse.json({ error: 'Status-Abfrage fehlgeschlagen' }, { status: 503 })
}
}
@@ -1,142 +0,0 @@
/**
* Consent Test API Proxy
* POST /api/sdk/v1/agent/consent-test → consent-tester:8094/scan → email via backend
*/
import { NextRequest, NextResponse } from 'next/server'
const CONSENT_TESTER_URL = process.env.CONSENT_TESTER_URL || 'http://bp-compliance-consent-tester:8094'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
interface Violation { service: string; severity: string; text: string; legal_ref: string }
function buildEmailHtml(data: any): string {
const url = data.url || ''
const banner = data.banner_detected ? data.banner_provider : 'Nicht erkannt'
const phases = data.phases || {}
const summary = data.summary || {}
const sev = (s: string) => s === 'CRITICAL'
? '<span style="background:#991b1b;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">KRITISCH</span>'
: '<span style="background:#ea580c;color:white;padding:2px 6px;border-radius:3px;font-size:11px;">HOCH</span>'
const violationRows = (violations: Violation[]) => violations.length === 0
? '<tr><td colspan="3" style="padding:6px;color:#16a34a;">✓ Keine Verstoesse</td></tr>'
: violations.map(v =>
`<tr><td style="padding:6px;">${sev(v.severity)}</td><td style="padding:6px;font-weight:600;">${v.service}</td><td style="padding:6px;">${v.text}<br><span style="color:#6b7280;font-size:11px;">${v.legal_ref}</span></td></tr>`
).join('')
const undocRows = (items: string[]) => items.length === 0
? ''
: items.map(s => `<tr><td style="padding:6px;">⚠</td><td style="padding:6px;font-weight:600;">${s}</td><td style="padding:6px;">Nicht in Cookie-Policy dokumentiert</td></tr>`).join('')
return `
<div style="font-family:-apple-system,sans-serif;max-width:700px;margin:0 auto;">
<div style="background:linear-gradient(135deg,#1e1b4b,#312e81);color:white;padding:20px 24px;border-radius:12px 12px 0 0;">
<h2 style="margin:0;font-size:18px;">Cookie-Consent-Test</h2>
<p style="margin:4px 0 0;opacity:0.8;font-size:13px;">${url}</p>
</div>
<div style="padding:20px 24px;border:1px solid #e2e8f0;border-top:none;">
<table style="width:100%;border-collapse:collapse;margin-bottom:20px;">
<tr><td style="padding:6px 0;color:#64748b;width:160px;">Cookie-Banner</td><td style="padding:6px 0;font-weight:600;">${data.banner_detected ? '✓ ' + banner : '✗ Nicht erkannt'}</td></tr>
<tr><td style="padding:6px 0;color:#64748b;">Kritische Verstoesse</td><td style="padding:6px 0;"><strong style="color:${summary.critical > 0 ? '#dc2626' : '#16a34a'}">${summary.critical || 0}</strong></td></tr>
<tr><td style="padding:6px 0;color:#64748b;">Hohe Verstoesse</td><td style="padding:6px 0;"><strong style="color:${summary.high > 0 ? '#ea580c' : '#16a34a'}">${summary.high || 0}</strong></td></tr>
<tr><td style="padding:6px 0;color:#64748b;">Undokumentiert</td><td style="padding:6px 0;">${summary.undocumented || 0}</td></tr>
</table>
<h3 style="color:#1e293b;font-size:14px;margin:20px 0 8px;border-bottom:2px solid #e2e8f0;padding-bottom:6px;">
🔍 Phase A: Vor Einwilligung
</h3>
<p style="color:#64748b;font-size:12px;margin:0 0 8px;">Was laedt OHNE dass der Nutzer etwas geklickt hat?</p>
<table style="width:100%;border-collapse:collapse;">${violationRows(phases.before_consent?.violations || [])}</table>
${data.banner_detected ? `
<h3 style="color:#1e293b;font-size:14px;margin:20px 0 8px;border-bottom:2px solid #e2e8f0;padding-bottom:6px;">
🚫 Phase B: Nach Ablehnung
</h3>
<p style="color:#64748b;font-size:12px;margin:0 0 8px;">Was laedt NACHDEM der Nutzer "Nur notwendige" geklickt hat?</p>
<table style="width:100%;border-collapse:collapse;">${violationRows(phases.after_reject?.violations || [])}</table>
<h3 style="color:#1e293b;font-size:14px;margin:20px 0 8px;border-bottom:2px solid #e2e8f0;padding-bottom:6px;">
✅ Phase C: Nach Zustimmung
</h3>
<p style="color:#64748b;font-size:12px;margin:0 0 8px;">Was laedt NACHDEM der Nutzer "Alle akzeptieren" geklickt hat?</p>
<table style="width:100%;border-collapse:collapse;">${undocRows(phases.after_accept?.undocumented || [])}</table>
${(phases.after_accept?.undocumented?.length || 0) === 0 ? '<p style="color:#16a34a;font-size:13px;">✓ Alle Dienste dokumentiert</p>' : ''}
` : `
<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:12px;margin:12px 0;">
<strong style="color:#dc2626;">Kein Cookie-Banner erkannt.</strong>
Alle Tracking-Dienste laden ohne Einwilligung — Verstoss gegen §25 TDDDG.
</div>
`}
${(summary.critical || 0) > 0 ? `
<div style="background:#fef2f2;border-left:4px solid #dc2626;padding:12px 16px;margin-top:20px;">
<strong style="color:#991b1b;">⚠ KRITISCH:</strong> Tracking-Dienste laden trotz Ablehnung.
Dies ist ein schwerer Verstoss gegen §25 TDDDG und kann als Dark Pattern gewertet werden.
Sofortige Korrektur der Cookie-Banner-Konfiguration empfohlen.
</div>
` : ''}
</div>
<div style="background:#f8fafc;padding:12px 24px;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;">
<p style="color:#94a3b8;font-size:11px;margin:0;">
Automatisch erstellt vom BreakPilot Compliance Agent (Playwright + Chromium)
</p>
</div>
</div>
`
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const url = body.url
// Step 1: Run consent test
const response = await fetch(`${CONSENT_TESTER_URL}/scan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(180000),
})
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json(
{ error: `Consent-Tester: ${response.status}`, detail: errorText },
{ status: response.status }
)
}
const data = await response.json()
// Step 2: Send email with phase-structured findings
try {
const total = (data.summary?.total_violations || 0)
const severity = (data.summary?.critical || 0) > 0 ? 'KRITISCH' : total > 0 ? 'FINDINGS' : 'OK'
await fetch(`${BACKEND_URL}/api/compliance/agent/notify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
recipient: body.recipient || 'dsb@breakpilot.local',
subject: `[COOKIE-TEST] [${severity}] ${url}${total} Verstoesse`,
body_html: buildEmailHtml({ ...data, url }),
role: total > 0 ? 'Datenschutzbeauftragter' : 'Kein Handlungsbedarf',
}),
signal: AbortSignal.timeout(10000),
})
} catch (emailErr) {
console.warn('Email send failed (non-blocking):', emailErr)
}
return NextResponse.json(data)
} catch (error) {
console.error('Consent test proxy error:', error)
return NextResponse.json(
{ error: 'Cookie-Test fehlgeschlagen oder Timeout' },
{ status: 503 }
)
}
}
@@ -1,39 +0,0 @@
/**
* Agent Doc-Check Proxy — Multi-URL document verification
* POST: start check, GET: poll status
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/doc-check`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(30000),
})
const data = await response.json()
return NextResponse.json(data, { status: response.status })
} catch (error) {
return NextResponse.json({ error: 'Pruefung konnte nicht gestartet werden' }, { status: 503 })
}
}
export async function GET(request: NextRequest) {
const checkId = request.nextUrl.searchParams.get('check_id')
if (!checkId) return NextResponse.json({ error: 'check_id required' }, { status: 400 })
try {
const response = await fetch(
`${BACKEND_URL}/api/compliance/agent/doc-check/${checkId}`,
{ signal: AbortSignal.timeout(10000) },
)
const data = await response.json()
return NextResponse.json(data)
} catch {
return NextResponse.json({ error: 'Status-Abfrage fehlgeschlagen' }, { status: 503 })
}
}
@@ -1,27 +0,0 @@
/**
* Text Extraction Proxy — extract text from a URL via consent-tester
* POST: { url: string } -> { text, word_count, title, error }
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/extract-text`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(120000),
})
const data = await response.json()
return NextResponse.json(data, { status: response.status })
} catch (error) {
return NextResponse.json(
{ text: '', word_count: 0, title: '', error: 'Text-Extraktion fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,28 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/findings/<checkId>
* -> backend GET /api/compliance/agent/findings/<checkId>
*
* Forwards all query params (source, severity, doc_type, status, q, limit).
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ checkId: string }> },
) {
const { checkId } = await params
const qs = request.nextUrl.searchParams.toString()
const url = `${BACKEND_URL}/api/compliance/agent/findings/${checkId}${qs ? `?${qs}` : ''}`
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(20000) })
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Findings-Abfrage fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,25 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/migration/<checkId>/banner-preview
* -> backend GET /api/compliance/agent/migration/<checkId>/banner-preview
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
request: NextRequest,
{ params }: { params: { checkId: string } },
) {
const qs = request.nextUrl.searchParams.toString()
const url = `${BACKEND_URL}/api/compliance/agent/migration/${params.checkId}/banner-preview${qs ? `?${qs}` : ''}`
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(15000) })
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Banner-Preview fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,24 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/migration/<checkId>/document-preview
* -> backend GET /api/compliance/agent/migration/<checkId>/document-preview
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
_request: NextRequest,
{ params }: { params: { checkId: string } },
) {
const url = `${BACKEND_URL}/api/compliance/agent/migration/${params.checkId}/document-preview`
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(15000) })
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Dokument-Preview fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,24 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/agent/migration/<checkId>/summary
* -> backend GET /api/compliance/agent/migration/<checkId>/summary
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function GET(
_request: NextRequest,
{ params }: { params: { checkId: string } },
) {
const url = `${BACKEND_URL}/api/compliance/agent/migration/${params.checkId}/summary`
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(15000) })
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json(
{ error: 'Migrations-Summary fehlgeschlagen' },
{ status: 503 },
)
}
}
@@ -1,30 +0,0 @@
/**
* Agent Notify API Proxy
* POST /api/sdk/v1/agent/notify → backend-compliance /api/compliance/agent/notify
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/notify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(15000),
})
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json({ error: errorText }, { status: response.status })
}
return NextResponse.json(await response.json())
} catch (error) {
console.error('Agent notify proxy error:', error)
return NextResponse.json({ error: 'Email-Versand fehlgeschlagen' }, { status: 503 })
}
}
@@ -1,70 +0,0 @@
/**
* Agent Scan API Proxy — async scan with polling
*
* POST /api/sdk/v1/agent/scan → starts scan, returns scan_id
* GET /api/sdk/v1/agent/scan?scan_id=xxx → poll status/results
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
// Start async scan — returns immediately with scan_id
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/scan`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(300000), // 5 min — multi-page scan + LLM calls
})
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json(
{ error: `Backend: ${response.status}`, detail: errorText },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Agent scan proxy error:', error)
return NextResponse.json(
{ error: 'Scan konnte nicht gestartet werden' },
{ status: 503 }
)
}
}
export async function GET(request: NextRequest) {
const scanId = request.nextUrl.searchParams.get('scan_id')
if (!scanId) {
return NextResponse.json({ error: 'scan_id parameter required' }, { status: 400 })
}
try {
const response = await fetch(
`${BACKEND_URL}/api/compliance/agent/scan/${scanId}`,
{ signal: AbortSignal.timeout(10000) }
)
if (!response.ok) {
return NextResponse.json(
{ error: `Backend: ${response.status}` },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
return NextResponse.json(
{ error: 'Status-Abfrage fehlgeschlagen' },
{ status: 503 }
)
}
}
@@ -1,36 +0,0 @@
/**
* PDF Export Proxy
* POST /api/sdk/v1/agent/scans/pdf → backend /api/compliance/agent/scans/pdf
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_API_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const response = await fetch(`${BACKEND_URL}/api/compliance/agent/scans/pdf`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(30000),
})
if (!response.ok) {
return NextResponse.json({ error: 'PDF generation failed' }, { status: response.status })
}
const pdfBytes = await response.arrayBuffer()
return new NextResponse(pdfBytes, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="compliance-report.pdf"',
},
})
} catch (error) {
console.error('PDF proxy error:', error)
return NextResponse.json({ error: 'PDF generation failed' }, { status: 503 })
}
}
@@ -1,47 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const resp = await fetch(`${SDK_URL}/sdk/v1/ai-registration/${id}`)
const data = await resp.json()
return NextResponse.json(data)
} catch (err) {
return NextResponse.json({ error: 'Failed to fetch registration' }, { status: 500 })
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const body = await request.json()
const resp = await fetch(`${SDK_URL}/sdk/v1/ai-registration/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'X-Tenant-ID': tenantId },
body: JSON.stringify(body),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (err) {
return NextResponse.json({ error: 'Failed to update registration' }, { status: 500 })
}
}
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const body = await request.json()
const resp = await fetch(`${SDK_URL}/sdk/v1/ai-registration/${id}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (err) {
return NextResponse.json({ error: 'Failed to update status' }, { status: 500 })
}
}
@@ -1,32 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const resp = await fetch(`${SDK_URL}/sdk/v1/ai-registration`, {
headers: { 'X-Tenant-ID': tenantId },
})
const data = await resp.json()
return NextResponse.json(data)
} catch (err) {
return NextResponse.json({ error: 'Failed to fetch registrations' }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const body = await request.json()
const resp = await fetch(`${SDK_URL}/sdk/v1/ai-registration`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Tenant-ID': tenantId },
body: JSON.stringify(body),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (err) {
return NextResponse.json({ error: 'Failed to create registration' }, { status: 500 })
}
}
@@ -1,74 +0,0 @@
/**
* Banner API Proxy — catch-all route for cookie banner endpoints.
*
* Maps: /api/sdk/v1/banner/<path> → backend-compliance:8002/api/compliance/banner/<path>
*
* Solves: Browser cannot call backend-compliance:8093 directly due to
* self-signed SSL certificates. This proxy runs server-side where
* certificate validation is not an issue.
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
const DEFAULT_TENANT = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
async function proxyRequest(
request: NextRequest,
pathSegments: string[] | undefined,
method: string,
) {
const pathStr = pathSegments?.join('/') || ''
const qs = request.nextUrl.searchParams.toString()
const base = `${BACKEND_URL}/api/compliance/banner`
const url = pathStr
? `${base}/${pathStr}${qs ? `?${qs}` : ''}`
: `${base}${qs ? `?${qs}` : ''}`
try {
const headers: HeadersInit = {
'X-Tenant-ID': request.headers.get('x-tenant-id') || DEFAULT_TENANT,
}
const ct = request.headers.get('Content-Type')
if (ct) headers['Content-Type'] = ct
const opts: RequestInit = { method, headers, signal: AbortSignal.timeout(30000) }
if (method === 'POST' || method === 'PUT') {
const body = await request.text()
if (body) opts.body = body
}
const res = await fetch(url, opts)
const text = await res.text()
let data
try { data = JSON.parse(text) } catch { data = { raw: text } }
if (!res.ok) {
return NextResponse.json(
{ error: `Backend ${res.status}`, ...data },
{ status: res.status },
)
}
return NextResponse.json(data)
} catch (err: any) {
console.error('Banner proxy error:', err?.message)
return NextResponse.json(
{ error: 'Backend nicht erreichbar' },
{ status: 503 },
)
}
}
export async function GET(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxyRequest(req, (await params).path, 'GET')
}
export async function POST(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxyRequest(req, (await params).path, 'POST')
}
export async function PUT(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxyRequest(req, (await params).path, 'PUT')
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxyRequest(req, (await params).path, 'DELETE')
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest, ctx: { params: Promise<{ checkId: string }> }) {
const { checkId } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/checks/${checkId}/run`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenantId, 'Content-Type': 'application/json' },
body: body || '{}',
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest, ctx: { params: Promise<{ docId: string }> }) {
const { docId } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/documents/${docId}/approve`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenantId, 'Content-Type': 'application/json' },
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest, ctx: { params: Promise<{ docId: string }> }) {
const { docId } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/documents/${docId}`, {
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,20 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/backlog`, {
headers: { 'X-Tenant-ID': tenantId },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,41 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/checks`, {
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
/** POST /checks (no body) -> backend /checks/init creates default checks */
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/checks/init`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/documents/generate`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenantId, 'Content-Type': 'application/json' },
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,26 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const { searchParams } = new URL(request.url)
const qs = searchParams.toString()
try {
const resp = await fetch(
`${BACKEND_URL}/api/v1/cra/projects/${id}/documents${qs ? `?${qs}` : ''}`,
{ headers: { 'X-Tenant-ID': tenant(request) } }
)
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,20 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/monitoring`, {
headers: { 'X-Tenant-ID': tenantId },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,29 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/path-select`, {
method: 'POST',
headers: {
'X-Tenant-ID': tenantId,
'Content-Type': 'application/json',
},
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json(
{ error: 'Backend unreachable', details: String(err) },
{ status: 502 }
)
}
}
@@ -1,20 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/requirements`, {
headers: { 'X-Tenant-ID': tenantId },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,45 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
async function proxy(request: NextRequest, method: string, id: string, body?: string) {
const tenantId = tenantHeader(request)
const init: RequestInit = {
method,
headers: { 'X-Tenant-ID': tenantId, 'Content-Type': 'application/json' },
}
if (body !== undefined) init.body = body
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}`, init)
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json(
{ error: 'Backend unreachable', details: String(err) },
{ status: 502 }
)
}
}
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
return proxy(request, 'GET', id)
}
export async function PATCH(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const body = await request.text()
return proxy(request, 'PATCH', id, body)
}
export async function DELETE(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
return proxy(request, 'DELETE', id)
}
@@ -1,48 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
/** GET /sbom -> List uploads. We map this to the backend /sboms endpoint. */
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/sboms`, {
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
/** POST /sbom -> multipart upload to backend /sbom/upload */
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
try {
const formData = await request.formData()
const upstreamForm = new FormData()
for (const [key, value] of formData.entries()) {
upstreamForm.append(key, value)
}
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/sbom/upload`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenant(request) },
body: upstreamForm as unknown as BodyInit,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,24 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const tenantId = request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/scope-check`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenantId },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json(
{ error: 'Backend unreachable', details: String(err) },
{ status: 502 }
)
}
}
@@ -1,42 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/vulnerabilities`, {
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
export async function POST(request: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { id } = await ctx.params
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/${id}/vulnerabilities`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenant(request), 'Content-Type': 'application/json' },
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,56 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
/** GET /api/sdk/v1/cra/projects -> Backend list */
export async function GET(request: NextRequest) {
const tenantId = tenantHeader(request)
const { searchParams } = new URL(request.url)
const qs = searchParams.toString()
try {
const resp = await fetch(
`${BACKEND_URL}/api/v1/cra/projects${qs ? `?${qs}` : ''}`,
{ headers: { 'X-Tenant-ID': tenantId } }
)
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json(
{ error: 'Backend unreachable', details: String(err) },
{ status: 502 }
)
}
}
/** POST /api/sdk/v1/cra/projects -> Backend create */
export async function POST(request: NextRequest) {
const tenantId = tenantHeader(request)
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects`, {
method: 'POST',
headers: {
'X-Tenant-ID': tenantId,
'Content-Type': 'application/json',
},
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json(
{ error: 'Backend unreachable', details: String(err) },
{ status: 502 }
)
}
}
@@ -1,43 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenant(req: NextRequest) {
return req.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function PATCH(request: NextRequest, ctx: { params: Promise<{ vulnId: string }> }) {
const { vulnId } = await ctx.params
const body = await request.text()
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/vulnerabilities/${vulnId}`, {
method: 'PATCH',
headers: { 'X-Tenant-ID': tenant(request), 'Content-Type': 'application/json' },
body,
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
export async function DELETE(request: NextRequest, ctx: { params: Promise<{ vulnId: string }> }) {
const { vulnId } = await ctx.params
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/cra/projects/vulnerabilities/${vulnId}`, {
method: 'DELETE',
headers: { 'X-Tenant-ID': tenant(request) },
})
const text = await resp.text()
return new NextResponse(text, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,22 +0,0 @@
/**
* DSMS Gateway Proxy — forwards verify/history requests to dsms-gateway.
*/
import { NextRequest, NextResponse } from 'next/server'
const DSMS_URL = process.env.DSMS_GATEWAY_URL || 'http://dsms-gateway:8082'
export async function GET(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params
const target = `${DSMS_URL}/api/v1/${path.join('/')}`
try {
const resp = await fetch(target, {
headers: { Authorization: 'Bearer system-frontend' },
signal: AbortSignal.timeout(15000),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch {
return NextResponse.json({ error: 'DSMS not available' }, { status: 503 })
}
}
@@ -23,13 +23,12 @@ function getTenantId(request: NextRequest): string {
*/
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
{ params }: { params: { id: string } }
) {
try {
const { id } = await params
const tenantId = getTenantId(request)
const response = await fetch(
`${BACKEND_URL}/api/compliance/einwilligungen/consents/${id}/history`,
`${BACKEND_URL}/api/compliance/einwilligungen/consents/${params.id}/history`,
{
method: 'GET',
headers: {
@@ -1,55 +0,0 @@
/**
* Proxy: GET /api/sdk/v1/einwilligungen/export?format=csv|json&kind=consents|history
* -> backend /api/compliance/einwilligungen/export/<file>
*
* Streams the backend response straight through (CSV or JSON download).
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function getTenantHeader(request: NextRequest): HeadersInit {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const clientTenantId = request.headers.get('x-tenant-id') || request.headers.get('X-Tenant-ID')
const tenantId = (clientTenantId && uuidRegex.test(clientTenantId))
? clientTenantId
: (process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e')
return { 'X-Tenant-ID': tenantId }
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const fmt = (searchParams.get('format') || 'csv').toLowerCase()
const kind = (searchParams.get('kind') || 'consents').toLowerCase()
const filename = `${kind}.${fmt === 'json' ? 'json' : 'csv'}`
const upstreamPath = `/api/compliance/einwilligungen/export/${filename}`
const passthroughParams = new URLSearchParams()
for (const k of ['user_id', 'granted', 'since', 'consent_id']) {
const v = searchParams.get(k)
if (v) passthroughParams.set(k, v)
}
const qs = passthroughParams.toString()
const url = `${BACKEND_URL}${upstreamPath}${qs ? `?${qs}` : ''}`
try {
const r = await fetch(url, { headers: getTenantHeader(request) })
if (!r.ok) {
const text = await r.text()
return NextResponse.json({ error: text || `HTTP ${r.status}` }, { status: r.status })
}
return new NextResponse(r.body, {
status: 200,
headers: {
'Content-Type': r.headers.get('content-type') || 'application/octet-stream',
'Content-Disposition': r.headers.get('content-disposition') || `attachment; filename=${filename}`,
},
})
} catch (e) {
return NextResponse.json(
{ error: 'Export-Proxy fehlgeschlagen', detail: String(e) },
{ status: 503 },
)
}
}
@@ -30,15 +30,15 @@ async function proxyRequest(
headers['Authorization'] = authHeader
}
// Default tenant/user for IACE (same pattern as training proxy)
const DEFAULT_TENANT = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const DEFAULT_USER = '00000000-0000-0000-0000-000000000001'
const tenantHeader = request.headers.get('x-tenant-id')
headers['X-Tenant-Id'] = tenantHeader || DEFAULT_TENANT
if (tenantHeader) {
headers['X-Tenant-Id'] = tenantHeader
}
const userHeader = request.headers.get('x-user-id')
headers['X-User-Id'] = userHeader || DEFAULT_USER
if (userHeader) {
headers['X-User-Id'] = userHeader
}
const fetchOptions: RequestInit = {
method,
@@ -1,229 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
import { Pool } from 'pg'
// Disable SSL rejection for self-signed certs
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
const dbUrl = process.env.COMPLIANCE_DATABASE_URL ||
process.env.DATABASE_URL ||
'postgresql://breakpilot:breakpilot123@bp-core-postgres:5432/breakpilot_db'
const pool = new Pool({ connectionString: dbUrl })
/**
* MC API that returns data in the same format as the canonical controls
* endpoint. This allows the MC page to reuse ControlListView components.
*/
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const endpoint = searchParams.get('endpoint') || 'controls'
switch (endpoint) {
case 'frameworks':
return NextResponse.json([])
case 'controls':
return handleControls(searchParams)
case 'controls-count':
return handleCount(searchParams)
case 'controls-meta':
return handleMeta(searchParams)
case 'control':
return handleDetail(searchParams)
default:
return NextResponse.json({ error: 'unknown' }, { status: 400 })
}
} catch (e) {
return NextResponse.json({ error: String(e) }, { status: 500 })
}
}
async function handleControls(params: URLSearchParams) {
const search = params.get('search') || ''
const limit = Math.min(parseInt(params.get('limit') || '50'), 200)
const offset = parseInt(params.get('offset') || '0')
const sort = params.get('sort') || 'control_id'
const order = params.get('order') === 'desc' ? 'DESC' : 'ASC'
let where = "WHERE 1=1"
const args: unknown[] = []
let idx = 1
if (search) {
where += ` AND mc.canonical_name ILIKE $${idx}`
args.push(`%${search}%`)
idx++
}
const severity = params.get('severity') || ''
if (severity) {
if (severity === 'high') { where += ` AND mc.total_controls > 100` }
else if (severity === 'medium') { where += ` AND mc.total_controls BETWEEN 20 AND 100` }
else if (severity === 'low') { where += ` AND mc.total_controls < 20` }
}
const domain = params.get('domain') || ''
if (domain) {
where += ` AND mc.canonical_name LIKE $${idx}`
args.push(`${domain}%`)
idx++
}
const sortCol = sort === 'control_id' ? 'mc.master_control_id' :
sort === 'created_at' ? 'mc.created_at' :
sort === 'source' ? 'mc.canonical_name' : 'mc.master_control_id'
args.push(limit, offset)
const res = await pool.query(`
SELECT mc.master_control_id as control_id,
mc.canonical_name as title,
'Master Control mit ' || mc.total_controls || ' Atomic Controls' as objective,
CASE WHEN mc.total_controls > 100 THEN 'high'
WHEN mc.total_controls > 20 THEN 'medium'
ELSE 'low' END as severity,
'master_control' as category,
mc.total_controls,
mc.phases_covered,
mc.id,
mc.created_at
FROM compliance.master_controls mc
${where}
ORDER BY ${sortCol} ${order}
LIMIT $${idx} OFFSET $${idx + 1}
`, args)
// Map to canonical control format
const controls = res.rows.map(r => ({
id: r.id,
control_id: r.control_id,
title: r.title,
objective: r.objective,
severity: r.severity,
category: r.category,
release_state: 'active',
source_citation: null,
verification_method: null,
evidence_type: null,
target_audience: [],
requirements: [],
test_procedure: [],
evidence: [],
open_anchors: [],
total_controls: r.total_controls,
phases_covered: r.phases_covered,
created_at: r.created_at,
scope: { platforms: [], components: [], data_classes: [] },
risk_score: null,
implementation_effort: null,
}))
return NextResponse.json(controls)
}
async function handleCount(params: URLSearchParams) {
const search = params.get('search') || ''
let where = "WHERE 1=1"
const args: unknown[] = []
if (search) {
where += ` AND mc.canonical_name ILIKE $1`
args.push(`%${search}%`)
}
const res = await pool.query(
`SELECT count(*) FROM compliance.master_controls mc ${where}`, args
)
return NextResponse.json({ total: parseInt(res.rows[0].count) })
}
async function handleMeta(params: URLSearchParams) {
const res = await pool.query(`
SELECT count(*) as total,
count(CASE WHEN total_controls > 100 THEN 1 END) as high_count,
count(CASE WHEN total_controls BETWEEN 20 AND 100 THEN 1 END) as medium_count,
count(CASE WHEN total_controls < 20 THEN 1 END) as low_count
FROM compliance.master_controls
`)
const r = res.rows[0]
// Get top L1 tokens as "domains"
const domainRes = await pool.query(`
SELECT split_part(canonical_name, '_', 1) as domain, count(*) as count
FROM compliance.master_controls
GROUP BY 1 ORDER BY 2 DESC LIMIT 30
`)
return NextResponse.json({
total: parseInt(r.total),
severity_counts: {
high: parseInt(r.high_count),
medium: parseInt(r.medium_count),
low: parseInt(r.low_count),
},
domains: domainRes.rows.map(d => ({ domain: d.domain, count: parseInt(d.count) })),
sources: [],
no_source_count: 0,
release_state_counts: { active: parseInt(r.total) },
verification_method_counts: {},
category_counts: {},
evidence_type_counts: {},
})
}
async function handleDetail(params: URLSearchParams) {
const id = params.get('id') || ''
const res = await pool.query(`
SELECT mc.id, mc.master_control_id as control_id, mc.canonical_name as title,
'Master Control mit ' || mc.total_controls || ' Atomic Controls' as objective,
mc.total_controls, mc.phases_covered, mc.phase_control_count, mc.created_at
FROM compliance.master_controls mc
WHERE mc.master_control_id = $1 OR mc.id::text = $1
`, [id])
if (res.rows.length === 0) {
return NextResponse.json({ error: 'not found' }, { status: 404 })
}
const mc = res.rows[0]
// Load members
const membersRes = await pool.query(`
SELECT cc.control_id, cc.title, cc.severity, mcm.phase, mcm.action
FROM compliance.master_control_members mcm
JOIN compliance.canonical_controls cc ON cc.id = mcm.control_uuid
WHERE mcm.master_control_uuid = $1
ORDER BY mcm.phase, cc.control_id
LIMIT 100
`, [mc.id])
return NextResponse.json({
id: mc.id,
control_id: mc.control_id,
title: mc.title,
objective: mc.objective,
severity: mc.total_controls > 100 ? 'high' : mc.total_controls > 20 ? 'medium' : 'low',
category: 'master_control',
release_state: 'active',
total_controls: mc.total_controls,
phases_covered: mc.phases_covered,
phase_control_count: mc.phase_control_count,
members: membersRes.rows,
requirements: membersRes.rows.map((m: { control_id: string; title: string; phase: string }) =>
`[${m.phase}] ${m.control_id}: ${m.title}`
),
test_procedure: [],
evidence: [],
open_anchors: [],
target_audience: [],
source_citation: null,
scope: { platforms: [], components: [], data_classes: [] },
risk_score: null,
implementation_effort: null,
created_at: mc.created_at,
})
}
@@ -1,52 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const DEFAULT_USER_ID = '00000000-0000-0000-0000-000000000001'
function buildUrl(request: NextRequest, params: { path?: string[] }) {
const subPath = params.path?.join('/') || ''
const { searchParams } = new URL(request.url)
const qs = searchParams.toString()
return `${SDK_URL}/sdk/v1/maximizer/${subPath}${qs ? `?${qs}` : ''}`
}
function forwardHeaders(request: NextRequest): Record<string, string> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
headers['X-Tenant-ID'] = request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID
headers['X-User-ID'] = request.headers.get('X-User-ID') || DEFAULT_USER_ID
return headers
}
async function proxy(request: NextRequest, params: { path?: string[] }, method: string) {
try {
const url = buildUrl(request, params)
const init: RequestInit = { method, headers: forwardHeaders(request) }
if (method !== 'GET' && method !== 'DELETE') {
init.body = await request.text()
}
const response = await fetch(url, init)
if (!response.ok) {
const errorText = await response.text()
return NextResponse.json({ error: 'Maximizer backend error', details: errorText }, { status: response.status })
}
if (response.status === 204) return new NextResponse(null, { status: 204 })
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('Maximizer proxy error:', error)
return NextResponse.json({ error: 'Failed to connect to Maximizer backend' }, { status: 503 })
}
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxy(request, await params, 'GET')
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxy(request, await params, 'POST')
}
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
return proxy(request, await params, 'DELETE')
}
@@ -1,48 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const endpoint = searchParams.get('endpoint') || 'controls'
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
let path: string
switch (endpoint) {
case 'controls':
const domain = searchParams.get('domain') || ''
path = `/sdk/v1/payment-compliance/controls${domain ? `?domain=${domain}` : ''}`
break
case 'assessments':
path = '/sdk/v1/payment-compliance/assessments'
break
default:
path = '/sdk/v1/payment-compliance/controls'
}
const resp = await fetch(`${SDK_URL}${path}`, {
headers: { 'X-Tenant-ID': tenantId },
})
const data = await resp.json()
return NextResponse.json(data)
} catch (err) {
return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const body = await request.json()
const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/assessments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Tenant-ID': tenantId },
body: JSON.stringify(body),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (err) {
return NextResponse.json({ error: 'Failed to create' }, { status: 500 })
}
}
@@ -1,28 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/tender/${id}`)
return NextResponse.json(await resp.json())
} catch {
return NextResponse.json({ error: 'Failed' }, { status: 500 })
}
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const { searchParams } = new URL(request.url)
const action = searchParams.get('action') || 'extract'
const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/tender/${id}/${action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
return NextResponse.json(await resp.json(), { status: resp.status })
} catch {
return NextResponse.json({ error: 'Failed' }, { status: 500 })
}
}
@@ -1,30 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export async function GET(request: NextRequest) {
try {
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/tender`, {
headers: { 'X-Tenant-ID': tenantId },
})
return NextResponse.json(await resp.json())
} catch {
return NextResponse.json({ error: 'Failed' }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const formData = await request.formData()
const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/tender/upload`, {
method: 'POST',
headers: { 'X-Tenant-ID': tenantId },
body: formData,
})
return NextResponse.json(await resp.json(), { status: resp.status })
} catch {
return NextResponse.json({ error: 'Upload failed' }, { status: 500 })
}
}
@@ -1,27 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ derived_id: string }> }
) {
const { derived_id } = await params
try {
const resp = await fetch(
`${BACKEND_URL}/api/v1/quaidal/controls/${encodeURIComponent(derived_id)}`,
{ headers: { 'X-Tenant-ID': tenantHeader(request) }, cache: 'no-store' }
)
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,25 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const qs = searchParams.toString()
try {
const resp = await fetch(
`${BACKEND_URL}/api/v1/quaidal/controls${qs ? `?${qs}` : ''}`,
{ headers: { 'X-Tenant-ID': tenantHeader(request) }, cache: 'no-store' }
)
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,27 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ section_id: string }> }
) {
const { section_id } = await params
try {
const resp = await fetch(
`${BACKEND_URL}/api/v1/quaidal/criteria/${encodeURIComponent(section_id)}`,
{ headers: { 'X-Tenant-ID': tenantHeader(request) }, cache: 'no-store' }
)
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest) {
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/quaidal/criteria`, {
headers: { 'X-Tenant-ID': tenantHeader(request) },
cache: 'no-store',
})
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,23 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
function tenantHeader(request: NextRequest): string {
return request.headers.get('x-tenant-id') || '00000000-0000-0000-0000-000000000001'
}
export async function GET(request: NextRequest) {
try {
const resp = await fetch(`${BACKEND_URL}/api/v1/quaidal/stats`, {
headers: { 'X-Tenant-ID': tenantHeader(request) },
cache: 'no-store',
})
const body = await resp.text()
return new NextResponse(body, {
status: resp.status,
headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
})
} catch (err) {
return NextResponse.json({ error: 'Backend unreachable', details: String(err) }, { status: 502 })
}
}
@@ -1,26 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const qs = searchParams.toString()
const url = `${SDK_URL}/sdk/v1/regulatory-news${qs ? `?${qs}` : ''}`
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
},
})
if (!response.ok) {
return NextResponse.json({ error: 'SDK error' }, { status: response.status })
}
return NextResponse.json(await response.json())
} catch {
return NextResponse.json({ error: 'Connection failed' }, { status: 503 })
}
}
@@ -92,17 +92,11 @@ class PostgreSQLStateStore implements StateStore {
private pool: Pool
constructor(connectionString: string) {
// Strip sslmode from URL — pg driver overrides our ssl config if it's in the URL.
// We handle SSL ourselves via the ssl option below.
const cleanUrl = connectionString.replace(/[?&]sslmode=[^&]*/g, '').replace(/\?$/, '')
const needsSsl = connectionString.includes('sslmode=require') || connectionString.includes('sslmode=verify')
this.pool = new Pool({
connectionString: cleanUrl,
connectionString,
max: 5,
// Set search_path for compliance schema
options: '-c search_path=compliance,core,public',
// Accept self-signed certificates (Hetzner PostgreSQL)
ssl: needsSsl ? { rejectUnauthorized: false } : false,
})
}
@@ -1,41 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
/**
* Proxy: POST /api/sdk/v1/ucca/assess-enriched → Go Backend POST /sdk/v1/ucca/assess-enriched
* Accepts { intake, company_profile? } and returns enriched assessment with obligations + hints.
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const response = await fetch(`${SDK_URL}/sdk/v1/ucca/assess-enriched`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
},
body: JSON.stringify(body),
})
if (!response.ok) {
const errorText = await response.text()
console.error('UCCA assess-enriched error:', errorText)
return NextResponse.json(
{ error: 'UCCA backend error', details: errorText },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data, { status: 201 })
} catch (error) {
console.error('Failed to call UCCA assess-enriched:', error)
return NextResponse.json(
{ error: 'Failed to connect to UCCA backend' },
{ status: 503 }
)
}
}
@@ -1,7 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
/**
* Proxy: GET /api/sdk/v1/ucca/assessments/[id] → Go Backend GET /sdk/v1/ucca/assessments/:id
@@ -17,7 +16,9 @@ export async function GET(
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
...(request.headers.get('X-Tenant-ID') && {
'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
}),
},
})
@@ -55,7 +56,9 @@ export async function PUT(
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
...(request.headers.get('X-Tenant-ID') && {
'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
}),
},
body: JSON.stringify(body),
})
@@ -93,7 +96,9 @@ export async function DELETE(
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
...(request.headers.get('X-Tenant-ID') && {
'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
}),
},
})
@@ -1,7 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
/**
* Proxy: GET /api/sdk/v1/ucca/assessments → Go Backend GET /sdk/v1/ucca/assessments
@@ -23,7 +22,9 @@ export async function GET(request: NextRequest) {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
...(request.headers.get('X-Tenant-ID') && {
'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
}),
},
})
@@ -1,57 +0,0 @@
import { NextRequest, NextResponse } from 'next/server'
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
const DEFAULT_TENANT = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
/**
* Proxy: /api/sdk/v1/ucca/decision-tree/... → Go Backend /sdk/v1/ucca/decision-tree/...
*/
async function proxyRequest(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
const { path } = await params
const subPath = path ? path.join('/') : ''
const search = request.nextUrl.search || ''
const targetUrl = `${SDK_URL}/sdk/v1/ucca/decision-tree/${subPath}${search}`
const tenantID = request.headers.get('X-Tenant-ID') || DEFAULT_TENANT
try {
const headers: Record<string, string> = {
'X-Tenant-ID': tenantID,
}
const fetchOptions: RequestInit = {
method: request.method,
headers,
}
if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
const body = await request.json()
headers['Content-Type'] = 'application/json'
fetchOptions.body = JSON.stringify(body)
}
const response = await fetch(targetUrl, fetchOptions)
if (!response.ok) {
const errorText = await response.text()
console.error(`Decision tree proxy error [${request.method} ${subPath}]:`, errorText)
return NextResponse.json(
{ error: 'Backend error', details: errorText },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data, { status: response.status })
} catch (error) {
console.error('Decision tree proxy connection error:', error)
return NextResponse.json(
{ error: 'Failed to connect to AI compliance backend' },
{ status: 503 }
)
}
}
export const GET = proxyRequest
export const POST = proxyRequest
export const DELETE = proxyRequest
@@ -1,58 +0,0 @@
/**
* Next.js Proxy: leitet POST /api/v1/founding-wizard/generate an Backend.
*
* Konvertiert das Backend-Response (base64 DOCX) in data: URLs,
* die das Frontend direkt als Download anbieten kann.
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_COMPLIANCE_URL || 'http://bp-compliance-backend:8002'
export async function POST(req: NextRequest) {
try {
const body = await req.json()
const backendRes = await fetch(`${BACKEND_URL}/v1/founding-wizard/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!backendRes.ok) {
const errorText = await backendRes.text()
return NextResponse.json(
{ error: 'Backend-Generierung fehlgeschlagen', detail: errorText },
{ status: backendRes.status }
)
}
const data = await backendRes.json()
const documents = (data.documents || []).map((doc: {
document_type: string
title: string
filename: string
content_base64: string
size_bytes: number
generated_at: string
}) => ({
document_type: doc.document_type,
title: doc.title,
filename: doc.filename,
download_url: `data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,${doc.content_base64}`,
size_bytes: doc.size_bytes,
generated_at: doc.generated_at,
}))
return NextResponse.json({
documents,
warnings: data.warnings || [],
})
} catch (e: unknown) {
const message = e instanceof Error ? e.message : 'Unbekannter Fehler'
return NextResponse.json(
{ error: 'Proxy-Fehler', detail: message },
{ status: 500 }
)
}
}
@@ -1,53 +0,0 @@
/**
* Vendor Assessment Status/Detail Proxy
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.COMPLIANCE_BACKEND_URL || 'http://backend-compliance:8002'
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params
try {
const resp = await fetch(
`${BACKEND_URL}/api/vendor-compliance/assessments/${id}`,
{ signal: AbortSignal.timeout(10000) },
)
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (error) {
console.error('Assessment status proxy error:', error)
return NextResponse.json(
{ error: 'Backend nicht erreichbar' },
{ status: 503 },
)
}
}
export async function POST(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params
try {
const resp = await fetch(
`${BACKEND_URL}/api/vendor-compliance/assessments/${id}/approve`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(10000),
},
)
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (error) {
console.error('Assessment approve proxy error:', error)
return NextResponse.json(
{ error: 'Backend nicht erreichbar' },
{ status: 503 },
)
}
}
@@ -1,41 +0,0 @@
/**
* Vendor Assessment API Proxy
* Proxies to backend-compliance (Python FastAPI)
*/
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.COMPLIANCE_BACKEND_URL || 'http://backend-compliance:8002'
export async function POST(request: NextRequest) {
try {
const body = await request.text()
const resp = await fetch(`${BACKEND_URL}/api/vendor-compliance/assessments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: AbortSignal.timeout(10000),
})
const data = await resp.json()
return NextResponse.json(data, { status: resp.status })
} catch (error) {
console.error('Vendor assessment proxy error:', error)
return NextResponse.json(
{ error: 'Backend nicht erreichbar' },
{ status: 503 },
)
}
}
export async function GET() {
try {
const resp = await fetch(`${BACKEND_URL}/api/vendor-compliance/assessments`, {
signal: AbortSignal.timeout(10000),
})
const data = await resp.json()
return NextResponse.json(data)
} catch (error) {
console.error('Vendor assessment list proxy error:', error)
return NextResponse.json({ assessments: [] })
}
}
@@ -1,92 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { COMPANY_PROFILE_PRESETS, type CompanyProfilePreset } from '@/lib/sdk/company-profile-presets'
import { DOC_LABELS, CATEGORY_COLORS } from './doc-labels'
export function PresetSection({ projectId }: { projectId?: string }) {
const [selectedPreset, setSelectedPreset] = useState<CompanyProfilePreset | null>(null)
// Group recommended docs by category
const groupedDocs = selectedPreset
? selectedPreset.recommendedDocs.reduce<Record<string, string[]>>((acc, docType) => {
const info = DOC_LABELS[docType]
if (!info) return acc
if (!acc[info.category]) acc[info.category] = []
acc[info.category].push(info.label)
return acc
}, {})
: null
return (
<div className="bg-gradient-to-br from-purple-50 to-white rounded-xl border border-purple-200 p-6 space-y-4">
<div>
<h2 className="text-lg font-bold text-gray-900">Schnellstart: Welcher Unternehmenstyp sind Sie?</h2>
<p className="text-sm text-gray-500 mt-1">
Waehlen Sie Ihre Branche wir zeigen Ihnen welche Dokumente Sie benoetigen.
</p>
</div>
{/* Preset Cards */}
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
{COMPANY_PROFILE_PRESETS.map((preset) => (
<button
key={preset.id}
onClick={() => setSelectedPreset(selectedPreset?.id === preset.id ? null : preset)}
className={`flex flex-col items-center gap-2 p-3 rounded-xl transition-all text-center ${
selectedPreset?.id === preset.id
? 'bg-purple-100 border-2 border-purple-500 shadow-md'
: 'bg-white border border-gray-200 hover:border-purple-300 hover:shadow-sm'
}`}
>
<span className="text-2xl">{preset.icon}</span>
<span className={`text-xs font-medium ${selectedPreset?.id === preset.id ? 'text-purple-700' : 'text-gray-900'}`}>
{preset.label}
</span>
<span className="text-[10px] text-gray-400 leading-tight">{preset.description}</span>
</button>
))}
</div>
{/* Document Preview — shown when a preset is selected */}
{selectedPreset && groupedDocs && (
<div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
<div className="flex items-center justify-between">
<div>
<h3 className="font-semibold text-gray-900">
{selectedPreset.icon} {selectedPreset.label} Ihre Dokumente
</h3>
<p className="text-xs text-gray-500 mt-0.5">
{selectedPreset.recommendedDocs.length} Dokumente werden fuer Sie vorbereitet
</p>
</div>
<Link
href={projectId
? `/sdk/company-profile?project=${projectId}&preset=${selectedPreset.id}`
: `/sdk/company-profile?preset=${selectedPreset.id}`}
className="px-4 py-2 bg-purple-600 text-white text-sm font-medium rounded-lg hover:bg-purple-700 transition-colors"
>
Jetzt starten
</Link>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{Object.entries(groupedDocs).map(([category, docs]) => (
<div key={category} className="space-y-1.5">
<span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-medium ${CATEGORY_COLORS[category] || 'bg-gray-100 text-gray-600'}`}>
{category}
</span>
{docs.map((doc) => (
<div key={doc} className="text-xs text-gray-700 pl-1">
{doc}
</div>
))}
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -1,131 +0,0 @@
/**
* Complete mapping of all document template types to display labels and categories.
* Used by PresetSection to show categorized document previews.
*/
export const DOC_LABELS: Record<string, { label: string; category: string }> = {
// ── Website ──────────────────────────────────────────────────────
privacy_policy: { label: 'Datenschutzerklaerung', category: 'Website' },
impressum: { label: 'Impressum', category: 'Website' },
cookie_policy: { label: 'Cookie-Richtlinie', category: 'Website' },
cookie_banner: { label: 'Cookie-Banner-Texte', category: 'Website' },
// ── Vertraege ────────────────────────────────────────────────────
agb: { label: 'AGB', category: 'Vertraege' },
dpa: { label: 'AVV (Auftragsverarbeitung)', category: 'Vertraege' },
nda: { label: 'Geheimhaltungsvereinbarung', category: 'Vertraege' },
sla: { label: 'Service Level Agreement', category: 'Vertraege' },
terms_of_use: { label: 'Nutzungsbedingungen', category: 'Vertraege' },
cloud_service_agreement: { label: 'Cloud-Vertrag', category: 'Vertraege' },
data_usage_clause: { label: 'Datennutzungsklausel', category: 'Vertraege' },
// ── Plattform ────────────────────────────────────────────────────
community_guidelines: { label: 'Community Guidelines', category: 'Plattform' },
acceptable_use: { label: 'Acceptable Use Policy', category: 'Plattform' },
media_content_policy: { label: 'Medien-Richtlinie', category: 'Plattform' },
copyright_policy: { label: 'Urheberrechtsrichtlinie', category: 'Plattform' },
// ── E-Commerce ───────────────────────────────────────────────────
widerruf: { label: 'Widerrufsbelehrung', category: 'E-Commerce' },
// ── HR / Personal ────────────────────────────────────────────────
employee_dsi: { label: 'Mitarbeiter-DSI', category: 'HR' },
applicant_dsi: { label: 'Bewerber-DSI', category: 'HR' },
whistleblower_policy: { label: 'Whistleblower-Richtlinie', category: 'HR' },
employee_security_policy: { label: 'Mitarbeiter-Sicherheitsrichtlinie', category: 'HR' },
security_awareness_policy: { label: 'Security-Awareness-Richtlinie', category: 'HR' },
remote_work_policy: { label: 'Remote-Work-Richtlinie', category: 'HR' },
offboarding_policy: { label: 'Offboarding-Richtlinie', category: 'HR' },
// ── Datenschutz (DSGVO) ──────────────────────────────────────────
tom_documentation: { label: 'TOM-Dokumentation', category: 'Datenschutz' },
vvt_register: { label: 'Verarbeitungsverzeichnis', category: 'Datenschutz' },
loeschkonzept: { label: 'Loeschkonzept', category: 'Datenschutz' },
dsfa: { label: 'Datenschutz-Folgenabschaetzung', category: 'Datenschutz' },
pflichtenregister: { label: 'Pflichtenregister', category: 'Datenschutz' },
data_protection_concept: { label: 'Datenschutzkonzept', category: 'Datenschutz' },
consent_texts: { label: 'Einwilligungstexte', category: 'Datenschutz' },
informationspflichten: { label: 'Informationspflichten', category: 'Datenschutz' },
verpflichtungserklaerung: { label: 'Verpflichtungserklaerung', category: 'Datenschutz' },
social_media_dsi: { label: 'Social-Media-DSI', category: 'Datenschutz' },
video_conference_dsi: { label: 'Videokonferenz-DSI', category: 'Datenschutz' },
// ── Daten-Policies ───────────────────────────────────────────────
data_protection_policy: { label: 'Datenschutzrichtlinie', category: 'Daten-Governance' },
data_classification_policy: { label: 'Datenklassifizierung', category: 'Daten-Governance' },
data_retention_policy: { label: 'Aufbewahrungsrichtlinie', category: 'Daten-Governance' },
data_transfer_policy: { label: 'Datentransfer-Richtlinie', category: 'Daten-Governance' },
privacy_incident_policy: { label: 'Datenschutzvorfall-Richtlinie', category: 'Daten-Governance' },
// ── Betroffenenrechte ────────────────────────────────────────────
dsr_process_art15: { label: 'Auskunftsrecht (Art. 15)', category: 'Betroffenenrechte' },
dsr_process_art16: { label: 'Berichtigungsrecht (Art. 16)', category: 'Betroffenenrechte' },
dsr_process_art17: { label: 'Loeschungsrecht (Art. 17)', category: 'Betroffenenrechte' },
dsr_process_art18: { label: 'Einschraenkungsrecht (Art. 18)', category: 'Betroffenenrechte' },
dsr_process_art19: { label: 'Mitteilungspflicht (Art. 19)', category: 'Betroffenenrechte' },
dsr_process_art20: { label: 'Datenportabilitaet (Art. 20)', category: 'Betroffenenrechte' },
dsr_process_art21: { label: 'Widerspruchsrecht (Art. 21)', category: 'Betroffenenrechte' },
// ── IT-Sicherheit (Konzepte) ─────────────────────────────────────
it_security_concept: { label: 'IT-Sicherheitskonzept', category: 'IT-Sicherheit' },
backup_recovery_concept: { label: 'Backup- & Recovery-Konzept', category: 'IT-Sicherheit' },
logging_concept: { label: 'Logging-Konzept', category: 'IT-Sicherheit' },
incident_response_plan: { label: 'Incident-Response-Plan', category: 'IT-Sicherheit' },
access_control_concept: { label: 'Zugriffskonzept', category: 'IT-Sicherheit' },
risk_management_concept: { label: 'Risikomanagement-Konzept', category: 'IT-Sicherheit' },
isms_manual: { label: 'ISMS-Handbuch', category: 'IT-Sicherheit' },
// ── IT-Sicherheit (Policies) ─────────────────────────────────────
information_security_policy: { label: 'Informationssicherheitsrichtlinie', category: 'IT-Policies' },
access_control_policy: { label: 'Zugriffskontrollrichtlinie', category: 'IT-Policies' },
password_policy: { label: 'Passwortrichtlinie', category: 'IT-Policies' },
encryption_policy: { label: 'Verschluesselungsrichtlinie', category: 'IT-Policies' },
logging_policy: { label: 'Protokollierungsrichtlinie', category: 'IT-Policies' },
backup_policy: { label: 'Datensicherungsrichtlinie', category: 'IT-Policies' },
incident_response_policy: { label: 'Incident-Response-Richtlinie', category: 'IT-Policies' },
change_management_policy: { label: 'Change-Management-Richtlinie', category: 'IT-Policies' },
patch_management_policy: { label: 'Patch-Management-Richtlinie', category: 'IT-Policies' },
asset_management_policy: { label: 'Asset-Management-Richtlinie', category: 'IT-Policies' },
cloud_security_policy: { label: 'Cloud-Security-Richtlinie', category: 'IT-Policies' },
devsecops_policy: { label: 'DevSecOps-Richtlinie', category: 'IT-Policies' },
secrets_management_policy: { label: 'Secrets-Management-Richtlinie', category: 'IT-Policies' },
vulnerability_management_policy: { label: 'Schwachstellenmanagement', category: 'IT-Policies' },
// ── Lieferanten / Drittanbieter ──────────────────────────────────
vendor_risk_management_policy: { label: 'Lieferanten-Risikomanagement', category: 'Lieferanten' },
third_party_security_policy: { label: 'Drittanbieter-Sicherheit', category: 'Lieferanten' },
supplier_security_policy: { label: 'Lieferanten-Anforderungen', category: 'Lieferanten' },
transfer_impact_assessment: { label: 'Transfer Impact Assessment', category: 'Lieferanten' },
scc_companion: { label: 'SCC-Begleitdokument', category: 'Lieferanten' },
// ── BCM / Notfall ────────────────────────────────────────────────
business_continuity_policy: { label: 'Business-Continuity', category: 'BCM' },
disaster_recovery_policy: { label: 'Disaster-Recovery', category: 'BCM' },
crisis_management_policy: { label: 'Krisenmanagement', category: 'BCM' },
// ── KI / Cyber ───────────────────────────────────────────────────
ai_usage_policy: { label: 'KI-Nutzungsrichtlinie', category: 'KI & Cyber' },
cybersecurity_policy: { label: 'Cybersecurity-Richtlinie (CRA)', category: 'KI & Cyber' },
byod_policy: { label: 'BYOD-Richtlinie', category: 'KI & Cyber' },
// ── SOP ──────────────────────────────────────────────────────────
standard_operating_procedure: { label: 'Standard Operating Procedure', category: 'Prozesse' },
}
export const CATEGORY_COLORS: Record<string, string> = {
Website: 'bg-blue-50 text-blue-700',
Vertraege: 'bg-purple-50 text-purple-700',
Plattform: 'bg-indigo-50 text-indigo-700',
'E-Commerce': 'bg-green-50 text-green-700',
HR: 'bg-amber-50 text-amber-700',
Datenschutz: 'bg-red-50 text-red-700',
'Daten-Governance': 'bg-rose-50 text-rose-700',
Betroffenenrechte: 'bg-fuchsia-50 text-fuchsia-700',
'IT-Sicherheit': 'bg-gray-100 text-gray-700',
'IT-Policies': 'bg-slate-100 text-slate-700',
Lieferanten: 'bg-orange-50 text-orange-700',
BCM: 'bg-yellow-50 text-yellow-700',
'KI & Cyber': 'bg-cyan-50 text-cyan-700',
Marketing: 'bg-pink-50 text-pink-700',
Prozesse: 'bg-teal-50 text-teal-700',
}
@@ -2,7 +2,6 @@
import React from 'react'
import { AssessmentResultCard } from '@/components/sdk/use-case-assessment/AssessmentResultCard'
import { OptimizerUpsellCard } from '@/components/sdk/compliance-optimizer/OptimizerUpsellCard'
interface Props {
result: unknown
@@ -36,13 +35,6 @@ export function ResultView({ result, onGoToAssessment, onGoToOverview }: Props)
{r.result && (
<AssessmentResultCard result={r.result as unknown as Parameters<typeof AssessmentResultCard>[0]['result']} />
)}
{r.result && r.assessment?.id && (
<OptimizerUpsellCard
feasibility={(r.result as { feasibility?: string }).feasibility || 'YES'}
assessmentId={r.assessment.id}
riskScore={(r.result as { risk_score?: number }).risk_score}
/>
)}
</div>
)
}
@@ -7,116 +7,6 @@ export interface AdvisoryForm {
custom_data_types: string[]
purposes: string[]
automation: string
// BetrVG / works council
employee_monitoring: boolean
hr_decision_support: boolean
works_council_consulted: boolean
// Domain-specific contexts (Annex III)
hr_automated_screening: boolean
hr_automated_rejection: boolean
hr_candidate_ranking: boolean
hr_bias_audits: boolean
hr_agg_visible: boolean
hr_human_review: boolean
hr_performance_eval: boolean
edu_grade_influence: boolean
edu_exam_evaluation: boolean
edu_student_selection: boolean
edu_minors: boolean
edu_teacher_review: boolean
hc_diagnosis: boolean
hc_treatment: boolean
hc_triage: boolean
hc_patient_data: boolean
hc_medical_device: boolean
hc_clinical_validation: boolean
// Legal
leg_legal_advice: boolean
leg_court_prediction: boolean
leg_client_confidential: boolean
// Public Sector
pub_admin_decision: boolean
pub_benefit_allocation: boolean
pub_transparency: boolean
// Critical Infrastructure
crit_grid_control: boolean
crit_safety_critical: boolean
crit_redundancy: boolean
// Automotive
auto_autonomous: boolean
auto_safety: boolean
auto_functional_safety: boolean
// Retail
ret_pricing: boolean
ret_profiling: boolean
ret_credit_scoring: boolean
ret_dark_patterns: boolean
// IT Security
its_surveillance: boolean
its_threat_detection: boolean
its_data_retention: boolean
// Logistics
log_driver_tracking: boolean
log_workload_scoring: boolean
// Construction
con_tenant_screening: boolean
con_worker_safety: boolean
// Marketing
mkt_deepfake: boolean
mkt_minors: boolean
mkt_targeting: boolean
mkt_labeled: boolean
// Manufacturing
mfg_machine_safety: boolean
mfg_ce_required: boolean
mfg_validated: boolean
// Agriculture
agr_pesticide: boolean
agr_animal_welfare: boolean
agr_environmental: boolean
// Social Services
soc_vulnerable: boolean
soc_benefit: boolean
soc_case_mgmt: boolean
// Hospitality
hos_guest_profiling: boolean
hos_dynamic_pricing: boolean
hos_review_manipulation: boolean
// Insurance
ins_risk_class: boolean
ins_claims: boolean
ins_premium: boolean
ins_fraud: boolean
// Investment
inv_algo_trading: boolean
inv_advice: boolean
inv_robo: boolean
// Defense
def_dual_use: boolean
def_export: boolean
def_classified: boolean
// Supply Chain
sch_supplier: boolean
sch_human_rights: boolean
sch_environmental: boolean
// Facility
fac_access: boolean
fac_occupancy: boolean
fac_energy: boolean
// Sports
spo_athlete: boolean
spo_fan: boolean
spo_doping: boolean
// Finance / Banking
fin_credit_scoring: boolean
fin_aml_kyc: boolean
fin_algo_decisions: boolean
fin_customer_profiling: boolean
// General
gen_affects_people: boolean
gen_automated_decisions: boolean
gen_sensitive_data: boolean
// Hosting
hosting_provider: string
hosting_region: string
model_usage: string[]
@@ -51,71 +51,6 @@ function AdvisoryBoardPageInner() {
custom_data_types: [],
purposes: [],
automation: '',
// BetrVG / works council
employee_monitoring: false,
hr_decision_support: false,
works_council_consulted: false,
// Domain-specific contexts (Annex III)
hr_automated_screening: false,
hr_automated_rejection: false,
hr_candidate_ranking: false,
hr_bias_audits: false,
hr_agg_visible: false,
hr_human_review: false,
hr_performance_eval: false,
edu_grade_influence: false,
edu_exam_evaluation: false,
edu_student_selection: false,
edu_minors: false,
edu_teacher_review: false,
hc_diagnosis: false,
hc_treatment: false,
hc_triage: false,
hc_patient_data: false,
hc_medical_device: false,
hc_clinical_validation: false,
// Legal
leg_legal_advice: false, leg_court_prediction: false, leg_client_confidential: false,
// Public Sector
pub_admin_decision: false, pub_benefit_allocation: false, pub_transparency: false,
// Critical Infrastructure
crit_grid_control: false, crit_safety_critical: false, crit_redundancy: false,
// Automotive
auto_autonomous: false, auto_safety: false, auto_functional_safety: false,
// Retail
ret_pricing: false, ret_profiling: false, ret_credit_scoring: false, ret_dark_patterns: false,
// IT Security
its_surveillance: false, its_threat_detection: false, its_data_retention: false,
// Logistics
log_driver_tracking: false, log_workload_scoring: false,
// Construction
con_tenant_screening: false, con_worker_safety: false,
// Marketing
mkt_deepfake: false, mkt_minors: false, mkt_targeting: false, mkt_labeled: false,
// Manufacturing
mfg_machine_safety: false, mfg_ce_required: false, mfg_validated: false,
// Agriculture
agr_pesticide: false, agr_animal_welfare: false, agr_environmental: false,
// Social Services
soc_vulnerable: false, soc_benefit: false, soc_case_mgmt: false,
// Hospitality
hos_guest_profiling: false, hos_dynamic_pricing: false, hos_review_manipulation: false,
// Insurance
ins_risk_class: false, ins_claims: false, ins_premium: false, ins_fraud: false,
// Investment
inv_algo_trading: false, inv_advice: false, inv_robo: false,
// Defense
def_dual_use: false, def_export: false, def_classified: false,
// Supply Chain
sch_supplier: false, sch_human_rights: false, sch_environmental: false,
// Facility
fac_access: false, fac_occupancy: false, fac_energy: false,
// Sports
spo_athlete: false, spo_fan: false, spo_doping: false,
// Finance / Banking
fin_credit_scoring: false, fin_aml_kyc: false, fin_algo_decisions: false, fin_customer_profiling: false,
// General
gen_affects_people: false, gen_automated_decisions: false, gen_sensitive_data: false,
hosting_provider: '',
hosting_region: '',
model_usage: [],
@@ -198,164 +133,18 @@ function AdvisoryBoardPageInner() {
retention_purpose: form.retention_purpose,
contracts_list: form.contracts,
subprocessors: form.subprocessors,
employee_monitoring: form.employee_monitoring,
hr_decision_support: form.hr_decision_support,
works_council_consulted: form.works_council_consulted,
// Domain-specific contexts
hr_context: ['hr', 'recruiting'].includes(form.domain) ? {
automated_screening: form.hr_automated_screening,
automated_rejection: form.hr_automated_rejection,
candidate_ranking: form.hr_candidate_ranking,
bias_audits_done: form.hr_bias_audits,
agg_categories_visible: form.hr_agg_visible,
human_review_enforced: form.hr_human_review,
performance_evaluation: form.hr_performance_eval,
} : undefined,
education_context: ['education', 'higher_education', 'vocational_training', 'research'].includes(form.domain) ? {
grade_influence: form.edu_grade_influence,
exam_evaluation: form.edu_exam_evaluation,
student_selection: form.edu_student_selection,
minors_involved: form.edu_minors,
teacher_review_required: form.edu_teacher_review,
} : undefined,
healthcare_context: ['healthcare', 'medical_devices', 'pharma', 'elderly_care'].includes(form.domain) ? {
diagnosis_support: form.hc_diagnosis,
treatment_recommendation: form.hc_treatment,
triage_decision: form.hc_triage,
patient_data_processed: form.hc_patient_data,
medical_device: form.hc_medical_device,
clinical_validation: form.hc_clinical_validation,
} : undefined,
legal_context: ['legal', 'consulting', 'tax_advisory'].includes(form.domain) ? {
legal_advice: form.leg_legal_advice,
court_prediction: form.leg_court_prediction,
client_confidential: form.leg_client_confidential,
} : undefined,
public_sector_context: ['public_sector', 'defense', 'justice'].includes(form.domain) ? {
admin_decision: form.pub_admin_decision,
benefit_allocation: form.pub_benefit_allocation,
transparency_ensured: form.pub_transparency,
} : undefined,
critical_infra_context: ['energy', 'utilities', 'oil_gas'].includes(form.domain) ? {
grid_control: form.crit_grid_control,
safety_critical: form.crit_safety_critical,
redundancy_exists: form.crit_redundancy,
} : undefined,
automotive_context: ['automotive', 'aerospace'].includes(form.domain) ? {
autonomous_driving: form.auto_autonomous,
safety_relevant: form.auto_safety,
functional_safety: form.auto_functional_safety,
} : undefined,
retail_context: ['retail', 'ecommerce', 'wholesale'].includes(form.domain) ? {
pricing_personalized: form.ret_pricing,
credit_scoring: form.ret_credit_scoring,
dark_patterns: form.ret_dark_patterns,
} : undefined,
it_security_context: ['it_services', 'cybersecurity', 'telecom'].includes(form.domain) ? {
employee_surveillance: form.its_surveillance,
threat_detection: form.its_threat_detection,
data_retention_logs: form.its_data_retention,
} : undefined,
logistics_context: ['logistics'].includes(form.domain) ? {
driver_tracking: form.log_driver_tracking,
workload_scoring: form.log_workload_scoring,
} : undefined,
construction_context: ['construction', 'real_estate', 'facility_management'].includes(form.domain) ? {
tenant_screening: form.con_tenant_screening,
worker_safety: form.con_worker_safety,
} : undefined,
marketing_context: ['marketing', 'media', 'entertainment'].includes(form.domain) ? {
deepfake_content: form.mkt_deepfake,
behavioral_targeting: form.mkt_targeting,
minors_targeted: form.mkt_minors,
ai_content_labeled: form.mkt_labeled,
} : undefined,
manufacturing_context: ['mechanical_engineering', 'electrical_engineering', 'plant_engineering', 'chemicals', 'food_beverage'].includes(form.domain) ? {
machine_safety: form.mfg_machine_safety,
ce_marking_required: form.mfg_ce_required,
safety_validated: form.mfg_validated,
} : undefined,
agriculture_context: ['agriculture', 'forestry', 'fishing'].includes(form.domain) ? {
pesticide_ai: form.agr_pesticide,
animal_welfare: form.agr_animal_welfare,
environmental_data: form.agr_environmental,
} : undefined,
social_services_context: ['social_services', 'nonprofit'].includes(form.domain) ? {
vulnerable_groups: form.soc_vulnerable,
benefit_decision: form.soc_benefit,
case_management: form.soc_case_mgmt,
} : undefined,
hospitality_context: ['hospitality', 'tourism'].includes(form.domain) ? {
guest_profiling: form.hos_guest_profiling,
dynamic_pricing: form.hos_dynamic_pricing,
review_manipulation: form.hos_review_manipulation,
} : undefined,
insurance_context: ['insurance'].includes(form.domain) ? {
risk_classification: form.ins_risk_class,
claims_automation: form.ins_claims,
premium_calculation: form.ins_premium,
fraud_detection: form.ins_fraud,
} : undefined,
investment_context: ['investment'].includes(form.domain) ? {
algo_trading: form.inv_algo_trading,
investment_advice: form.inv_advice,
robo_advisor: form.inv_robo,
} : undefined,
defense_context: ['defense'].includes(form.domain) ? {
dual_use: form.def_dual_use,
export_controlled: form.def_export,
classified_data: form.def_classified,
} : undefined,
supply_chain_context: ['textiles', 'packaging'].includes(form.domain) ? {
supplier_monitoring: form.sch_supplier,
human_rights_check: form.sch_human_rights,
environmental_impact: form.sch_environmental,
} : undefined,
facility_context: ['facility_management'].includes(form.domain) ? {
access_control_ai: form.fac_access,
occupancy_tracking: form.fac_occupancy,
energy_optimization: form.fac_energy,
} : undefined,
sports_context: ['sports'].includes(form.domain) ? {
athlete_tracking: form.spo_athlete,
fan_profiling: form.spo_fan,
} : undefined,
store_raw_text: true,
// Finance/Banking and General don't need separate context structs —
// their fields are evaluated via existing FinancialContext or generic rules
}
const url = isEditMode
? `/api/sdk/v1/ucca/assessments/${editId}`
: '/api/sdk/v1/ucca/assess-enriched'
: '/api/sdk/v1/ucca/assess'
const method = isEditMode ? 'PUT' : 'POST'
// For new assessments, send enriched payload with company profile
const payload = isEditMode ? intake : {
intake,
company_profile: sdkState.companyProfile ? {
company_name: sdkState.companyProfile.companyName ?? '',
legal_form: sdkState.companyProfile.legalForm ?? '',
industry: Array.isArray(sdkState.companyProfile.industry)
? sdkState.companyProfile.industry.join(', ')
: (sdkState.companyProfile.industry ?? ''),
employee_count: sdkState.companyProfile.employeeCount ?? '',
annual_revenue: sdkState.companyProfile.annualRevenue ?? '',
headquarters_country: sdkState.companyProfile.headquartersCountry ?? 'DE',
is_data_controller: sdkState.companyProfile.isDataController ?? true,
is_data_processor: sdkState.companyProfile.isDataProcessor ?? false,
uses_ai: true,
dpo_name: sdkState.companyProfile.dpoName ?? null,
subject_to_nis2: false,
subject_to_ai_act: false,
subject_to_iso27001: false,
} : undefined,
}
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
body: JSON.stringify(intake),
})
if (!response.ok) {
@@ -1,57 +0,0 @@
'use client'
import React from 'react'
import type { AnalysisResult } from '../_hooks/useAgentAnalysis'
const DOC_TYPE_LABELS: Record<string, string> = {
privacy_policy: 'DSE',
cookie_banner: 'Cookie',
terms_of_service: 'AGB',
imprint: 'Impressum',
dpa: 'AVV',
other: 'Sonstig',
}
const RISK_DOT: Record<string, string> = {
low: 'bg-green-500',
medium: 'bg-yellow-500',
high: 'bg-orange-500',
critical: 'bg-red-500',
}
interface Props {
history: AnalysisResult[]
onSelect: (result: AnalysisResult) => void
}
export function AnalysisHistory({ history, onSelect }: Props) {
if (history.length === 0) return null
return (
<div>
<h3 className="text-sm font-medium text-gray-700 mb-3">Letzte Analysen</h3>
<div className="space-y-2">
{history.map((item, i) => (
<button
key={i}
onClick={() => onSelect(item)}
className="w-full text-left p-3 bg-white border border-gray-200 rounded-lg hover:border-purple-300 hover:bg-purple-50 transition-colors"
>
<div className="flex items-center gap-3">
<span className={`w-2.5 h-2.5 rounded-full ${RISK_DOT[item.risk_level] || 'bg-gray-400'}`} />
<span className="text-xs font-medium text-gray-500 w-16">
{DOC_TYPE_LABELS[item.classification] || item.classification}
</span>
<span className="text-sm text-gray-700 truncate flex-1">
{new URL(item.url).hostname}
</span>
<span className="text-xs text-gray-400">
{new Date(item.analyzed_at).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
</span>
</div>
</button>
))}
</div>
</div>
)
}
@@ -1,109 +0,0 @@
'use client'
import React from 'react'
import type { AnalysisResult as AnalysisResultType } from '../_hooks/useAgentAnalysis'
const RISK_COLORS: Record<string, { bg: string; text: string; label: string }> = {
low: { bg: 'bg-green-100', text: 'text-green-800', label: 'Niedrig' },
medium: { bg: 'bg-yellow-100', text: 'text-yellow-800', label: 'Mittel' },
high: { bg: 'bg-orange-100', text: 'text-orange-800', label: 'Hoch' },
critical: { bg: 'bg-red-100', text: 'text-red-800', label: 'Kritisch' },
unknown: { bg: 'bg-gray-100', text: 'text-gray-800', label: 'Unbekannt' },
}
const DOC_TYPE_LABELS: Record<string, string> = {
privacy_policy: 'Datenschutzerklaerung',
cookie_banner: 'Cookie-Banner',
terms_of_service: 'AGB',
imprint: 'Impressum',
dpa: 'Auftragsverarbeitung (AVV)',
other: 'Sonstiges',
}
interface Props {
result: AnalysisResultType
}
export function AnalysisResult({ result }: Props) {
const risk = RISK_COLORS[result.risk_level] || RISK_COLORS.unknown
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-gray-900">
{DOC_TYPE_LABELS[result.classification] || result.classification}
</h3>
<p className="text-sm text-gray-500 truncate max-w-md">{result.url}</p>
</div>
<span className={`px-3 py-1 rounded-full text-sm font-medium ${risk.bg} ${risk.text}`}>
{risk.label} ({result.risk_score}/100)
</span>
</div>
{/* Role Assignment */}
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
<div className="flex items-center gap-2">
<svg className="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<span className="text-sm font-medium text-purple-900">
Zugewiesen an: <strong>{result.responsible_role}</strong>
</span>
<span className="text-xs text-purple-600 ml-auto">
Eskalationsstufe {result.escalation_level}
</span>
</div>
</div>
{/* Summary */}
{result.summary && (
<div className="bg-gray-50 rounded-lg p-4">
<h4 className="text-sm font-medium text-gray-700 mb-2">Zusammenfassung</h4>
<p className="text-sm text-gray-600 whitespace-pre-wrap">{result.summary}</p>
</div>
)}
{/* Findings */}
{result.findings.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 mb-2">Findings ({result.findings.length})</h4>
<ul className="space-y-1">
{result.findings.map((f, i) => (
<li key={i} className="flex items-start gap-2 text-sm text-gray-600">
<span className="text-orange-500 mt-0.5">!</span>
{f}
</li>
))}
</ul>
</div>
)}
{/* Required Controls */}
{result.required_controls.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 mb-2">Erforderliche Massnahmen</h4>
<ul className="space-y-1">
{result.required_controls.map((c, i) => (
<li key={i} className="flex items-start gap-2 text-sm text-gray-600">
<span className="text-blue-500 mt-0.5">&#10003;</span>
{c}
</li>
))}
</ul>
</div>
)}
{/* Email Status */}
<div className="flex items-center gap-2 text-sm text-gray-500 pt-2 border-t">
<span className={result.email_status === 'sent' ? 'text-green-600' : 'text-yellow-600'}>
{result.email_status === 'sent' ? '&#9993; Email gesendet' : '&#9993; Email ausstehend'}
</span>
<span className="ml-auto text-xs">
{new Date(result.analyzed_at).toLocaleString('de-DE')}
</span>
</div>
</div>
)
}
@@ -1,73 +0,0 @@
'use client'
import React from 'react'
interface AuthCheck {
found: boolean
text: string
legal_ref: string
}
interface AuthData {
url: string
authenticated: boolean
login_error: string
checks: Record<string, AuthCheck>
findings_count: number
}
const CHECK_LABELS: Record<string, { label: string; icon: string }> = {
cancel_subscription: { label: 'Kuendigungsbutton (2 Klicks)', icon: '🚫' },
delete_account: { label: 'Konto loeschen', icon: '🗑️' },
export_data: { label: 'Daten exportieren', icon: '📥' },
consent_settings: { label: 'Einwilligungen widerrufen', icon: '⚙️' },
profile_visible: { label: 'Profildaten einsehen', icon: '👤' },
}
export function AuthTestResult({ data }: { data: AuthData }) {
if (!data.authenticated) {
return (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<p className="text-sm font-medium text-red-800">Login fehlgeschlagen</p>
<p className="text-xs text-red-600 mt-1">{data.login_error || 'Credentials oder Formular nicht erkannt'}</p>
</div>
)
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full bg-green-500" />
<span className="text-sm font-medium text-gray-900">Erfolgreich eingeloggt</span>
<span className={`ml-auto text-xs px-2 py-1 rounded font-medium ${data.findings_count > 0 ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'}`}>
{data.findings_count} fehlende Funktionen
</span>
</div>
<div className="space-y-2">
{Object.entries(data.checks).map(([key, check]) => {
const info = CHECK_LABELS[key] || { label: key, icon: '❓' }
return (
<div key={key} className={`flex items-center gap-3 p-3 rounded-lg border ${check.found ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
<span className="text-lg">{info.icon}</span>
<div className="flex-1">
<p className={`text-sm font-medium ${check.found ? 'text-green-800' : 'text-red-800'}`}>
{check.found ? '✓' : '✗'} {info.label}
</p>
{check.text && <p className="text-xs text-gray-500 mt-0.5">{check.text}</p>}
</div>
<span className="text-[10px] text-gray-400">{check.legal_ref}</span>
</div>
)
})}
</div>
{data.findings_count > 0 && (
<div className="bg-red-50 border-l-4 border-red-500 p-3 text-xs text-red-700">
<strong>{data.findings_count} Pflichtfunktion(en) fehlen.</strong> Der Nutzer kann seine Rechte
nach DSGVO nicht vollstaendig ausueben.
</div>
)}
</div>
)
}
@@ -1,374 +0,0 @@
'use client'
import React, { useState } from 'react'
import { ChecklistView } from './ChecklistView'
interface CheckItem {
id: string
label: string
passed: boolean
severity: string
matched_text: string
level?: number
parent?: string | null
skipped?: boolean
hint?: string
}
interface BannerResult {
banner_detected: boolean
banner_provider: string
banner_checks?: {
violations: { code: string; text: string; severity: string }[]
has_impressum_link?: boolean
has_dse_link?: boolean
}
structured_checks?: CheckItem[]
completeness_pct?: number
correctness_pct?: number
phases?: {
before_consent: { cookies: string[]; scripts: string[]; tracking_services: string[]; violations: any[] }
after_reject: { cookies: string[]; scripts: string[]; new_tracking: string[]; violations: any[] }
after_accept: { cookies: string[]; scripts: string[]; new_tracking: string[]; undocumented: string[] }
}
email_status?: string
}
const CATEGORIES = [
{ id: 'all', label: 'Alle Kategorien' },
{ id: 'necessary', label: 'Notwendig' },
{ id: 'statistics', label: 'Statistik' },
{ id: 'marketing', label: 'Marketing' },
{ id: 'functional', label: 'Funktional' },
{ id: 'preferences', label: 'Praeferenzen' },
]
export function BannerCheckTab() {
const [url, setUrl] = useState(() =>
typeof window !== 'undefined' ? localStorage.getItem('banner-check-url') || '' : ''
)
const [loading, setLoading] = useState(false)
const [progress, setProgress] = useState('')
const [error, setError] = useState<string | null>(null)
const [result, setResult] = useState<BannerResult | null>(() => {
if (typeof window === 'undefined') return null
try { const s = localStorage.getItem('banner-check-result'); return s ? JSON.parse(s) : null } catch { return null }
})
const [categories, setCategories] = useState<string[]>(['all'])
const [useAgent, setUseAgent] = useState(false)
const [mcResults, setMcResults] = useState<any>(null)
const [history, setHistory] = useState<{ url: string; date: string; provider: string; violations: number; pct: number; resultKey: string }[]>(() => {
if (typeof window === 'undefined') return []
try { return JSON.parse(localStorage.getItem('banner-check-history') || '[]') } catch { return [] }
})
// Persist URL
React.useEffect(() => { localStorage.setItem('banner-check-url', url) }, [url])
const toggleCategory = (id: string) => {
if (id === 'all') {
setCategories(['all'])
return
}
setCategories(prev => {
const without = prev.filter(c => c !== 'all' && c !== id)
const next = prev.includes(id) ? without : [...without, id]
return next.length === 0 ? ['all'] : next
})
}
const handleScan = async (e: React.FormEvent) => {
e.preventDefault()
if (!url.trim()) return
setLoading(true)
setError(null)
setResult(null)
setProgress('Cookie-Banner wird analysiert...')
const selectedCategories = categories.includes('all') ? [] : categories
try {
const res = await fetch('/api/sdk/v1/agent/banner-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url.trim(), categories: selectedCategories }),
})
if (!res.ok) throw new Error(`Fehler: ${res.status}`)
const data = await res.json()
setResult(data)
localStorage.setItem('banner-check-result', JSON.stringify(data))
// If agent mode: also run cookie doc-check with 381 MCs
if (useAgent) {
setProgress('KI-Agent prueft Cookie-Richtlinie (381 MCs)...')
try {
const mcRes = await fetch('/api/sdk/v1/agent/doc-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
entries: [{ doc_type: 'cookie', label: 'Cookie-Richtlinie', url: url.trim() }],
recipient: 'dsb@breakpilot.local',
use_agent: true,
}),
})
if (mcRes.ok) {
const { check_id } = await mcRes.json()
if (check_id) {
for (let i = 0; i < 60; i++) {
await new Promise(r => setTimeout(r, 3000))
const poll = await fetch(`/api/sdk/v1/agent/doc-check?check_id=${check_id}`)
if (!poll.ok) continue
const pd = await poll.json()
if (pd.progress) setProgress(`KI-Agent: ${pd.progress}`)
if (pd.status === 'completed' && pd.result) { setMcResults(pd.result); break }
if (pd.status === 'failed') break
}
}
}
} catch { /* agent check is optional */ }
}
// Add to history with persistent result
const violations = data.structured_checks?.filter((c: CheckItem) => !c.passed && !c.skipped).length || 0
const resultKey = `banner-check-result-${Date.now()}`
try { localStorage.setItem(resultKey, JSON.stringify(data)) } catch { /* quota */ }
const entry = {
url: url.trim(),
date: new Date().toISOString(),
provider: data.banner_provider || 'Unbekannt',
violations,
pct: data.completeness_pct ?? 0,
resultKey,
}
const updated = [entry, ...history].slice(0, 30)
setHistory(updated)
localStorage.setItem('banner-check-history', JSON.stringify(updated))
} catch (e) {
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
} finally {
setLoading(false)
setProgress('')
}
}
const loadFromHistory = (entry: { url: string; resultKey?: string }) => {
setUrl(entry.url)
if (entry.resultKey) {
try {
const saved = localStorage.getItem(entry.resultKey)
if (saved) { setResult(JSON.parse(saved)); return }
} catch {}
}
// Fallback: load last result
try {
const last = localStorage.getItem('banner-check-result')
if (last) setResult(JSON.parse(last))
} catch {}
}
const structuredChecks = result?.structured_checks || []
const hasStructured = structuredChecks.length > 0
const compPct = result?.completeness_pct ?? 0
const corrPct = result?.correctness_pct ?? 0
const checklistResults = hasStructured ? [{
label: `Cookie-Banner: ${result?.banner_provider || 'Unbekannt'}`,
url: url,
doc_type: 'banner',
word_count: 0,
completeness_pct: compPct,
correctness_pct: corrPct,
checks: structuredChecks,
findings_count: structuredChecks.filter(c => !c.passed && !c.skipped).length,
error: '',
}] : []
return (
<div className="space-y-4">
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h3 className="text-sm font-semibold text-blue-900">Cookie-Banner Compliance Check</h3>
<p className="text-xs text-blue-700 mt-1">
Playwright-basierter 3-Phasen-Test: Vor Interaktion, nach Ablehnen, nach Akzeptieren.
Prueft Dark Patterns, Pre-Consent-Cookies, Farbkontrast, Klick-Paritaet und 36 weitere Kriterien.
</p>
</div>
<div className="flex items-center gap-3">
<button type="button" onClick={() => setUseAgent(!useAgent)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
useAgent ? 'bg-emerald-100 border-emerald-300 text-emerald-800' : 'bg-gray-50 border-gray-200 text-gray-500 hover:bg-gray-100'
}`}>
<span className={`w-2 h-2 rounded-full ${useAgent ? 'bg-emerald-500' : 'bg-gray-300'}`} />
{useAgent ? 'KI-Agent aktiv (381 Cookie-MCs)' : 'KI-Agent aus'}
</button>
</div>
<form onSubmit={handleScan} className="space-y-3">
<div className="flex gap-3">
<input
type="url" value={url} onChange={e => setUrl(e.target.value)}
placeholder="https://www.example.com/"
className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
disabled={loading} required
/>
<button type="submit" disabled={loading || !url.trim()}
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors flex items-center gap-2 text-sm font-medium whitespace-nowrap">
{loading ? (
<><svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>Pruefe...</>
) : 'Banner pruefen'}
</button>
</div>
<div className="flex flex-wrap gap-2">
{CATEGORIES.map(cat => (
<label key={cat.id}
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer border transition-colors ${
categories.includes(cat.id)
? 'bg-purple-100 border-purple-300 text-purple-800'
: 'bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100'
}`}
>
<input type="checkbox" checked={categories.includes(cat.id)}
onChange={() => toggleCategory(cat.id)} className="sr-only" />
<span className={`w-3 h-3 rounded-sm border flex items-center justify-center ${
categories.includes(cat.id) ? 'bg-purple-600 border-purple-600' : 'border-gray-400'
}`}>
{categories.includes(cat.id) && (
<svg className="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 12 12">
<path d="M10 3L4.5 8.5 2 6" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
</span>
{cat.label}
</label>
))}
</div>
</form>
{progress && (
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4 text-sm text-purple-700 flex items-center gap-3">
<svg className="animate-spin w-5 h-5 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
{progress}
</div>
)}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700">{error}</div>
)}
{result && (
<div className="space-y-4">
{result.phases && (
<div className="bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden">
<div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
<div className="flex items-center gap-3">
<span className="text-2xl">{result.banner_detected ? '🛡️' : '⚠️'}</span>
<div>
<h3 className="text-sm font-semibold text-gray-900">
{result.banner_detected
? `Banner erkannt: ${result.banner_provider || 'Unbekannter Anbieter'}`
: 'Kein Cookie-Banner erkannt'}
</h3>
<p className="text-xs text-gray-500 mt-0.5">3-Phasen-Analyse: Cookies und Scripts vor/nach Interaktion</p>
</div>
</div>
</div>
<div className="px-6 py-3 grid grid-cols-3 gap-4">
<PhaseBox label="Vor Consent" icon="🔒"
cookies={result.phases.before_consent.cookies?.length ?? 0}
scripts={result.phases.before_consent.scripts?.length ?? 0}
violations={result.phases.before_consent.violations?.length ?? 0} />
<PhaseBox label="Nach Ablehnen" icon="🚫"
cookies={result.phases.after_reject.cookies?.length ?? 0}
scripts={result.phases.after_reject.scripts?.length ?? 0}
violations={result.phases.after_reject.violations?.length ?? 0} />
<PhaseBox label="Nach Akzeptieren" icon="&#x2705;"
cookies={result.phases.after_accept.cookies?.length ?? 0}
scripts={result.phases.after_accept.scripts?.length ?? 0}
violations={0} />
</div>
</div>
)}
{hasStructured && (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
<ChecklistView results={checklistResults} />
</div>
)}
{result.email_status && (
<div className="text-xs text-gray-500 flex items-center gap-2">
<span className={`w-2 h-2 rounded-full ${result.email_status === 'sent' ? 'bg-green-400' : 'bg-gray-300'}`} />
E-Mail: {result.email_status === 'sent' ? 'Gesendet' : result.email_status}
</div>
)}
{/* MC Agent Results (Cookie-Richtlinie) */}
{mcResults?.results && (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
<h4 className="text-sm font-semibold text-gray-800 mb-3">KI-Agent: Cookie-Richtlinie (381 MCs)</h4>
<ChecklistView results={mcResults.results} />
</div>
)}
{!result.banner_detected && !hasStructured && (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
<p className="text-sm text-gray-500">
Kein Cookie-Banner auf dieser Seite gefunden. Falls Cookies gesetzt werden, ist ein Banner nach §25 TDDDG Pflicht.
</p>
</div>
)}
</div>
)}
{/* History */}
{history.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Banner-Checks</h4>
<div className="space-y-1">
{history.map((h, i) => (
<button key={i} onClick={() => loadFromHistory(h)}
className="w-full flex items-center justify-between p-2.5 rounded-lg border border-gray-100 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left">
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-gray-900 truncate">{h.url}</div>
<div className="text-xs text-gray-500">
{new Date(h.date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
{' · '}{h.provider}
</div>
</div>
<div className="flex items-center gap-3 shrink-0 ml-3">
<span className={`text-xs font-medium ${h.violations > 0 ? 'text-red-600' : 'text-green-600'}`}>
{h.violations} Findings
</span>
<span className={`text-xs font-medium ${h.pct === 100 ? 'text-green-700' : h.pct >= 50 ? 'text-yellow-700' : 'text-red-700'}`}>
{h.pct}%
</span>
</div>
</button>
))}
</div>
</div>
)}
</div>
)
}
function PhaseBox({ label, icon, cookies, scripts, violations }: {
label: string; icon: string; cookies: number; scripts: number; violations: number
}) {
return (
<div className="text-center">
<div className="text-lg">{icon}</div>
<div className="text-xs font-medium text-gray-700">{label}</div>
<div className="text-xs text-gray-500 mt-1">{cookies} Cookies, {scripts} Scripts</div>
{violations > 0 && <div className="text-xs text-red-600 font-medium">{violations} Verstoesse</div>}
</div>
)
}
@@ -1,290 +0,0 @@
'use client'
import React, { useState } from 'react'
interface CheckItem {
id: string
label: string
passed: boolean
severity: string
matched_text: string
level?: number
parent?: string | null
skipped?: boolean
hint?: string
}
interface DocResult {
label: string
url: string
doc_type: string
word_count: number
completeness_pct: number
correctness_pct?: number
checks: CheckItem[]
findings_count: number
error: string
scenario?: string // regenerate | fix | import | skip
}
const SCENARIO_LABELS: Record<string, { label: string; color: string; bg: string }> = {
regenerate: { label: 'Neugenerierung', color: 'text-red-700', bg: 'bg-red-100' },
fix: { label: 'Korrekturen', color: 'text-amber-700', bg: 'bg-amber-100' },
import: { label: 'Konform', color: 'text-green-700', bg: 'bg-green-100' },
missing: { label: 'Fehlt', color: 'text-gray-600', bg: 'bg-gray-100' },
}
const DOC_TYPE_LABELS: Record<string, string> = {
dse: 'DSI', agb: 'AGB', impressum: 'Impressum',
cookie: 'Cookie', widerruf: 'Widerruf', other: 'Sonstiges',
social_media: 'Social Media', dsfa: 'DSFA', joint_controller: 'Art. 26',
eu_institution: 'EU-Inst.', banner: 'Banner',
}
interface GroupedCheck {
check: CheckItem
children: CheckItem[]
}
function groupChecks(checks: CheckItem[]): GroupedCheck[] {
const l1 = checks.filter(c => (c.level ?? 1) === 1)
return l1.map(c => ({
check: c,
children: checks.filter(ch => ch.parent === c.id && (ch.level ?? 1) === 2),
}))
}
function CheckIcon({ passed, skipped, isInfo }: { passed: boolean; skipped?: boolean; isInfo?: boolean }) {
if (skipped) {
return (
<svg className="w-4 h-4 text-gray-300 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
</svg>
)
}
if (passed) {
return (
<svg className="w-4 h-4 text-green-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
)
}
if (isInfo) {
return (
<svg className="w-4 h-4 text-gray-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
)
}
return (
<svg className="w-4 h-4 text-red-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
)
}
function L2Summary({ children }: { children: CheckItem[] }) {
const active = children.filter(c => !c.skipped)
if (active.length === 0) return null
const passed = active.filter(c => c.passed).length
return (
<span className="text-xs text-gray-400 ml-1">
({passed}/{active.length})
</span>
)
}
export function ChecklistView({ results }: { results: DocResult[] }) {
const [expanded, setExpanded] = useState<number | null>(null)
if (!results || results.length === 0) return null
const scenarioCounts = {
regenerate: results.filter(r => r.scenario === 'regenerate').length,
fix: results.filter(r => r.scenario === 'fix').length,
import: results.filter(r => r.scenario === 'import').length,
missing: results.filter(r => r.scenario === 'missing').length,
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between flex-wrap gap-2">
<h3 className="text-sm font-semibold text-gray-800">
Dokumenten-Pruefung ({results.length} Dokumente)
</h3>
<div className="flex gap-2 text-[10px]">
{scenarioCounts.import > 0 && <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full">{scenarioCounts.import} konform</span>}
{scenarioCounts.fix > 0 && <span className="bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full">{scenarioCounts.fix} Korrekturen</span>}
{scenarioCounts.regenerate > 0 && <span className="bg-red-100 text-red-700 px-2 py-0.5 rounded-full">{scenarioCounts.regenerate} Neugenerierung</span>}
{scenarioCounts.missing > 0 && <span className="bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{scenarioCounts.missing} fehlt</span>}
</div>
</div>
<div className="space-y-2">
{results.map((r, i) => {
const isExp = expanded === i
const pct = r.completeness_pct
const cpct = r.correctness_pct ?? 0
const barColor = pct === 100 ? 'bg-green-500' : pct >= 80 ? 'bg-green-400' : pct >= 50 ? 'bg-yellow-500' : 'bg-red-500'
const cBarColor = cpct >= 80 ? 'bg-blue-400' : cpct >= 50 ? 'bg-blue-300' : 'bg-blue-200'
const typeLabel = DOC_TYPE_LABELS[r.doc_type] || r.doc_type
const grouped = groupChecks(r.checks)
const l1Checks = r.checks.filter(c => (c.level ?? 1) === 1)
const l1Scoreable = l1Checks.filter(c => c.severity !== 'INFO')
const l2Active = r.checks.filter(c => (c.level ?? 1) === 2 && !c.skipped)
const l1Passed = l1Scoreable.filter(c => c.passed).length
const l2Passed = l2Active.filter(c => c.passed).length
return (
<div key={i} className="border border-gray-200 rounded-lg overflow-hidden">
<button
onClick={() => setExpanded(isExp ? null : i)}
className="w-full flex items-center justify-between px-4 py-3 hover:bg-gray-50 text-left"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<svg className={`w-4 h-4 text-gray-400 transition-transform shrink-0 ${isExp ? 'rotate-90' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
<span className="text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-medium shrink-0">
{typeLabel}
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-gray-900 truncate flex items-center gap-2">
{r.label}
{r.scenario && SCENARIO_LABELS[r.scenario] && (
<span className={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${SCENARIO_LABELS[r.scenario].bg} ${SCENARIO_LABELS[r.scenario].color}`}>
{SCENARIO_LABELS[r.scenario].label}
</span>
)}
</div>
<div className="text-xs text-gray-500 truncate">
{l1Checks.length > 0
? `${l1Passed}/${l1Scoreable.length} Pflichtangaben`
+ (l2Active.length > 0 ? `, ${l2Passed}/${l2Active.length} Detailpruefungen` : '')
: r.url}
</div>
</div>
</div>
<div className="flex items-center gap-3 shrink-0 ml-3">
{r.error && r.error.startsWith("Auf der Website nicht gefunden") ? (
<span className="text-xs text-amber-700 font-medium px-2 py-0.5 bg-amber-100 rounded-full whitespace-nowrap">
Nicht gefunden
</span>
) : r.error && r.error.startsWith("Nicht eingereicht") ? (
<span className="text-xs text-gray-500 font-medium px-2 py-0.5 bg-gray-100 rounded-full whitespace-nowrap">
Nicht eingereicht
</span>
) : r.error ? (
<span className="text-xs text-red-600 font-medium">Fehler</span>
) : (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2" title={`Pflichtangaben: ${l1Passed}/${l1Scoreable.length}`}>
<span className="text-[10px] text-gray-400 w-7">Pflicht</span>
<div className="w-14 h-1.5 bg-gray-200 rounded-full overflow-hidden">
<div className={`h-full rounded-full ${barColor}`} style={{ width: `${pct}%` }} />
</div>
<span className={`text-xs font-medium w-10 text-right ${
pct === 100 ? 'text-green-700' : pct >= 50 ? 'text-yellow-700' : 'text-red-700'
}`}>{pct}%</span>
</div>
{l2Active.length > 0 && (
<div className="flex items-center gap-2" title={`Detailpruefung: ${l2Passed}/${l2Active.length}`}>
<span className="text-[10px] text-gray-400 w-7">Detail</span>
<div className="w-14 h-1.5 bg-gray-200 rounded-full overflow-hidden">
<div className={`h-full rounded-full ${cBarColor}`} style={{ width: `${cpct}%` }} />
</div>
<span className="text-xs font-medium w-10 text-right text-blue-600">{cpct}%</span>
</div>
)}
</div>
)}
</div>
</button>
{isExp && (
<div className="px-4 py-3 border-t border-gray-100 bg-gray-50/50">
{r.error ? (
<p className="text-sm text-red-600">{r.error}</p>
) : (
<div className="space-y-1">
{grouped.map((g) => {
const l1Info = g.check.severity === 'INFO' && !g.check.passed
return (
<div key={g.check.id}>
{/* L1 check */}
<div className="flex items-start gap-2">
<CheckIcon passed={g.check.passed} isInfo={l1Info} />
<div className="flex-1">
<div className={`text-sm ${
g.check.passed ? 'text-gray-700'
: l1Info ? 'text-gray-500' : 'text-red-700 font-medium'
}`}>
{g.check.label}
{g.children.length > 0 && <L2Summary>{g.children}</L2Summary>}
</div>
{g.check.passed && g.check.matched_text && g.children.length === 0 && (
<div className="text-xs text-gray-400 mt-0.5 font-mono truncate">
&quot;...{g.check.matched_text}...&quot;
</div>
)}
{!g.check.passed && g.check.hint && (
<div className={`text-xs mt-0.5 ${l1Info ? 'text-gray-400' : 'text-red-600/80'}`}>
{g.check.hint}
</div>
)}
</div>
</div>
{/* L2 children — always visible */}
{g.children.length > 0 && (
<div className="ml-6 mt-0.5 mb-1 space-y-0.5 border-l-2 border-gray-200 pl-3">
{g.children.map((ch) => {
const chInfo = ch.severity === 'INFO' && !ch.passed && !ch.skipped
return (
<div key={ch.id} className="flex items-start gap-2">
<CheckIcon passed={ch.passed} skipped={ch.skipped} isInfo={chInfo} />
<div className="flex-1">
<div className={`text-xs ${
ch.skipped ? 'text-gray-400 italic'
: ch.passed ? 'text-gray-600'
: chInfo ? 'text-gray-400' : 'text-red-600 font-medium'
}`}>
{ch.label}
{ch.skipped && ' (uebersprungen)'}
</div>
{ch.passed && ch.matched_text && (
<div className="text-xs text-gray-400 mt-0.5 font-mono truncate">
&quot;...{ch.matched_text}...&quot;
</div>
)}
{!ch.passed && !ch.skipped && ch.hint && (
<div className={`text-xs mt-0.5 ${chInfo ? 'text-gray-400' : 'text-red-500/80'}`}>
{ch.hint}
</div>
)}
</div>
</div>
)
})}
</div>
)}
</div>
)
})}
{r.word_count > 0 && (
<div className="text-xs text-gray-400 mt-2 pt-2 border-t border-gray-200">
{r.word_count} Woerter analysiert
</div>
)}
</div>
)}
</div>
)}
</div>
)
})}
</div>
</div>
)
}
@@ -1,96 +0,0 @@
'use client'
import React from 'react'
interface SiteResult {
url: string
domain: string
risk_level: string
risk_score: number
findings_count: number
services_count: number
has_impressum: boolean
has_datenschutz: boolean
has_cookie_banner: boolean
has_google_fonts: boolean
scan_status: string
}
const RISK_COLOR: Record<string, string> = {
MINIMAL: 'text-green-700 bg-green-50',
LOW: 'text-yellow-700 bg-yellow-50',
LIMITED: 'text-orange-700 bg-orange-50',
HIGH: 'text-red-700 bg-red-50',
UNACCEPTABLE: 'text-red-900 bg-red-100',
}
export function CompareResult({ sites }: { sites: SiteResult[] }) {
if (!sites.length) return null
const checks = [
{ key: 'has_datenschutz', label: 'Datenschutzerklaerung' },
{ key: 'has_impressum', label: 'Impressum' },
{ key: 'has_cookie_banner', label: 'Cookie-Banner' },
{ key: 'has_google_fonts', label: 'Google Fonts (lokal?)' },
]
return (
<div className="space-y-4">
<div className="overflow-x-auto">
<table className="w-full text-sm border-collapse">
<thead>
<tr className="bg-gray-50">
<th className="text-left px-3 py-2 text-xs font-medium text-gray-500 w-44">Pruefung</th>
{sites.map((s, i) => (
<th key={i} className="text-center px-3 py-2 text-xs font-medium text-gray-700">
{s.domain}
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
<tr>
<td className="px-3 py-2 text-gray-600">Risiko-Score</td>
{sites.map((s, i) => (
<td key={i} className="px-3 py-2 text-center">
<span className={`px-2 py-0.5 rounded text-xs font-medium ${RISK_COLOR[s.risk_level] || 'text-gray-600 bg-gray-50'}`}>
{s.risk_level || '?'} ({s.risk_score}/100)
</span>
</td>
))}
</tr>
<tr>
<td className="px-3 py-2 text-gray-600">Findings</td>
{sites.map((s, i) => (
<td key={i} className={`px-3 py-2 text-center font-medium ${s.findings_count > 0 ? 'text-red-700' : 'text-green-700'}`}>
{s.findings_count}
</td>
))}
</tr>
<tr>
<td className="px-3 py-2 text-gray-600">Dienste erkannt</td>
{sites.map((s, i) => (
<td key={i} className="px-3 py-2 text-center text-gray-700">{s.services_count}</td>
))}
</tr>
{checks.map(check => (
<tr key={check.key}>
<td className="px-3 py-2 text-gray-600">{check.label}</td>
{sites.map((s, i) => {
const val = (s as any)[check.key]
const isInverted = check.key === 'has_google_fonts'
const good = isInverted ? !val : val
return (
<td key={i} className={`px-3 py-2 text-center font-medium ${good ? 'text-green-600' : 'text-red-600'}`}>
{good ? '✓' : '✗'}
</td>
)
})}
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
@@ -1,507 +0,0 @@
'use client'
import React, { useState, useCallback } from 'react'
import { ChecklistView } from './ChecklistView'
import { DocumentRow } from './DocumentRow'
import { MigrationPanel } from './MigrationPanel'
const DOCUMENT_TYPES = [
{ id: 'dse', label: 'DSI (Datenschutzinformation)', required: true },
{ id: 'impressum', label: 'Impressum', required: true },
{ id: 'social_media', label: 'Social Media DSE', required: false },
{ id: 'cookie', label: 'Cookie-Richtlinie', required: false },
{ id: 'agb', label: 'AGB', required: false },
{ id: 'nutzungsbedingungen', label: 'Nutzungsbedingungen', required: false },
{ id: 'widerruf', label: 'Widerrufsbelehrung', required: false },
{ id: 'dsb', label: 'DSB-Kontakt', required: false },
] as const
type DocTypeId = typeof DOCUMENT_TYPES[number]['id']
interface DocState {
url: string
text: string
loading: boolean
error: string | null
}
type DocsState = Record<DocTypeId, DocState>
const STORAGE_KEY_STATE = 'compliance-check-state'
const STORAGE_KEY_RESULTS = 'compliance-check-results'
const STORAGE_KEY_HISTORY = 'compliance-check-history'
const STORAGE_KEY_CHECK_ID = 'compliance-check-active-id'
function emptyDocState(): DocState {
return { url: '', text: '', loading: false, error: null }
}
function initState(): DocsState {
if (typeof window === 'undefined') {
return Object.fromEntries(DOCUMENT_TYPES.map(d => [d.id, emptyDocState()])) as DocsState
}
try {
const saved = localStorage.getItem(STORAGE_KEY_STATE)
if (saved) {
const parsed = JSON.parse(saved) as Record<string, { url?: string; text?: string }>
return Object.fromEntries(
DOCUMENT_TYPES.map(d => [d.id, {
url: parsed[d.id]?.url || '',
text: parsed[d.id]?.text || '',
loading: false,
error: null,
}])
) as DocsState
}
} catch { /* ignore */ }
return Object.fromEntries(DOCUMENT_TYPES.map(d => [d.id, emptyDocState()])) as DocsState
}
function countWords(text: string): number {
if (!text.trim()) return 0
return text.trim().split(/\s+/).length
}
interface HistoryEntry {
date: string
docCount: number
findings: number
resultKey: string
checkId?: string
}
export function ComplianceCheckTab() {
const [docs, setDocs] = useState<DocsState>(initState)
const [useAgent, setUseAgent] = useState(false)
const [tdmOverride, setTdmOverride] = useState(false)
const [tdmOverrideReason, setTdmOverrideReason] = useState('')
const [loading, setLoading] = useState(false)
const [progress, setProgress] = useState('')
const [progressPct, setProgressPct] = useState(0)
const [results, setResults] = useState<any>(() => {
if (typeof window === 'undefined') return null
try { const s = localStorage.getItem(STORAGE_KEY_RESULTS); return s ? JSON.parse(s) : null } catch { return null }
})
const [error, setError] = useState<string | null>(null)
const [activeCheckId, setActiveCheckId] = useState<string>(() =>
typeof window !== 'undefined' ? localStorage.getItem(STORAGE_KEY_CHECK_ID) || '' : ''
)
const [history, setHistory] = useState<HistoryEntry[]>(() => {
if (typeof window === 'undefined') return []
try { return JSON.parse(localStorage.getItem(STORAGE_KEY_HISTORY) || '[]') } catch { return [] }
})
// Persist URLs and texts (not loading/error state)
React.useEffect(() => {
const toSave: Record<string, { url: string; text: string }> = {}
for (const [key, val] of Object.entries(docs)) {
toSave[key] = { url: val.url, text: val.text }
}
try { localStorage.setItem(STORAGE_KEY_STATE, JSON.stringify(toSave)) } catch { /* quota */ }
}, [docs])
// Resume polling if check was in progress when navigating away
React.useEffect(() => {
if (!activeCheckId || results) return
let cancelled = false
setLoading(true)
setProgress('Pruefung laeuft noch...')
const poll = async () => {
while (!cancelled) {
await new Promise(r => setTimeout(r, 3000))
try {
const res = await fetch(`/api/sdk/v1/agent/compliance-check?check_id=${activeCheckId}`)
if (!res.ok) continue
const data = await res.json()
if (data.progress) setProgress(data.progress)
if (typeof data.progress_pct === 'number') setProgressPct(data.progress_pct)
if (data.status === 'completed' && data.result) {
setResults(data.result); setProgress(''); setProgressPct(0); setLoading(false)
localStorage.setItem(STORAGE_KEY_RESULTS, JSON.stringify(data.result))
localStorage.removeItem(STORAGE_KEY_CHECK_ID); setActiveCheckId('')
return
}
if (['failed', 'not_found', 'skipped_tdm'].includes(data.status)) {
if (data.status !== 'not_found') setError(data.error || (data.status === 'skipped_tdm' ? 'TDM-Vorbehalt erkannt — Crawl uebersprungen' : 'Pruefung fehlgeschlagen'))
setProgress(''); setProgressPct(0); setLoading(false); localStorage.removeItem(STORAGE_KEY_CHECK_ID); setActiveCheckId(''); return
}
} catch { /* retry */ }
}
}
poll()
return () => { cancelled = true }
}, []) // eslint-disable-line react-hooks/exhaustive-deps
const updateDoc = useCallback((docType: DocTypeId, patch: Partial<DocState>) => {
setDocs(prev => ({ ...prev, [docType]: { ...prev[docType], ...patch } }))
}, [])
const handleFetchText = useCallback(async (docType: DocTypeId) => {
const url = docs[docType].url.trim()
if (!url) return
updateDoc(docType, { loading: true, error: null })
try {
const res = await fetch('/api/sdk/v1/agent/extract-text', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
})
if (!res.ok) {
const msg = res.status === 404
? 'Seite nicht erreichbar'
: `Fehler beim Laden (${res.status})`
throw new Error(msg)
}
const data = await res.json()
updateDoc(docType, { text: data.text || '', loading: false })
} catch (e) {
updateDoc(docType, {
loading: false,
error: e instanceof Error ? e.message : 'Text konnte nicht geladen werden',
})
}
}, [docs, updateDoc])
const handleFileUpload = useCallback(async (docType: DocTypeId, file: File) => {
// For now, read as text. PDF/DOCX parsing can be added server-side later.
const reader = new FileReader()
reader.onload = () => {
updateDoc(docType, { text: reader.result as string })
}
reader.readAsText(file)
}, [updateDoc])
const filledCount = Object.values(docs).filter(d => d.url.trim() || d.text.trim()).length
const handleSubmit = async () => {
if (filledCount === 0) return
setLoading(true)
setError(null)
setResults(null)
setProgress('Compliance-Check wird gestartet...')
setProgressPct(0)
try {
const entries = DOCUMENT_TYPES
.filter(dt => docs[dt.id].url.trim() || docs[dt.id].text.trim())
.map(dt => ({
doc_type: dt.id,
label: dt.label,
url: docs[dt.id].url.trim(),
text: docs[dt.id].text.trim() || undefined,
}))
const startRes = await fetch('/api/sdk/v1/agent/compliance-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
documents: entries,
use_agent: useAgent,
tdm_override: tdmOverride && tdmOverrideReason.trim().length >= 10,
tdm_override_reason: tdmOverrideReason.trim(),
}),
})
if (!startRes.ok) throw new Error(`Pruefung konnte nicht gestartet werden: ${startRes.status}`)
const { check_id } = await startRes.json()
if (!check_id) throw new Error('Keine Check-ID erhalten')
setActiveCheckId(check_id)
localStorage.setItem(STORAGE_KEY_CHECK_ID, check_id)
// Poll for results (max 25 min = 500 polls x 3s)
let attempts = 0
while (attempts < 500) {
await new Promise(r => setTimeout(r, 3000))
const pollRes = await fetch(`/api/sdk/v1/agent/compliance-check?check_id=${check_id}`)
if (!pollRes.ok) { attempts++; continue }
const pollData = await pollRes.json()
if (pollData.progress) setProgress(pollData.progress)
if (typeof pollData.progress_pct === 'number') setProgressPct(pollData.progress_pct)
if (pollData.status === 'completed' && pollData.result) {
setResults(pollData.result)
setProgress('')
setProgressPct(0)
localStorage.setItem(STORAGE_KEY_RESULTS, JSON.stringify(pollData.result))
localStorage.removeItem(STORAGE_KEY_CHECK_ID); setActiveCheckId('')
const resultKey = `compliance-check-result-${Date.now()}`
try { localStorage.setItem(resultKey, JSON.stringify(pollData.result)) } catch { /* quota */ }
const entry: HistoryEntry = {
date: new Date().toISOString(),
docCount: entries.length,
findings: pollData.result.total_findings || 0,
resultKey,
}
const updated = [entry, ...history].slice(0, 30)
setHistory(updated)
localStorage.setItem(STORAGE_KEY_HISTORY, JSON.stringify(updated))
break
}
if (['failed', 'skipped_tdm'].includes(pollData.status)) {
localStorage.removeItem(STORAGE_KEY_CHECK_ID); setActiveCheckId('')
throw new Error(pollData.error || (pollData.status === 'skipped_tdm' ? 'TDM-Vorbehalt' : 'Pruefung fehlgeschlagen'))
}
attempts++
}
if (attempts >= 500) {
localStorage.removeItem(STORAGE_KEY_CHECK_ID); setActiveCheckId('')
throw new Error('Zeitlimit ueberschritten (15 Min)')
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
setProgress('')
setProgressPct(0)
} finally {
setLoading(false)
}
}
const loadFromHistory = (entry: HistoryEntry) => {
if (entry.resultKey) {
try {
const saved = localStorage.getItem(entry.resultKey)
if (saved) { setResults(JSON.parse(saved)); return }
} catch { /* ignore */ }
}
try {
const last = localStorage.getItem(STORAGE_KEY_RESULTS)
if (last) setResults(JSON.parse(last))
} catch { /* ignore */ }
}
return (
<div className="space-y-4">
{/* Info box */}
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
<h3 className="text-sm font-semibold text-purple-900">Compliance-Check (Alle Dokumente)</h3>
<p className="text-xs text-purple-700 mt-1">
Geben Sie die URLs Ihrer Rechtstexte ein oder laden Sie die Dokumente hoch.
Das System prueft alle Pflichtangaben nach DSGVO, TDDDG, TMG und UWG.
Pflichtdokumente sind mit * markiert.
</p>
</div>
{/* Document rows */}
<div className="space-y-2">
{DOCUMENT_TYPES.map(dt => (
<DocumentRow
key={dt.id}
label={dt.label}
docType={dt.id}
required={dt.required}
url={docs[dt.id].url}
text={docs[dt.id].text}
loading={docs[dt.id].loading}
error={docs[dt.id].error}
wordCount={countWords(docs[dt.id].text)}
onUrlChange={url => updateDoc(dt.id, { url })}
onFetchText={() => handleFetchText(dt.id)}
onTextChange={text => updateDoc(dt.id, { text })}
onFileUpload={file => handleFileUpload(dt.id, file)}
/>
))}
</div>
{/* Agent toggle + submit */}
<div className="flex items-center justify-between">
<button
type="button"
onClick={() => setUseAgent(!useAgent)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
useAgent
? 'bg-emerald-100 border-emerald-300 text-emerald-800'
: 'bg-gray-50 border-gray-200 text-gray-500 hover:bg-gray-100'
}`}
>
<span className={`w-2 h-2 rounded-full ${useAgent ? 'bg-emerald-500' : 'bg-gray-300'}`} />
{useAgent ? 'KI-Agent aktiv (alle MCs)' : 'KI-Agent aus'}
</button>
<span className="text-xs text-gray-500">
{filledCount} von {DOCUMENT_TYPES.length} Dokumenten ausgefuellt
</span>
</div>
<div className="bg-amber-50/60 border border-amber-200 rounded-lg p-3 space-y-2">
<label className="flex items-start gap-2 cursor-pointer"><input type="checkbox" checked={tdmOverride} onChange={e => setTdmOverride(e.target.checked)} className="mt-0.5 accent-amber-600" /><span className="text-xs text-amber-900"><strong>Schriftliche Crawl-Erlaubnis vorhanden</strong> uebergeht TDM-Vorbehalte (robots.txt / ai.txt)</span></label>
{tdmOverride && <input type="text" value={tdmOverrideReason} onChange={e => setTdmOverrideReason(e.target.value)} placeholder="z.B. Auftragsbeziehung Safetykon GmbH, Email Hr. X vom 18.05.2026" className="w-full px-3 py-2 text-xs border border-amber-300 rounded bg-white" />}
{tdmOverride && tdmOverrideReason.trim().length < 10 && <p className="text-[10px] text-amber-700">Pflicht: Reason mit min. 10 Zeichen (Audit-Spur).</p>}
</div>
{/* Submit button */}
<button
onClick={handleSubmit}
disabled={loading || filledCount === 0 || (tdmOverride && tdmOverrideReason.trim().length < 10)}
className="w-full px-4 py-3 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 disabled:opacity-50 transition-colors text-sm flex items-center justify-center gap-2"
>
{loading ? (
<>
<svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
Pruefe...
</>
) : (
`Compliance-Check starten (${filledCount} Dokument${filledCount !== 1 ? 'e' : ''})`
)}
</button>
{/* Progress */}
{progress && (
<div className="bg-purple-50 border border-purple-200 rounded-lg p-3 text-sm text-purple-700 space-y-2">
<div className="flex items-center gap-3">
<svg className="animate-spin w-4 h-4 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
<span className="flex-1">{progress}</span>
<span className="text-xs font-mono text-purple-600 tabular-nums">{progressPct}%</span>
</div>
<div className="h-1.5 bg-purple-100 rounded-full overflow-hidden">
<div
className="h-full bg-purple-500 rounded-full transition-all duration-500 ease-out"
style={{ width: `${Math.max(2, progressPct)}%` }}
/>
</div>
</div>
)}
{/* Error */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">{error}</div>
)}
{/* Results */}
{results && results.results && (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
{/* Business Profile */}
{results.business_profile && (
<div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-xs">
<div className="font-semibold text-blue-900 mb-1">Erkanntes Geschaeftsmodell</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-blue-700">
<span>Typ: <strong>{results.business_profile.business_type?.toUpperCase()}</strong></span>
<span>Branche: {results.business_profile.industry}</span>
{results.business_profile.has_online_shop && <span className="text-amber-700">Online-Shop</span>}
{results.business_profile.is_regulated_profession && <span className="text-amber-700">Regulierter Beruf ({results.business_profile.regulated_profession_type})</span>}
</div>
</div>
)}
{/* Extracted Profile — pre-fill suggestion */}
{results.extracted_profile?.company_profile && Object.keys(results.extracted_profile.company_profile).length > 0 && (
<div className="mb-4 p-3 bg-emerald-50 border border-emerald-200 rounded-lg text-xs">
<div className="flex items-center justify-between mb-1">
<span className="font-semibold text-emerald-900">Aus Dokumenten extrahiert</span>
<button className="text-emerald-700 hover:text-emerald-900 text-xs font-medium underline"
onClick={() => { /* TODO: navigate to company profile with pre-fill */ }}>
In Company Profile uebernehmen
</button>
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-emerald-700">
{results.extracted_profile.company_profile.companyName && (
<span>Firma: <strong>{results.extracted_profile.company_profile.companyName}</strong></span>
)}
{results.extracted_profile.company_profile.legalForm && (
<span>Rechtsform: {results.extracted_profile.company_profile.legalForm.toUpperCase()}</span>
)}
{results.extracted_profile.company_profile.headquartersCity && (
<span>Sitz: {results.extracted_profile.company_profile.headquartersZip} {results.extracted_profile.company_profile.headquartersCity}</span>
)}
{results.extracted_profile.company_profile.dpoEmail && (
<span>DSB: {results.extracted_profile.company_profile.dpoEmail}</span>
)}
{results.extracted_profile.company_profile.ustIdNr && (
<span>USt-IdNr: {results.extracted_profile.company_profile.ustIdNr}</span>
)}
</div>
{results.extracted_profile.compliance_scope_hints?.length > 0 && (
<div className="mt-2 pt-2 border-t border-emerald-200 text-emerald-600">
<span className="font-medium">Scope-Hinweise: </span>
{results.extracted_profile.compliance_scope_hints.map((h: any, i: number) => (
<span key={i} className="inline-block bg-emerald-100 rounded px-1.5 py-0.5 mr-1 mb-1">
{h.source}
</span>
))}
</div>
)}
</div>
)}
{/* Banner Check Result */}
{results.banner_result && (
<div className={`mb-4 p-3 rounded-lg border text-xs ${
results.banner_result.violations > 0
? 'bg-amber-50 border-amber-200'
: results.banner_result.detected
? 'bg-green-50 border-green-200'
: 'bg-gray-50 border-gray-200'
}`}>
<div className="flex items-center gap-2">
<span className={`w-2 h-2 rounded-full ${
results.banner_result.violations > 0 ? 'bg-amber-500'
: results.banner_result.detected ? 'bg-green-500' : 'bg-gray-400'
}`} />
<span className="font-semibold text-gray-900">
Cookie-Banner-Check (automatisch)
</span>
</div>
<div className="mt-1 text-gray-600 ml-4">
{results.banner_result.detected ? (
<>
Banner erkannt{results.banner_result.provider ? ` (${results.banner_result.provider})` : ''}.
{results.banner_result.violations > 0
? ` ${results.banner_result.violations} Auffaelligkeit${results.banner_result.violations !== 1 ? 'en' : ''} gefunden.`
: ' Keine Auffaelligkeiten.'}
</>
) : (
'Kein Cookie-Banner erkannt oder Banner-Check nicht moeglich.'
)}
</div>
</div>
)}
<ChecklistView results={results.results} />
{/* Email + Migration + Full-audit */}
{results.email_status && (
<div className="mt-3 text-xs text-gray-500 flex items-center gap-2">
<span className={`w-2 h-2 rounded-full ${results.email_status === 'sent' ? 'bg-green-400' : 'bg-gray-300'}`} />
E-Mail: {results.email_status === 'sent' ? 'Gesendet' : results.email_status}
</div>
)}
{results.check_id && <MigrationPanel checkId={results.check_id} />}
</div>
)}
{/* History */}
{history.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Compliance-Checks</h4>
<div className="space-y-1">
{history.map((h, i) => (
<button
key={i}
onClick={() => loadFromHistory(h)}
className="w-full flex items-center justify-between text-sm py-2 px-2 rounded-lg border border-gray-50 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left"
>
<span className="text-gray-600">
{new Date(h.date).toLocaleDateString('de-DE', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit',
})}
</span>
<div className="flex items-center gap-3">
<span className="text-xs text-gray-500">{h.docCount} Dok.</span>
<span className={`text-xs font-medium ${h.findings > 0 ? 'text-amber-600' : 'text-green-600'}`}>
{h.findings} Findings
</span>
</div>
</button>
))}
</div>
</div>
)}
</div>
)
}
@@ -1,145 +0,0 @@
'use client'
import React, { useState } from 'react'
interface FAQItem {
q: string
a: string
}
const FAQ_ITEMS: FAQItem[] = [
{
q: "Was passiert wenn ein Unternehmen wegen unzureichender Datenschutzerklaerung oder Cookie-Richtlinie verklagt wird?",
a: `Es gibt vier Durchsetzungswege:
**1. Bussgelder durch Aufsichtsbehoerden (Art. 83 DSGVO)**
Aufsichtsbehoerden pruefen von Amts wegen oder auf Beschwerde — kein Klaeger noetig. Bussgelder bis 20 Mio. EUR oder 4% des Jahresumsatzes. Beispiele: CNIL gegen Google (150 Mio. EUR), Facebook (60 Mio. EUR), H&M (35 Mio. EUR). Auch KMU sind betroffen — der LfDI Baden-Wuerttemberg hat Bussgelder ab 10.000 EUR verhaengt.
**2. Abmahnungen durch Verbraucherschutzverbaende**
Verbaende wie vzbv oder DUH koennen ohne individuellen Schaden klagen (§2 UKlaG). Das ist der groesste praktische Druck: Unterlassungsklage + Anwaltskosten (5.000-20.000 EUR pro Fall). Seit EuGH C-319/20 (Meta/vzbv) duerfen Verbaende DSGVO-Verstoesse auch ohne Betroffenenauftrag klagen.
**3. Individueller Schadensersatz (Art. 82 DSGVO)**
Seit EuGH C-300/21 (Oesterreichische Post) genuegt bereits der "Kontrollverlust" ueber Daten als immaterieller Schaden — kein messbarer finanzieller Schaden noetig. Typisch: 100-5.000 EUR pro Betroffenem. Legaltech-Firmen wie NOYB buendeln Massenverfahren.
**4. Wettbewerber-Abmahnungen (UWG)**
Seit 2021 eingeschraenkt, aber Impressums-Maengel oder fehlende Cookie-Einwilligung bleiben abmahnfaehig.
Die Aufsichtsbehoerden erhalten ueber 10.000 Beschwerden pro Jahr. Eine Beschwerde einzureichen ist kostenlos und mit einem Klick moeglich.`,
},
{
q: "Wie funktioniert die Dokumentenpruefung?",
a: `Die Pruefung laeuft in drei Schritten:
**1. Text-Extraktion** — Playwright laedt die Seite, expandiert Accordions/Tabs und extrahiert den vollstaendigen Text.
**2. Regex-Checks (138 Pruefpunkte)** — Zwei Ebenen: L1 prueft ob Pflichtangaben erwaehnt sind (z.B. "Verantwortlicher"), L2 prueft ob sie korrekt und vollstaendig sind (z.B. "Hat der Verantwortliche eine ladungsfaehige Anschrift mit PLZ?").
**3. LLM-Verifikation** — Jeder fehlgeschlagene Check wird von einem KI-Modell (Qwen) gegen den Originaltext gegengeprueft, um Fehlalarme zu eliminieren.
Das Ergebnis: Zwei Scores pro Dokument — Vollstaendigkeit (sind alle Pflichtangaben da?) und Korrektheit (sind sie richtig formuliert?). Jeder fehlende Punkt hat eine konkrete Handlungsanweisung mit Rechtsbezug.`,
},
{
q: "Welche Dokumenttypen werden geprueft?",
a: `Sieben Dokumenttypen mit jeweils eigener Checkliste:
- **Datenschutzinformation (DSI)** — Art. 13/14 DSGVO (31 Checks)
- **Cookie-Richtlinie** — §25 TDDDG (15 Checks)
- **Impressum** — §5 TMG / §18 MStV (16 Checks)
- **AGB** — §305ff BGB (21 Checks)
- **Widerrufsbelehrung** — §355 BGB (15 Checks)
- **Social Media DSE** — Art. 26 DSGVO Joint Controller (20 Checks)
- **DSFA** — Art. 35 DSGVO (18 Checks)
Sub-Sektionen (z.B. Cookie-Abschnitt innerhalb der DSI) werden automatisch erkannt und separat geprueft.`,
},
{
q: "Wie zuverlaessig sind die Ergebnisse?",
a: `Die Pruefung wurde gegen mehrere Ground-Truth-Websites validiert (IHK Konstanz, ETO Gruppe, BMW, Stadt Koeln, Sparkasse, Spiegel u.a.). Ergebnis: **0 False Positives** bei validierten Testfaellen — jeder rote Punkt ist ein echtes Finding.
Durch die LLM-Verifikation werden Regex-Fehlalarme (z.B. durch ungewoehnliche Formatierung oder Soft Hyphens im HTML) automatisch korrigiert. Trotzdem gilt: Das Tool ersetzt keine Rechtsberatung, sondern identifiziert Handlungsbedarf.`,
},
{
q: "Was kostet ein Verstoss gegen die DSGVO in der Praxis?",
a: `Bussgelder nach Art. 83 DSGVO staffeln sich in zwei Stufen:
- **Bis 10 Mio. EUR / 2% Umsatz**: Verstoesse gegen technische/organisatorische Pflichten (Art. 25, 28, 32)
- **Bis 20 Mio. EUR / 4% Umsatz**: Verstoesse gegen Grundsaetze, Betroffenenrechte, Drittlandtransfer
Typische Praxis-Bussgelder in Deutschland: 5.000-50.000 EUR fuer KMU, 100.000-1 Mio. EUR fuer groessere Unternehmen. Dazu kommen Anwaltskosten bei Abmahnungen (5.000-20.000 EUR pro Fall) und Reputationsschaden.`,
},
{
q: "Was ist der aktuelle Stand bei harmonisierten Normen unter der neuen Maschinenverordnung (EU) 2023/1230?",
a: `Die Maschinenverordnung (EU) 2023/1230 hat in Anhang I die wesentlichen Gesundheits- und Sicherheitsanforderungen und verweist darauf, dass harmonisierte Normen die technischen Details liefern sollen (Konformitaetsvermutung).
**Aktueller Stand:** Es gibt noch KEINE harmonisierten Normen die unter der neuen Maschinenverordnung im EU-Amtsblatt veroeffentlicht sind. Die bestehenden ~800 harmonisierten Normen gelten noch unter der alten Maschinenrichtlinie 2006/42/EC.
**Zeitplan:**
- **Juni 2023** — Maschinenverordnung veroeffentlicht
- **Januar 2025** — EU-Kommission hat Normungsauftrag an CEN/CENELEC erteilt
- **Januar 2026** — CEN/CENELEC soll bestehende Normen bestaetigen oder Nachfolgenormen verabschieden
- **Januar 2027** — Maschinenverordnung tritt vollstaendig in Kraft, ersetzt alte Richtlinie 2006/42/EC
**Wichtig fuer Hersteller:** Bis die neuen harmonisierten Normen veroeffentlicht sind, koennen Hersteller die bestehenden Normen der alten Maschinenrichtlinie weiterhin anwenden. Nach dem 20. Januar 2027 muessen Maschinen aber die Anforderungen der neuen Verordnung erfuellen — auch wenn die harmonisierten Normen bis dahin nicht vollstaendig vorliegen.
**IACE Normen-Bibliothek:** Die aktuelle Liste unter /sdk/iace/library enthaelt 751 harmonisierte Normen (1 A-Norm, 19 B1, 126 B2, 605 C-Normen). Diese muessen regelmaessig gegen das EU-Amtsblatt abgeglichen werden, da einige Normen zurueckgezogen oder ersetzt wurden.`,
},
{
q: "Warum muss ich harmonisierte Normen kaufen obwohl sie EU-Recht sind?",
a: `Harmonisierte Normen werden von privaten Organisationen (CEN/CENELEC) erstellt und ueber nationale Normungsinstitute wie DIN/Beuth (Deutschland), ASI (Oesterreich) oder SNV (Schweiz) verkauft — typisch 50-300 EUR pro Norm.
**Das Problem:** Die EU-Kommission beauftragt die Normung, Industrieexperten schreiben die Normen ehrenamtlich in Technischen Komitees, aber ein privater Verlag verkauft das Ergebnis. Unternehmen muessen Normen kaufen die ihre eigenen Mitarbeiter geschrieben haben.
**EuGH-Urteil C-588/21 P (5. Maerz 2024):**
Der Europaeische Gerichtshof hat entschieden, dass harmonisierte Normen **Teil des EU-Rechts** sind, weil sie eine Konformitaetsvermutung erzeugen. Das Rechtsstaatsprinzip verlangt, dass Buerger die Regeln kennen koennen die fuer sie gelten. Daher muessen harmonisierte Normen grundsaetzlich **frei zugaenglich** sein.
**Aktueller Stand (2026):** Das Urteil ist noch nicht vollstaendig umgesetzt. CEN/CENELEC und die nationalen Normungsinstitute wehren sich, weil ihr Geschaeftsmodell auf dem Verkauf basiert. Die EU-Kommission arbeitet an einer Loesung.
**Was das fuer Unternehmen bedeutet:**
- Aktuell muessen Normen weiterhin gekauft werden
- Normnummern und Titel sind frei nutzbar (bibliographische Daten)
- BSI-Grundschutz und NIST-Standards sind kostenlose Alternativen die inhaltlich aehnliche Anforderungen abdecken
- Die IACE-Bibliothek in BreakPilot listet alle harmonisierten Normen mit Status (aktiv/zurueckgezogen) ohne kostenpflichtigen Normtext`,
},
]
export function ComplianceFAQ() {
const [open, setOpen] = useState<number | null>(null)
return (
<div className="border border-gray-200 rounded-xl overflow-hidden">
<div className="px-4 py-3 bg-gray-50 border-b border-gray-200">
<h3 className="text-sm font-semibold text-gray-800">Haeufige Fragen</h3>
</div>
<div className="divide-y divide-gray-100">
{FAQ_ITEMS.map((item, i) => (
<div key={i}>
<button
onClick={() => setOpen(open === i ? null : i)}
className="w-full flex items-center justify-between px-4 py-3 text-left hover:bg-gray-50 transition-colors"
>
<span className="text-sm font-medium text-gray-900 pr-4">{item.q}</span>
<svg
className={`w-4 h-4 text-gray-400 shrink-0 transition-transform ${open === i ? 'rotate-180' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{open === i && (
<div className="px-4 pb-4 text-sm text-gray-600 prose prose-sm max-w-none">
{item.a.split('\n\n').map((para, pi) => (
<p key={pi} className="mb-2 last:mb-0" dangerouslySetInnerHTML={{
__html: para
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\n- /g, '<br/>• ')
.replace(/\n/g, '<br/>')
}} />
))}
</div>
)}
</div>
))}
</div>
</div>
)
}
@@ -1,248 +0,0 @@
'use client'
import React from 'react'
interface Violation {
service: string
severity: string
text: string
legal_ref: string
}
interface PhaseData {
scripts: string[]
cookies: string[]
tracking_services?: string[]
new_tracking?: string[]
violations?: Violation[]
undocumented?: string[]
}
interface ConsentData {
banner_detected: boolean
banner_provider: string
phases: {
before_consent: PhaseData
after_reject: PhaseData
after_accept: PhaseData
}
summary: {
critical: number
high: number
undocumented: number
total_violations: number
category_violations?: number
categories_tested?: number
}
banner_checks?: {
has_impressum_link: boolean
has_dse_link: boolean
violations: { service: string; severity: string; text: string; legal_ref: string }[]
}
category_tests?: {
category: string
category_label: string
tracking_services: string[]
violations: { service: string; severity: string; text: string }[]
}[]
}
const SEV = {
CRITICAL: { bg: 'bg-red-100 border-red-300', text: 'text-red-800', badge: 'bg-red-600' },
HIGH: { bg: 'bg-orange-100 border-orange-300', text: 'text-orange-800', badge: 'bg-orange-500' },
}
function PhaseCard({ title, icon, data, type }: {
title: string; icon: string; data: PhaseData; type: 'before' | 'reject' | 'accept'
}) {
const violations = data.violations || []
const tracking = data.tracking_services || data.new_tracking || []
const undocumented = data.undocumented || []
const hasProblem = violations.length > 0 || undocumented.length > 0
return (
<div className={`border rounded-lg p-4 ${hasProblem ? 'border-red-200 bg-red-50' : 'border-green-200 bg-green-50'}`}>
<h4 className="text-sm font-semibold text-gray-900 mb-2 flex items-center gap-2">
<span>{icon}</span> {title}
</h4>
{/* Violations */}
{violations.map((v, i) => (
<div key={i} className={`mb-2 p-2 rounded border ${SEV[v.severity as keyof typeof SEV]?.bg || SEV.HIGH.bg}`}>
<div className="flex items-center gap-2">
<span className={`text-[10px] px-1.5 py-0.5 rounded text-white ${SEV[v.severity as keyof typeof SEV]?.badge || SEV.HIGH.badge}`}>
{v.severity}
</span>
<span className={`text-xs font-medium ${SEV[v.severity as keyof typeof SEV]?.text || SEV.HIGH.text}`}>
{v.service}
</span>
</div>
<p className="text-xs text-gray-700 mt-1">{v.text}</p>
<p className="text-[10px] text-gray-500 mt-0.5">{v.legal_ref}</p>
</div>
))}
{/* Undocumented (Phase C only) */}
{undocumented.map((s, i) => (
<div key={i} className="mb-2 p-2 rounded border border-yellow-300 bg-yellow-50">
<span className="text-xs text-yellow-800"> {s} nicht in Cookie-Policy dokumentiert</span>
</div>
))}
{/* Tracking services (no violations) */}
{violations.length === 0 && undocumented.length === 0 && tracking.length > 0 && (
<div className="text-xs text-green-700">
{tracking.map((t, i) => <div key={i}> {t} {type === 'accept' ? 'mit Consent OK' : 'erkannt'}</div>)}
</div>
)}
{violations.length === 0 && undocumented.length === 0 && tracking.length === 0 && (
<p className="text-xs text-green-700"> Keine Tracking-Dienste erkannt</p>
)}
{/* Cookie/Script count */}
<div className="flex gap-3 mt-2 text-[10px] text-gray-400">
<span>{data.scripts?.length || 0} Scripts</span>
<span>{data.cookies?.length || 0} Cookies</span>
</div>
</div>
)
}
export function ConsentTestResult({ data }: { data: ConsentData }) {
const s = data.summary
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<span className={`w-3 h-3 rounded-full ${data.banner_detected ? 'bg-green-500' : 'bg-red-500'}`} />
<span className="text-sm font-medium text-gray-900">
Cookie-Banner: {data.banner_detected ? data.banner_provider : 'Nicht erkannt'}
</span>
</div>
<div className="flex gap-2">
{s.critical > 0 && (
<span className="text-xs px-2 py-1 rounded bg-red-600 text-white font-medium">
{s.critical} Kritisch
</span>
)}
{s.high > 0 && (
<span className="text-xs px-2 py-1 rounded bg-orange-500 text-white font-medium">
{s.high} Hoch
</span>
)}
{s.total_violations === 0 && (
<span className="text-xs px-2 py-1 rounded bg-green-500 text-white font-medium">
Keine Verstoesse
</span>
)}
</div>
</div>
{/* Three Phases */}
<div className="space-y-3">
<PhaseCard
title="Phase A: Vor Einwilligung"
icon="🔍"
data={data.phases.before_consent}
type="before"
/>
{data.banner_detected && (
<>
<PhaseCard
title="Phase B: Nach Ablehnung"
icon="🚫"
data={data.phases.after_reject}
type="reject"
/>
<PhaseCard
title="Phase C: Nach Zustimmung"
icon="✅"
data={data.phases.after_accept}
type="accept"
/>
</>
)}
</div>
{/* Banner Text Checks */}
{data.banner_checks && (data.banner_checks.violations?.length > 0 || data.banner_checks.has_impressum_link !== undefined) && (
<div className="border rounded-lg p-4 border-gray-200 bg-gray-50">
<h4 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
<span>📝</span> Banner-Text Pruefung
</h4>
<div className="flex gap-3 mb-3 text-xs">
<span className={data.banner_checks.has_impressum_link ? 'text-green-600' : 'text-red-600'}>
{data.banner_checks.has_impressum_link ? '✓' : '✗'} Impressum-Link
</span>
<span className={data.banner_checks.has_dse_link ? 'text-green-600' : 'text-red-600'}>
{data.banner_checks.has_dse_link ? '✓' : '✗'} DSE-Link
</span>
</div>
{data.banner_checks.violations?.map((v: any, i: number) => {
const isHigh = v.severity === 'HIGH' || v.severity === 'CRITICAL'
return (
<div key={i} className={`mb-2 p-2 rounded border ${isHigh ? 'border-red-300 bg-red-50' : 'border-yellow-300 bg-yellow-50'}`}>
<div className="flex items-start gap-2">
<span className={`text-[10px] px-1.5 py-0.5 rounded text-white ${isHigh ? 'bg-red-600' : 'bg-yellow-600'}`}>
{v.severity}
</span>
<div>
<p className="text-xs text-gray-800">{v.text}</p>
<p className="text-[10px] text-gray-500 mt-0.5">{v.legal_ref}</p>
</div>
</div>
</div>
)
})}
{(!data.banner_checks.violations || data.banner_checks.violations.length === 0) && (
<p className="text-xs text-green-700"> Keine Banner-Text-Verstoesse erkannt</p>
)}
</div>
)}
{/* Category Tests (Phase D-F) */}
{data.category_tests && data.category_tests.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-semibold text-gray-900 mt-2">Kategorie-Tests ({data.category_tests.length})</h4>
{data.category_tests.map((ct, i) => {
const hasViolations = ct.violations.length > 0
return (
<div key={i} className={`border rounded-lg p-4 ${hasViolations ? 'border-red-200 bg-red-50' : 'border-green-200 bg-green-50'}`}>
<h4 className="text-sm font-semibold text-gray-900 mb-2 flex items-center gap-2">
<span>🔀</span> Nur &quot;{ct.category_label}&quot;
</h4>
{ct.violations.length > 0 ? (
ct.violations.map((v, vi) => (
<div key={vi} className="mb-2 p-2 rounded border border-red-300 bg-red-100">
<span className="text-xs font-bold text-red-800 px-1.5 py-0.5 rounded bg-red-200">FALSCH</span>
<span className="text-xs text-red-700 ml-2">{v.text}</span>
</div>
))
) : (
<div className="text-xs text-green-700">
{ct.tracking_services.length > 0 ? (
ct.tracking_services.map((s, si) => <div key={si}> {s} korrekte Kategorie</div>)
) : (
<div> Keine Tracking-Dienste geladen korrekt</div>
)}
</div>
)}
</div>
)
})}
</div>
)}
{/* No banner warning */}
{!data.banner_detected && (
<div className="bg-red-50 border border-red-200 rounded-lg p-3 text-xs text-red-700">
<strong>Kein Cookie-Banner erkannt.</strong> Alle erkannten Tracking-Dienste laden ohne
Einwilligung dies ist ein Verstoss gegen §25 TDDDG.
</div>
)}
</div>
)
}
@@ -1,357 +0,0 @@
'use client'
import React, { useState } from 'react'
import { ChecklistView } from './ChecklistView'
import { ResultsTabsView } from './ResultsTabsView'
import { PreScanWizard, useScanContext, isContextComplete } from './PreScanWizard'
import { safeSetItem } from './storageHelpers'
interface DocEntry {
id: string
type: string
label: string
url: string
text: string // P-Paste: User kopiert Doc-Text direkt rein
mode: 'url' | 'text' // welcher Input wird aktiv genutzt
}
const DOC_TYPES = [
{ id: 'dse', label: 'Datenschutzerklärung / DSI' },
{ id: 'cookie', label: 'Cookie-Richtlinie' },
{ id: 'impressum', label: 'Impressum' },
{ id: 'agb', label: 'AGB' },
{ id: 'nutzungsbedingungen', label: 'Nutzungsbedingungen' },
{ id: 'widerruf', label: 'Widerrufsbelehrung' },
{ id: 'social_media', label: 'DSE Social Media (Art. 26)' },
{ id: 'dsfa', label: 'DSFA (Art. 35)' },
{ id: 'dsa', label: 'DSA / Digital Services Act' },
{ id: 'legal_notice', label: 'Rechtliche Hinweise (IP, Forward-Looking)' },
{ id: 'lizenzhinweise', label: 'Lizenzhinweise Dritter (OSS)' },
{ id: 'other', label: 'Sonstiges' },
]
function newEntry(): DocEntry {
return { id: crypto.randomUUID().slice(0, 8), type: 'dse', label: '',
url: '', text: '', mode: 'url' }
}
export function DocCheckTab() {
const [scanContext, setScanContext] = useScanContext()
const [entries, setEntries] = useState<DocEntry[]>(() => {
if (typeof window === 'undefined') return [newEntry()]
try { const s = localStorage.getItem('doc-check-entries'); return s ? JSON.parse(s) : [newEntry()] } catch { return [newEntry()] }
})
const [checkCookieBanner, setCheckCookieBanner] = useState(false)
const [useAgent, setUseAgent] = useState(false)
const [loading, setLoading] = useState(false)
const [progress, setProgress] = useState('')
const [results, setResults] = useState<any>(() => {
if (typeof window === 'undefined') return null
try { const s = localStorage.getItem('doc-check-results'); return s ? JSON.parse(s) : null } catch { return null }
})
const [error, setError] = useState<string | null>(null)
const [history, setHistory] = useState<{ date: string; urls: number; findings: number; resultKey: string }[]>(() => {
if (typeof window === 'undefined') return []
try { return JSON.parse(localStorage.getItem('doc-check-history') || '[]') } catch { return [] }
})
// Persist entries
React.useEffect(() => { localStorage.setItem('doc-check-entries', JSON.stringify(entries)) }, [entries])
const updateEntry = (id: string, field: keyof DocEntry, value: string) => {
setEntries(prev => prev.map(e => e.id === id ? { ...e, [field]: value } : e))
}
const removeEntry = (id: string) => {
setEntries(prev => prev.filter(e => e.id !== id))
}
const addEntry = () => {
setEntries(prev => [...prev, newEntry()])
}
// Auto-detect label from URL
const autoLabel = (entry: DocEntry) => {
if (entry.label) return
try {
const path = new URL(entry.url).pathname
const last = path.split('/').filter(Boolean).pop() || ''
const label = last.replace(/-\d+$/, '').replace(/-/g, ' ')
.replace(/\b\w/g, c => c.toUpperCase())
if (label.length > 3) {
updateEntry(entry.id, 'label', label)
}
} catch { /* invalid URL */ }
}
const handleSubmit = async () => {
const validEntries = entries.filter(e => e.url.trim() || e.text.trim())
if (validEntries.length === 0) return
setLoading(true)
setError(null)
setResults(null)
setProgress('Pruefung wird gestartet...')
try {
const startRes = await fetch('/api/sdk/v1/agent/doc-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
entries: validEntries.map(e => ({
doc_type: e.type,
label: e.label
|| (e.url ? e.url.split('/').pop() : '')
|| `${e.type}-paste`,
url: e.mode === 'text' ? '' : e.url.trim(),
// Backend nimmt text > url. Wenn beide gefuellt sind und
// mode='url', schicken wir den text NICHT mit.
text: e.mode === 'text' ? e.text.trim() : '',
})),
check_cookie_banner: checkCookieBanner,
use_agent: useAgent,
scan_context: scanContext,
}),
})
if (!startRes.ok) throw new Error(`Pruefung konnte nicht gestartet werden: ${startRes.status}`)
const { check_id } = await startRes.json()
if (!check_id) throw new Error('Keine Check-ID erhalten')
// Poll for results
let attempts = 0
while (attempts < 120) {
await new Promise(r => setTimeout(r, 3000))
const pollRes = await fetch(`/api/sdk/v1/agent/doc-check?check_id=${check_id}`)
if (!pollRes.ok) { attempts++; continue }
const pollData = await pollRes.json()
if (pollData.progress) setProgress(pollData.progress)
if (pollData.status === 'completed' && pollData.result) {
setResults(pollData.result)
setProgress('')
safeSetItem('doc-check-results', JSON.stringify(pollData.result))
const resultKey = `doc-check-result-${Date.now()}`
safeSetItem(resultKey, JSON.stringify(pollData.result))
const entry = { date: new Date().toISOString(), urls: validEntries.length, findings: pollData.result.total_findings || 0, resultKey }
const updated = [entry, ...history].slice(0, 30)
setHistory(updated)
safeSetItem('doc-check-history', JSON.stringify(updated))
break
}
if (pollData.status === 'failed') {
throw new Error(pollData.error || 'Pruefung fehlgeschlagen')
}
attempts++
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
setProgress('')
} finally {
setLoading(false)
}
}
const contextReady = isContextComplete(scanContext)
return (
<div className="space-y-4">
{/* P79 Pre-Scan-Wizard — 8 Pflichtfelder */}
<PreScanWizard value={scanContext} onChange={setScanContext} />
{/* URL / Text Entries */}
<div className="space-y-3">
{entries.map((entry, i) => (
<div key={entry.id} className="space-y-1.5">
<div className="flex items-center gap-2">
<select
value={entry.type}
onChange={e => updateEntry(entry.id, 'type', e.target.value)}
className="w-48 px-3 py-2.5 border border-gray-300 rounded-lg text-sm bg-white shrink-0"
>
{DOC_TYPES.map(t => (
<option key={t.id} value={t.id}>{t.label}</option>
))}
</select>
<input
type="text"
value={entry.label}
onChange={e => updateEntry(entry.id, 'label', e.target.value)}
placeholder={entry.type === 'other' ? 'Dokumentname' : 'Version / Stand (optional)'}
className="w-40 px-3 py-2.5 border border-gray-300 rounded-lg text-sm shrink-0"
/>
{/* Mode-Toggle URL / Text */}
<div className="inline-flex border border-gray-300 rounded-lg overflow-hidden text-xs shrink-0">
<button type="button"
onClick={() => updateEntry(entry.id, 'mode', 'url')}
className={`px-3 py-2 ${entry.mode === 'url'
? 'bg-purple-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
URL
</button>
<button type="button"
onClick={() => updateEntry(entry.id, 'mode', 'text')}
className={`px-3 py-2 ${entry.mode === 'text'
? 'bg-purple-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50'}`}>
Text einfügen
</button>
</div>
{entry.mode === 'url' && (
<input
type="url"
value={entry.url}
onChange={e => updateEntry(entry.id, 'url', e.target.value)}
onBlur={() => autoLabel(entry)}
placeholder="https://example.com/datenschutz"
className="flex-1 px-3 py-2.5 border border-gray-300 rounded-lg text-sm"
/>
)}
{entries.length > 1 && (
<button onClick={() => removeEntry(entry.id)}
className="p-2 text-gray-400 hover:text-red-500 shrink-0">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
{entry.mode === 'text' && (
<div className="ml-[400px]">
<textarea
value={entry.text}
onChange={e => updateEntry(entry.id, 'text', e.target.value)}
placeholder={
entry.type === 'cookie'
? 'Kopiere hier die komplette Cookie-Tabelle rein (Tab-getrennt oder mit | als Trenner — wir parsen alle Spalten deterministisch)…'
: 'Kopiere hier den vollständigen Doc-Text rein. Wir erkennen automatisch ob es zu „' + (DOC_TYPES.find(t => t.id === entry.type)?.label ?? entry.type) + '" passt.'
}
className="w-full h-32 px-3 py-2 border border-gray-300 rounded-lg text-xs font-mono resize-y"
/>
<div className="text-[10px] text-gray-500 mt-1">
{entry.text.trim().length > 0
? `${entry.text.trim().length.toLocaleString('de-DE')} Zeichen · ${entry.text.trim().split(/\s+/).length.toLocaleString('de-DE')} Wörter`
: 'Der Crawler wird übersprungen — die Analyse läuft direkt auf dem eingefügten Text.'}
</div>
</div>
)}
</div>
))}
</div>
{/* Add URL + Options */}
<div className="flex items-center justify-between">
<button onClick={addEntry}
className="flex items-center gap-1.5 text-sm text-purple-600 hover:text-purple-700 font-medium">
<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>
URL hinzufuegen
</button>
<label className="flex items-center gap-2 text-sm text-gray-600">
<input
type="checkbox"
checked={checkCookieBanner}
onChange={e => setCheckCookieBanner(e.target.checked)}
className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
/>
Cookie-Banner pruefen
</label>
<button
type="button"
onClick={() => setUseAgent(!useAgent)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
useAgent
? 'bg-emerald-100 border-emerald-300 text-emerald-800'
: 'bg-gray-50 border-gray-200 text-gray-500 hover:bg-gray-100'
}`}
>
<span className={`w-2 h-2 rounded-full ${useAgent ? 'bg-emerald-500' : 'bg-gray-300'}`} />
{useAgent ? 'KI-Agent aktiv (1.874 MCs)' : 'KI-Agent aus'}
</button>
</div>
{/* Submit */}
<button
onClick={handleSubmit}
disabled={loading
|| entries.every(e => !e.url.trim() && !e.text.trim())
|| !contextReady}
className="w-full px-4 py-3 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 disabled:opacity-50 transition-colors text-sm flex items-center justify-center gap-2"
title={!contextReady ? 'Bitte zuerst die 8 Pflichtfelder ausfüllen' : undefined}
>
{loading ? (
<>
<svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
Pruefe...
</>
) : !contextReady ? (
`Klassifizierung unvollständig (8 Pflichtfelder)`
) : (
`${entries.filter(e => e.url.trim()).length} Dokument${entries.filter(e => e.url.trim()).length !== 1 ? 'e' : ''} pruefen`
)}
</button>
{/* Progress */}
{progress && (
<div className="bg-purple-50 border border-purple-200 rounded-lg p-3 text-sm text-purple-700 flex items-center gap-3">
<svg className="animate-spin w-4 h-4 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
{progress}
</div>
)}
{/* Error */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">{error}</div>
)}
{/* Results — als Tab-Ansicht (Übersicht/Cookies/DSE/Impressum/AGB/Banner/Mail) */}
{results && results.results && (
<ResultsTabsView results={results} />
)}
{/* History */}
{history.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Pruefungen</h4>
<div className="space-y-1">
{history.map((h, i) => (
<button key={i} onClick={() => {
if (h.resultKey) {
try {
const saved = localStorage.getItem(h.resultKey)
if (saved) { setResults(JSON.parse(saved)); return }
} catch {}
}
// Fallback: load last result
try {
const last = localStorage.getItem('doc-check-results')
if (last) setResults(JSON.parse(last))
} catch {}
}}
className="w-full flex items-center justify-between text-sm py-2 px-2 rounded-lg border border-gray-50 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left">
<span className="text-gray-600">
{new Date(h.date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
</span>
<div className="flex items-center gap-3">
<span className="text-xs text-gray-500">{h.urls} Dok.</span>
<span className={`text-xs font-medium ${h.findings > 0 ? 'text-amber-600' : 'text-green-600'}`}>
{h.findings} Findings
</span>
</div>
</button>
))}
</div>
</div>
)}
</div>
)
}
@@ -1,163 +0,0 @@
'use client'
import React, { useState, useRef } from 'react'
interface DocumentRowProps {
label: string
docType: string
required?: boolean
url: string
text: string
loading: boolean
error: string | null
wordCount: number
onUrlChange: (url: string) => void
onFetchText: () => void
onTextChange: (text: string) => void
onFileUpload: (file: File) => void
}
export function DocumentRow({
label,
docType,
required,
url,
text,
loading,
error,
wordCount,
onUrlChange,
onFetchText,
onTextChange,
onFileUpload,
}: DocumentRowProps) {
const [showText, setShowText] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
const textVisible = showText || text.length > 0
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
// Read text-based files directly
const reader = new FileReader()
reader.onload = () => {
const content = reader.result as string
onTextChange(content)
}
reader.onerror = () => {
// Let parent handle via onFileUpload for binary formats
onFileUpload(file)
}
if (file.name.endsWith('.txt') || file.type === 'text/plain') {
reader.readAsText(file)
} else {
// PDF, DOCX — pass to parent for server-side parsing
onFileUpload(file)
}
// Reset input so the same file can be re-selected
e.target.value = ''
}
return (
<div className="border border-gray-200 rounded-lg p-3 space-y-2">
{/* Header row: label + inputs */}
<div className="flex items-center gap-2">
<div className="w-52 shrink-0">
<span className="text-sm font-medium text-gray-700">
{label}
{required && <span className="text-red-500 ml-0.5">*</span>}
</span>
</div>
<input
type="url"
value={url}
onChange={e => onUrlChange(e.target.value)}
placeholder="https://example.com/datenschutz"
className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent"
/>
{/* Fetch text button */}
<button
type="button"
onClick={onFetchText}
disabled={loading || !url.trim()}
className="px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap transition-colors"
>
{loading ? (
<svg className="animate-spin w-4 h-4 text-purple-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
'Text laden'
)}
</button>
{/* File upload button */}
<button
type="button"
onClick={() => fileRef.current?.click()}
className="px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50 transition-colors"
title="PDF, DOCX oder TXT hochladen"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
</svg>
</button>
<input
ref={fileRef}
type="file"
accept=".pdf,.docx,.doc,.txt"
onChange={handleFileChange}
className="hidden"
/>
{/* Toggle text area */}
<button
type="button"
onClick={() => setShowText(!showText)}
className={`px-3 py-2 border rounded-lg text-sm transition-colors ${
textVisible
? 'border-purple-300 bg-purple-50 text-purple-700'
: 'border-gray-300 text-gray-700 hover:bg-gray-50'
}`}
title={textVisible ? 'Text ausblenden' : 'Text anzeigen'}
>
<svg className={`w-4 h-4 transition-transform ${textVisible ? 'rotate-180' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{/* Word count badge */}
{wordCount > 0 && (
<span className="text-xs px-2 py-1 rounded-full bg-green-100 text-green-700 font-medium shrink-0">
{wordCount.toLocaleString('de-DE')} W.
</span>
)}
</div>
{/* Error */}
{error && (
<div className="text-xs text-red-600 px-1">{error}</div>
)}
{/* Collapsible textarea */}
{textVisible && (
<textarea
value={text}
onChange={e => onTextChange(e.target.value)}
placeholder="Dokumenttext hier einfuegen oder per URL / Upload laden..."
rows={6}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono resize-y focus:ring-2 focus:ring-purple-500 focus:border-transparent"
/>
)}
</div>
)
}
@@ -1,91 +0,0 @@
'use client'
import React from 'react'
import type { FollowUpQuestion } from '../_hooks/useAgentAnalysis'
const SEVERITY_STYLE: Record<string, { border: string; bg: string; icon: string }> = {
high: { border: 'border-red-300', bg: 'bg-red-50', icon: '!!' },
medium: { border: 'border-yellow-300', bg: 'bg-yellow-50', icon: '!' },
low: { border: 'border-blue-300', bg: 'bg-blue-50', icon: 'i' },
}
interface Props {
questions: FollowUpQuestion[]
answers: Record<string, boolean>
onAnswer: (questionId: string, answer: boolean) => void
}
export function FollowUpQuestions({ questions, answers, onAnswer }: Props) {
const unanswered = questions.filter(q => answers[q.id] === undefined)
const answered = questions.filter(q => answers[q.id] !== undefined)
if (questions.length === 0) return null
return (
<div className="space-y-3">
<h4 className="text-sm font-medium text-gray-700 flex items-center gap-2">
<svg className="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Rueckfragen zur manuellen Pruefung ({unanswered.length} offen)
</h4>
{/* Unanswered questions */}
{unanswered.map(q => {
const style = SEVERITY_STYLE[q.severity] || SEVERITY_STYLE.medium
return (
<div key={q.id} className={`border ${style.border} ${style.bg} rounded-lg p-4`}>
<div className="flex items-start gap-3">
<span className={`mt-0.5 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${
q.severity === 'high' ? 'bg-red-200 text-red-800' :
q.severity === 'medium' ? 'bg-yellow-200 text-yellow-800' :
'bg-blue-200 text-blue-800'
}`}>
{SEVERITY_STYLE[q.severity]?.icon || '?'}
</span>
<div className="flex-1">
<p className="text-sm font-medium text-gray-900">{q.question}</p>
<p className="text-xs text-gray-500 mt-1">Rechtsgrundlage: {q.legal_basis}</p>
<div className="flex gap-2 mt-3">
<button
onClick={() => onAnswer(q.id, true)}
className="px-4 py-1.5 text-sm bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
>
Ja
</button>
<button
onClick={() => onAnswer(q.id, false)}
className="px-4 py-1.5 text-sm bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
>
Nein
</button>
</div>
</div>
</div>
</div>
)
})}
{/* Answered questions */}
{answered.map(q => {
const isYes = answers[q.id]
return (
<div key={q.id} className={`border rounded-lg p-3 ${isYes ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}`}>
<div className="flex items-center gap-2">
<span className={`text-sm ${isYes ? 'text-green-700' : 'text-red-700'}`}>
{isYes ? '✓' : '✗'}
</span>
<span className="text-sm text-gray-700">{q.question}</span>
<span className={`ml-auto text-xs font-medium ${isYes ? 'text-green-600' : 'text-red-600'}`}>
{isYes ? 'Ja — OK' : 'Nein — Finding erstellt'}
</span>
</div>
{!isYes && (
<p className="text-xs text-red-600 mt-1 ml-6">{q.finding_if_no}</p>
)}
</div>
)
})}
</div>
)
}
@@ -1,181 +0,0 @@
'use client'
import React, { useState } from 'react'
import { ChecklistView } from './ChecklistView'
interface CheckItem {
id: string; label: string; passed: boolean; severity: string
matched_text: string; level?: number; parent?: string | null
skipped?: boolean; hint?: string
}
export function ImpressumCheckTab() {
const [url, setUrl] = useState(() =>
typeof window !== 'undefined' ? localStorage.getItem('impressum-check-url') || '' : ''
)
const [loading, setLoading] = useState(false)
const [progress, setProgress] = useState('')
const [error, setError] = useState<string | null>(null)
const [results, setResults] = useState<any>(() => {
if (typeof window === 'undefined') return null
try { const s = localStorage.getItem('impressum-check-results'); return s ? JSON.parse(s) : null } catch { return null }
})
const [history, setHistory] = useState<{ url: string; date: string; findings: number; pct: number; resultKey: string }[]>(() => {
if (typeof window === 'undefined') return []
try { return JSON.parse(localStorage.getItem('impressum-check-history') || '[]') } catch { return [] }
})
const [useAgent, setUseAgent] = useState(false)
React.useEffect(() => { localStorage.setItem('impressum-check-url', url) }, [url])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!url.trim()) return
setLoading(true)
setError(null)
setResults(null)
setProgress('Impressum wird geprueft...')
try {
const startRes = await fetch('/api/sdk/v1/agent/doc-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
entries: [{ doc_type: 'impressum', label: 'Impressum', url: url.trim() }],
recipient: 'dsb@breakpilot.local',
use_agent: useAgent,
}),
})
if (!startRes.ok) throw new Error(`Fehler: ${startRes.status}`)
const { check_id } = await startRes.json()
if (!check_id) throw new Error('Keine Check-ID erhalten')
let attempts = 0
while (attempts < 120) {
await new Promise(r => setTimeout(r, 3000))
const pollRes = await fetch(`/api/sdk/v1/agent/doc-check?check_id=${check_id}`)
if (!pollRes.ok) { attempts++; continue }
const pollData = await pollRes.json()
if (pollData.progress) setProgress(pollData.progress)
if (pollData.status === 'completed' && pollData.result) {
setResults(pollData.result)
setProgress('')
localStorage.setItem('impressum-check-results', JSON.stringify(pollData.result))
const resultKey = `impressum-result-${Date.now()}`
try { localStorage.setItem(resultKey, JSON.stringify(pollData.result)) } catch {}
const total = pollData.result.total_findings || 0
const pct = pollData.result.results?.[0]?.completeness_pct || 0
const entry = { url: url.trim(), date: new Date().toISOString(), findings: total, pct, resultKey }
const updated = [entry, ...history].slice(0, 30)
setHistory(updated)
localStorage.setItem('impressum-check-history', JSON.stringify(updated))
break
}
if (pollData.status === 'failed') throw new Error(pollData.error || 'Pruefung fehlgeschlagen')
attempts++
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
setProgress('')
} finally {
setLoading(false)
}
}
return (
<div className="space-y-4">
<div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
<h3 className="text-sm font-semibold text-amber-900">Impressum-Check (§5 TMG / §18 MStV)</h3>
<p className="text-xs text-amber-700 mt-1">
Prueft 16 Pflichtangaben: Anbietername, Anschrift, Kontaktdaten, Handelsregister,
USt-IdNr., Vertretungsberechtigte, V.i.S.d.P., Streitbeilegung.
</p>
</div>
<div className="flex items-center gap-3">
<button type="button" onClick={() => setUseAgent(!useAgent)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
useAgent ? 'bg-emerald-100 border-emerald-300 text-emerald-800' : 'bg-gray-50 border-gray-200 text-gray-500 hover:bg-gray-100'
}`}>
<span className={`w-2 h-2 rounded-full ${useAgent ? 'bg-emerald-500' : 'bg-gray-300'}`} />
{useAgent ? 'KI-Agent aktiv (75 MCs)' : 'KI-Agent aus'}
</button>
</div>
<form onSubmit={handleSubmit} className="flex gap-3">
<input type="url" value={url} onChange={e => setUrl(e.target.value)}
placeholder="https://www.example.com/impressum"
className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
disabled={loading} required />
<button type="submit" disabled={loading || !url.trim()}
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors flex items-center gap-2 text-sm font-medium whitespace-nowrap">
{loading ? (
<><svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>Pruefe...</>
) : 'Impressum pruefen'}
</button>
</form>
{progress && (
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4 text-sm text-purple-700 flex items-center gap-3">
<svg className="animate-spin w-5 h-5 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
{progress}
</div>
)}
{error && <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700">{error}</div>}
{results?.results && (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
<ChecklistView results={results.results} />
{results.email_status && (
<div className="mt-3 text-xs text-gray-500 flex items-center gap-2">
<span className={`w-2 h-2 rounded-full ${results.email_status === 'sent' ? 'bg-green-400' : 'bg-gray-300'}`} />
E-Mail: {results.email_status === 'sent' ? 'Gesendet' : results.email_status}
</div>
)}
</div>
)}
{history.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Impressum-Checks</h4>
<div className="space-y-1">
{history.map((h, i) => (
<button key={i} onClick={() => {
setUrl(h.url)
if (h.resultKey) {
try { const s = localStorage.getItem(h.resultKey); if (s) { setResults(JSON.parse(s)); return } } catch {}
}
try { const l = localStorage.getItem('impressum-check-results'); if (l) setResults(JSON.parse(l)) } catch {}
}}
className="w-full flex items-center justify-between p-2.5 rounded-lg border border-gray-100 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left">
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-gray-900 truncate">{h.url}</div>
<div className="text-xs text-gray-500">
{new Date(h.date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
</div>
</div>
<div className="flex items-center gap-3 shrink-0 ml-3">
<span className={`text-xs font-medium ${h.findings > 0 ? 'text-red-600' : 'text-green-600'}`}>
{h.findings} Findings
</span>
<span className={`text-xs font-medium ${h.pct === 100 ? 'text-green-700' : h.pct >= 50 ? 'text-yellow-700' : 'text-red-700'}`}>
{h.pct}%
</span>
</div>
</button>
))}
</div>
</div>
)}
</div>
)
}
@@ -1,194 +0,0 @@
'use client'
import { useState } from 'react'
interface BannerFlag {
level: 'ERROR' | 'WARNING' | 'INFO'
vendor: string
issue: string
message: string
}
interface BannerPreview {
config: { categories: { id: string; cookies: { name: string }[] }[] }
flags: BannerFlag[]
summary: {
vendors_total: number
vendors_with_no_cookies: number
cookies_total: number
categories: Record<string, number>
flags_error: number
flags_warning: number
flags_info: number
}
}
interface DocumentPreview {
check_id: string
vendor_count: number
templates: Record<string, {
templateType: string
initialContent: string
suggested_template_search?: string
}>
}
type Mode = 'banner' | 'documents'
export function MigrationPanel({ checkId }: { checkId: string }) {
const [open, setOpen] = useState(false)
const [mode, setMode] = useState<Mode>('banner')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [banner, setBanner] = useState<BannerPreview | null>(null)
const [docs, setDocs] = useState<DocumentPreview | null>(null)
async function loadPreview(next: Mode) {
setMode(next)
setOpen(true)
setError(null)
setLoading(true)
try {
const path = next === 'banner'
? `/api/sdk/v1/agent/migration/${checkId}/banner-preview`
: `/api/sdk/v1/agent/migration/${checkId}/document-preview`
const r = await fetch(path)
if (!r.ok) throw new Error(`HTTP ${r.status}`)
const data = await r.json()
if (next === 'banner') setBanner(data)
else setDocs(data)
} catch (e) {
setError(e instanceof Error ? e.message : 'Preview-Ladefehler')
} finally {
setLoading(false)
}
}
return (
<>
<div className="mt-3 flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-2">
<button onClick={() => loadPreview('banner')}
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-purple-50 text-purple-700 border border-purple-200 hover:bg-purple-100">
Cookie-Banner uebernehmen
</button>
<button onClick={() => loadPreview('documents')}
className="px-3 py-1.5 text-xs font-medium rounded-lg bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100">
Dokumente vorbefuellen
</button>
</div>
<a href={`/sdk/agent/audit/${checkId}`} target="_blank" rel="noopener"
className="text-xs text-blue-700 hover:text-blue-900 underline">
Voll-Audit oeffnen (alle MCs) &rarr;
</a>
</div>
{open && (
<div className="fixed inset-0 z-50 bg-black/40 flex items-start justify-center p-6 overflow-y-auto">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl p-6 mt-12">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-900">
{mode === 'banner' ? 'Cookie-Banner Migration' : 'Dokument-Vorbefuellung'}
</h3>
<button onClick={() => setOpen(false)}
className="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
</div>
{loading && <div className="text-sm text-gray-500">Lade Preview ...</div>}
{error && <div className="text-sm text-red-600">Fehler: {error}</div>}
{!loading && !error && mode === 'banner' && banner && (
<BannerPreviewBody data={banner} />
)}
{!loading && !error && mode === 'documents' && docs && (
<DocumentPreviewBody data={docs} />
)}
<div className="mt-5 flex justify-end gap-2">
<button onClick={() => setOpen(false)}
className="px-3 py-1.5 text-sm rounded-lg border border-gray-200 hover:bg-gray-50">
Schliessen
</button>
<a href={mode === 'banner' ? '/sdk/einwilligungen' : '/sdk/document-generator'}
className="px-3 py-1.5 text-sm rounded-lg bg-purple-600 text-white hover:bg-purple-700">
Im Editor oeffnen
</a>
</div>
</div>
</div>
)}
</>
)
}
function BannerPreviewBody({ data }: { data: BannerPreview }) {
const { summary, flags, config } = data
return (
<div className="space-y-4 text-sm">
<div className="grid grid-cols-3 gap-3">
<Stat label="Anbieter" value={summary.vendors_total} />
<Stat label="Cookies" value={summary.cookies_total} />
<Stat label="Kategorien" value={Object.values(summary.categories).filter(n => n > 0).length} />
</div>
<div className="grid grid-cols-3 gap-3">
<Stat label="Fehler" value={summary.flags_error} tone="red" />
<Stat label="Warnungen" value={summary.flags_warning} tone="amber" />
<Stat label="Hinweise" value={summary.flags_info} tone="gray" />
</div>
<div>
<h4 className="font-medium text-gray-700 mb-1">Kategorien</h4>
<ul className="text-xs text-gray-600 space-y-0.5">
{config.categories.map(c => (
<li key={c.id}>{c.id}: {c.cookies.length} Cookie(s)</li>
))}
</ul>
</div>
{flags.length > 0 && (
<div>
<h4 className="font-medium text-gray-700 mb-1">Pruefpunkte</h4>
<ul className="text-xs space-y-0.5 max-h-48 overflow-y-auto">
{flags.map((f, i) => (
<li key={i} className={f.level === 'ERROR' ? 'text-red-700' : f.level === 'WARNING' ? 'text-amber-700' : 'text-gray-600'}>
[{f.level}] {f.vendor}: {f.message}
</li>
))}
</ul>
</div>
)}
</div>
)
}
function DocumentPreviewBody({ data }: { data: DocumentPreview }) {
return (
<div className="space-y-4 text-sm">
<div className="text-xs text-gray-600">
{data.vendor_count} Anbieter werden in {Object.keys(data.templates).length} Vorlagen eingespielt.
</div>
{Object.entries(data.templates).map(([key, tpl]) => (
<div key={key} className="border border-gray-200 rounded-lg p-3">
<div className="flex items-center justify-between mb-2">
<h4 className="font-medium text-gray-800">{tpl.templateType}</h4>
{tpl.suggested_template_search && (
<span className="text-xs text-gray-500">Vorschlag: {tpl.suggested_template_search}</span>
)}
</div>
<pre className="text-xs bg-gray-50 rounded p-2 max-h-48 overflow-auto whitespace-pre-wrap">
{tpl.initialContent.slice(0, 1200)}{tpl.initialContent.length > 1200 ? '\n…' : ''}
</pre>
</div>
))}
</div>
)
}
function Stat({ label, value, tone = 'gray' }: { label: string; value: number; tone?: 'red' | 'amber' | 'gray' }) {
const color = tone === 'red' ? 'text-red-700' : tone === 'amber' ? 'text-amber-700' : 'text-gray-800'
return (
<div className="border border-gray-200 rounded-lg p-2 text-center">
<div className={`text-lg font-semibold ${color}`}>{value}</div>
<div className="text-xs text-gray-500">{label}</div>
</div>
)
}
@@ -1,269 +0,0 @@
'use client'
/**
* P79 Pre-Scan-Wizard (8 Pflichtfelder).
*
* 8 Pflichtfelder die vor dem Lauf abgefragt werden. Werte landen im
* scan_context und filtern später die MC-Auswertung (zusammen mit P72
* scope_doc_type + applicable_industries). Erwartete Noise-Reduktion:
* 70-80% bei falsch zugeordneten HIGH-MCs.
*/
import React, { useState, useEffect } from 'react'
export interface ScanContext {
industry: string
business_model: string
direct_sales: string
legal_form: string
group_structure: string
employee_count: string
special_data: string[]
third_country_transfer: string
}
const INDUSTRIES = [
{ id: '', label: '— bitte wählen —' },
{ id: 'automotive', label: 'Automotive / OEM' },
{ id: 'ecommerce', label: 'E-Commerce / Online-Handel' },
{ id: 'saas', label: 'SaaS / Software' },
{ id: 'banking', label: 'Banking / Finance' },
{ id: 'insurance', label: 'Insurance / Versicherung' },
{ id: 'healthcare', label: 'Healthcare / Gesundheit' },
{ id: 'education', label: 'Bildung / Schule' },
{ id: 'public', label: 'Öffentliche Verwaltung' },
{ id: 'manufacturing', label: 'Industrie / Manufacturing' },
{ id: 'media', label: 'Medien / Verlag' },
{ id: 'other', label: 'Sonstige' },
]
const LEGAL_FORMS = [
{ id: '', label: '— bitte wählen —' },
{ id: 'ag', label: 'AG (Aktiengesellschaft)' },
{ id: 'gmbh', label: 'GmbH' },
{ id: 'gmbh_co_kg', label: 'GmbH & Co. KG' },
{ id: 'kg', label: 'KG' },
{ id: 'ohg', label: 'OHG' },
{ id: 'ug', label: 'UG (haftungsbeschränkt)' },
{ id: 'ek', label: 'e.K. / Einzelunternehmen' },
{ id: 'verein', label: 'Verein' },
{ id: 'stiftung', label: 'Stiftung' },
{ id: 'behoerde', label: 'Behörde / Körperschaft öff. Rechts' },
{ id: 'other', label: 'Sonstige' },
]
const GROUP_STRUCTURES = [
{ id: '', label: '— bitte wählen —' },
{ id: 'standalone', label: 'Eigenständig' },
{ id: 'parent', label: 'Konzern-Mutter' },
{ id: 'subsidiary', label: 'Konzern-Tochter' },
{ id: 'joint_venture', label: 'Joint Venture' },
{ id: 'processor', label: 'Reiner Auftragsverarbeiter' },
]
const EMPLOYEE_COUNTS = [
{ id: '', label: '— bitte wählen —' },
{ id: 'lt10', label: 'unter 10' },
{ id: '10_19', label: '10-19' },
{ id: '20_49', label: '20-49 (DSB ab 20 Pflicht)' },
{ id: '50_249', label: '50-249 (Whistleblower-Pflicht)' },
{ id: '250_499', label: '250-499' },
{ id: '500_999', label: '500-999' },
{ id: '1000_plus', label: '1.000+ (Konzern)' },
]
const SPECIAL_DATA_OPTIONS = [
{ id: 'health', label: 'Gesundheitsdaten' },
{ id: 'biometric', label: 'Biometrische Daten' },
{ id: 'ethnicity', label: 'Religiöse / ethnische Herkunft' },
{ id: 'sexual', label: 'Sexuelle Orientierung' },
{ id: 'criminal', label: 'Strafrechtliche Daten' },
{ id: 'minors', label: 'Minderjährige (<16)' },
{ id: 'none', label: 'Keine besonderen Daten' },
]
const STORAGE_KEY = 'compliance-scan-context'
function emptyContext(): ScanContext {
return {
industry: '',
business_model: '',
direct_sales: '',
legal_form: '',
group_structure: '',
employee_count: '',
special_data: [],
third_country_transfer: '',
}
}
export function isContextComplete(ctx: ScanContext): boolean {
return Boolean(
ctx.industry &&
ctx.business_model &&
ctx.direct_sales &&
ctx.legal_form &&
ctx.group_structure &&
ctx.employee_count &&
ctx.special_data.length > 0 &&
ctx.third_country_transfer
)
}
export function PreScanWizard({
value,
onChange,
}: {
value: ScanContext
onChange: (ctx: ScanContext) => void
}) {
const update = <K extends keyof ScanContext>(key: K, val: ScanContext[K]) => {
onChange({ ...value, [key]: val })
}
const toggleSpecialData = (id: string) => {
const next = value.special_data.includes(id)
? value.special_data.filter(x => x !== id)
: [...value.special_data.filter(x => x !== 'none' || id === 'none'), id]
onChange({ ...value, special_data: id === 'none' ? ['none'] : next.filter(x => x !== 'none') })
}
return (
<div style={{
background: '#f0f9ff',
border: '1px solid #bfdbfe',
borderRadius: 8,
padding: '14px 16px',
marginBottom: 14,
}}>
<div style={{ fontSize: 11, color: '#1e40af', textTransform: 'uppercase',
letterSpacing: 1.2, marginBottom: 4, fontWeight: 600 }}>
Pflichtangaben zur Klassifizierung des Audits
</div>
<h3 style={{ margin: '0 0 6px', fontSize: 14, color: '#1e293b' }}>
Vor dem Scan: 8 Angaben zum Unternehmen
</h3>
<p style={{ margin: '0 0 12px', fontSize: 11, color: '#475569', lineHeight: 1.5 }}>
Diese Angaben filtern irrelevante Compliance-Themen heraus (z.B. eHealth-
Vorschriften bei einem Autobauer) und liefern eine realistische
Einschätzung statt pauschaler Verstoss-Listen.
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
<Field label="1. Branche*">
<select value={value.industry} onChange={e => update('industry', e.target.value)} style={inputStyle}>
{INDUSTRIES.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</Field>
<Field label="2. Geschäftsmodell*">
<select value={value.business_model} onChange={e => update('business_model', e.target.value)} style={inputStyle}>
<option value=""> bitte wählen </option>
<option value="b2b">B2B</option>
<option value="b2c">B2C</option>
<option value="both">Beides (B2B + B2C)</option>
</select>
</Field>
<Field label="3. Direkt-Vertrieb (Webshop/Buchung)*">
<select value={value.direct_sales} onChange={e => update('direct_sales', e.target.value)} style={inputStyle}>
<option value=""> bitte wählen </option>
<option value="yes">Ja</option>
<option value="no">Nein</option>
<option value="lead_funnel">Nur Lead-Funnel (Probefahrten, Anfragen)</option>
</select>
</Field>
<Field label="4. Rechtsform*">
<select value={value.legal_form} onChange={e => update('legal_form', e.target.value)} style={inputStyle}>
{LEGAL_FORMS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</Field>
<Field label="5. Konzern-Struktur*">
<select value={value.group_structure} onChange={e => update('group_structure', e.target.value)} style={inputStyle}>
{GROUP_STRUCTURES.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</Field>
<Field label="6. Mitarbeiterzahl*">
<select value={value.employee_count} onChange={e => update('employee_count', e.target.value)} style={inputStyle}>
{EMPLOYEE_COUNTS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</Field>
<Field label="7. Besondere Datenkategorien*" colSpan={2}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{SPECIAL_DATA_OPTIONS.map(o => (
<label key={o.id} style={{ fontSize: 12, display: 'inline-flex',
alignItems: 'center', gap: 4,
padding: '4px 8px', background: '#fff',
border: '1px solid #cbd5e1',
borderRadius: 4 }}>
<input type="checkbox"
checked={value.special_data.includes(o.id)}
onChange={() => toggleSpecialData(o.id)} />
{o.label}
</label>
))}
</div>
</Field>
<Field label="8. Bekannter Drittland-Transfer*" colSpan={2}>
<select value={value.third_country_transfer} onChange={e => update('third_country_transfer', e.target.value)} style={inputStyle}>
<option value=""> bitte wählen </option>
<option value="yes">Ja (USA, CN, IN, UK, ...)</option>
<option value="no">Nein (nur EU/EWR)</option>
<option value="unknown">Weiß nicht (bitte automatisch prüfen)</option>
</select>
</Field>
</div>
{!isContextComplete(value) && (
<div style={{ marginTop: 10, fontSize: 11, color: '#92400e',
background: '#fef3c7', padding: '6px 10px',
borderRadius: 4, border: '1px solid #fde68a' }}>
Bitte alle 8 Pflichtfelder ausfüllen der Scan-Button wird erst aktiv,
wenn die Klassifizierung komplett ist.
</div>
)}
</div>
)
}
const inputStyle: React.CSSProperties = {
width: '100%',
padding: '6px 8px',
fontSize: 12,
border: '1px solid #cbd5e1',
borderRadius: 4,
background: '#fff',
}
function Field({ label, children, colSpan }: { label: string; children: React.ReactNode; colSpan?: number }) {
return (
<div style={{ gridColumn: colSpan ? `span ${colSpan}` : undefined }}>
<label style={{ display: 'block', fontSize: 11, color: '#475569',
marginBottom: 4, fontWeight: 600 }}>
{label}
</label>
{children}
</div>
)
}
export function useScanContext(): [ScanContext, (ctx: ScanContext) => void] {
const [ctx, setCtx] = useState<ScanContext>(() => {
if (typeof window === 'undefined') return emptyContext()
try {
const s = localStorage.getItem(STORAGE_KEY)
return s ? { ...emptyContext(), ...JSON.parse(s) } : emptyContext()
} catch {
return emptyContext()
}
})
useEffect(() => {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(ctx)) } catch {}
}, [ctx])
return [ctx, setCtx]
}
@@ -1,353 +0,0 @@
'use client'
/**
* ResultsTabsView strukturierte Tab-Ansicht der Audit-Ergebnisse.
*
* Statt einer langen Scroll-Seite gibt es:
* 1. Übersicht (Score + GF-Kurzfassung)
* 2. Cookies (3-Quellen-Compliance-Vergleich + Vendor-/Cookie-Listen)
* 3. Datenschutzerklärung
* 4. Impressum
* 5. AGB / Widerruf
* 6. Banner (Cookie-Banner-Checks)
* 7. Vollständige Mail (HTML-Preview)
*
* Tab-Headers sticky oben, Content scrollbar unten.
*/
import React, { useState, useMemo } from 'react'
import { ChecklistView } from './ChecklistView'
interface ResultsTabsViewProps {
results: any
}
type TabId = 'overview' | 'cookies' | 'dse' | 'impressum' | 'agb' | 'banner' | 'mail'
const TABS: { id: TabId; label: string; icon: string }[] = [
{ id: 'overview', label: 'Übersicht', icon: '◉' },
{ id: 'cookies', label: 'Cookies & VVT', icon: '🍪' },
{ id: 'dse', label: 'Datenschutzerkl.', icon: '📄' },
{ id: 'impressum', label: 'Impressum', icon: '🏢' },
{ id: 'agb', label: 'AGB / Widerruf', icon: '⚖️' },
{ id: 'banner', label: 'Cookie-Banner', icon: '🎛' },
{ id: 'mail', label: 'Mail-Vorschau', icon: '✉️' },
]
export function ResultsTabsView({ results }: ResultsTabsViewProps) {
const [active, setActive] = useState<TabId>('overview')
const r = results || {}
const docs: any[] = r.results || []
const banner = r.banner_result || r.cookie_banner_result || {}
const cmpVendors: any[] = r.cmp_vendors || []
const cookieAudit = r.cookie_audit || {}
const docsByType = useMemo(() => {
const m: Record<string, any> = {}
for (const d of docs) {
const t = (d.doc_type || '').toLowerCase()
if (!m[t]) m[t] = d
}
return m
}, [docs])
return (
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white">
{/* Sticky Tab-Header */}
<div className="flex border-b border-gray-200 bg-gray-50 overflow-x-auto sticky top-0 z-10">
{TABS.map(t => (
<button
key={t.id}
onClick={() => setActive(t.id)}
className={`px-4 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
active === t.id
? 'border-purple-600 text-purple-700 bg-white'
: 'border-transparent text-gray-600 hover:bg-gray-100'
}`}
>
<span className="mr-1.5">{t.icon}</span>
{t.label}
</button>
))}
</div>
{/* Tab-Content */}
<div className="p-4 min-h-[400px]">
{active === 'overview' && <OverviewTab results={r} />}
{active === 'cookies' && (
<CookiesTab
audit={cookieAudit}
vendors={cmpVendors}
banner={banner}
/>
)}
{active === 'dse' && <DocTab doc={docsByType['dse']} label="Datenschutzerklärung" />}
{active === 'impressum' && <DocTab doc={docsByType['impressum']} label="Impressum" />}
{active === 'agb' && <AgbWiderrufTab docs={docsByType} />}
{active === 'banner' && <BannerTab banner={banner} />}
{active === 'mail' && <MailPreviewTab results={r} />}
</div>
</div>
)
}
// ── Übersicht ──────────────────────────────────────────────────────────
function OverviewTab({ results }: { results: any }) {
const totalDocs = results.total_documents || (results.results?.length ?? 0)
const totalFindings = results.total_findings ?? 0
const banner = results.banner_result || results.cookie_banner_result || {}
const score = banner.compliance_score ?? banner.completeness_pct ?? null
const emailStatus = results.email_status
return (
<div className="space-y-4">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Kpi label="Geprüfte Dokumente" value={totalDocs} />
<Kpi label="Findings gesamt" value={totalFindings} tone={totalFindings > 5 ? 'warn' : 'ok'} />
<Kpi label="Vendors erkannt" value={results.cmp_vendors?.length || 0} />
<Kpi label="Score" value={score !== null ? `${score}%` : '—'}
tone={score === null ? 'neutral' : score >= 80 ? 'ok' : score >= 60 ? 'warn' : 'bad'} />
</div>
{emailStatus && (
<div className={`text-sm px-3 py-2 rounded ${
emailStatus === 'sent' ? 'bg-green-50 text-green-800' : 'bg-gray-100 text-gray-700'
}`}>
E-Mail: {emailStatus === 'sent' ? '✓ Gesendet an Empfänger' : emailStatus}
</div>
)}
<div className="bg-blue-50 border border-blue-200 rounded p-3 text-xs text-blue-900">
<strong>Wo welcher Inhalt steckt:</strong> in den Tabs oben findest du die
Detail-Auswertung pro Doc-Typ. Im Cookie-Tab steht der 3-Quellen-Compliance-
Vergleich (deklariert vs Browser vs Library) das ist der wichtigste
rechtliche Knackpunkt. Banner-Tab zeigt die echten Browser-Phasen-Checks.
</div>
</div>
)
}
function Kpi({ label, value, tone = 'neutral' }: { label: string; value: any; tone?: string }) {
const colors: Record<string, string> = {
ok: 'text-green-700 bg-green-50 border-green-200',
warn: 'text-amber-700 bg-amber-50 border-amber-200',
bad: 'text-red-700 bg-red-50 border-red-200',
neutral: 'text-gray-700 bg-gray-50 border-gray-200',
}
return (
<div className={`border rounded p-3 ${colors[tone]}`}>
<div className="text-[10px] uppercase tracking-wider opacity-70">{label}</div>
<div className="text-2xl font-bold mt-1">{value}</div>
</div>
)
}
// ── Cookies & VVT ──────────────────────────────────────────────────────
function CookiesTab({ audit, vendors, banner }: { audit: any; vendors: any[]; banner: any }) {
const declared = audit?.declared_count ?? 0
const browser = audit?.browser_count ?? 0
const both = (audit?.compliant ?? []).length
const undecl = (audit?.undeclared_in_browser ?? []).length
const decOnly = (audit?.declared_not_loaded ?? []).length
return (
<div className="space-y-4">
{/* Top-Bar mit Counts */}
<div className="grid grid-cols-3 md:grid-cols-5 gap-2">
<Kpi label="Deklariert" value={declared} />
<Kpi label="Im Browser" value={browser} />
<Kpi label="Compliant" value={both} tone="ok" />
<Kpi label="Undokumentiert" value={undecl} tone={undecl > 0 ? 'bad' : 'ok'} />
<Kpi label="Nicht geladen" value={decOnly} tone={decOnly > 0 ? 'warn' : 'neutral'} />
</div>
{/* 3-Spalten-Vergleichstabelle */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<CookieColumn
title={`❌ Undokumentiert (${undecl})`}
tone="bad"
subtitle="Geladen ABER nicht in der Richtlinie — Art. 13(1)(c) DSGVO Verstoß"
cookies={audit?.undeclared_in_browser ?? []}
/>
<CookieColumn
title={`✓ Compliant (${both})`}
tone="ok"
subtitle="Beide Quellen stimmen überein"
cookies={audit?.compliant ?? []}
/>
<CookieColumn
title={`⚠️ Nicht geladen (${decOnly})`}
tone="warn"
subtitle="In Richtlinie deklariert, aber bei diesem Lauf nicht im Browser"
cookies={audit?.declared_not_loaded ?? []}
/>
</div>
{/* Vendor-Liste (deduped) */}
<div>
<h3 className="text-sm font-semibold mb-2 text-gray-800">
Vendor-Liste ({vendors.length} unique nach Deduplizierung)
</h3>
<div className="overflow-x-auto border border-gray-200 rounded">
<table className="w-full text-xs">
<thead className="bg-gray-50">
<tr>
<th className="text-left px-3 py-2">Vendor</th>
<th className="text-left px-3 py-2">Kategorie</th>
<th className="text-left px-3 py-2">Quelle</th>
<th className="text-right px-3 py-2">Cookies</th>
</tr>
</thead>
<tbody>
{vendors.map((v, i) => (
<tr key={i} className="border-t border-gray-100 hover:bg-gray-50">
<td className="px-3 py-2 font-medium">{v.name}</td>
<td className="px-3 py-2 text-gray-600">{v.category || '—'}</td>
<td className="px-3 py-2 text-gray-500 font-mono text-[10px]">
{v.source || '—'}
</td>
<td className="px-3 py-2 text-right">{(v.cookies || []).length}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)
}
function CookieColumn({ title, tone, subtitle, cookies }: {
title: string; tone: string; subtitle: string; cookies: string[]
}) {
const colors: Record<string, string> = {
bad: 'bg-red-50 border-red-200 text-red-900',
ok: 'bg-green-50 border-green-200 text-green-900',
warn: 'bg-amber-50 border-amber-200 text-amber-900',
}
return (
<div className={`border rounded p-3 ${colors[tone]}`}>
<div className="text-xs font-semibold mb-1">{title}</div>
<div className="text-[10px] opacity-80 mb-2">{subtitle}</div>
<div className="font-mono text-[10px] max-h-56 overflow-auto">
{cookies.length === 0 && <span className="opacity-60"> keine </span>}
{cookies.map((c, i) => (
<div key={i} className="py-0.5">{c}</div>
))}
</div>
</div>
)
}
// ── Generic Doc-Tab ────────────────────────────────────────────────────
function DocTab({ doc, label }: { doc: any; label: string }) {
if (!doc) return <Empty label={label} />
const checks = doc.checks || []
const failed = checks.filter((c: any) => !c.passed && !c.skipped)
const passed = checks.filter((c: any) => c.passed)
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold">{label}</h3>
<div className="text-xs text-gray-600">
{doc.word_count?.toLocaleString('de-DE') || 0} Wörter ·{' '}
<span className="text-red-600">{failed.length} Findings</span> ·{' '}
<span className="text-green-600">{passed.length} OK</span>
</div>
</div>
{doc.url && (
<a href={doc.url} target="_blank" rel="noreferrer"
className="text-xs text-blue-600 hover:underline break-all">
{doc.url}
</a>
)}
<ChecklistView results={[doc]} />
</div>
)
}
function AgbWiderrufTab({ docs }: { docs: Record<string, any> }) {
const agb = docs['agb'] || docs['nutzungsbedingungen']
const wid = docs['widerruf']
return (
<div className="space-y-6">
<div>
<h3 className="text-sm font-semibold mb-2">AGB / Nutzungsbedingungen</h3>
{agb ? <ChecklistView results={[agb]} /> : <Empty label="AGB" inline />}
</div>
<div>
<h3 className="text-sm font-semibold mb-2">Widerrufsbelehrung</h3>
{wid ? <ChecklistView results={[wid]} /> : <Empty label="Widerruf" inline />}
</div>
</div>
)
}
function BannerTab({ banner }: { banner: any }) {
if (!banner || Object.keys(banner).length === 0) return <Empty label="Cookie-Banner" />
const phases = banner.phases || {}
const violations = banner.banner_checks?.violations || []
return (
<div className="space-y-3">
<div className="text-xs text-gray-700">
Banner erkannt: <strong>{banner.banner_detected ? 'Ja' : 'Nein'}</strong> ·{' '}
Provider: <strong>{banner.banner_provider || '—'}</strong> ·{' '}
Verstöße: <strong>{violations.length}</strong>
</div>
{violations.length > 0 && (
<div className="border border-red-200 bg-red-50 rounded p-3">
<div className="text-xs font-semibold text-red-800 mb-2">Verstöße</div>
<ul className="text-xs text-red-900 space-y-1">
{violations.map((v: any, i: number) => (
<li key={i}> {v.label || v.message || JSON.stringify(v)}</li>
))}
</ul>
</div>
)}
<div className="grid grid-cols-3 gap-2">
{Object.entries(phases).map(([name, ph]: [string, any]) => (
<div key={name} className="border border-gray-200 rounded p-2">
<div className="text-[10px] uppercase text-gray-500">{name}</div>
<div className="text-xs mt-1">
Cookies: <strong>{ph.cookies?.length || 0}</strong>
</div>
<div className="text-xs">
Vendors: <strong>{ph.vendors?.length || 0}</strong>
</div>
</div>
))}
</div>
</div>
)
}
function MailPreviewTab({ results }: { results: any }) {
return (
<div className="text-xs text-gray-600 space-y-2">
<p>
Die vollständige Mail wurde {results.email_status === 'sent' ? 'gesendet' : 'erstellt'}.
Snapshot-ID:{' '}
<code className="bg-gray-100 px-1.5 py-0.5 rounded">{results.check_id || '—'}</code>
</p>
{results.check_id && (
<a
href={`/api/compliance/agent/snapshots/${results.check_id}/pdf`}
target="_blank" rel="noreferrer"
className="inline-block text-purple-600 hover:underline"
>
PDF der Mail herunterladen
</a>
)}
</div>
)
}
function Empty({ label, inline }: { label: string; inline?: boolean }) {
return (
<div className={`text-xs text-gray-500 ${inline ? '' : 'py-8 text-center'}`}>
Keine Daten für {label}" in diesem Lauf.
</div>
)
}
@@ -1,317 +0,0 @@
'use client'
import React, { useState } from 'react'
import { TextReference } from './TextReference'
interface ServiceInfo {
name: string
category: string
provider: string
country: string
eu_adequate: boolean
requires_consent: boolean
legal_ref: string
in_dse: boolean
status: string
}
interface TextRef {
found: boolean
source_url: string
document_type: string
section_heading: string
section_number: string
parent_section: string
paragraph_index: number
original_text: string
issue: string
correction_type: string
correction_text: string
insert_after: string
}
interface ScanFinding {
code: string
severity: string
text: string
correction: string
text_reference: TextRef | null
}
interface ScanData {
pages_scanned: number
pages_list: string[]
services: ServiceInfo[]
findings: ScanFinding[]
discovered_documents?: DiscoveredDocument[]
ai_detected: boolean
chatbot_detected: boolean
chatbot_provider: string
missing_pages: Record<string, number>
email_status: string
}
const STATUS_ICON: Record<string, { icon: string; color: string }> = {
ok: { icon: '\u2713', color: 'text-green-600' },
undocumented: { icon: '\u2717', color: 'text-red-600' },
outdated: { icon: '~', color: 'text-yellow-600' },
}
const SEV_STYLE: Record<string, { bg: string; text: string; dot: string }> = {
HIGH: { bg: 'bg-red-50 border-red-200', text: 'text-red-800', dot: 'bg-red-500' },
MEDIUM: { bg: 'bg-yellow-50 border-yellow-200', text: 'text-yellow-800', dot: 'bg-yellow-500' },
LOW: { bg: 'bg-blue-50 border-blue-200', text: 'text-blue-800', dot: 'bg-blue-500' },
CRITICAL: { bg: 'bg-red-100 border-red-300', text: 'text-red-900', dot: 'bg-red-700' },
}
export function ScanResult({ data }: { data: ScanData }) {
const [expandedCorrection, setExpandedCorrection] = useState<string | null>(null)
const [expandedDoc, setExpandedDoc] = useState<string | null>(null)
const undocCount = data.services.filter(s => s.status === 'undocumented').length
const okCount = data.services.filter(s => s.status === 'ok').length
const highCount = data.findings.filter(f => f.severity === 'HIGH' || f.severity === 'CRITICAL').length
const docs = data.discovered_documents || []
// Group findings by doc_title
const docFindings: Record<string, ScanFinding[]> = {}
const generalFindings: ScanFinding[] = []
for (const f of data.findings) {
if (f.doc_title) {
if (!docFindings[f.doc_title]) docFindings[f.doc_title] = []
docFindings[f.doc_title].push(f)
} else {
generalFindings.push(f)
}
}
return (
<div className="space-y-5">
{/* Summary Bar */}
<div className="grid grid-cols-4 gap-3">
<div className="bg-gray-50 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-gray-900">{data.pages_scanned}</p>
<p className="text-xs text-gray-500">Seiten</p>
</div>
<div className="bg-green-50 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-green-700">{okCount}</p>
<p className="text-xs text-gray-500">Dokumentiert</p>
</div>
<div className="bg-red-50 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-red-700">{undocCount}</p>
<p className="text-xs text-gray-500">Nicht in DSE</p>
</div>
<div className="bg-purple-50 rounded-lg p-3 text-center">
<p className="text-2xl font-bold text-purple-700">{docs.length}</p>
<p className="text-xs text-gray-500">Dokumente</p>
</div>
</div>
{/* Scanned Pages */}
{data.pages_list?.length > 0 && (
<details className="text-sm">
<summary className="text-gray-600 cursor-pointer hover:text-gray-800">
{data.pages_scanned} Seiten gescannt
</summary>
<ul className="mt-2 space-y-1 ml-4">
{data.pages_list.map((p, i) => {
const isMissing = data.missing_pages[p]
return (
<li key={i} className={`text-xs ${isMissing ? 'text-red-600' : 'text-gray-500'}`}>
{isMissing ? '\u2717' : '\u2713'} {p}
</li>
)
})}
</ul>
</details>
)}
{/* Services Table */}
{data.services.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 mb-2">Dienstleister (SOLL/IST)</h4>
<div className="border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50">
<tr>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Status</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Dienst</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">Land</th>
<th className="px-3 py-2 text-left text-xs font-medium text-gray-500">In DSE</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{data.services.map((s, i) => {
const st = STATUS_ICON[s.status] || STATUS_ICON.ok
return (
<tr key={i} className={s.status === 'undocumented' ? 'bg-red-50' : ''}>
<td className={`px-3 py-2 font-bold ${st.color}`}>{st.icon}</td>
<td className="px-3 py-2">
<span className="font-medium text-gray-900">{s.name}</span>
<span className="text-gray-400 text-xs ml-2">{s.provider}</span>
</td>
<td className="px-3 py-2 text-gray-600">{s.country}</td>
<td className="px-3 py-2">{s.in_dse ? '\u2713' : <span className="text-red-600 font-medium">Nein</span>}</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)}
{/* === Document-Centric View === */}
{docs.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 mb-2">
Rechtliche Dokumente ({docs.length})
</h4>
<div className="space-y-2">
{docs.map((doc, i) => {
const isExpanded = expandedDoc === doc.title
const findings = docFindings[doc.title] || []
const pct = doc.completeness_pct
const barColor = pct >= 80 ? 'bg-green-500' : pct >= 50 ? 'bg-yellow-500' : 'bg-red-500'
const statusLabel = pct >= 80 ? 'OK' : pct >= 50 ? 'Lueckenhaft' : 'Mangelhaft'
const statusColor = pct >= 80 ? 'text-green-700 bg-green-50' : pct >= 50 ? 'text-yellow-700 bg-yellow-50' : 'text-red-700 bg-red-50'
return (
<div key={i} className="border border-gray-200 rounded-lg overflow-hidden">
<button
onClick={() => setExpandedDoc(isExpanded ? null : doc.title)}
className="w-full flex items-center justify-between px-4 py-3 bg-gray-50/50 hover:bg-gray-50 text-left"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<svg className={`w-4 h-4 text-gray-400 transition-transform shrink-0 ${isExpanded ? 'rotate-90' : ''}`}
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-gray-900 truncate">{doc.title}</div>
<div className="text-xs text-gray-500">
{doc.word_count} Woerter
{findings.length > 0 && <span className="text-red-600 ml-2">{findings.length} Maengel</span>}
</div>
</div>
</div>
<div className="flex items-center gap-3 shrink-0 ml-3">
{/* Completeness bar */}
<div className="w-20 h-2 bg-gray-200 rounded-full overflow-hidden">
<div className={`h-full rounded-full ${barColor}`} style={{ width: `${pct}%` }} />
</div>
<span className={`text-xs font-medium px-2 py-0.5 rounded ${statusColor}`}>
{pct}%
</span>
</div>
</button>
{isExpanded && (
<div className="px-4 py-3 border-t border-gray-100 space-y-2">
{findings.length > 0 ? (
findings.map((f, fi) => {
const sev = SEV_STYLE[f.severity] || SEV_STYLE.MEDIUM
return (
<div key={fi} className="flex items-start gap-2 text-sm">
<span className={`w-2 h-2 rounded-full mt-1.5 shrink-0 ${sev.dot}`} />
<span className="text-gray-700">{f.text}</span>
</div>
)
})
) : (
<p className="text-sm text-green-600">Alle Pflichtangaben vorhanden.</p>
)}
{doc.url && (
<a href={doc.url} target="_blank" rel="noopener noreferrer"
className="text-xs text-purple-600 hover:underline mt-2 inline-block">
Dokument oeffnen
</a>
)}
</div>
)}
</div>
)
})}
</div>
</div>
)}
{/* General Findings (not associated with a specific document) */}
{generalFindings.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-700 mb-2">
Allgemeine Findings ({generalFindings.length})
</h4>
<div className="space-y-2">
{generalFindings.map((f, i) => {
const sev = SEV_STYLE[f.severity] || SEV_STYLE.MEDIUM
const corrKey = `gen-${i}`
const isExp = expandedCorrection === corrKey
return (
<div key={i} className={`border rounded-lg p-3 ${sev.bg}`}>
<div className="flex items-start gap-2">
<span className={`text-xs font-bold px-2 py-0.5 rounded ${sev.text} bg-white`}>
{f.severity}
</span>
<p className="text-sm text-gray-800 flex-1">{f.text}</p>
</div>
{/* Text Reference (original text + position + correction) */}
{f.text_reference && (
<TextReference ref={f.text_reference} correction={f.correction} />
)}
{/* Fallback: correction without text reference */}
{!f.text_reference && f.correction && (
<div className="mt-2">
<button onClick={() => setExpandedCorrection(isExp ? null : corrKey)}
className="text-xs text-purple-600 hover:text-purple-800 font-medium">
{isExp ? 'Korrektur ausblenden' : 'Korrekturvorschlag'}
</button>
{isExp && (
<div className="mt-2 bg-white border border-gray-200 rounded-lg p-3 relative">
<pre className="text-xs text-gray-700 whitespace-pre-wrap font-sans">{f.correction}</pre>
<button onClick={() => navigator.clipboard.writeText(f.correction)}
className="absolute top-2 right-2 text-xs bg-gray-100 hover:bg-gray-200 px-2 py-1 rounded">
Kopieren
</button>
</div>
)}
</div>
)}
</div>
)
})}
</div>
</div>
)}
{/* PDF Export Button */}
<div className="pt-4 border-t flex gap-3">
<button
onClick={async () => {
try {
const res = await fetch('/api/sdk/v1/agent/scans/pdf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: '', scan_type: 'scan', analysis_mode: 'post_launch', result: data }),
})
if (res.ok) {
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'compliance-report.pdf'
a.click()
URL.revokeObjectURL(url)
}
} catch (e) { console.error('PDF export failed:', e) }
}}
className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-purple-700 bg-purple-50 border border-purple-200 rounded-lg hover:bg-purple-100 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
PDF herunterladen
</button>
</div>
</div>
)
}
@@ -1,108 +0,0 @@
'use client'
import React, { useState } from 'react'
interface TextRef {
found: boolean
source_url: string
document_type: string
section_heading: string
section_number: string
parent_section: string
paragraph_index: number
original_text: string
issue: string
correction_type: string
correction_text: string
insert_after: string
}
const ISSUE_LABELS: Record<string, { label: string; color: string }> = {
missing: { label: 'Fehlt in der DSE', color: 'text-red-700 bg-red-50' },
incomplete: { label: 'Unvollstaendig', color: 'text-yellow-700 bg-yellow-50' },
incorrect: { label: 'Fehlerhaft', color: 'text-orange-700 bg-orange-50' },
}
const CORRECTION_LABELS: Record<string, string> = {
insert: 'Neuen Abschnitt einfuegen',
append: 'Am Ende des Absatzes ergaenzen',
replace: 'Absatz ersetzen',
}
export function TextReference({ ref, correction }: { ref: TextRef; correction?: string }) {
const [showCorrection, setShowCorrection] = useState(false)
const issue = ISSUE_LABELS[ref.issue] || null
const correctionText = correction || ref.correction_text
return (
<div className="mt-3 space-y-2 text-sm">
{/* Original Text Block */}
<div>
<p className="text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<span>📄</span> Originaltextblock:
</p>
<div className={`rounded-lg p-3 border ${ref.found ? 'bg-gray-50 border-gray-200' : 'bg-red-50 border-red-200'}`}>
{ref.found ? (
<p className="text-gray-700 text-xs whitespace-pre-wrap">{ref.original_text || '(Textinhalt konnte nicht extrahiert werden)'}</p>
) : (
<p className="text-red-600 text-xs italic">Nicht vorhanden Eintrag fehlt in der {ref.document_type}.</p>
)}
</div>
</div>
{/* Position */}
<div>
<p className="text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<span>📍</span> Position:
</p>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-2 text-xs text-blue-800">
{ref.found ? (
<>
<span className="font-semibold">{ref.section_heading || 'Abschnitt unbekannt'}</span>
{ref.section_number && <span className="text-blue-600 ml-1">(Nr. {ref.section_number})</span>}
{ref.parent_section && <span className="text-blue-500 ml-1">in: {ref.parent_section}</span>}
{ref.paragraph_index > 0 && <span className="text-blue-500 ml-1">| Absatz {ref.paragraph_index}</span>}
</>
) : ref.insert_after ? (
<span><strong>{CORRECTION_LABELS[ref.correction_type] || 'Einfuegen'}</strong> nach Abschnitt &quot;{ref.insert_after}&quot;</span>
) : (
<span>Neuen Abschnitt in der {ref.document_type} anlegen</span>
)}
{ref.source_url && (
<div className="text-blue-400 mt-1 truncate">in: {ref.source_url}</div>
)}
</div>
</div>
{/* Correction */}
{correctionText && (
<div>
<button
onClick={() => setShowCorrection(!showCorrection)}
className="text-xs text-purple-600 hover:text-purple-800 font-medium flex items-center gap-1"
>
<span>{showCorrection ? '▼' : '▶'}</span>
<span></span> Korrekturvorschlag {showCorrection ? 'ausblenden' : 'anzeigen'}
</button>
{showCorrection && (
<div className="mt-2 bg-white border border-purple-200 rounded-lg p-3 relative">
{issue && (
<span className={`text-[10px] px-2 py-0.5 rounded-full font-medium mb-2 inline-block ${issue.color}`}>
{CORRECTION_LABELS[ref.correction_type] || issue.label}
</span>
)}
<pre className="text-xs text-gray-700 whitespace-pre-wrap font-sans mt-1">{correctionText}</pre>
<button
onClick={() => navigator.clipboard.writeText(correctionText)}
className="absolute top-2 right-2 text-xs bg-gray-100 hover:bg-gray-200 px-2 py-1 rounded transition-colors"
title="In Zwischenablage kopieren"
>
📋 Kopieren
</button>
</div>
)}
</div>
)}
</div>
)
}
@@ -1,71 +0,0 @@
/**
* P47 localStorage-Quota-Management.
*
* Wenn alte Compliance-Check-Ergebnisse den Browser-Storage fuellen,
* versucht das setItem mit QuotaExceededError zu fangen, prunet
* alte doc-check-result-*-Eintraege (oldest first) und retried.
*
* Wird von DocCheckTab/BannerCheckTab/etc beim Persistieren der
* Result-Bloebs benutzt.
*/
const RESULT_KEY_PREFIX = 'doc-check-result-'
const MAX_KEEP = 10 // Maximal 10 alte Result-Bloebs behalten.
export function safeSetItem(key: string, value: string): boolean {
try {
localStorage.setItem(key, value)
return true
} catch (err: any) {
if (err?.name !== 'QuotaExceededError'
&& err?.code !== 22 && err?.code !== 1014) {
console.warn('localStorage setItem failed:', err)
return false
}
pruneOldResults()
try {
localStorage.setItem(key, value)
return true
} catch {
// Pruning hat nicht gereicht — aggressiver pruefen
pruneOldResults(0)
try {
localStorage.setItem(key, value)
return true
} catch {
console.warn('localStorage immer noch voll, wert wird verworfen')
return false
}
}
}
}
function pruneOldResults(keep: number = MAX_KEEP): void {
try {
const keys: { key: string; ts: number }[] = []
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (!k || !k.startsWith(RESULT_KEY_PREFIX)) continue
const ts = Number(k.slice(RESULT_KEY_PREFIX.length)) || 0
keys.push({ key: k, ts })
}
keys.sort((a, b) => a.ts - b.ts) // oldest first
const toRemove = keys.slice(0, Math.max(0, keys.length - keep))
for (const k of toRemove) {
try { localStorage.removeItem(k.key) } catch {}
}
} catch {}
}
export function getStorageUsageMB(): number {
let bytes = 0
try {
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (!k) continue
const v = localStorage.getItem(k) || ''
bytes += k.length + v.length
}
} catch {}
return bytes / (1024 * 1024)
}
@@ -1,106 +0,0 @@
'use client'
import { useState } from 'react'
export interface FollowUpQuestion {
id: string
question: string
legal_basis: string
severity: 'high' | 'medium' | 'low'
finding_if_no: string
}
export interface AnalysisResult {
url: string
classification: string
risk_level: string
risk_score: number
escalation_level: string
responsible_role: string
findings: string[]
required_controls: string[]
summary: string
email_status: string
analyzed_at: string
follow_up_questions: FollowUpQuestion[]
follow_up_answers: Record<string, boolean>
}
const ESCALATION_ROLES: Record<string, string> = {
E0: 'Kein Handlungsbedarf',
E1: 'Teamleitung Datenschutz',
E2: 'Datenschutzbeauftragter (DSB)',
E3: 'DSB + Rechtsabteilung',
}
export function useAgentAnalysis() {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [result, setResult] = useState<AnalysisResult | null>(null)
const [history, setHistory] = useState<AnalysisResult[]>([])
async function analyze(url: string, mode: string = 'post_launch') {
setLoading(true)
setError(null)
setResult(null)
try {
const fetchRes = await fetch('/api/sdk/v1/agent/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, mode }),
})
if (!fetchRes.ok) {
throw new Error(`Analyse fehlgeschlagen: ${fetchRes.status}`)
}
const data = await fetchRes.json()
const analysisResult: AnalysisResult = {
url,
classification: data.classification || 'unknown',
risk_level: data.risk_level || 'unknown',
risk_score: data.risk_score || 0,
escalation_level: data.escalation_level || 'E0',
responsible_role: ESCALATION_ROLES[data.escalation_level] || ESCALATION_ROLES.E0,
findings: data.findings || [],
required_controls: data.required_controls || [],
summary: data.summary || '',
email_status: data.email_status || 'pending',
analyzed_at: new Date().toISOString(),
follow_up_questions: data.follow_up_questions || [],
follow_up_answers: {},
}
setResult(analysisResult)
setHistory(prev => [analysisResult, ...prev].slice(0, 20))
} catch (e) {
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
} finally {
setLoading(false)
}
}
function answerFollowUp(questionId: string, answer: boolean) {
if (!result) return
const question = result.follow_up_questions.find(q => q.id === questionId)
const newAnswers = { ...result.follow_up_answers, [questionId]: answer }
const newFindings = [...result.findings]
// If user answered "no" → add the finding
if (!answer && question) {
newFindings.push(question.finding_if_no)
}
const updated = {
...result,
findings: newFindings,
follow_up_answers: newAnswers,
}
setResult(updated)
// Update history too
setHistory(prev => prev.map(h => h.analyzed_at === result.analyzed_at ? updated : h))
}
return { analyze, answerFollowUp, loading, error, result, history }
}
@@ -1,302 +0,0 @@
'use client'
import React, { useEffect, useState } from 'react'
type Phase = {
cookies?: string[]
scripts?: string[]
tracking_services?: (string | { name?: string })[]
new_tracking?: unknown[]
violations?: Array<{ severity?: string; text?: string }>
undocumented?: unknown[]
}
type CategoryTest = {
category: string
category_label: string
tracking_services?: (string | { name?: string })[]
cookies_set?: string[]
provider_details_visible?: boolean
violations?: Array<{ severity?: string; text?: string; legal_ref?: string }>
}
type BannerViolation = {
severity?: string
text?: string
legal_ref?: string
}
type StructuredCheck = {
id: string
label: string
passed: boolean
skipped?: boolean
severity: string
level?: number
hint?: string
}
type BannerResp = {
found: boolean
check_id: string
banner?: {
banner_provider?: string
banner_detected?: boolean
completeness_pct?: number
correctness_pct?: number
phases?: Record<string, Phase>
banner_checks?: { violations?: BannerViolation[] }
category_tests?: CategoryTest[]
structured_checks?: StructuredCheck[]
summary?: Record<string, number>
}
}
const PHASE_LABEL: Record<string, string> = {
before_consent: 'Vor Consent',
after_reject: 'Nach Ablehnung',
after_accept: 'Nach Annahme',
}
const SEV_BADGE: Record<string, string> = {
CRITICAL: 'bg-red-600 text-white',
HIGH: 'bg-red-100 text-red-800',
MEDIUM: 'bg-amber-100 text-amber-800',
LOW: 'bg-blue-100 text-blue-800',
INFO: 'bg-gray-100 text-gray-600',
}
function pctColor(pct?: number): string {
if (pct === undefined || pct === null) return 'text-gray-400'
return pct >= 80 ? 'text-green-700' : pct >= 50 ? 'text-amber-700' : 'text-red-700'
}
export default function BannerTab({ checkId }: { checkId: string }) {
const [data, setData] = useState<BannerResp | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [checkFilter, setCheckFilter] = useState<'all' | 'fail' | 'critical'>('fail')
useEffect(() => {
let cancelled = false
setLoading(true)
fetch(`/api/sdk/v1/agent/banner/${checkId}`)
.then(r => r.json())
.then(d => { if (!cancelled) setData(d) })
.catch(e => { if (!cancelled) setError(String(e)) })
.finally(() => { if (!cancelled) setLoading(false) })
return () => { cancelled = true }
}, [checkId])
if (loading) return <div className="p-6 text-sm text-gray-500">Lade Banner-Daten</div>
if (error) return <div className="p-6 text-sm text-red-600">Fehler: {error}</div>
if (!data?.found || !data.banner) {
return <div className="p-6 text-sm text-gray-500">Keine Banner-Daten zu diesem Check.</div>
}
const b = data.banner
const phases = b.phases || {}
const cats = b.category_tests || []
const violations = b.banner_checks?.violations || []
const checks = b.structured_checks || []
const summary = b.summary || {}
const filteredChecks = checks.filter(c => {
if (checkFilter === 'all') return true
if (checkFilter === 'fail') return !c.passed && !c.skipped
return !c.passed && !c.skipped && ['CRITICAL', 'HIGH'].includes(c.severity)
})
return (
<div className="space-y-6">
{/* Quality Cards */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-xs">
<div className="border rounded p-3">
<div className="text-[10px] uppercase text-gray-500">Vollstaendigkeit</div>
<div className={`text-2xl font-semibold ${pctColor(b.completeness_pct)}`}>
{b.completeness_pct ?? ''}{b.completeness_pct !== undefined && '%'}
</div>
</div>
<div className="border rounded p-3">
<div className="text-[10px] uppercase text-gray-500">Korrektheit</div>
<div className={`text-2xl font-semibold ${pctColor(b.correctness_pct)}`}>
{b.correctness_pct ?? ''}{b.correctness_pct !== undefined && '%'}
</div>
</div>
<div className="border rounded p-3">
<div className="text-[10px] uppercase text-gray-500">Verstoesse</div>
<div className="text-2xl font-semibold text-red-700">
{summary.total_violations ?? violations.length}
</div>
<div className="text-[10px] text-gray-500 mt-1">
crit:{summary.critical ?? 0} · high:{summary.high ?? 0}
</div>
</div>
<div className="border rounded p-3">
<div className="text-[10px] uppercase text-gray-500">CMP</div>
<div className="text-sm font-medium text-gray-800 truncate">
{b.banner_provider || 'unbekannt'}
</div>
<div className="text-[10px] text-gray-500 mt-1">
{b.banner_detected ? 'Banner erkannt' : 'kein Banner'}
</div>
</div>
</div>
{/* Phases */}
<div className="border rounded-lg overflow-hidden">
<div className="px-4 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">
Cookie-Setzungen pro Phase (echter Browser-Test)
</div>
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Phase</th>
<th className="px-3 py-2 text-center">Cookies</th>
<th className="px-3 py-2 text-center">Tracker</th>
<th className="px-3 py-2 text-left">Auffaelligkeiten</th>
</tr>
</thead>
<tbody>
{(['before_consent', 'after_reject', 'after_accept'] as const).map(key => {
const p = phases[key] || {}
const nc = (p.cookies || []).length
const nt = (p.tracking_services || []).length
const issues: string[] = []
if (p.violations?.length) issues.push(`${p.violations.length} Verstoss`)
if (p.new_tracking?.length) issues.push(`${p.new_tracking.length} neue Tracker`)
if (p.undocumented?.length) issues.push(`${p.undocumented.length} undokumentiert`)
const color = key === 'before_consent'
? (nc === 0 ? 'text-green-600' : 'text-red-600')
: key === 'after_reject'
? (nc <= 1 ? 'text-green-600' : 'text-amber-600')
: 'text-gray-700'
return (
<tr key={key} className="border-t">
<td className="px-3 py-2 font-medium">{PHASE_LABEL[key]}</td>
<td className={`px-3 py-2 text-center font-semibold ${color}`}>{nc}</td>
<td className="px-3 py-2 text-center">{nt}</td>
<td className="px-3 py-2 text-gray-500">{issues.join(', ') || '—'}</td>
</tr>
)
})}
</tbody>
</table>
</div>
{/* Per-Category */}
{cats.length > 0 && (
<div className="border rounded-lg overflow-hidden">
<div className="px-4 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">
Provider-Listing pro Kategorie (P19 Click-Through-Test)
</div>
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Kategorie</th>
<th className="px-3 py-2 text-center">Anbieter sichtbar</th>
<th className="px-3 py-2 text-center">Tracker erkannt</th>
<th className="px-3 py-2 text-left">Violations</th>
</tr>
</thead>
<tbody>
{cats.map(c => {
const pdv = c.provider_details_visible
const pdv_label = pdv === true ? 'Ja' : pdv === false ? 'Nein' : ''
const pdv_color = pdv === false ? 'text-red-700' : pdv === true ? 'text-green-700' : 'text-gray-400'
return (
<tr key={c.category} className="border-t">
<td className="px-3 py-2">{c.category_label}</td>
<td className={`px-3 py-2 text-center font-semibold ${pdv_color}`}>{pdv_label}</td>
<td className="px-3 py-2 text-center">{(c.tracking_services || []).length}</td>
<td className="px-3 py-2 text-red-700 text-[10px]">
{(c.violations || []).map(v => v.text?.slice(0, 80)).join('; ') || '—'}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
{/* Banner-Checks Violations */}
{violations.length > 0 && (
<div className="border rounded-lg overflow-hidden">
<div className="px-4 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700">
Banner-Verstoesse ({violations.length})
</div>
<ul className="text-xs divide-y">
{violations.map((v, i) => {
const sev = (v.severity || 'MEDIUM').toUpperCase()
return (
<li key={i} className="px-3 py-2">
<div className="flex items-start gap-2">
<span className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${SEV_BADGE[sev] || 'bg-gray-100'}`}>{sev}</span>
<div>
<div className="text-gray-900">{v.text}</div>
{v.legal_ref && <div className="text-[10px] text-gray-400 italic mt-1">Quelle: {v.legal_ref}</div>}
</div>
</div>
</li>
)
})}
</ul>
</div>
)}
{/* 46 structured_checks Drilldown */}
<div className="border rounded-lg overflow-hidden">
<div className="px-4 py-2 bg-gray-50 border-b text-sm font-medium text-gray-700 flex items-center gap-3">
<span>Banner-Checks ({checks.length})</span>
<div className="ml-auto flex gap-1">
{(['all', 'fail', 'critical'] as const).map(f => (
<button key={f}
onClick={() => setCheckFilter(f)}
className={`px-2 py-1 rounded text-[10px] border ${
checkFilter === f ? 'bg-blue-600 text-white border-blue-600'
: 'bg-white text-gray-600 border-gray-200'
}`}>
{f === 'all' ? 'Alle' : f === 'fail' ? 'Nur Fail' : 'Nur CRIT/HIGH'}
</button>
))}
</div>
</div>
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Status</th>
<th className="px-3 py-2 text-left">Sev</th>
<th className="px-3 py-2 text-left">Check</th>
</tr>
</thead>
<tbody>
{filteredChecks.map(c => (
<tr key={c.id} className="border-t">
<td className="px-3 py-2">
{c.passed ? <span className="text-green-600"></span>
: c.skipped ? <span className="text-gray-400"></span>
: <span className="text-red-600"></span>}
</td>
<td className="px-3 py-2">
<span className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${SEV_BADGE[c.severity] || 'bg-gray-100'}`}>
{c.severity}
</span>
</td>
<td className="px-3 py-2">
<div className="text-gray-900">{c.label}</div>
{c.hint && !c.passed && (
<div className="text-[10px] text-gray-500 mt-1">{c.hint.slice(0, 200)}</div>
)}
</td>
</tr>
))}
{filteredChecks.length === 0 && (
<tr><td colSpan={3} className="px-3 py-4 text-center text-gray-400">Keine Checks fuer den Filter.</td></tr>
)}
</tbody>
</table>
</div>
</div>
)
}
@@ -1,275 +0,0 @@
'use client'
import React, { useEffect, useMemo, useState } from 'react'
type Finding = {
id: number
source_type: string
doc_type: string
severity: string
status: string
regulation: string
label: string
hint: string
action_recipe: Record<string, string>
anchor_excerpt: string
anchor_conf: number
vendor_name: string
category: string
payload: Record<string, unknown>
}
type Summary = {
total: number
by_source: Record<string, number>
by_severity: Record<string, number>
by_status: Record<string, number>
by_doc_type: Record<string, number>
}
type Resp = {
found: boolean
summary: Summary
count: number
findings: Finding[]
}
const SOURCE_LABEL: Record<string, string> = {
all: 'Alle Quellen',
mc: 'Master-Controls',
pflichtangabe: 'Pflichtangaben',
vendor: 'Vendor-Findings',
redundanz: 'Redundanzen',
}
const SEVERITY_COLOR: Record<string, string> = {
CRITICAL: 'bg-red-600 text-white',
HIGH: 'bg-red-100 text-red-800',
MEDIUM: 'bg-amber-100 text-amber-800',
LOW: 'bg-blue-100 text-blue-800',
INFO: 'bg-gray-100 text-gray-600',
}
const STATUS_LABEL: Record<string, string> = {
failed: 'Fail',
passed: 'Pass',
skipped: 'Skip',
na: 'N/A',
info: 'Info',
}
const SEVERITY_OPTS = ['all', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO']
const STATUS_OPTS = ['all', 'failed', 'passed', 'skipped', 'na', 'info']
export default function FindingsTab({ checkId }: { checkId: string }) {
const [data, setData] = useState<Resp | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [source, setSource] = useState('all')
const [severity, setSeverity] = useState('all')
const [docType, setDocType] = useState('all')
const [status, setStatus] = useState('failed')
const [q, setQ] = useState('')
const [expanded, setExpanded] = useState<number | null>(null)
useEffect(() => {
let cancelled = false
setLoading(true)
const qs = new URLSearchParams({
source, severity, doc_type: docType, status, q, limit: '1500',
}).toString()
fetch(`/api/sdk/v1/agent/findings/${checkId}?${qs}`)
.then(r => r.json())
.then(d => { if (!cancelled) setData(d) })
.catch(e => { if (!cancelled) setError(String(e)) })
.finally(() => { if (!cancelled) setLoading(false) })
return () => { cancelled = true }
}, [checkId, source, severity, docType, status, q])
const docTypes = useMemo(
() => Object.keys(data?.summary?.by_doc_type ?? {}).filter(d => d !== '-').sort(),
[data],
)
const csvExport = () => {
const rows = data?.findings ?? []
const head = ['Quelle', 'Doc', 'Severity', 'Status', 'Regulation', 'Label', 'Vendor', 'Hint']
const lines = [head.join(',')]
for (const r of rows) {
const cells = [
r.source_type, r.doc_type, r.severity, r.status,
r.regulation, r.label, r.vendor_name, r.hint,
].map(c => `"${String(c ?? '').replace(/"/g, '""').replace(/\n/g, ' ')}"`)
lines.push(cells.join(','))
}
const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `findings-${checkId}.csv`
a.click()
URL.revokeObjectURL(url)
}
if (loading && !data) return <div className="p-6 text-sm text-gray-500">Lade Voll-Audit</div>
if (error) return <div className="p-6 text-sm text-red-600">Fehler: {error}</div>
if (!data?.found) {
return (
<div className="p-6 text-sm text-gray-500">
Keine unified findings für diesen Run gespeichert (alter Run vor P5?).
</div>
)
}
const sum = data.summary
const findings = data.findings
return (
<div className="space-y-4">
{/* Summary Cards */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-xs">
{Object.entries(SOURCE_LABEL).filter(([k]) => k !== 'all').map(([k, label]) => {
const count = sum.by_source?.[k] ?? 0
return (
<button key={k}
onClick={() => setSource(source === k ? 'all' : k)}
className={`text-left rounded-lg border px-3 py-2 transition ${
source === k
? 'border-blue-500 bg-blue-50 text-blue-900'
: 'border-gray-200 hover:border-gray-300 bg-white'
}`}>
<div className="text-[10px] uppercase tracking-wide text-gray-500">{label}</div>
<div className="text-lg font-semibold">{count}</div>
</button>
)
})}
</div>
{/* Filter row */}
<div className="flex flex-wrap gap-2 items-center text-xs">
<select value={severity} onChange={e => setSeverity(e.target.value)}
className="border border-gray-200 rounded px-2 py-1">
{SEVERITY_OPTS.map(s => (
<option key={s} value={s}>
{s === 'all' ? 'Alle Severities' : s}
{s !== 'all' && sum.by_severity?.[s] != null ? ` (${sum.by_severity[s]})` : ''}
</option>
))}
</select>
<select value={status} onChange={e => setStatus(e.target.value)}
className="border border-gray-200 rounded px-2 py-1">
{STATUS_OPTS.map(s => (
<option key={s} value={s}>
{s === 'all' ? 'Alle Status' : STATUS_LABEL[s] ?? s}
{s !== 'all' && sum.by_status?.[s] != null ? ` (${sum.by_status[s]})` : ''}
</option>
))}
</select>
<select value={docType} onChange={e => setDocType(e.target.value)}
className="border border-gray-200 rounded px-2 py-1">
<option value="all">Alle Doc-Types</option>
{docTypes.map(d => (
<option key={d} value={d}>{d} ({sum.by_doc_type?.[d] ?? 0})</option>
))}
</select>
<input value={q} onChange={e => setQ(e.target.value)}
placeholder="Suche Label / Anbieter…"
className="border border-gray-200 rounded px-2 py-1 min-w-[180px]" />
<button onClick={csvExport}
className="ml-auto border border-gray-200 hover:border-gray-300 rounded px-2 py-1">
CSV exportieren
</button>
<span className="text-gray-500">{data.count} Treffer</span>
</div>
{/* Findings table */}
<div className="border rounded-lg overflow-hidden">
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Quelle</th>
<th className="px-3 py-2 text-left">Doc</th>
<th className="px-3 py-2 text-left">Sev</th>
<th className="px-3 py-2 text-left">Status</th>
<th className="px-3 py-2 text-left">Finding</th>
</tr>
</thead>
<tbody>
{findings.map(f => (
<React.Fragment key={f.id}>
<tr className="border-t cursor-pointer hover:bg-gray-50"
onClick={() => setExpanded(expanded === f.id ? null : f.id)}>
<td className="px-3 py-2 text-gray-500 capitalize">{f.source_type}</td>
<td className="px-3 py-2 text-gray-700">{f.doc_type === '-' ? '—' : f.doc_type}</td>
<td className="px-3 py-2">
<span className={`px-2 py-0.5 rounded text-[10px] font-medium ${
SEVERITY_COLOR[f.severity] || 'bg-gray-100'
}`}>{f.severity}</span>
</td>
<td className="px-3 py-2 text-gray-600">{STATUS_LABEL[f.status] ?? f.status}</td>
<td className="px-3 py-2 text-gray-900">
{f.label}
{f.vendor_name && (
<span className="ml-2 text-[10px] text-gray-400">
· {f.vendor_name}
</span>
)}
{(() => {
const rl = String(f.payload?.risk_label ?? '')
if (!rl) return null
const cls = rl === 'kritisch' ? 'bg-red-600 text-white' :
rl === 'hoch' ? 'bg-red-100 text-red-800' :
rl === 'mittel' ? 'bg-amber-100 text-amber-800' :
rl === 'gering' ? 'bg-green-50 text-green-700' :
'bg-gray-100 text-gray-500'
return <span className={`ml-2 px-1.5 py-0.5 rounded text-[10px] font-medium ${cls}`}>Risk: {rl}</span>
})()}
</td>
</tr>
{expanded === f.id && (
<tr className="bg-gray-50/50">
<td colSpan={5} className="px-3 py-3 text-xs space-y-2">
{f.hint && (
<div className="text-gray-700">{f.hint}</div>
)}
{f.action_recipe?.fix_text && (
<div className="bg-amber-50 border-l-2 border-amber-300 pl-3 py-2">
<div className="font-medium text-amber-800 mb-1">Empfehlung</div>
<div className="whitespace-pre-line text-amber-900">
{f.action_recipe.fix_text}
</div>
{f.action_recipe.where && (
<div className="text-[10px] text-amber-700 mt-1">
Einfuegen in: {f.action_recipe.where}
</div>
)}
</div>
)}
{f.anchor_excerpt && (
<div className="bg-blue-50 border-l-2 border-blue-300 pl-3 py-2">
<div className="font-medium text-blue-800 mb-1">
Fundstelle im Dokument (Konfidenz {Math.round((f.anchor_conf || 0) * 100)}%)
</div>
<div className="italic text-blue-900">"{f.anchor_excerpt}"</div>
</div>
)}
<div className="text-[10px] text-gray-400">
Source: {f.source_type} · Regulation: {f.regulation || '—'}
{f.category && ` · Kategorie: ${f.category}`}
</div>
</td>
</tr>
)}
</React.Fragment>
))}
{findings.length === 0 && (
<tr><td colSpan={5} className="px-3 py-6 text-center text-gray-400">
Keine Findings fuer die aktuellen Filter.
</td></tr>
)}
</tbody>
</table>
</div>
</div>
)
}
@@ -1,329 +0,0 @@
'use client'
import React, { useEffect, useState, useMemo } from 'react'
import { use as useUnwrap } from 'react'
import FindingsTab from './FindingsTab'
import BannerTab from './BannerTab'
type MCRow = {
id: number
doc_type: string
mc_id: string
label: string
passed: number
skipped: number
severity: string
regulation: string
matched_text: string
hint: string
}
type ScorecardRow = {
regulation: string
total: number
passed: number
failed: number
skipped: number
pct: number
severity: Record<string, number>
}
type AuditResponse = {
found: boolean
run?: {
check_id: string
ts: string
site_name: string
base_domain: string
doc_count: number
scorecard: { by_regulation: ScorecardRow[]; totals: any }
vvt_summary: { total?: number; internal?: number; external?: number }
}
mc_count?: number
results?: MCRow[]
}
// P8: MC-Audit ist eine Checkliste, KEINE Severity-Drohung. Statt
// rotem HIGH-Badge zeigen wir die Quellen-Prioritaet (Gesetz vs.
// Behoerden-Leitlinie vs. Best-Practice) und einen 3-Tier-Status
// (erfuellt / nicht erfuellt / selbst pruefen).
const PRIORITY_BADGE: Record<string, string> = {
Gesetz: 'bg-slate-800 text-white',
'Behoerden-Leitlinie': 'bg-blue-100 text-blue-800',
'Best-Practice': 'bg-gray-100 text-gray-600',
'—': 'bg-gray-50 text-gray-400',
}
function regulationToPriority(reg: string): keyof typeof PRIORITY_BADGE {
const r = (reg || '').toLowerCase()
if (/dsgvo|gdpr|eprivacy|tdddg|tkg|bdsg|ttdsg/.test(r)) return 'Gesetz'
if (/edpb|dsk|cnil|lfdi|eugh|orientierungshilfe|leitlinie|guideline/.test(r))
return 'Behoerden-Leitlinie'
if (/iso|nist|bsi|cobit|sox/.test(r)) return 'Best-Practice'
return '—'
}
const _CONDITIONAL_RE = /\b(falls|sofern|wenn|soweit|ggf\.|gegebenenfalls)\b/i
function rowReviewStatus(r: MCRow): 'pass' | 'fail' | 'review' | 'na' {
if (r.passed) return 'pass'
if (r.skipped) return 'na'
// failed: harter Fail nur bei matched_text-Beleg ODER nicht-konditionalem Label
if (!r.matched_text && _CONDITIONAL_RE.test(r.label || '')) return 'review'
return 'fail'
}
const STATUS_FILTERS = [
{ value: 'all', label: 'Alle' },
{ value: 'fail', label: 'Nicht erfuellt' },
{ value: 'review', label: 'Selbst pruefen' },
{ value: 'pass', label: 'Erfuellt' },
{ value: 'na', label: 'Nicht anwendbar' },
] as const
export default function AuditPage(
{ params }: { params: Promise<{ checkId: string }> },
) {
const { checkId } = useUnwrap(params)
const [data, setData] = useState<AuditResponse | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [filterStatus, setFilterStatus] = useState<typeof STATUS_FILTERS[number]['value']>('fail')
const [filterReg, setFilterReg] = useState<string>('')
const [filterDoc, setFilterDoc] = useState<string>('')
const [expanded, setExpanded] = useState<number | null>(null)
const [tab, setTab] = useState<'mc' | 'all' | 'banner'>('all')
useEffect(() => {
let cancelled = false
setLoading(true)
fetch(`/api/sdk/v1/agent/audit/${checkId}`)
.then(r => r.json())
.then(d => { if (!cancelled) setData(d) })
.catch(e => { if (!cancelled) setError(String(e)) })
.finally(() => { if (!cancelled) setLoading(false) })
return () => { cancelled = true }
}, [checkId])
const allRows = data?.results ?? []
const docTypes = useMemo(
() => Array.from(new Set(allRows.map(r => r.doc_type))).sort(),
[allRows],
)
const regulations = useMemo(
() => Array.from(new Set(allRows.map(r => r.regulation).filter(Boolean))).sort(),
[allRows],
)
const filtered = allRows.filter(r => {
if (filterStatus !== 'all' && rowReviewStatus(r) !== filterStatus) return false
if (filterReg && r.regulation !== filterReg) return false
if (filterDoc && r.doc_type !== filterDoc) return false
return true
})
if (loading) {
return <div className="p-6 text-sm text-gray-500">Lade Audit</div>
}
if (error || !data?.found) {
return (
<div className="p-6 text-sm text-red-600">
Audit nicht gefunden{error ? `: ${error}` : ''}.
</div>
)
}
const run = data.run!
const scorecard = run.scorecard?.by_regulation ?? []
const totals = run.scorecard?.totals ?? { total: 0, passed: 0, failed: 0, pct: 0 }
return (
<div className="space-y-6 p-6 max-w-6xl">
{/* Header */}
<div>
<h1 className="text-xl font-semibold text-gray-900">
MC-Audit: {run.site_name}
</h1>
<p className="text-xs text-gray-500 mt-1">
check_id <code className="bg-gray-100 px-1 rounded">{checkId}</code> ·{' '}
{new Date(run.ts).toLocaleString('de-DE')} · {run.doc_count} Dokumente ·{' '}
{data.mc_count} MC-Eintraege
</p>
</div>
{/* Tab switcher */}
<div className="flex gap-2 border-b border-gray-200">
{([
{ key: 'all', label: 'Voll-Audit (alle Findings)' },
{ key: 'banner', label: 'Cookie-Banner-Analyse' },
{ key: 'mc', label: 'Nur MC-Scorecard' },
] as const).map(t => (
<button key={t.key}
onClick={() => setTab(t.key)}
className={`px-4 py-2 text-sm border-b-2 -mb-px transition ${
tab === t.key
? 'border-blue-600 text-blue-700 font-medium'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}>{t.label}</button>
))}
</div>
{tab === 'all' && <FindingsTab checkId={checkId} />}
{tab === 'banner' && <BannerTab checkId={checkId} />}
{tab === 'mc' && <>
{/* Scorecard */}
<div className="border rounded-lg overflow-hidden">
<div className="px-4 py-3 bg-blue-50 border-b border-blue-100">
<h2 className="text-sm font-medium text-blue-900">
Compliance-Scorecard nach Regulation
<span className="ml-2 text-blue-700 font-semibold text-base">
{totals.pct}%
</span>
<span className="ml-2 text-xs text-blue-600">
({totals.passed} bestanden, {totals.failed} Fail,{' '}
{totals.skipped} skipped {totals.total} gesamt)
</span>
</h2>
</div>
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Regulation</th>
<th className="px-3 py-2 text-center">Passed</th>
<th className="px-3 py-2 text-center">Failed</th>
<th className="px-3 py-2 text-center">HIGH</th>
<th className="px-3 py-2 text-center">MEDIUM</th>
<th className="px-3 py-2 text-right">Score</th>
</tr>
</thead>
<tbody>
{scorecard.map(row => (
<tr key={row.regulation} className="border-t hover:bg-blue-50/30 cursor-pointer"
onClick={() => setFilterReg(row.regulation === filterReg ? '' : row.regulation)}>
<td className="px-3 py-2 font-medium">{row.regulation}</td>
<td className="px-3 py-2 text-center text-green-700">{row.passed}</td>
<td className="px-3 py-2 text-center text-red-700">{row.failed}</td>
<td className="px-3 py-2 text-center text-red-700">
{(row.severity.HIGH || 0) + (row.severity.CRITICAL || 0)}
</td>
<td className="px-3 py-2 text-center text-amber-700">
{row.severity.MEDIUM || 0}
</td>
<td className={`px-3 py-2 text-right font-semibold ${
row.pct >= 80 ? 'text-green-700' :
row.pct >= 50 ? 'text-amber-700' : 'text-red-700'
}`}>{row.pct}%</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Filters */}
<div className="flex flex-wrap gap-3 items-center text-xs">
<div className="flex gap-1">
{STATUS_FILTERS.map(f => (
<button key={f.value}
onClick={() => setFilterStatus(f.value)}
className={`px-2.5 py-1 rounded-full border ${
filterStatus === f.value
? 'bg-blue-600 text-white border-blue-600'
: 'bg-white text-gray-600 border-gray-200 hover:border-gray-300'
}`}>{f.label}</button>
))}
</div>
<select value={filterDoc} onChange={e => setFilterDoc(e.target.value)}
className="border border-gray-200 rounded px-2 py-1">
<option value="">Alle Doc-Types</option>
{docTypes.map(d => <option key={d} value={d}>{d}</option>)}
</select>
<select value={filterReg} onChange={e => setFilterReg(e.target.value)}
className="border border-gray-200 rounded px-2 py-1">
<option value="">Alle Regulations</option>
{regulations.map(r => <option key={r} value={r}>{r}</option>)}
</select>
<span className="text-gray-500">
{filtered.length} von {allRows.length}
</span>
</div>
{/* Results */}
<div className="border rounded-lg overflow-hidden">
<table className="w-full text-xs">
<thead className="bg-gray-50 text-gray-600">
<tr>
<th className="px-3 py-2 text-left">Status</th>
<th className="px-3 py-2 text-left">Doc</th>
<th className="px-3 py-2 text-left">Regulation</th>
<th className="px-3 py-2 text-left">MC</th>
<th className="px-3 py-2 text-left">Prioritaet</th>
</tr>
</thead>
<tbody>
{filtered.map(row => (
<React.Fragment key={row.id}>
<tr className="border-t cursor-pointer hover:bg-gray-50"
onClick={() => setExpanded(expanded === row.id ? null : row.id)}>
<td className="px-3 py-2">
{(() => {
const st = rowReviewStatus(row)
if (st === 'pass') return <span className="text-green-600" title="Erfuellt"></span>
if (st === 'na') return <span className="text-gray-400" title="Nicht anwendbar"></span>
if (st === 'review') return <span className="text-amber-600" title="Selbst pruefen">?</span>
return <span className="text-red-600" title="Nicht erfuellt"></span>
})()}
</td>
<td className="px-3 py-2 text-gray-700">{row.doc_type}</td>
<td className="px-3 py-2 text-gray-500">{row.regulation || '—'}</td>
<td className="px-3 py-2 text-gray-900">{row.label}</td>
<td className="px-3 py-2">
{(() => {
const prio = regulationToPriority(row.regulation)
return (
<span className={`px-2 py-0.5 rounded text-[10px] font-medium ${PRIORITY_BADGE[prio]}`}>
{prio}
</span>
)
})()}
</td>
</tr>
{expanded === row.id && (
<tr className="bg-gray-50/50">
<td colSpan={5} className="px-3 py-3 text-xs">
<div className="text-gray-500 mb-1">
MC-ID: <code>{row.mc_id}</code>
</div>
{row.matched_text && (
<div className="mb-2">
<span className="text-green-700 font-medium">Treffer: </span>
<span className="font-mono text-gray-700">
"{row.matched_text}"
</span>
</div>
)}
{row.hint && (
<div className="text-amber-700 bg-amber-50 border-l-2 border-amber-200 pl-2 py-1">
{row.hint}
</div>
)}
</td>
</tr>
)}
</React.Fragment>
))}
{filtered.length === 0 && (
<tr>
<td colSpan={5} className="px-3 py-6 text-center text-gray-400">
Keine MCs entsprechen den aktuellen Filtern.
</td>
</tr>
)}
</tbody>
</table>
</div>
</>}
</div>
)
}
-193
View File
@@ -1,193 +0,0 @@
'use client'
import React, { useState } from 'react'
import { ScanResult } from './_components/ScanResult'
import { ComplianceCheckTab } from './_components/ComplianceCheckTab'
import { BannerCheckTab } from './_components/BannerCheckTab'
import { ComplianceFAQ } from './_components/ComplianceFAQ'
type AnalysisTab = 'scan' | 'compliance-check' | 'banner-check'
const TABS: { id: AnalysisTab; label: string; desc: string }[] = [
{ id: 'scan', label: 'Website-Scan', desc: 'Rechtliche Dokumente finden + Dienstleister erkennen' },
{ id: 'compliance-check', label: 'Compliance-Check', desc: 'Alle rechtlichen Dokumente zusammen pruefen' },
{ id: 'banner-check', label: 'Banner-Check', desc: 'Cookie-Banner auf DSGVO-Konformitaet testen' },
]
export default function AgentPage() {
const [url, setUrl] = useState(() => typeof window !== 'undefined' ? localStorage.getItem('agent-scan-url') || '' : '')
const [tab, setTab] = useState<AnalysisTab>(() => (typeof window !== 'undefined' ? localStorage.getItem('agent-scan-tab') as AnalysisTab : null) || 'compliance-check')
const [scanLoading, setScanLoading] = useState(false)
const [scanError, setScanError] = useState<string | null>(null)
const [scanData, setScanData] = useState<any>(() => {
if (typeof window === 'undefined') return null
try { const s = localStorage.getItem('agent-scan-result'); return s ? JSON.parse(s) : null } catch { return null }
})
const [scanProgress, setScanProgress] = useState<string>('')
const [activeScanId, setActiveScanId] = useState<string>(() => typeof window !== 'undefined' ? localStorage.getItem('agent-scan-id') || '' : '')
const [scanHistory, setScanHistory] = useState<{ url: string; date: string; findings: number; docs: number; resultKey: string }[]>(() => {
if (typeof window === 'undefined') return []
try { return JSON.parse(localStorage.getItem('agent-scan-history') || '[]') } catch { return [] }
})
React.useEffect(() => { localStorage.setItem('agent-scan-url', url) }, [url])
React.useEffect(() => { localStorage.setItem('agent-scan-tab', tab) }, [tab])
// Resume polling if scan was in progress
React.useEffect(() => {
if (!activeScanId || scanData?.services) return
let cancelled = false
setScanLoading(true)
setScanProgress('Scan laeuft noch...')
const poll = async () => {
while (!cancelled) {
await new Promise(r => setTimeout(r, 5000))
try {
const res = await fetch(`/api/sdk/v1/agent/scan?scan_id=${activeScanId}`)
if (!res.ok) continue
const data = await res.json()
if (data.progress) setScanProgress(data.progress)
if (data.status === 'completed' && data.result) {
setScanData(data.result); setScanProgress(''); setScanLoading(false)
localStorage.setItem('agent-scan-result', JSON.stringify(data.result))
localStorage.removeItem('agent-scan-id'); setActiveScanId('')
_addToHistory(data.result); return
}
if (data.status === 'failed' || data.status === 'not_found') {
if (data.status === 'failed') setScanError(data.error || 'Scan fehlgeschlagen')
setScanProgress(''); setScanLoading(false)
localStorage.removeItem('agent-scan-id'); setActiveScanId(''); return
}
} catch {}
}
}
poll()
return () => { cancelled = true }
}, []) // eslint-disable-line react-hooks/exhaustive-deps
const _addToHistory = (result: any) => {
const resultKey = `scan-result-${Date.now()}`
try { localStorage.setItem(resultKey, JSON.stringify(result)) } catch {}
const entry = { url: url || result.url || '', date: new Date().toISOString(), findings: result.findings?.length || 0, docs: result.discovered_documents?.length || 0, resultKey }
const updated = [entry, ...scanHistory].slice(0, 30)
setScanHistory(updated); localStorage.setItem('agent-scan-history', JSON.stringify(updated))
}
const handleScan = async (e: React.FormEvent) => {
e.preventDefault()
if (!url.trim()) return
setScanLoading(true); setScanError(null); setScanData(null); setScanProgress('Scan wird gestartet...')
try {
const startRes = await fetch('/api/sdk/v1/agent/scan', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: url.trim(), mode: 'post_launch' }) })
if (!startRes.ok) throw new Error(`Scan konnte nicht gestartet werden: ${startRes.status}`)
const { scan_id } = await startRes.json()
if (!scan_id) throw new Error('Keine Scan-ID erhalten')
setActiveScanId(scan_id); localStorage.setItem('agent-scan-id', scan_id)
let attempts = 0
while (attempts < 120) {
await new Promise(r => setTimeout(r, 5000))
const pollRes = await fetch(`/api/sdk/v1/agent/scan?scan_id=${scan_id}`)
if (!pollRes.ok) { attempts++; continue }
const pollData = await pollRes.json()
if (pollData.progress) setScanProgress(pollData.progress)
if (pollData.status === 'completed' && pollData.result) {
setScanData(pollData.result); setScanProgress('')
localStorage.setItem('agent-scan-result', JSON.stringify(pollData.result))
localStorage.removeItem('agent-scan-id'); setActiveScanId(''); _addToHistory(pollData.result); break
}
if (pollData.status === 'failed') throw new Error(pollData.error || 'Scan fehlgeschlagen')
attempts++
}
if (attempts >= 120) throw new Error('Scan-Timeout (10 Minuten)')
} catch (e) { setScanError(e instanceof Error ? e.message : 'Unbekannter Fehler'); setScanProgress('') }
finally { setScanLoading(false) }
}
const navigateToCheck = (targetTab: AnalysisTab, checkUrl: string) => {
const keyMap: Record<string, string> = { 'doc-check': 'doc-check-prefill-url', 'banner-check': 'banner-check-url', 'impressum-check': 'impressum-check-url' }
if (keyMap[targetTab]) localStorage.setItem(keyMap[targetTab], checkUrl)
setTab(targetTab)
}
const discoveredDocs = scanData?.discovered_documents || []
const scannedUrl = scanData?.url || url
return (
<div className="space-y-6 max-w-4xl">
<div>
<h1 className="text-2xl font-bold text-gray-900">Compliance Agent</h1>
<p className="text-gray-500 mt-1">Analysiere Webseiten und Dokumente auf DSGVO-Konformitaet.</p>
</div>
<div className="flex border-b border-gray-200 overflow-x-auto">
{TABS.map(t => (
<button key={t.id} onClick={() => setTab(t.id)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
tab === t.id ? 'border-purple-500 text-purple-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}>
{t.label}
</button>
))}
</div>
{tab === 'scan' && (
<div className="space-y-4">
<div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
<h3 className="text-sm font-semibold text-indigo-900">Website-Scan (Discovery)</h3>
<p className="text-xs text-indigo-700 mt-1">Findet alle rechtlichen Dokumente (DSI, AGB, Impressum, Cookie, Widerruf), erkennt eingesetzte Drittdienste und prueft ob sie in der DSE dokumentiert sind.</p>
</div>
<form onSubmit={handleScan} className="flex gap-3">
<input type="url" value={url} onChange={e => setUrl(e.target.value)} placeholder="https://www.example.com/"
className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm" disabled={scanLoading} required />
<button type="submit" disabled={scanLoading || !url.trim()}
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors flex items-center gap-2 text-sm font-medium whitespace-nowrap">
{scanLoading ? (<><svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>Scanne...</>) : 'Website scannen'}
</button>
</form>
{scanProgress && <div className="bg-purple-50 border border-purple-200 rounded-lg p-4 text-sm text-purple-700 flex items-center gap-3"><svg className="animate-spin w-5 h-5 text-purple-500 shrink-0" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>{scanProgress}</div>}
{scanError && <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700">{scanError}</div>}
{scanData && (
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
<h4 className="text-sm font-semibold text-gray-800 mb-3">Jetzt pruefen</h4>
<div className="grid grid-cols-2 gap-2">
<button onClick={() => navigateToCheck('banner-check', scannedUrl)} className="p-3 rounded-lg border border-gray-200 hover:border-purple-300 hover:bg-purple-50 transition-all text-left">
<div className="text-sm font-medium text-gray-900">Cookie-Banner pruefen</div>
<div className="text-xs text-gray-500 mt-0.5">3-Phasen Dark-Pattern-Analyse</div>
</button>
<button onClick={() => navigateToCheck('impressum-check', scannedUrl + '/impressum')} className="p-3 rounded-lg border border-gray-200 hover:border-purple-300 hover:bg-purple-50 transition-all text-left">
<div className="text-sm font-medium text-gray-900">Impressum pruefen</div>
<div className="text-xs text-gray-500 mt-0.5">§5 TMG Pflichtangaben</div>
</button>
{discoveredDocs.map((doc: any, i: number) => (
<button key={i} onClick={() => navigateToCheck('doc-check', doc.url)} className="p-3 rounded-lg border border-gray-200 hover:border-purple-300 hover:bg-purple-50 transition-all text-left">
<div className="text-sm font-medium text-gray-900 truncate">{doc.title || doc.url}</div>
<div className="text-xs text-gray-500 mt-0.5">{doc.doc_type?.toUpperCase()} · {doc.word_count || '?'} Woerter{doc.completeness_pct != null && ` · ${doc.completeness_pct}%`}</div>
</button>
))}
</div>
</div>
)}
{scanData?.services && <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm"><ScanResult data={scanData} /></div>}
{scanHistory.length > 0 && (
<div className="border border-gray-200 rounded-xl p-4">
<h4 className="text-sm font-medium text-gray-700 mb-3">Letzte Scans</h4>
<div className="space-y-2">
{scanHistory.map((h, i) => (
<button key={i} onClick={() => { setUrl(h.url); if (h.resultKey) { try { const s = localStorage.getItem(h.resultKey); if (s) { setScanData(JSON.parse(s)); return } } catch {} } }}
className="w-full flex items-center justify-between p-3 rounded-lg border border-gray-100 hover:border-purple-200 hover:bg-purple-50/30 transition-all text-left">
<div className="min-w-0 flex-1"><div className="text-sm font-medium text-gray-900 truncate">{h.url}</div><div className="text-xs text-gray-500">{new Date(h.date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</div></div>
<div className="flex items-center gap-3 shrink-0 ml-3">{h.docs > 0 && <span className="text-xs text-purple-600">{h.docs} Dok.</span>}<span className={`text-xs font-medium ${h.findings > 0 ? 'text-red-600' : 'text-green-600'}`}>{h.findings} Findings</span></div>
</button>
))}
</div>
</div>
)}
</div>
)}
{tab === 'compliance-check' && <ComplianceCheckTab />}
{tab === 'banner-check' && <BannerCheckTab />}
<ComplianceFAQ />
</div>
)
}
@@ -1,45 +0,0 @@
'use client'
import Link from 'next/link'
interface Props {
/** Risk classification of the AI system. Tile is only rendered for high_risk / unacceptable. */
riskLevel: string
}
/**
* Renders a tile pointing to the BSI QUAIDAL-based data-quality control tab.
* AI Act Article 10 obligations (training-data quality) apply only to high-risk
* systems, so the tile is skipped for limited / minimal / not-applicable classes.
*/
export function Art10Tile({ riskLevel }: Props) {
if (riskLevel !== 'high_risk' && riskLevel !== 'unacceptable') return null
return (
<Link
href="/sdk/quality?category=data_quality"
className="block mt-3 p-3 rounded-lg border border-purple-200 bg-purple-50 hover:bg-purple-100 transition-colors"
>
<div className="flex items-start gap-3">
<div className="w-9 h-9 rounded-full bg-purple-200 text-purple-700 flex items-center justify-center shrink-0">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7M3 7l9 6 9-6M3 7l9-4 9 4" />
</svg>
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-semibold text-purple-900">
Art. 10 Datenqualität (Hochrisiko-KI)
</div>
<div className="text-xs text-purple-700 mt-0.5">
BSI QUAIDAL Controls: 10 Kriterien, 15 Bausteine, 30 Maßnahmen, 140 Metriken.
Klicken zum Öffnen des Trainingsdaten-Qualität-Moduls.
</div>
</div>
<svg className="w-4 h-4 text-purple-500 shrink-0 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</Link>
)
}
+82 -307
View File
@@ -8,180 +8,9 @@ import { LoadingSkeleton } from './_components/LoadingSkeleton'
import { RiskPyramid } from './_components/RiskPyramid'
import { AddSystemForm } from './_components/AddSystemForm'
import { AISystemCard } from './_components/AISystemCard'
import DecisionTreeWizard from '@/components/sdk/ai-act/DecisionTreeWizard'
import { Art10Tile } from './_components/Art10Tile'
type TabId = 'overview' | 'decision-tree' | 'results'
// SAVED RESULTS TAB
// =============================================================================
interface SavedResult {
id: string
system_name: string
system_description?: string
high_risk_result: string
gpai_result: { gpai_category: string; is_systemic_risk: boolean }
combined_obligations: string[]
created_at: string
}
function SavedResultsTab() {
const [results, setResults] = useState<SavedResult[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
const load = async () => {
try {
const res = await fetch('/api/sdk/v1/ucca/decision-tree/results')
if (res.ok) {
const data = await res.json()
setResults(data.results || [])
}
} catch {
// Ignore
} finally {
setLoading(false)
}
}
load()
}, [])
const handleDelete = async (id: string) => {
if (!confirm('Ergebnis wirklich löschen?')) return
try {
const res = await fetch(`/api/sdk/v1/ucca/decision-tree/results/${id}`, { method: 'DELETE' })
if (res.ok) {
setResults(prev => prev.filter(r => r.id !== id))
}
} catch {
// Ignore
}
}
const riskLabels: Record<string, string> = {
unacceptable: 'Unzulässig',
high_risk: 'Hochrisiko',
limited_risk: 'Begrenztes Risiko',
minimal_risk: 'Minimales Risiko',
not_applicable: 'Nicht anwendbar',
}
const riskColors: Record<string, string> = {
unacceptable: 'bg-red-100 text-red-700',
high_risk: 'bg-orange-100 text-orange-700',
limited_risk: 'bg-yellow-100 text-yellow-700',
minimal_risk: 'bg-green-100 text-green-700',
not_applicable: 'bg-gray-100 text-gray-500',
}
const gpaiLabels: Record<string, string> = {
none: 'Kein GPAI',
standard: 'GPAI Standard',
systemic: 'GPAI Systemisch',
}
const gpaiColors: Record<string, string> = {
none: 'bg-gray-100 text-gray-500',
standard: 'bg-blue-100 text-blue-700',
systemic: 'bg-purple-100 text-purple-700',
}
if (loading) {
return <LoadingSkeleton />
}
if (results.length === 0) {
return (
<div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
<div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center mb-4">
<svg className="w-8 h-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
</div>
<h3 className="text-lg font-semibold text-gray-900">Keine Ergebnisse vorhanden</h3>
<p className="mt-2 text-gray-500">Nutzen Sie den Entscheidungsbaum, um KI-Systeme zu klassifizieren.</p>
</div>
)
}
return (
<div className="space-y-4">
{results.map(r => (
<div key={r.id} className="bg-white rounded-xl border border-gray-200 p-5">
<div className="flex items-start justify-between">
<div>
<h4 className="font-semibold text-gray-900">{r.system_name}</h4>
{r.system_description && (
<p className="text-sm text-gray-500 mt-0.5">{r.system_description}</p>
)}
<div className="flex items-center gap-2 mt-2">
<span className={`px-2 py-1 text-xs rounded-full ${riskColors[r.high_risk_result] || 'bg-gray-100 text-gray-500'}`}>
{riskLabels[r.high_risk_result] || r.high_risk_result}
</span>
<span className={`px-2 py-1 text-xs rounded-full ${gpaiColors[r.gpai_result?.gpai_category] || 'bg-gray-100 text-gray-500'}`}>
{gpaiLabels[r.gpai_result?.gpai_category] || 'Kein GPAI'}
</span>
{r.gpai_result?.is_systemic_risk && (
<span className="px-2 py-1 text-xs rounded-full bg-red-100 text-red-700">Systemisch</span>
)}
</div>
<div className="text-xs text-gray-400 mt-2">
{r.combined_obligations?.length || 0} Pflichten &middot; {new Date(r.created_at).toLocaleDateString('de-DE')}
</div>
</div>
<button
onClick={() => handleDelete(r.id)}
className="px-3 py-1 text-xs text-red-600 hover:bg-red-50 rounded transition-colors"
>
Löschen
</button>
</div>
<Art10Tile riskLevel={r.high_risk_result} />
</div>
))}
</div>
)
}
// TABS
// =============================================================================
const TABS: { id: TabId; label: string; icon: React.ReactNode }[] = [
{
id: 'overview',
label: 'Übersicht',
icon: (
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" />
</svg>
),
},
{
id: 'decision-tree',
label: 'Entscheidungsbaum',
icon: (
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 010 3.75H5.625a1.875 1.875 0 010-3.75z" />
</svg>
),
},
{
id: 'results',
label: 'Ergebnisse',
icon: (
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z" />
</svg>
),
},
]
// MAIN PAGE
export default function AIActPage() {
const { state } = useSDK()
const [activeTab, setActiveTab] = useState<TabId>('overview')
const [systems, setSystems] = useState<AISystem[]>([])
const [filter, setFilter] = useState<string>('all')
const [showAddForm, setShowAddForm] = useState(false)
@@ -349,48 +178,17 @@ export default function AIActPage() {
explanation={stepInfo.explanation}
tips={stepInfo.tips}
>
{activeTab === 'overview' && (
<button
onClick={() => setShowAddForm(true)}
className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
KI-System registrieren
</button>
)}
<button
onClick={() => setShowAddForm(true)}
className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
KI-System registrieren
</button>
</StepHeader>
<div className="px-4 py-2 bg-emerald-50 border border-emerald-200 rounded-lg text-xs text-emerald-800 flex items-start gap-2">
<span className="font-semibold">Quellen &amp; Lizenz:</span>
<span>
Inhalte gemaess <strong>EU-Verordnung 2024/1689 (KI-Verordnung / AI Act)</strong>
Lizenzregel R1 (EU_LAW, woertlich uebernehmbar).
Risiko-Klassifizierungslogik basiert auf Anhang III der Verordnung.{' '}
<a href="/sdk/licenses" className="underline">Quellenverzeichnis</a>
</span>
</div>
{/* Tabs */}
<div className="flex items-center gap-1 bg-gray-100 p-1 rounded-lg w-fit">
{TABS.map(tab => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
activeTab === tab.id
? 'bg-white text-purple-700 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
{tab.icon}
{tab.label}
</button>
))}
</div>
{/* Error Banner */}
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
<span>{error}</span>
@@ -398,105 +196,82 @@ export default function AIActPage() {
</div>
)}
{/* Tab: Overview */}
{activeTab === 'overview' && (
<>
{/* Add/Edit System Form */}
{showAddForm && (
<AddSystemForm
onSubmit={handleAddSystem}
onCancel={() => { setShowAddForm(false); setEditingSystem(null) }}
initialData={editingSystem}
{showAddForm && (
<AddSystemForm
onSubmit={handleAddSystem}
onCancel={() => { setShowAddForm(false); setEditingSystem(null) }}
initialData={editingSystem}
/>
)}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="text-sm text-gray-500">KI-Systeme gesamt</div>
<div className="text-3xl font-bold text-gray-900">{systems.length}</div>
</div>
<div className="bg-white rounded-xl border border-orange-200 p-6">
<div className="text-sm text-orange-600">Hochrisiko</div>
<div className="text-3xl font-bold text-orange-600">{highRiskCount}</div>
</div>
<div className="bg-white rounded-xl border border-green-200 p-6">
<div className="text-sm text-green-600">Konform</div>
<div className="text-3xl font-bold text-green-600">{compliantCount}</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="text-sm text-gray-500">Nicht klassifiziert</div>
<div className="text-3xl font-bold text-gray-500">{unclassifiedCount}</div>
</div>
</div>
<RiskPyramid systems={systems} />
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm text-gray-500">Filter:</span>
{['all', 'high-risk', 'limited-risk', 'minimal-risk', 'unclassified', 'compliant', 'non-compliant'].map(f => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1 text-sm rounded-full transition-colors ${
filter === f ? 'bg-purple-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{f === 'all' ? 'Alle' :
f === 'high-risk' ? 'Hochrisiko' :
f === 'limited-risk' ? 'Begrenztes Risiko' :
f === 'minimal-risk' ? 'Minimales Risiko' :
f === 'unclassified' ? 'Nicht klassifiziert' :
f === 'compliant' ? 'Konform' : 'Nicht konform'}
</button>
))}
</div>
{loading && <LoadingSkeleton />}
{!loading && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{filteredSystems.map(system => (
<AISystemCard
key={system.id}
system={system}
onAssess={() => handleAssess(system.id)}
onEdit={() => handleEdit(system)}
onDelete={() => handleDelete(system.id)}
assessing={assessingId === system.id}
/>
)}
{/* Stats */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="text-sm text-gray-500">KI-Systeme gesamt</div>
<div className="text-3xl font-bold text-gray-900">{systems.length}</div>
</div>
<div className="bg-white rounded-xl border border-orange-200 p-6">
<div className="text-sm text-orange-600">Hochrisiko</div>
<div className="text-3xl font-bold text-orange-600">{highRiskCount}</div>
</div>
<div className="bg-white rounded-xl border border-green-200 p-6">
<div className="text-sm text-green-600">Konform</div>
<div className="text-3xl font-bold text-green-600">{compliantCount}</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 p-6">
<div className="text-sm text-gray-500">Nicht klassifiziert</div>
<div className="text-3xl font-bold text-gray-500">{unclassifiedCount}</div>
</div>
</div>
{/* Risk Pyramid */}
<RiskPyramid systems={systems} />
{/* Filter */}
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm text-gray-500">Filter:</span>
{['all', 'high-risk', 'limited-risk', 'minimal-risk', 'unclassified', 'compliant', 'non-compliant'].map(f => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1 text-sm rounded-full transition-colors ${
filter === f
? 'bg-purple-600 text-white'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{f === 'all' ? 'Alle' :
f === 'high-risk' ? 'Hochrisiko' :
f === 'limited-risk' ? 'Begrenztes Risiko' :
f === 'minimal-risk' ? 'Minimales Risiko' :
f === 'unclassified' ? 'Nicht klassifiziert' :
f === 'compliant' ? 'Konform' : 'Nicht konform'}
</button>
))}
</div>
{/* Loading */}
{loading && <LoadingSkeleton />}
{/* AI Systems List */}
{!loading && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{filteredSystems.map(system => (
<AISystemCard
key={system.id}
system={system}
onAssess={() => handleAssess(system.id)}
onEdit={() => handleEdit(system)}
onDelete={() => handleDelete(system.id)}
assessing={assessingId === system.id}
/>
))}
</div>
)}
{!loading && filteredSystems.length === 0 && (
<div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
<div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center mb-4">
<svg className="w-8 h-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
</div>
<h3 className="text-lg font-semibold text-gray-900">Keine KI-Systeme gefunden</h3>
<p className="mt-2 text-gray-500">Passen Sie den Filter an oder registrieren Sie ein neues KI-System.</p>
</div>
)}
</>
))}
</div>
)}
{/* Tab: Decision Tree */}
{activeTab === 'decision-tree' && (
<DecisionTreeWizard />
)}
{/* Tab: Results */}
{activeTab === 'results' && (
<SavedResultsTab />
{!loading && filteredSystems.length === 0 && (
<div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
<div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center mb-4">
<svg className="w-8 h-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
</div>
<h3 className="text-lg font-semibold text-gray-900">Keine KI-Systeme gefunden</h3>
<p className="mt-2 text-gray-500">Passen Sie den Filter an oder registrieren Sie ein neues KI-System.</p>
</div>
)}
</div>
)
@@ -1,491 +0,0 @@
'use client'
import React, { useState, useEffect } from 'react'
interface Registration {
id: string
system_name: string
system_version: string
risk_classification: string
gpai_classification: string
registration_status: string
eu_database_id: string
provider_name: string
created_at: string
}
const STATUS_STYLES: Record<string, { bg: string; text: string; label: string }> = {
draft: { bg: 'bg-gray-100', text: 'text-gray-700', label: 'Entwurf' },
ready: { bg: 'bg-blue-100', text: 'text-blue-700', label: 'Bereit' },
submitted: { bg: 'bg-yellow-100', text: 'text-yellow-700', label: 'Eingereicht' },
registered: { bg: 'bg-green-100', text: 'text-green-700', label: 'Registriert' },
update_required: { bg: 'bg-orange-100', text: 'text-orange-700', label: 'Update noetig' },
withdrawn: { bg: 'bg-red-100', text: 'text-red-700', label: 'Zurueckgezogen' },
}
const RISK_STYLES: Record<string, { bg: string; text: string }> = {
high_risk: { bg: 'bg-red-100', text: 'text-red-700' },
limited_risk: { bg: 'bg-yellow-100', text: 'text-yellow-700' },
minimal_risk: { bg: 'bg-green-100', text: 'text-green-700' },
not_classified: { bg: 'bg-gray-100', text: 'text-gray-500' },
}
const INITIAL_FORM = {
system_name: '',
system_version: '1.0',
system_description: '',
intended_purpose: '',
provider_name: '',
provider_legal_form: '',
provider_address: '',
provider_country: 'DE',
eu_representative_name: '',
eu_representative_contact: '',
risk_classification: 'not_classified',
annex_iii_category: '',
gpai_classification: 'none',
conformity_assessment_type: 'internal',
notified_body_name: '',
notified_body_id: '',
ce_marking: false,
training_data_summary: '',
}
export default function AIRegistrationPage() {
const [registrations, setRegistrations] = useState<Registration[]>([])
const [loading, setLoading] = useState(true)
const [showWizard, setShowWizard] = useState(false)
const [wizardStep, setWizardStep] = useState(1)
const [form, setForm] = useState({ ...INITIAL_FORM })
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => { loadRegistrations() }, [])
async function loadRegistrations() {
try {
setLoading(true)
const resp = await fetch('/api/sdk/v1/ai-registration')
if (resp.ok) {
const data = await resp.json()
setRegistrations(data.registrations || [])
}
} catch {
setError('Fehler beim Laden')
} finally {
setLoading(false)
}
}
async function handleSubmit() {
setSubmitting(true)
try {
const resp = await fetch('/api/sdk/v1/ai-registration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
})
if (resp.ok) {
setShowWizard(false)
setForm({ ...INITIAL_FORM })
setWizardStep(1)
loadRegistrations()
} else {
const data = await resp.json()
setError(data.error || 'Fehler beim Erstellen')
}
} catch {
setError('Netzwerkfehler')
} finally {
setSubmitting(false)
}
}
async function handleExport(id: string) {
try {
const resp = await fetch(`/api/sdk/v1/ai-registration/${id}`)
if (resp.ok) {
const reg = await resp.json()
// Build export JSON client-side
const exportData = {
schema_version: '1.0',
submission_type: 'ai_system_registration',
regulation: 'EU AI Act (EU) 2024/1689',
article: 'Art. 49',
provider: { name: reg.provider_name, address: reg.provider_address, country: reg.provider_country },
system: { name: reg.system_name, version: reg.system_version, description: reg.system_description, purpose: reg.intended_purpose },
classification: { risk_level: reg.risk_classification, annex_iii: reg.annex_iii_category, gpai: reg.gpai_classification },
conformity: { type: reg.conformity_assessment_type, ce_marking: reg.ce_marking },
}
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `eu_ai_registration_${reg.system_name.replace(/\s+/g, '_')}.json`
a.click()
URL.revokeObjectURL(url)
}
} catch {
setError('Export fehlgeschlagen')
}
}
async function handleStatusChange(id: string, status: string) {
try {
await fetch(`/api/sdk/v1/ai-registration/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status }),
})
loadRegistrations()
} catch {
setError('Status-Aenderung fehlgeschlagen')
}
}
const updateForm = (updates: Partial<typeof form>) => setForm(prev => ({ ...prev, ...updates }))
const STEPS = [
{ id: 1, title: 'Anbieter', desc: 'Unternehmensangaben' },
{ id: 2, title: 'System', desc: 'KI-System Details' },
{ id: 3, title: 'Klassifikation', desc: 'Risikoeinstufung' },
{ id: 4, title: 'Konformitaet', desc: 'CE & Notified Body' },
{ id: 5, title: 'Trainingsdaten', desc: 'Datenzusammenfassung' },
{ id: 6, title: 'Pruefung', desc: 'Zusammenfassung & Export' },
]
return (
<div className="max-w-5xl mx-auto p-6">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold text-gray-900">EU AI Database Registrierung</h1>
<p className="text-sm text-gray-500 mt-1">Art. 49 KI-Verordnung (EU) 2024/1689 Registrierung von Hochrisiko-KI-Systemen</p>
</div>
<button
onClick={() => setShowWizard(true)}
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
>
+ Neue Registrierung
</button>
</div>
{error && (
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
{error}
<button onClick={() => setError(null)} className="ml-2 underline">Schliessen</button>
</div>
)}
{/* Stats */}
<div className="grid grid-cols-4 gap-4 mb-8">
{['draft', 'ready', 'submitted', 'registered'].map(status => {
const count = registrations.filter(r => r.registration_status === status).length
const style = STATUS_STYLES[status]
return (
<div key={status} className={`p-4 rounded-xl border ${style.bg}`}>
<div className={`text-2xl font-bold ${style.text}`}>{count}</div>
<div className="text-sm text-gray-600">{style.label}</div>
</div>
)
})}
</div>
{/* Registrations List */}
{loading ? (
<div className="text-center py-12 text-gray-500">Lade...</div>
) : registrations.length === 0 ? (
<div className="text-center py-12 text-gray-400">
<p className="text-lg mb-2">Noch keine Registrierungen</p>
<p className="text-sm">Erstelle eine neue Registrierung fuer dein Hochrisiko-KI-System.</p>
</div>
) : (
<div className="space-y-4">
{registrations.map(reg => {
const status = STATUS_STYLES[reg.registration_status] || STATUS_STYLES.draft
const risk = RISK_STYLES[reg.risk_classification] || RISK_STYLES.not_classified
return (
<div key={reg.id} className="bg-white rounded-xl border border-gray-200 p-6 hover:border-purple-300 transition-all">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="text-lg font-semibold text-gray-900">{reg.system_name}</h3>
<span className="text-sm text-gray-400">v{reg.system_version}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${status.bg} ${status.text}`}>{status.label}</span>
<span className={`px-2 py-0.5 text-xs rounded-full ${risk.bg} ${risk.text}`}>{reg.risk_classification.replace('_', ' ')}</span>
{reg.gpai_classification !== 'none' && (
<span className="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-700">GPAI: {reg.gpai_classification}</span>
)}
</div>
<div className="text-sm text-gray-500">
{reg.provider_name && <span>{reg.provider_name} · </span>}
{reg.eu_database_id && <span>EU-ID: {reg.eu_database_id} · </span>}
<span>{new Date(reg.created_at).toLocaleDateString('de-DE')}</span>
</div>
</div>
<div className="flex gap-2">
<button onClick={() => handleExport(reg.id)} className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg hover:bg-gray-50">
JSON Export
</button>
{reg.registration_status === 'draft' && (
<button onClick={() => handleStatusChange(reg.id, 'ready')} className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">
Bereit markieren
</button>
)}
{reg.registration_status === 'ready' && (
<button onClick={() => handleStatusChange(reg.id, 'submitted')} className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700">
Als eingereicht markieren
</button>
)}
</div>
</div>
</div>
)
})}
</div>
)}
{/* Wizard Modal */}
{showWizard && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
<div className="p-6 border-b">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold text-gray-900">Neue EU AI Registrierung</h2>
<button onClick={() => { setShowWizard(false); setWizardStep(1) }} className="text-gray-400 hover:text-gray-600 text-2xl">&times;</button>
</div>
{/* Step Indicator */}
<div className="flex gap-1">
{STEPS.map(step => (
<button key={step.id} onClick={() => setWizardStep(step.id)}
className={`flex-1 py-2 text-xs rounded-lg transition-all ${
wizardStep === step.id ? 'bg-purple-100 text-purple-700 font-medium' :
wizardStep > step.id ? 'bg-green-50 text-green-700' : 'bg-gray-50 text-gray-400'
}`}>
{wizardStep > step.id ? '✓ ' : ''}{step.title}
</button>
))}
</div>
</div>
<div className="p-6 space-y-4">
{/* Step 1: Provider */}
{wizardStep === 1 && (
<>
<h3 className="font-semibold text-gray-900">Anbieter-Informationen</h3>
<p className="text-sm text-gray-500">Angaben zum Anbieter des KI-Systems gemaess Art. 49 KI-VO.</p>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Firmenname *</label>
<input value={form.provider_name} onChange={e => updateForm({ provider_name: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="Acme GmbH" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Rechtsform</label>
<input value={form.provider_legal_form} onChange={e => updateForm({ provider_legal_form: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="GmbH" />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Adresse</label>
<input value={form.provider_address} onChange={e => updateForm({ provider_address: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="Musterstr. 1, 20095 Hamburg" />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Land</label>
<select value={form.provider_country} onChange={e => updateForm({ provider_country: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
<option value="DE">Deutschland</option>
<option value="AT">Oesterreich</option>
<option value="CH">Schweiz</option>
<option value="OTHER">Anderes Land</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">EU-Repraesentant (falls Non-EU)</label>
<input value={form.eu_representative_name} onChange={e => updateForm({ eu_representative_name: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="Optional" />
</div>
</div>
</>
)}
{/* Step 2: System */}
{wizardStep === 2 && (
<>
<h3 className="font-semibold text-gray-900">KI-System Details</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Systemname *</label>
<input value={form.system_name} onChange={e => updateForm({ system_name: 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. HR Copilot" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Version</label>
<input value={form.system_version} onChange={e => updateForm({ system_version: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="1.0" />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Systembeschreibung</label>
<textarea value={form.system_description} onChange={e => updateForm({ system_description: e.target.value })} rows={3}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="Beschreibe was das KI-System tut..." />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Einsatzzweck (Intended Purpose)</label>
<textarea value={form.intended_purpose} onChange={e => updateForm({ intended_purpose: e.target.value })} rows={2}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="Wofuer wird das System eingesetzt?" />
</div>
</>
)}
{/* Step 3: Classification */}
{wizardStep === 3 && (
<>
<h3 className="font-semibold text-gray-900">Risiko-Klassifikation</h3>
<p className="text-sm text-gray-500">Basierend auf dem AI Act Decision Tree oder manueller Einstufung.</p>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Risikoklasse</label>
<select value={form.risk_classification} onChange={e => updateForm({ risk_classification: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
<option value="not_classified">Noch nicht klassifiziert</option>
<option value="minimal_risk">Minimal Risk</option>
<option value="limited_risk">Limited Risk</option>
<option value="high_risk">High Risk</option>
</select>
</div>
{form.risk_classification === 'high_risk' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Annex III Kategorie</label>
<select value={form.annex_iii_category} onChange={e => updateForm({ annex_iii_category: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
<option value="">Bitte waehlen...</option>
<option value="biometric">1. Biometrische Identifizierung</option>
<option value="critical_infrastructure">2. Kritische Infrastruktur</option>
<option value="education">3. Bildung und Berufsausbildung</option>
<option value="employment">4. Beschaeftigung und Arbeitnehmerverwaltung</option>
<option value="essential_services">5. Zugang zu wesentlichen Diensten</option>
<option value="law_enforcement">6. Strafverfolgung</option>
<option value="migration">7. Migration und Grenzkontrolle</option>
<option value="justice">8. Rechtspflege und Demokratie</option>
</select>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">GPAI Klassifikation</label>
<select value={form.gpai_classification} onChange={e => updateForm({ gpai_classification: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
<option value="none">Kein GPAI</option>
<option value="standard">GPAI (Standard)</option>
<option value="systemic">GPAI mit systemischem Risiko</option>
</select>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
<strong>Tipp:</strong> Nutze den <a href="/sdk/ai-act" className="underline">AI Act Decision Tree</a> fuer eine strukturierte Klassifikation.
</div>
</>
)}
{/* Step 4: Conformity */}
{wizardStep === 4 && (
<>
<h3 className="font-semibold text-gray-900">Konformitaetsbewertung</h3>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Art der Konformitaetsbewertung</label>
<select value={form.conformity_assessment_type} onChange={e => updateForm({ conformity_assessment_type: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
<option value="not_required">Nicht erforderlich</option>
<option value="internal">Interne Konformitaetsbewertung</option>
<option value="third_party">Drittpartei-Bewertung (Notified Body)</option>
</select>
</div>
{form.conformity_assessment_type === 'third_party' && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Notified Body Name</label>
<input value={form.notified_body_name} onChange={e => updateForm({ notified_body_name: 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">Notified Body ID</label>
<input value={form.notified_body_id} onChange={e => updateForm({ notified_body_id: 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="flex items-center gap-3 p-3 rounded-lg border hover:bg-gray-50 cursor-pointer">
<input type="checkbox" checked={form.ce_marking} onChange={e => updateForm({ ce_marking: e.target.checked })}
className="w-4 h-4 rounded border-gray-300 text-purple-600" />
<span className="text-sm font-medium text-gray-900">CE-Kennzeichnung angebracht</span>
</label>
</>
)}
{/* Step 5: Training Data */}
{wizardStep === 5 && (
<>
<h3 className="font-semibold text-gray-900">Trainingsdaten-Zusammenfassung</h3>
<p className="text-sm text-gray-500">Art. 10 KI-VO Keine vollstaendige Offenlegung, sondern Kategorien und Herkunft.</p>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Zusammenfassung der Trainingsdaten</label>
<textarea value={form.training_data_summary} onChange={e => updateForm({ training_data_summary: e.target.value })} rows={5}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
placeholder="Beschreibe die verwendeten Datenquellen:&#10;- Oeffentliche Daten (z.B. Wikipedia, Common Crawl)&#10;- Lizenzierte Daten (z.B. Fachpublikationen)&#10;- Synthetische Daten&#10;- Unternehmensinterne Daten" />
</div>
</>
)}
{/* Step 6: Review */}
{wizardStep === 6 && (
<>
<h3 className="font-semibold text-gray-900">Zusammenfassung</h3>
<div className="space-y-3 text-sm">
<div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
<div><span className="text-gray-500">Anbieter:</span> <strong>{form.provider_name || ''}</strong></div>
<div><span className="text-gray-500">Land:</span> <strong>{form.provider_country}</strong></div>
<div><span className="text-gray-500">System:</span> <strong>{form.system_name || ''}</strong></div>
<div><span className="text-gray-500">Version:</span> <strong>{form.system_version}</strong></div>
<div><span className="text-gray-500">Risiko:</span> <strong>{form.risk_classification}</strong></div>
<div><span className="text-gray-500">GPAI:</span> <strong>{form.gpai_classification}</strong></div>
<div><span className="text-gray-500">Konformitaet:</span> <strong>{form.conformity_assessment_type}</strong></div>
<div><span className="text-gray-500">CE:</span> <strong>{form.ce_marking ? 'Ja' : 'Nein'}</strong></div>
</div>
{form.intended_purpose && (
<div className="p-4 bg-gray-50 rounded-lg">
<span className="text-gray-500">Zweck:</span> {form.intended_purpose}
</div>
)}
</div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-sm text-yellow-800">
<strong>Hinweis:</strong> Die EU AI Datenbank befindet sich noch im Aufbau. Die Registrierung wird lokal gespeichert und kann spaeter uebermittelt werden.
</div>
</>
)}
</div>
{/* Navigation */}
<div className="p-6 border-t flex justify-between">
<button onClick={() => wizardStep > 1 ? setWizardStep(wizardStep - 1) : setShowWizard(false)}
className="px-4 py-2 text-gray-700 border rounded-lg hover:bg-gray-50">
{wizardStep === 1 ? 'Abbrechen' : 'Zurueck'}
</button>
{wizardStep < 6 ? (
<button onClick={() => setWizardStep(wizardStep + 1)}
disabled={wizardStep === 2 && !form.system_name}
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50">
Weiter
</button>
) : (
<button onClick={handleSubmit} disabled={submitting || !form.system_name}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50">
{submitting ? 'Speichere...' : 'Registrierung erstellen'}
</button>
)}
</div>
</div>
</div>
)}
</div>
)
}

Some files were not shown because too many files have changed in this diff Show More