Compare commits
115
Commits
V0.9
...
vor_Multi_Group
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d34c0a73d | ||
|
|
ae51d201bc | ||
|
|
220a16429c | ||
|
|
e759076a6c | ||
|
|
8175e239b4 | ||
|
|
8f5af49a6f | ||
|
|
e7dc6a6cd3 | ||
|
|
e09a2284e9 | ||
|
|
b0faa4bfab | ||
|
|
a1a3f2e0a1 | ||
|
|
45bc049c0d | ||
|
|
e4e362b0a9 | ||
|
|
300d916fad | ||
|
|
1631bd2e02 | ||
|
|
2e105a99b8 | ||
|
|
4235246cd7 | ||
|
|
57a8957c93 | ||
|
|
930a786315 | ||
|
|
9da29a2231 | ||
|
|
b06d026dd0 | ||
|
|
32ba008660 | ||
|
|
657fcc241a | ||
|
|
c69edc6952 | ||
|
|
789b640ad0 | ||
|
|
14cf8a1a53 | ||
|
|
ea4c1f87f6 | ||
|
|
2fa1db55fd | ||
|
|
75ddd06d6a | ||
|
|
597486bef1 | ||
|
|
ebad8025f4 | ||
|
|
c7650cac2f | ||
|
|
4b2848c7c3 | ||
|
|
255fa45e90 | ||
|
|
7043addd15 | ||
|
|
1c268555f6 | ||
|
|
85163ad440 | ||
|
|
502dddd3b3 | ||
|
|
00edc7a93d | ||
|
|
d50bed428b | ||
|
|
49adb395dd | ||
|
|
81fd7d9b3b | ||
|
|
3898e8bc2c | ||
|
|
d3ddc52118 | ||
|
|
79dabbca5a | ||
|
|
ed15f73727 | ||
|
|
a8942a9e4e | ||
|
|
5dc93d9a8c | ||
|
|
805ad3c5a5 | ||
|
|
13efce6e36 | ||
|
|
cf9932990e | ||
|
|
38d84ecdf6 | ||
|
|
ce63d46cf4 | ||
|
|
435da7f17a | ||
|
|
4e654e50c0 | ||
|
|
12fd3926b2 | ||
|
|
919910d52a | ||
|
|
3dc4c9c79e | ||
|
|
8a9f9f960f | ||
|
|
f4f5642c21 | ||
|
|
05042ee9ec | ||
|
|
e96951728d | ||
|
|
bfaf532ab2 | ||
|
|
e41908af73 | ||
|
|
c1243651bb | ||
|
|
59d53d6154 | ||
|
|
98edb282ed | ||
|
|
81b9e8f601 | ||
|
|
04663e090a | ||
|
|
56fc6d853d | ||
|
|
5cf61289ec | ||
|
|
9af28faa35 | ||
|
|
34e93101f1 | ||
|
|
bb4d927090 | ||
|
|
8dd748e7d9 | ||
|
|
bacba311ae | ||
|
|
24bf3f7035 | ||
|
|
0dbcd4175c | ||
|
|
2f7e1e50ad | ||
|
|
60709df615 | ||
|
|
3c0e63757c | ||
|
|
ee54f8380f | ||
|
|
f79f83e8f9 | ||
|
|
fb8837574e | ||
|
|
1ce6d929ce | ||
|
|
1640fe6045 | ||
|
|
61baf26da6 | ||
|
|
0edc86e05a | ||
|
|
b2b7bd423d | ||
|
|
56e952f084 | ||
|
|
6586d3b68b | ||
|
|
fff30b49e1 | ||
|
|
f544975a6c | ||
|
|
4bc24b4caf | ||
|
|
42aec79ad1 | ||
|
|
9ac8200b41 | ||
|
|
000e78e976 | ||
|
|
34235ef46d | ||
|
|
8cda5c27ec | ||
|
|
aff3020b13 | ||
|
|
456ead72b6 | ||
|
|
030eb41429 | ||
|
|
5db8f8588c | ||
|
|
8992c300f1 | ||
|
|
b9adf6da84 | ||
|
|
80936b226d | ||
|
|
8bed0199b6 | ||
|
|
cfab5c2d69 | ||
|
|
8261fa4420 | ||
|
|
75d6a40817 | ||
|
|
d7ed0c0e9b | ||
|
|
d73ed13f87 | ||
|
|
6abc911e94 | ||
|
|
28ca64b5b4 | ||
|
|
fc33bfbdeb | ||
|
|
be0385922d |
No files matched your search
@@ -1,21 +1,25 @@
|
||||
# Shinkan Jinkendo - Projekt-Status
|
||||
|
||||
**Stand:** 2026-05-08
|
||||
**Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||
**Stand:** 2026-05-12
|
||||
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||
**Branch:** develop
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge), plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop mit Auto-Scroll, Vorschau-/Rückweg-UX). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
|
||||
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`**, **Papierkorb & Lifecycle**, plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag-and-Drop mit Auto-Scroll). **Governance:** Sichtbarkeit **`official`** nur **Superadmin** (Übungen und Medien). **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert.
|
||||
|
||||
**Melde- und Transparenzpfad (P-13, seit 0.8.87 ff.):** **Inhaltsmeldungen** mit Workflow im Posteingang, Club-Admin-Beteiligung für Vereinsmedien, Legal-Hold-Anbindung, Badges in der Medienbibliothek; Folgepakete P-14–P-16 bewusst offen (siehe `docs/HANDOVER.md`).
|
||||
|
||||
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
||||
|
||||
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
||||
|
||||
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
|
||||
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-12, für **neue Session**):
|
||||
|
||||
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
|
||||
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
|
||||
@@ -23,15 +27,16 @@
|
||||
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
|
||||
5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
|
||||
|
||||
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** Abschnitt 11; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||
|
||||
---
|
||||
|
||||
**Nächste Schritte (Auszug — Planung/Rahmen):**
|
||||
**Nächste Schritte (Auszug — Planung/Rahmen & Kombination):**
|
||||
|
||||
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
||||
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
|
||||
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
|
||||
4. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -150,17 +155,18 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
| Dokument | Pfad | Stand | Status |
|
||||
|----------|------|-------|--------|
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-08 | ✅ Aktualisiert (§12 Medien inkl. Inline 0.8.60–0.8.64) |
|
||||
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-12 | neu, Ist-Überblick |
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-12 | Verweis Version siehe `version.py` |
|
||||
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
|
||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
|
||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-07 | ✅ Abschnitt Medien-Archiv |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
||||
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
|
||||
|
||||
---
|
||||
|
||||
@@ -171,4 +177,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
|
||||
**Letzte Aktualisierung:** 2026-05-12 (Version 0.8.96, Executive Summary P-13/P-01, `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo - Fachliches Domänenmodell
|
||||
|
||||
**Version:** 0.4.4
|
||||
**Stand:** 2026-05-08 (Medien-Archiv **`media_assets`** / Bibliothek **`/media`** im Ist; **Inline-Medien** im Fließtext umgesetzt — `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11)
|
||||
**Version:** 0.4.6
|
||||
**Stand:** 2026-05-14 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||
|
||||
---
|
||||
@@ -474,6 +474,16 @@ skill_level_definitions (
|
||||
|
||||
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
|
||||
|
||||
### Parallele Trainingsstreams (Breakout, Entwurf)
|
||||
|
||||
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
|
||||
|
||||
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
|
||||
|
||||
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||
|
||||
**Schema-Hinweis (2026-05):** Tabelle `training_unit_sections` hat **`UNIQUE (training_unit_id, order_index)`** (Migration 031). Damit sind **zwei gleichzeitige „Spuren“ mit jeweils eigener Sektion auf derselben `order_index`** nicht abbildbar — Voraussetzung für Parallele Streams ist eine **geplante Migrations-/Constraint-Anpassung** (partielle Uniques pro Phase/Stream); siehe Arbeitsdokument `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`. **Keine invasive Migration ohne explizite Freigabe.**
|
||||
|
||||
---
|
||||
|
||||
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Parallele Trainingsstreams (Breakout) — Fachkonzept
|
||||
|
||||
**Status:** Entwurf zur Abstimmung · **Stand:** 2026-05-14
|
||||
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
|
||||
|
||||
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
**Domänenbegriffe (Überblick):** `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||
|
||||
---
|
||||
|
||||
## 1. Ausgangslage und Problem
|
||||
|
||||
In Kinder- und Breitensport-Training ist ein typischer Ablauf:
|
||||
|
||||
1. **Gemeinsam:** Aufwärmen, Koordination, Ansagen.
|
||||
2. **Getrennt:** Kinder in mehrere Gruppen teilen; **Co-Trainer** leiten jeweils eigene Inhalte **gleichzeitig**.
|
||||
3. **Gemeinsam:** Abschluss, gemeinsame Übungen, Verabschiedung.
|
||||
|
||||
Die aktuelle Shinkan-Planung modelliert pro Termin **eine lineare Folge von Abschnitten und Übungen** pro Einheit. Das genügt nicht, wenn **mehrere gleichzeitige „Unter-Sessions“** mit unterschiedlichen Plänen dokumentiert und auf der Matte geführt werden sollen.
|
||||
|
||||
---
|
||||
|
||||
## 2. Ziele (fachlich)
|
||||
|
||||
| ID | Ziel |
|
||||
|----|------|
|
||||
| PT‑01 | Eine **Kalender-Einheit** bleibt **ein** Termin (eine Halle, eine Gruppe, ein Datum) — kein Splitten in künstlich mehrere Kalendereinträge nur für Parallelität. |
|
||||
| PT‑02 | **Unbegrenzte** Anzahl paralleler **Streams** (Teilstrecken) in einer oder mehreren **Parallelphasen**. |
|
||||
| PT‑03 | **Phasenmodell:** klar erkennbar **Gemeinsam** vs. **Parallel** vs. wieder **Gemeinsam** (auch mehrfach hintereinander möglich). |
|
||||
| PT‑04 | **Rollen:** Leitung (Haupttrainer) und Co-Trainer; Zuordnung der Co-Trainer **soll** an konkrete Streams anschließbar sein (heute: nur flache Liste pro Einheit — siehe technische Spec). |
|
||||
| PT‑05 | **Sonderfall Stationen:** rotierender Ablauf (z. B. Wechsel alle 20 Min.) **inhaltlich** unterscheiden zwischen (a) Rotation **innerhalb** einer Teilstrecke und (b) **synchron** getakteter Hallen-Rotation — siehe §5. |
|
||||
| PT‑06 | **Durchführung:** Trainer können „ihre“ Spur auf dem Gerät abarbeiten; Fortschritt pro Spur nachvollziehbar. |
|
||||
|
||||
**Nicht-Ziel (frühe Stufen):** Echtzeit-Synchronisation mehrerer Geräte; individuelles Athleten-Tracking; automatische Raumbelegung.
|
||||
|
||||
---
|
||||
|
||||
## 3. Begriffe
|
||||
|
||||
| Begriff | Definition |
|
||||
|---------|------------|
|
||||
| **Einheit / Termin** | Geplante `training_unit` für Gruppe und Datum — übergeordneter Rahmen des Abends. |
|
||||
| **Phase** | Organisatorischer Block innerhalb der Einheit: entweder **ganze Gruppe** oder **parallel**. |
|
||||
| **Stream / Teilstrecke** | Innerhalb einer Parallelphase: eine von N **gleichzeitig** stattfindenden Unter-Abläufen mit **eigenem** Miniplan (Abschnitte, Übungen, Notizen — analog heutiger Planung). |
|
||||
| **Synchronisationspunkt** | Fachlich: alle treffen sich wieder (Beginn einer **Gemeinschaftsphase** nach Parallelität). |
|
||||
| **Station (Rotation)** | Inhaltlicher Fokus oder Platz, den Teilnehmer **wechselnd** anlaufen; kann als Kombinations-/Zirkellogik oder als koordinierter Hallenrhythmus modelliert werden (§5). |
|
||||
|
||||
**Abgrenzung „Rahmenprogramm-Slot“:** Ein Slot im **Rahmenprogramm** ist eine **Session in einer Serie** (z. B. Woche 1 vs. Woche 2), **nicht** „Teilgruppe A gleichzeitig mit Teilgruppe B in derselben Stunde“. Parallele Streams sind **innerhalb einer Einheit**, orthogonal zum Rahmen-Slot.
|
||||
|
||||
**Abgrenzung **Kombinationsübung**:** Eine Kombi-Übung bündelt **mehrere Einzelübungen** mit Methodenprofil (Archetyp, ggf. Rotation) **in einem Plan-Item**. Sie ersetzt **nicht** mehrere Trainer mit **jeweils eigenem Gesamtablauf**, kann aber **pro Stream** für Stationslogik genutzt werden.
|
||||
|
||||
---
|
||||
|
||||
## 4. Szenarien
|
||||
|
||||
### 4.1 Klassischer Breakout
|
||||
|
||||
30 Min. gemeinsam → 25 Min. drei parallele Streams (Gruppe an Matte / an Schlagsack / Fußarbeit) → 15 Min. gemeinsam.
|
||||
|
||||
### 4.2 Viele Kinder, mehrere Co-Trainer
|
||||
|
||||
Haupttrainer plant die Gesamtstruktur; jeder Co-Trainer sieht in der Durchführung primär die zugewiesene Teilstrecke.
|
||||
|
||||
### 4.3 Rollierendes Stationssystem
|
||||
|
||||
Alle Gruppen arbeiten an **verschiedenen Schwerpunkten** und **wechseln** nach festem Intervall die Station — entweder **nur innerhalb einer Spur** oder **hallenweit synchron** (offene fachliche Präzisierung in MVP vs. später, §5).
|
||||
|
||||
---
|
||||
|
||||
## 5. Sonderfall: Stationen und Kombinationsübungen
|
||||
|
||||
### 5.1 Variante A — Rotation innerhalb einer Teilstrecke
|
||||
|
||||
Eine Teilgruppe rotiert durch mehrere Übungen (Zeit oder Runden). Das liegt nah an einer **Kombinationsübung** mit Archetyp z. B. „Zirkel / zeitgesteuerte Rotation“ und Parametern (Wechselintervall). **Empfehlung:** Diese Variante über **bestehendes** Kombinationsübungs-Konzept in der jeweiligen **Stream-Planung** abbilden (`planning_method_profile`).
|
||||
|
||||
### 5.2 Variante B — Synchron getaktete Hallen-Rotation
|
||||
|
||||
Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächsten Station; Startstation kann pro Teilgruppe **versetzt** sein. Das ist **organisatorisch** schwerer: es braucht entweder **Phasen-Metadaten** (globaler Takt) oder eine explizite **Rot/Matrix**. **Empfehlung:** In einer **zweiten Ausbaustufe** abbilden; MVP kann bei Variante A starten, sofern fachlich ausreichend.
|
||||
|
||||
---
|
||||
|
||||
## 6. Rollen und Verantwortlichkeiten
|
||||
|
||||
- **Leitungstrainer:** Hält den Faden, startet Gemeinschaftsphasen, koordiniert Parallelbeginn/-ende (fachlich; ggf. später UI-Hinweise).
|
||||
- **Co-Trainer:** Verantwortlich für **zugeteilte** Streams; Zuordnung soll **pro Stream** möglich werden (Erweiterung gegenüber reiner Einheits-Co-Trainer-Liste).
|
||||
|
||||
---
|
||||
|
||||
## 7. Offene fachliche Entscheidungen
|
||||
|
||||
1. **MVP Umfang:** Reicht **freie Parallelität** ohne **synchronen** Hallenwechsel (Variante B)?
|
||||
2. **Dauer:** Sollen Phasen oder Streams **Soll-Minuten** tragen (nur Anzeige vs. später Timer)?
|
||||
3. **Vorlagen:** Müssen `training_plan_templates` parallel-fähig werden **vor** oder **mit** der ersten Implementierung?
|
||||
4. **Sichtbarkeit:** Dürfen alle Co-Trainer alle Streams sehen, oder „nur meine Spur“?
|
||||
|
||||
---
|
||||
|
||||
## 8. Verwandte Dokumente
|
||||
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slots = Serien-Sessions, **nicht** Intra-Einheit-Parallelität |
|
||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
|
||||
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
|
||||
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
|
||||
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
|
||||
@@ -4,11 +4,15 @@ Ausführliche fachliche Inhalte:
|
||||
|
||||
| Dokument | Inhalt |
|
||||
|----------|--------|
|
||||
| [**Fachliche Nutzerfunktionen (Ist, Überblick)**](../../../docs/FACHLICHE_NUTZERFUNKTIONEN.md) | Kompakte **Nutzer-/Rollen-Perspektive** zur Übergabe an Design & Product (ohne Implementierungsdetail) |
|
||||
| [shinkan_anforderungsdokument_entwurf.md](./shinkan_anforderungsdokument_entwurf.md) | Gesamtentwurf Anforderungen |
|
||||
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (§11.2), **Medien-Archiv** (Abschnitt 2026-05) |
|
||||
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **geplante Inline-Medien §11** |
|
||||
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (Abschnitt 11.2), **Medien-Archiv** (Abschnitt 2026-05) |
|
||||
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **Inline-Medien** (Spec Abschnitt 11, umgesetzt) |
|
||||
| [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan |
|
||||
| [**Trainingsmodule & Kombinationsübungen (Fachspez V3)**](./Shinkan%20Trainingsmodule%20Kombinationsuebungen%20Spezifikation%20V2.md) | Produktlogik Module/Kombinationen, **Methoden-Archetypen**, **Coaching-Stufen (§ 10.4)**, kanonische Archetyp-IDs **§ 10.2.1**, **Anhang A** Implementierungsabgleich |
|
||||
| [**Umsetzungsplan Trainingsmodule & Kombination**](../working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md) | Phase 1–5, Coaching-Pakete 4a–4d, Verweis auf Code-Stand |
|
||||
| [**Technischer Entwurf Module/Kombination**](../technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md) | API/Daten-Ideen; aktueller Coach-/Archetyp-Abgleich im Kopfabschnitt |
|
||||
|
||||
**Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) §12, Repo-Root **`docs/HANDOVER.md`**.
|
||||
**Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) (Abschnitt 12), Repo-Root **`docs/HANDOVER.md`**, **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**.
|
||||
|
||||
`CLAUDE.md` (Repo-Root) verweist hierher als Einstieg.
|
||||
+829
@@ -0,0 +1,829 @@
|
||||
# Trainingsmodule und Kombinationsübungen — fachliche Spezifikation V3
|
||||
|
||||
**Status:** fachlicher Spezifikationsentwurf
|
||||
**Stand:** 2026-05-12 (Anhang A App **0.8.110**; Zeit‑Pfad **`COMBINATION_TIMING_PROFILE_PLAN.md`**) · **Coaching/Archetypen:** § 10.2.1, § 10.4–10.6, **§ 5.4/§ 6.3** Methoden/Archetypen/Zeitschicht · **Anhang A**
|
||||
**Zweck:** Produkt- und Fachspezifikation für Trainingsmodule, Kombinationsübungen, Trainingsmethodenbezug, Planungsintegration und Coaching-Modus in Shinkan.
|
||||
|
||||
**Wichtige Leitlinie dieser Version:**
|
||||
Diese Spezifikation beschreibt bewusst **keine verbindlichen Tabellen, API-Pfade, Spaltennamen oder konkrete Implementierungsdetails**. Die technische Umsetzung soll durch den Coding Agent auf Basis der bestehenden Codebasis geplant werden. Ziel dieses Dokuments ist es, die fachliche Zielarchitektur, Nutzerlogik, Datenbedeutung und Produktentscheidungen so klar zu beschreiben, dass spätere große Refactorings vermieden werden, ohne die bestehende Anwendung durch zu frühe technische Festlegungen zu destabilisieren.
|
||||
|
||||
---
|
||||
|
||||
## 1. Ausgangslage
|
||||
|
||||
Shinkan ist eine trainerzentrierte App für Übungsverwaltung, Trainingsplanung, Rahmenprogramme und Durchführung. Die bestehende Planung arbeitet fachlich mit Trainingseinheiten, Trainingsabschnitten und Einträgen wie Übungen oder Notizen.
|
||||
|
||||
Für die nächste Ausbaustufe werden zwei zusätzliche fachliche Bausteine benötigt:
|
||||
|
||||
1. **Kombinationsübungen**
|
||||
Strukturierte Übungsformen, bei denen mehrere Einzelübungen, Stationen, Rollen oder Schritte methodisch zusammenwirken.
|
||||
|
||||
2. **Trainingsmodule**
|
||||
Wiederverwendbare Planungsbausteine, also gespeicherte Übungsfolgen oder Trainingsblöcke, die in konkrete Trainings oder Rahmenprogramme übernommen werden können.
|
||||
|
||||
Zusätzlich muss geklärt werden, wie **Trainingsmethoden**, **Methoden-Archetypen** und **konkrete Ablaufprofile** fachlich voneinander getrennt werden.
|
||||
|
||||
---
|
||||
|
||||
## 2. Fachliche Grundentscheidungen
|
||||
|
||||
### 2.1 Trainingsabschnitte bleiben Makrostruktur
|
||||
|
||||
Trainingsabschnitte beschreiben die grobe Struktur einer Trainingseinheit, z. B.:
|
||||
|
||||
* Aufwärmen,
|
||||
* Hauptteil,
|
||||
* Kumite,
|
||||
* Kata,
|
||||
* Selbstschutz,
|
||||
* Abschluss.
|
||||
|
||||
Ein Abschnitt ist damit ein Gliederungselement der gesamten Trainingseinheit.
|
||||
|
||||
### 2.2 Kombinationsübungen sind nicht an genau einen Abschnitt gebunden
|
||||
|
||||
Eine Kombinationsübung darf nicht fachlich oder technisch auf genau einen Trainingsabschnitt reduziert werden.
|
||||
|
||||
Sie kann:
|
||||
|
||||
* innerhalb eines Abschnitts verwendet werden,
|
||||
* einen Abschnitt faktisch ausfüllen,
|
||||
* zwischen zwei Abschnitten stehen,
|
||||
* als zentraler Block der Einheit auf Trainingsebene liegen,
|
||||
* Bestandteil eines Trainingsmoduls sein,
|
||||
* Bestandteil eines Rahmenprogramms oder Rahmen-Slots sein.
|
||||
|
||||
Der Abschnitt kann ein sinnvoller Anzeige- oder Planungskontext sein, ist aber nicht die fachliche Heimat der Kombinationsübung.
|
||||
|
||||
### 2.3 Kombinationsübungen gehören fachlich zum Übungsbereich
|
||||
|
||||
Eine Kombinationsübung ist eine Sonderform einer Übung. Sie besitzt daher die typischen Eigenschaften einer Übung:
|
||||
|
||||
* Titel,
|
||||
* Ziel,
|
||||
* Durchführung,
|
||||
* Trainerhinweise,
|
||||
* Vorbereitung,
|
||||
* Hilfsmittel,
|
||||
* Dauer,
|
||||
* Zielgruppe,
|
||||
* Fähigkeiten,
|
||||
* Methodenbezug,
|
||||
* Medien,
|
||||
* Sichtbarkeit,
|
||||
* Freigabestatus.
|
||||
|
||||
Zusätzlich besitzt sie eine interne Struktur:
|
||||
|
||||
* Slots,
|
||||
* Stationen,
|
||||
* Rollen,
|
||||
* Schritte,
|
||||
* Übungspools,
|
||||
* Methoden-Archetyp,
|
||||
* Ablaufprofil für Planung und Coaching.
|
||||
|
||||
### 2.4 Trainingsmodule gehören fachlich zur Planung
|
||||
|
||||
Trainingsmodule sind keine Übungen, sondern wiederverwendbare Planungsbausteine.
|
||||
|
||||
Ein Trainingsmodul kann enthalten:
|
||||
|
||||
* einzelne Übungen,
|
||||
* Kombinationsübungen,
|
||||
* Notizen,
|
||||
* methodische Hinweise,
|
||||
* kurze wiederverwendbare Übungsfolgen,
|
||||
* größere Blöcke innerhalb einer Einheit.
|
||||
|
||||
Trainingsmodule sollten deshalb fachlich unter **Planung / Bibliothek / Module** verortet werden.
|
||||
|
||||
### 2.5 Einfügen bedeutet Kopie mit Herkunft, nicht Live-Verknüpfung
|
||||
|
||||
Wenn ein Trainingsmodul oder eine Kombinationsübung in eine konkrete Trainingseinheit übernommen wird, entsteht eine bearbeitbare Planungsinstanz.
|
||||
|
||||
Grundsatz:
|
||||
|
||||
> Bibliothek = Vorlage.
|
||||
> Planung = lokal bearbeitbare Übernahme.
|
||||
> Durchführung = tatsächliche Nutzung im Training.
|
||||
|
||||
Spätere Änderungen an der Vorlage dürfen bereits geplante oder historische Einheiten nicht ungefragt verändern.
|
||||
|
||||
---
|
||||
|
||||
## 3. Zentrale Begriffe
|
||||
|
||||
| Begriff | Fachliche Bedeutung |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Trainingseinheit** | Konkretes geplantes oder durchgeführtes Training. |
|
||||
| **Trainingsabschnitt** | Makrostruktur der Einheit, z. B. Aufwärmen oder Hauptteil. |
|
||||
| **Planungsblock** | Zusammenhängender Inhalt innerhalb einer Einheit, z. B. Modul, Kombinationsübung oder manuell gruppierter Block. |
|
||||
| **Kombinationsübung** | Sonderform einer Übung mit interner Struktur aus Slots, Stationen, Rollen oder Schritten. |
|
||||
| **Trainingsmodul** | Wiederverwendbarer Planungsbaustein aus Übungen, Kombinationsübungen und Notizen. |
|
||||
| **Trainingsmethode** | Fachlicher Katalogeintrag, der beschreibt, wie eine Trainingsform didaktisch oder sportmethodisch einzuordnen ist. |
|
||||
| **Methoden-Archetyp** | Ablaufmuster für Planung und Coaching, z. B. rotierender Zirkel oder lineare Sequenz. |
|
||||
| **Ablaufprofil** | Konkrete Ausprägung eines Archetyps, z. B. Arbeitszeit, Wechselzeit, Runden oder Erklärphase. |
|
||||
| **Slot** | Platzhalter innerhalb einer Kombinationsübung, z. B. Station 1, Rolle A oder Schritt 2. |
|
||||
| **Slot-Pool** | Menge möglicher Übungen für einen Slot, aus denen bei der Planung eine konkrete Auswahl getroffen werden kann. |
|
||||
|
||||
---
|
||||
|
||||
## 4. Trainingsmethoden: Ablage und Beschreibung
|
||||
|
||||
### 4.1 Rolle des Methodenkatalogs
|
||||
|
||||
Trainingsmethoden sollen als eigenständige fachliche Katalogobjekte geführt werden.
|
||||
|
||||
Sie beschreiben nicht eine konkrete Übung, sondern die methodische Qualität einer Trainingsform.
|
||||
|
||||
Beispiele:
|
||||
|
||||
* Zirkeltraining,
|
||||
* Rollenspiel,
|
||||
* strukturierte Übung,
|
||||
* Koordinationstraining,
|
||||
* plyometrisches Training,
|
||||
* Dauermethode,
|
||||
* extensive Intervallmethode,
|
||||
* Partnerübung,
|
||||
* freie Anwendung,
|
||||
* Reflexionsformat.
|
||||
|
||||
Der Methodenkatalog dient:
|
||||
|
||||
* der Übungsbeschreibung,
|
||||
* der Suche und Filterung,
|
||||
* der Trainingsplanung,
|
||||
* der fachlichen Standardisierung im Verein,
|
||||
* der späteren KI- oder Assistenzunterstützung,
|
||||
* der Qualitätssicherung bei offiziellen Inhalten.
|
||||
|
||||
### 4.2 Abgrenzung: Methode, Archetyp, Ablaufprofil
|
||||
|
||||
Die drei Begriffe müssen getrennt bleiben.
|
||||
|
||||
| Ebene | Frage | Beispiel |
|
||||
| --------------------- | ---------------------------------------------- | --------------------------------------------------------- |
|
||||
| **Trainingsmethode** | Welche fachliche Methode wird verwendet? | Zirkeltraining, Rollenspiel, Intervalltraining. |
|
||||
| **Methoden-Archetyp** | Nach welchem Ablaufmuster wird gesteuert? | rotierender Zirkel, parallele Stationen, lineare Sequenz. |
|
||||
| **Ablaufprofil** | Wie ist die konkrete Durchführung eingestellt? | 45 Sekunden Arbeit, 15 Sekunden Wechsel, 3 Runden. |
|
||||
|
||||
Wichtig:
|
||||
|
||||
> Der Methoden-Archetyp ersetzt nicht die Trainingsmethode. Er ergänzt sie nur dort, wo der Ablauf für Planung oder Coaching maschinenlesbar interpretiert werden muss.
|
||||
|
||||
### 4.3 Fachliche Beschreibung einer Trainingsmethode
|
||||
|
||||
Eine Trainingsmethode sollte aus Trainersicht so beschrieben werden, dass sie zuverlässig angewendet, gesucht und von anderen Methoden unterschieden werden kann.
|
||||
|
||||
Empfohlene fachliche Beschreibungsfelder:
|
||||
|
||||
| Feld | Zweck |
|
||||
| ---------------------------------- | -------------------------------------------------------------------------- |
|
||||
| **Name** | Eindeutige Bezeichnung der Methode. |
|
||||
| **Kurzbeschreibung** | Schnelle Orientierung in Listen und Auswahlfeldern. |
|
||||
| **Langbeschreibung** | Fachliche Erklärung der Methode. |
|
||||
| **Ziel / Nutzen** | Wofür diese Methode besonders geeignet ist. |
|
||||
| **Typische Einsatzsituationen** | Wann die Methode sinnvoll eingesetzt wird. |
|
||||
| **Geeignete Zielgruppen** | Altersgruppen, Leistungsgruppen oder Trainingskontexte. |
|
||||
| **Organisationsform** | Einzelarbeit, Partnerarbeit, Gruppe, Stationen, Kreis, freie Fläche usw. |
|
||||
| **Belastungscharakter** | locker, technisch, koordinativ, intensiv, intervallartig, spielerisch usw. |
|
||||
| **Typische Dauer** | Orientierung für Planung und Zeitmanagement. |
|
||||
| **Benötigte Rahmenbedingungen** | Platz, Material, Gruppengröße, Sicherheitsabstände. |
|
||||
| **Trainerhinweise** | Wichtige Hinweise für Anleitung und Steuerung. |
|
||||
| **Risiken / typische Fehler** | Was bei falscher Anwendung problematisch sein kann. |
|
||||
| **Geeignete Fähigkeiten** | Fähigkeiten, die mit der Methode häufig adressiert werden. |
|
||||
| **Verwandte Methoden** | Ähnliche oder kombinierbare Methoden. |
|
||||
| **Abgrenzung zu anderen Methoden** | Wann eine andere Methode passender wäre. |
|
||||
| **Optionale Standard-Archetypen** | Falls die Methode häufig mit bestimmten Ablaufmustern genutzt wird. |
|
||||
| **Status und Sichtbarkeit** | Entwurf, freigegeben, offiziell, vereinsintern usw. |
|
||||
|
||||
Diese Felder sind fachliche Anforderungen. Die konkrete technische Ablage soll der Coding Agent anhand der bestehenden Methodendomäne planen.
|
||||
|
||||
### 4.4 Haupt- und Nebenmethoden
|
||||
|
||||
Eine Übung sollte fachlich mindestens eine Hauptmethode haben können.
|
||||
|
||||
Zusätzlich können Nebenmethoden sinnvoll sein, weil eine Übung aus mehreren methodischen Perspektiven beschrieben werden kann.
|
||||
|
||||
Beispiel:
|
||||
|
||||
* Hauptmethode: Zirkeltraining
|
||||
* Nebenmethode: plyometrisches Training
|
||||
* weitere Nebenmethode: Koordinationstraining
|
||||
|
||||
Produktentscheidung:
|
||||
|
||||
> Übungen und Kombinationsübungen sollen eine Hauptmethode und optional weitere Nebenmethoden unterstützen.
|
||||
|
||||
Perspektivisch kann zusätzlich unterschieden werden zwischen:
|
||||
|
||||
* sportmethodischer Methode,
|
||||
* didaktischer Vermittlungsmethode,
|
||||
* organisatorischer Durchführungsform.
|
||||
|
||||
Diese Unterscheidung sollte aber im MVP nicht übermodelliert werden.
|
||||
|
||||
### 4.5 Trainingsmethoden in Kombinationsübungen
|
||||
|
||||
Bei Kombinationsübungen ist der Methodenbezug besonders wichtig.
|
||||
|
||||
Eine Kombinationsübung sollte daher fachlich drei Dinge besitzen:
|
||||
|
||||
1. **Methode**
|
||||
Beispiel: Zirkeltraining.
|
||||
|
||||
2. **Archetyp**
|
||||
Beispiel: rotierender Zeit-Zirkel.
|
||||
|
||||
3. **Ablaufprofil**
|
||||
Beispiel: 6 Stationen, 45 Sekunden Arbeit, 15 Sekunden Wechsel, 3 Runden.
|
||||
|
||||
So kann dieselbe Methode unterschiedlich angewendet werden:
|
||||
|
||||
| Methode | Archetyp | Beispiel |
|
||||
| ------------------- | ------------------- | --------------------------------------------------- |
|
||||
| Zirkeltraining | rotierender Zirkel | Alle Gruppen wechseln gemeinsam weiter. |
|
||||
| Zirkeltraining | parallele Stationen | Stationen laufen parallel, kein gemeinsamer Umlauf. |
|
||||
| Intervalltraining | Intervallblock | Gemeinsame Zeitdomäne ohne Stationen. |
|
||||
| Strukturierte Übung | lineare Sequenz | Schritt 1, Schritt 2, Schritt 3. |
|
||||
|
||||
### 4.6 Methoden in Trainingsmodulen
|
||||
|
||||
Trainingsmodule können ebenfalls einen Methodenbezug besitzen, aber anders als Übungen.
|
||||
|
||||
Ein Modul kann:
|
||||
|
||||
* eine dominante Methode haben,
|
||||
* mehrere Methoden enthalten,
|
||||
* methodisch neutral sein,
|
||||
* nur aus einzelnen Übungen bestehen, die selbst Methoden besitzen.
|
||||
|
||||
Empfehlung:
|
||||
|
||||
> Ein Trainingsmodul darf optional eine primäre methodische Ausrichtung besitzen, sollte aber nicht zwingend eine Methode erzwingen.
|
||||
|
||||
Beispiel:
|
||||
|
||||
* Modul: „Aktivierung und Reaktion“
|
||||
* Primäre methodische Ausrichtung: Koordinationstraining
|
||||
* Enthaltene Übungen: Reaktionsspiel, Sprintsignal, Partneraufgabe
|
||||
|
||||
### 4.7 Methoden in der Suche und Planung
|
||||
|
||||
Der Methodenkatalog soll in der Nutzung sichtbar werden.
|
||||
|
||||
Benötigte Such- und Planungsfunktionen:
|
||||
|
||||
* Übungen nach Methode filtern,
|
||||
* Kombinationsübungen nach Methode und Archetyp filtern,
|
||||
* Trainingsmodule nach methodischer Ausrichtung filtern,
|
||||
* in der Planung passende Methoden für ein Trainingsziel finden,
|
||||
* Methoden als Qualitätsmerkmal offizieller Vereinsinhalte nutzen,
|
||||
* bei der Auswahl einer Kombinationsübung passende Ablaufmuster vorschlagen.
|
||||
|
||||
Beispiel aus Trainersicht:
|
||||
|
||||
> „Ich suche eine Übung für Kumite, Jugendliche, Schwerpunkt Beinarbeit, Methode Zirkeltraining oder Koordinationstraining, Dauer maximal 15 Minuten.“
|
||||
|
||||
### 4.8 Governance des Methodenkatalogs
|
||||
|
||||
Trainingsmethoden sind fachliche Standardobjekte. Daher sollten sie stärker kontrolliert werden als private Trainingsnotizen.
|
||||
|
||||
Empfehlung:
|
||||
|
||||
* offizielle Methoden werden durch Administratoren oder Inhaltsverantwortliche gepflegt,
|
||||
* Vereine können eigene Ergänzungen oder Spezialisierungen anlegen,
|
||||
* Trainer können Vorschläge oder private methodische Hinweise erfassen,
|
||||
* Änderungen an offiziellen Methoden sollten nicht ungeprüft globale Inhalte verändern.
|
||||
|
||||
---
|
||||
|
||||
## 5. Methoden-Archetypen für Kombinationsübungen
|
||||
|
||||
### 5.1 Zweck
|
||||
|
||||
Archetypen beschreiben wiederkehrende Ablaufmuster, die für Planung und Coaching relevant sind.
|
||||
|
||||
Sie beantworten nicht die Frage „Welche Methode ist das?“, sondern:
|
||||
|
||||
> Wie soll dieser Block im Training durchlaufen oder angezeigt werden?
|
||||
|
||||
### 5.2 Empfohlene Start-Archetypen
|
||||
|
||||
| Archetyp | Fachliche Bedeutung | Coaching-Idee |
|
||||
| ------------------------ | -------------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| **Lineare Sequenz** | Übungen bauen nacheinander aufeinander auf. | Schrittfolge mit optionalem Timer. |
|
||||
| **Rotierender Zirkel** | Mehrere Stationen, Gruppen wechseln nach Zeit weiter. | Gemeinsamer Timer, Wechselhinweis, Rundenzähler. |
|
||||
| **Parallele Stationen** | Mehrere Stationen laufen gleichzeitig, aber ohne zwingende Rotation. | Vorher erklären, dann paralleler Betrieb. |
|
||||
| **Parcours** | Stationen oder Aufgaben entlang eines Wegs oder Ablaufs. | Navigation, Abhaken, flexible Reihenfolge möglich. |
|
||||
| **Partner-/Paarwechsel** | Rollen oder Aufgaben wechseln gekoppelt. | A/B-Logik, Rollenhinweise, Wechselimpulse. |
|
||||
| **Intervallblock** | Gemeinsame Zeitdomäne mit wiederholten Belastungsphasen. | Globale Uhr, Intervallanzeige. |
|
||||
| **Freier Methodenblock** | Methodischer Zusammenhang ohne harte Steuerungslogik. | Kompakte Anzeige, manuelles Abhaken. |
|
||||
|
||||
### 5.3 Mindestanforderung an Archetypen
|
||||
|
||||
Für jeden Archetyp muss fachlich beschrieben sein:
|
||||
|
||||
* wann er verwendet wird,
|
||||
* welche Informationen der Trainer bei der Planung benötigt,
|
||||
* welche Informationen im Coaching-Modus angezeigt werden,
|
||||
* welche Angaben verpflichtend sind,
|
||||
* welche Angaben optional sind,
|
||||
* wann ein anderer Archetyp besser geeignet wäre.
|
||||
|
||||
Die technische Validierung und konkrete Ablage dieser Angaben soll der Coding Agent planen.
|
||||
|
||||
### 5.4 Einordnung: Trainingsformen wie HIIT, Dauer, plyometrisch ↔ Archetypen
|
||||
|
||||
**Wichtige Trennung (bleibt fachlich zwingend):**
|
||||
|
||||
* **Trainingsmethode im Methodenkatalog** (z. B. HIIT, extensive Intervallmethode, Dauermethode, plyometrisches Training) beschreibt primär den **didaktisch/belastungsmethodischen Kontext („was für eine Trainingsqualität ist das?“)**.
|
||||
* **`method_archetype`** beschreibt **das Ablaufmuster („wie soll der Trainer den Block strukturieren und im Coach geführt werden?“)** — insbesondere **Parallelität, Rotation, Sequenz, Zeitdomänen**.
|
||||
|
||||
Dieselbe Methode kann in der Praxis mit **mehreren** Archetypen sinnvoll kombiniert sein; das ist **kein Widerspruch**.
|
||||
|
||||
| Beispiel (Methoden-/Belastungsbegriff) | Typischer Archetyp (Orientierung), nicht Pflicht |
|
||||
| -------------------------------------- | ---------------------------------------------- |
|
||||
| **HIIT**, Tabata-ähnlich, Kurzintervalle oft mit hoher Intention | sehr oft **`time_domain_interval`** oder innerhalb eines Zirkels **`circuit_rotate_time`** mit kurzen Arbeitsphasen; Partnerformen zusätzlich **`pair_superset`**. |
|
||||
| **Klassisches Intervalltraining** (längere Arbeit, definierte Erholung, N Wiederholungen) | überwiegend **`time_domain_interval`** oder **`circuit_rotate_time`**, wenn die „Intervallschicht“ an Stationen gebunden ist. |
|
||||
| **Dauermethode** (überwiegend durchgehend ohne harte Arbeit-Erholung-Takte) | eher **`free_method_block`** oder **`sequence_linear`** mit optionalen Hinweiten; **weniger** `time_domain_interval`, sofern kein geregeltes Intervallschema gemeint ist. |
|
||||
| **Plyometrisch**, Explosivblöcke, Technik-Schichtung | häufig **`sequence_linear`** (Progression vor Ort) oder **`circuit_rotate_time`** / **`time_domain_interval`**, wenn klar Zeitfenster oder Wiederholungsblöcke vorgegeben sind. |
|
||||
| Rein **organisatorisches** Stationslaufen ohne gemeinsamen Intervalltakt | **`circuit_rotate_time`** oder **`station_parcours`**, **`circuit_all_parallel`**, je nach ob rotiert wird oder parallel aktiv ist. |
|
||||
|
||||
**Shinkan-Zielrichtung bleibt trainerzentriert:** Es geht **nicht** um individuelle Pulsonomie eines Sportlers, sondern darum, dass der **Trainer Belastungs- und Erholungsphasen, Durchläufe und ggf. Umlauf-/Parallellogik** vorgibt und der **Coach** diese Vorgaben **sichtbar und später steuerbar** macht
|
||||
(siehe **§ 6.3** zu Phasen jenseits „nur Gesamtminuten auf dem Planungsitem“).
|
||||
|
||||
### 5.5 Erweiterbarkeit von Archetypen (aktuell zurückgestellt)
|
||||
|
||||
Die Idee einer **von Superadmins zur Laufzeit editierbare Archetyp-Registry**, die den Coaching-Modus **völlig frei parametrierbar** macht, wird **zurückgestellt**. Vorerst reicht die **festgelegte, versionierte Liste** kanonischer Archetyp-IDs (**§ 10.2.1**); **weitere Archetypen** können später **wie bisher durch Produkt-/Release entschieden** ergänzt werden (Code oder kuratierter Import), ohne freies „Beliebig-Neuanlegen“ ohne definierten Coach-Verhaltens-Anker.
|
||||
|
||||
---
|
||||
|
||||
## 6. Kombinationsübungen
|
||||
|
||||
### 6.1 Fachliche Beschreibung
|
||||
|
||||
Eine Kombinationsübung ist eine wiederverwendbare Übungsform mit interner Struktur.
|
||||
|
||||
Beispiele:
|
||||
|
||||
* Kumite-Zirkel mit fünf Stationen,
|
||||
* Koordinationsparcours,
|
||||
* Selbstschutz-Parcours,
|
||||
* Partnerwechselübung,
|
||||
* methodische Sequenz zur Distanzkontrolle,
|
||||
* Reaktions- und Explosivitätsblock,
|
||||
* Aufwärmparcours für Kinder.
|
||||
|
||||
### 6.2 Bestandteile
|
||||
|
||||
Eine Kombinationsübung sollte fachlich enthalten:
|
||||
|
||||
* allgemeine Übungsbeschreibung,
|
||||
* Ziel,
|
||||
* Durchführung,
|
||||
* Trainerhinweise,
|
||||
* Vorbereitung,
|
||||
* Hilfsmittel,
|
||||
* Zielgruppe,
|
||||
* Fähigkeiten,
|
||||
* Hauptmethode,
|
||||
* optionale Nebenmethoden,
|
||||
* Archetyp,
|
||||
* Slots / Stationen / Rollen / Schritte,
|
||||
* mögliche Übungen je Slot,
|
||||
* strukturierte **Zeitphasen und Belastungs-/Erholungsvorgaben** innerhalb der Kombination (**`method_profile`**, Überblick § 6.3; Details § 10.5) — **zusätzlich** zu allenfalls geplanten **Gesamtminuten am Planungseintrag**,
|
||||
* optionale klassische Hinweise zu Dauer, Runden oder Wechsel aus der Übung heraus,
|
||||
* Hinweise für den Coaching-Modus.
|
||||
|
||||
### 6.3 Zeitschicht: Phasen innerhalb der Kombination (Bibliothek) und Anpassungen in der Planung
|
||||
|
||||
Ein **einzelnes** Feld „Geplante Minuten für diesen Eintrag in der Einheit“ kann die **innenliegende zeitliche Logik** einer Kombinationsübung **nicht** ersetzen. Für Trainersteuerung (und später für Coaching **Stufe C**) soll die Kombination in der Bibliotheksbeschreibung vorsehen können:
|
||||
|
||||
**A) Kombinationseinheit („global“ über die Slots)**
|
||||
|
||||
* **Arbeits-** und **Erholungszeiten** (Sekunden/Minuten) und **Anzahl der Durchläufe** oder **Intervalle**,
|
||||
* ggf. **gemeinsamer Takt** für alle Teilnehmenden (z. B. rotierender Zirkel oder eine gemeinsame Intervalluhr),
|
||||
* **Erklär- oder Aufbauzeit** vor dem eigentlichen Start,
|
||||
* dort, wo der Archetyp passt: **Runden-/Umlaufzahl** oder vergleichbare Strukturen.
|
||||
|
||||
Alle diese Angaben sind **Anweisungen an den Trainer** und **Coach‑Assistenz**, **keine** individuelle Pulssonde oder ähnliche Personenmessung.
|
||||
|
||||
**B) Optional pro Slot oder Schritt**
|
||||
|
||||
* wenn fachlich sinnvoll: **von Station zu Station variierende Arbeitsphasen** oder Mini‑Sequenzen innerhalb eines Slots — technisch z. B. als strukturierte Liste in `method_profile` mit Bezug zum `slot_index` (Ausarbeitung Coding Agent).
|
||||
|
||||
**Nach Einplanung in eine konkrete Trainingseinheit** muss diese Zeitschicht (oder ihr Abgleich mit der Einheitsposition) für den Trainer **bearbeitbar** bleiben, **ohne** die Bibliotheksvorlage still zu überschreiben (kopier-/instanzbasierte Anpassungen — siehe bereits § 2.5 und § 8.3).
|
||||
|
||||
**Umsetzung in der App (Stand 0.8.110):** Pro Übungszeile in einer Trainingseinheit kann optional ein **JSON-Snapshot** des Ablaufprofils gespeichert werden (`planning_method_profile` in der DB, Migration **057**). **`null`** oder fehlender Key: für **Anzeige und Editor** wirkt das **Zusammenführen** aus **Katalog** (`exercises.method_profile` bzw. Join `catalog_method_profile`) **+** Snapshot — der Katalog wird **nicht** durch ein leeres Planungsobjekt verworfen; fehlende bzw. JSON-`null`-Werte im Snapshot **überschreiben** keine Katalogfelder; `slot_profiles_v1` wird **je `slot_index`** zusammengeführt (inkl. konsistenter Steuerungslogik Zeit vs. Ziel‑Wdh.). Persistenz: der Snapshot speichert nur die vom Trainer **gesetzten** Planungsdaten (nach STZ-„Runde“ können leere Objekte als `null` normalisiert werden). **Konkrete Logik:** Frontend `effectiveComboMethodProfile` / `merge` in `frontend/src/utils/comboPlanningMethodProfile.js` (Coach, Planungseditor, Druck/Vorschau konsistent). Bearbeitung in der Planungs-UI: Modal **„Ablauf bearbeiten…“** mit `CombinationMethodProfileEditor` + Vorschau `CombinationPlanBracket`.
|
||||
|
||||
**Coach:** soll die wirksamen Werte nach **Übernahme** und **Einheitsübersteuerungen** konsistent nachvollziehen (**§ 10.4**).
|
||||
|
||||
**Geplantes kanonisches Zeitmodell:** Globale Eckwerte (z. B. Anzahl der Durchläufe / Runden, optionale Gesamt-/Einführungszeit als Ziel oder Rechenhilfe) und **pro Platz (Slot)** die Dimensionen „Belastung“, „wie viele gleiche Übung hintereinander“, „kurze Pause dazwischen“, „Übergangszeit zur nächsten Übung/arbeitstation“ — dokumentiert für die technische Angleichung in **`.claude/docs/working/COMBINATION_TIMING_PROFILE_PLAN.md`** (Felder **`slot_profiles_v1`**, `timing_schema`). Archetypen können **Strukturen und typische Schnellwahlen** vorgeben (z. B. Zirkel: Relation Belastungszeit = Übergangszeit oder Erholungsanteil ≈ 2/3 der Belastung); der Archetyp **Freier Methodenblock** bildet den **Maximal‑Pfad** ohne stärkere stille Annahmen. **Pyramidale/abhängige Pausen** (Pause abhängig von vorheriger Belastung) sind **nicht Teil des aktuellen Umsetzungspfads**, können später als eigener Untertyp ergänzt werden.
|
||||
|
||||
**Fortschritt pro Slot (Stand 0.8.109):** optional **`advance_mode`** je Eintrag in **`slot_profiles_v1`**: `timed` — Standard (`load_sec` = geplante Arbeitsdauer für Timer im Coach; fehlende Angabe entspricht `timed` ohne Sekundenfeld), **`rep`** — mengenorientiert (Zielzahl über **`consecutive_reps`**; keine verbindliche Arbeitsuhr), **`manual`** — coachgeführt (Fortschritt bewusst per Schritt später im Coach, optional Richtwert über **`consecutive_reps`**). Optional **`rep_series_count`**: Standard **1** (wird im Formular/API explizit geführt); Ausnahmen nur, wenn der **Methoden‑Archetyp** in `ARCHETYPE_DEFAULT_REP_SERIES_COUNT` eine andere Vorgabe definiert oder der Nutzer eine andere Zahl setzt. ≥ 2 ermöglicht Pause **zwischen Serien** (`intra_rep_rest_sec`). Bei nur **einer** Serie: kein **`intra_rep_rest_sec`** in UI und Payload; **`transition_after_sec`** = Wechsel zur nächsten Station.
|
||||
|
||||
### 6.4 Slot- und Pool-Logik
|
||||
|
||||
Slots können fest oder variabel sein.
|
||||
|
||||
Beispiel fest:
|
||||
|
||||
* Station 1 = Seilspringen
|
||||
* Station 2 = Liegestütz
|
||||
* Station 3 = Beinarbeit
|
||||
|
||||
Beispiel variabel:
|
||||
|
||||
* Station 1 = eine Übung aus Pool „Beinarbeit“
|
||||
* Station 2 = eine Übung aus Pool „Reaktion“
|
||||
* Station 3 = eine Übung aus Pool „Konter“
|
||||
|
||||
Die konkrete Auswahl kann bei der Planung angepasst werden, ohne die Bibliotheksvorlage zu ändern.
|
||||
|
||||
---
|
||||
|
||||
## 7. Trainingsmodule
|
||||
|
||||
### 7.1 Fachliche Beschreibung
|
||||
|
||||
Ein Trainingsmodul ist ein wiederverwendbarer Planungsbaustein.
|
||||
|
||||
Beispiele:
|
||||
|
||||
* Standard-Aufwärmen für Kinder,
|
||||
* Mobilisation und Aktivierung,
|
||||
* Kumite-Beinarbeit 20 Minuten,
|
||||
* SV-Einstieg Wahrnehmung und Distanz,
|
||||
* Abschlussritual mit Reflexion,
|
||||
* prüfungsnaher Kihon-Block.
|
||||
|
||||
### 7.2 Bestandteile
|
||||
|
||||
Ein Trainingsmodul sollte fachlich enthalten:
|
||||
|
||||
* Titel,
|
||||
* Kurzbeschreibung,
|
||||
* Ziel,
|
||||
* empfohlene Dauer,
|
||||
* empfohlene Zielgruppe,
|
||||
* optional empfohlener Einsatzbereich,
|
||||
* optionale methodische Ausrichtung,
|
||||
* enthaltene Übungen,
|
||||
* enthaltene Kombinationsübungen,
|
||||
* Notizen oder Trainerhinweise,
|
||||
* Sichtbarkeit,
|
||||
* Freigabestatus.
|
||||
|
||||
### 7.3 Keine harte Abschnittsbindung
|
||||
|
||||
Ein Modul kann für einen Abschnitt empfohlen sein, z. B. „Aufwärmen“, darf aber nicht technisch darauf beschränkt werden.
|
||||
|
||||
Ein Modul kann:
|
||||
|
||||
* in einen Abschnitt eingefügt werden,
|
||||
* als eigener Block auf Einheitsebene eingefügt werden,
|
||||
* zwischen Abschnitten eingefügt werden,
|
||||
* in ein Rahmenprogramm übernommen werden.
|
||||
|
||||
---
|
||||
|
||||
## 8. Planungslogik
|
||||
|
||||
### 8.1 Planungsblöcke
|
||||
|
||||
Für die Produktlogik braucht Shinkan den Begriff des Planungsblocks.
|
||||
|
||||
Ein Planungsblock ist ein zusammengehöriger Inhalt in einer Trainingseinheit.
|
||||
|
||||
Planungsblöcke können sein:
|
||||
|
||||
* eingefügtes Trainingsmodul,
|
||||
* eingefügte Kombinationsübung,
|
||||
* manuell gruppierter Block,
|
||||
* später ggf. weitere Blocktypen.
|
||||
|
||||
### 8.2 Verhältnis zu Abschnitten
|
||||
|
||||
Ein Planungsblock kann einem Abschnitt zugeordnet sein, muss aber nicht vollständig in einem Abschnitt aufgehen.
|
||||
|
||||
Produktregel:
|
||||
|
||||
> Abschnitte gliedern die Einheit. Planungsblöcke gliedern den konkreten Trainingsinhalt.
|
||||
|
||||
### 8.3 Lokale Anpassbarkeit
|
||||
|
||||
Nach dem Einfügen muss ein Planungsblock lokal angepasst werden können:
|
||||
|
||||
* Dauer ändern,
|
||||
* **bei Kombinationsübungen:** Ablaufprofil **optional nur für diese Platzierung** überschreiben (aktuell: Snapshot parallel zum Katalog-`method_profile`, z. B. Arbeit-, Erholungs- und Runden-/Intervallangaben über die gleichen strukturierten Felder wie im Übungskatalog) — zusätzlich zu den **Gepl.-Min.** am Eintrag; **Stations-/Slot-Austausch** am konkreten Vorkommen weiter über die bestehende Übungs-/Planungslogik, nicht gesondert als „Kombi-Programmierung“ je Zeile,
|
||||
* Übung austauschen,
|
||||
* Station ergänzen,
|
||||
* Hinweise anpassen,
|
||||
* Reihenfolge ändern,
|
||||
* Block auflösen,
|
||||
* Block duplizieren,
|
||||
* Block als neues Modul speichern.
|
||||
|
||||
Diese Änderungen betreffen nur die konkrete Einheit oder den konkreten Rahmen-Slot, nicht automatisch das Bibliotheksexemplar.
|
||||
|
||||
---
|
||||
|
||||
## 9. UX-Anforderungen
|
||||
|
||||
### 9.1 Inhalt hinzufügen
|
||||
|
||||
Im Planungseditor sollte der Trainer fachlich klar wählen können:
|
||||
|
||||
* Übung hinzufügen,
|
||||
* Kombinationsübung hinzufügen,
|
||||
* Trainingsmodul hinzufügen,
|
||||
* Notiz hinzufügen,
|
||||
* manuellen Block erstellen.
|
||||
|
||||
### 9.2 Modul erstellen
|
||||
|
||||
Ein Modul sollte auf mehreren Wegen entstehen können:
|
||||
|
||||
* leer anlegen,
|
||||
* aus bestehendem Abschnitt speichern,
|
||||
* aus markierten Übungen speichern,
|
||||
* aus einem Teil eines alten Trainings speichern.
|
||||
|
||||
### 9.3 Kombinationsübung erstellen
|
||||
|
||||
Eine Kombinationsübung sollte geführt angelegt werden:
|
||||
|
||||
1. Grunddaten erfassen,
|
||||
2. Methode wählen,
|
||||
3. Archetyp wählen,
|
||||
4. Slots / Stationen / Rollen definieren,
|
||||
5. Übungen oder Pools zuordnen,
|
||||
6. Ablaufprofil festlegen,
|
||||
7. Coaching-Vorschau prüfen,
|
||||
8. speichern.
|
||||
|
||||
### 9.4 Methoden auswählen
|
||||
|
||||
Die Methodenauswahl sollte Trainer unterstützen, nicht belasten.
|
||||
|
||||
Empfohlene UX:
|
||||
|
||||
* Hauptmethode prominent,
|
||||
* Nebenmethoden optional,
|
||||
* passende Methoden vorschlagen,
|
||||
* Methoden kurz erklären,
|
||||
* bei Kombinationsübungen passende Archetypen vorschlagen,
|
||||
* keine Pflicht zur Überklassifizierung bei einfachen Übungen.
|
||||
|
||||
---
|
||||
|
||||
## 10. Coaching- und Assistenzmodus
|
||||
|
||||
### 10.1 Ziel
|
||||
|
||||
Der Coaching-Modus soll die Durchführung unterstützen, ohne den Trainer zu zwingen, exakt dem Plan zu folgen.
|
||||
|
||||
Grundsatz:
|
||||
|
||||
> Der Coaching-Modus gibt Orientierung, Zeitstruktur und Ablaufhilfe, bleibt aber in der Praxis flexibel.
|
||||
|
||||
### 10.2 Unterschiedliche Anzeige je Archetyp
|
||||
|
||||
| Archetyp | Coaching-Anzeige |
|
||||
| -------------------- | -------------------------------------------- |
|
||||
| Lineare Sequenz | Schrittfolge mit Weiter/Zurück. |
|
||||
| Rotierender Zirkel | Stationen, Arbeitszeit, Wechselzeit, Runden. |
|
||||
| Parallele Stationen | Erst Erklärübersicht, dann Parallelbetrieb. |
|
||||
| Parcours | Stationen oder Wegpunkte zum Abhaken. |
|
||||
| Partner-/Paarwechsel | Rollen, Aufgaben und Wechselhinweise. |
|
||||
| Intervallblock | Globale Zeit, Intervallzähler, Aufgaben. |
|
||||
| Freier Methodenblock | Kompakte Übersicht und manuelle Steuerung. |
|
||||
|
||||
#### 10.2.1 Kanonische Archetyp-IDs (Abgleich Fachbegriff, UI und API)
|
||||
|
||||
Damit Produktbeschreibung, Formularfelder (`method_archetype`), Trainingscoach und Backend‑Validierung **dieselben Werte** nutzen und es keinen dokumentationsbedingten Drift gibt, gelten diese **festen Schlüssel** (Maschinen‑IDs):
|
||||
|
||||
| Archetyp (fachlicher Name in § 5.2) | Schlüssel `method_archetype` (`exercises.method_archetype`) |
|
||||
| ----------------------------------- | ----------------------------------------------------------- |
|
||||
| Lineare Sequenz | `sequence_linear` |
|
||||
| Rotierender Zirkel (Zeit) | `circuit_rotate_time` |
|
||||
| Parallele Stationen | `circuit_all_parallel` |
|
||||
| Parcours | `station_parcour` |
|
||||
| Partner- / Paarwechsel | `pair_superset` |
|
||||
| Intervallblock (Zeitdomäne) | `time_domain_interval` |
|
||||
| Freier Methodenblock | `free_method_block` |
|
||||
|
||||
Änderungen an dieser Zuordnung nur **gemeinsam** (Produkt, Backend‑Enum und UI‑Konstanten); siehe Implementierungsanhang weiter unten.
|
||||
|
||||
### 10.3 Durchführungsdokumentation
|
||||
|
||||
Perspektivisch sollte dokumentierbar sein:
|
||||
|
||||
* was durchgeführt wurde,
|
||||
* was übersprungen wurde,
|
||||
* was verändert wurde,
|
||||
* tatsächliche Dauer,
|
||||
* Trainerhinweise,
|
||||
* Reflexion,
|
||||
* Vorschläge zur Verbesserung einer Übung oder eines Moduls.
|
||||
|
||||
Die konkrete technische Umsetzung wird nicht in dieser Spezifikation festgelegt.
|
||||
|
||||
### 10.4 Coaching-Reifegrade (Normierung ohne technisches Pflichtenheft)
|
||||
|
||||
Archetyp-spezifisches Coaching soll **nicht** als ein einziges UX-„Monolith“ gebaut werden, sondern in **nachvollziehbaren Stufen**, damit frühere Umsetzungen nicht überschrieben wirken und der Fortschritt in Doku/Umsetzungsplan nachverfolgt werden kann:
|
||||
|
||||
| Stufe | Bezeichnung (Arbeitstitel) | Inhalt aus Trainersicht | Abgrenzung |
|
||||
| ----- | ---------------------------- | ------------------------ | ----------- |
|
||||
| **A** | **Informations-/Struktursicht** | Pro Kombinationsübung: Kopf‑Kontext aus Katalog **plus** strukturierte Darstellung der **Slots** und der **einzelnen Kandidatenübungen** (Titel, Kurztext, Detail aufklappbar); **ein zeitlicher Schritt im Coach** entspricht weiter **einem** Planungseintrag (ein Item in der Einheit). | Kein eigener Rundenzähler, kein eigener Stations‑Timer‑State pro Archetyp. |
|
||||
| **B** | **Archetyp-Steuerung in der bestehenden Zeitleiste** | Optionale Aufspaltung: z. B. bei **`sequence_linear`** pro Slot **ein Coach‑Schritt** (Weiter/Zurück pro Station), ohne die Datenbank-Semantik der Einheit zu zerstückeln (Virtuelle Schritte oder materialisierte Hilfs‑Einträge – technische Variante dokumentieren). | Bewusste Produkt-/Architekturentscheidung nötig, damit IST‑Zeiten und Abschluss‑PUT konsistent bleiben. |
|
||||
| **C** | **Interaktive Assistenz je Archetyp** | Gemeinschafts-/Stations‑Timer, Wechselimpulse (**`circuit_rotate_time`**), Vorab‑„Erklärphase“‑Flag (**`circuit_all_parallel`**), Abhaken (**`station_parcour`**), gekoppelte A/B‑Ansicht (**`pair_superset`**), globale Intervalluhr (**`time_domain_interval`**) — jeweils an Parameter aus **`method_profile`** angebunden, wo diese in Stufe A/B bereits sichtbar gepflegt werden. | Keine verpflichtende KI‑Steuerung; Trainer kann überspringen (Grundsatz § 10.1). |
|
||||
|
||||
**Aktuelle Zielrichtung:** Stufe **A** soll für **alle** in § 10.2.1 genannten Archetypen **inhaltsgleich** die Slot‑ und Kandidateninformation liefern; **unterschiedliche Kopf-/Hilfstexte und UI-Mikrolayouts** nach Archetyp sind Teil von A und sollten gemeinsam mit Stufe B/C wachsen (kein „still“ abweichendes Verhalten ohne Doku‑Update).
|
||||
|
||||
### 10.5 Fachliche Mindestinfos im **Ablaufprofil** (`method_profile`) pro Archetyp
|
||||
|
||||
`method_profile` ist das **konkretisierende** JSON (o. ä.) zum gewählten Archetyp: Zeiten, Runden, Schalter. Technische Pflichtfelder und Validierung regelt die technische Umsetzung — **fachlich** gilt folgende Minimal-Erwartung, damit Stufe B/C sinnvoll nutzbar ist:
|
||||
|
||||
| Archetyp-Schlüssel | Mindest-Parameter (fachlich sinnvoll; Benennung in der Umsetzung kanonisch festlegen). Typische Zuordnung methodischer Überbegriffe: **§ 5.4** |
|
||||
| ------------------ | ------------------------------------------------------------------------------------- |
|
||||
| `sequence_linear` | Orientierungs-Arbeits-/Pausenhinweise je Schritt oder global; Reihenfolge = Slotreihenfolge — u. a. für **Skillschichtungen**, Aufwärmserien ohne festen Rotationstakt oder **Ausdauer-/Technikketten ohne Intervalltakt**. |
|
||||
| `circuit_rotate_time` | **Arbeit** je Station oder Umlauf, **optional Wechsel/Transition**, **optional Erholung zwischen Runden**, **optional Rundenanzahl**; Kern für rotierenden Zirkel inkl. vieler HIIT-/Zirkelmischformen über Stationen hinweg (**§ 5.4**). |
|
||||
| `circuit_all_parallel` | „Erst gemeinsame Erklärung, dann gleichzeitiger Betrieb aller Stationen“; Zeitfenster Vorab‑Erklärung optional — z. B. wenn keine Rotation, aber gemeinsamer Startzeitpunkt gewünscht ist. |
|
||||
| `station_parcour` | Fokus Stationsbeschreibung; optional freie Besuchsreihenfolge (Profil/Archetyp); weniger zentral **feste Arbeit/Erholung-Takte**, mehr Navigation/Abhaken (später Stufe C). |
|
||||
| `pair_superset` | Arbeit und Wechsel bei **gekoppelten** Rollen; typisch wenn zwei Linien oder Partnerblöcke im Takt gewechselt werden. |
|
||||
| `time_domain_interval` | Klare Zeitdomäne: **Belastungs-, Erholungsblöcke** und **Anzahl Wiederholungen** der Domäne bzw. **Gesamtblockbegrenzung** — zentrale Schicht für viele Formen aus **„Intervall/HIIT/Zeitschachtelungs“‑**Methodenkatalog ohne individuelle Messung (**§ 5.4**). |
|
||||
| `free_method_block` | Keine zusätzlichen Pflichtparameter; **unterstützt** etwa **reibungsarmere Dauer- oder Spielformen**, wo der Trainer keine starke Taktuhr braucht, aber Stationsideen strukturiert bündeln will. |
|
||||
|
||||
#### 10.5.1 Mehrschichtiges Planen (Überblick)
|
||||
|
||||
| Ebene | Inhalt zeitlicher Art |
|
||||
| ----- | --------------------- |
|
||||
| **Einheit / Planungsitem** | z. B. geplante **Gesamtminuten** dieser Platzierung („der Block soll heute etwa 25 Min einnehmen“). |
|
||||
| **Kombinationsübung (Bibliothek)** | strukturierte **Phasen in `method_profile`** (arbeiten, pausieren, Runden…) — § 6.3. |
|
||||
| **Einheitliche Planungsinstanz** | optionale Abweiche vom Bibliotheksprofil **nur für dieses Training** (§ 8.3). |
|
||||
| **Coach** | liest wirksamen Stand (Bibliothek + Overrides) zur **Orientierung**, später automatisierte Taktassistenz (**§ 10.4**). |
|
||||
|
||||
Solange diese Mindestinfos in der Datenpflege noch **nicht** validiert oder nicht geführt erfasst werden, bleibt Coaching bei **Informations-Schicht und manuellen Timern des bestehenden Coach-Dialogs** die fachlich ehrliche Darstellung (siehe Anhang A).
|
||||
|
||||
### 10.6 Offene und geplante Erweiterungen (Produkt-Backlog, Stand 2026-05-12)
|
||||
|
||||
Die folgenden Punkte stammen aus **Session-/Chat-Arbeit** an Planung, Klammerdarstellung und Coach **Stufe A**; sie sind **noch nicht** als vollständige Produktfunktion abgeschlossen bzw. bewusst zurückgestellt:
|
||||
|
||||
| Thema | Kurzbeschreibung | Status |
|
||||
| ----- | ---------------- | ------ |
|
||||
| **Coaching Stufe B/C (individuelle Archetyp-Steuerung)** | Über **Stufe A** (lesend: Slots, Zeiten, Archetyp-Hinweis, Kandidaten-Texte) hinaus: **pro Archetyp** gesteuerte Durchführung (z. B. Substeps bei Sequenz, Stations-/Rotations-Timer beim Zirkel, Erklärphase bei parallelen Stationen, Abhaken Parcours, Intervalluhr). § 10.4 Stufe **B** (Zeitleiste) und **C** (Assistenz). | **Offen** — aktuell nur informativ/Orientierung; kein archetypspezifischer Zustand im Coach. |
|
||||
| **Administrierbarkeit der Archetypen** | Archetypen sind **fest** im Code (`COMBINATION_ARCHETYPE_IDS` Backend, `COMBINATION_ARCHETYPE_OPTIONS` Frontend); **keine** DB-/Admin-Oberfläche für Labels, Defaults, Sichtbarkeit oder club-spezifische Erweiterungen. | **Offen** — Änderungen nur per Release/Code-Review. |
|
||||
| **Einfache Vorbelegung aller Zeit- und Anzahlfelder** | Teilweise: Schnellwahlen (**Zirkel**, **Intervall**), Serien-Default **1**, Archetyp-Map `ARCHETYPE_DEFAULT_REP_SERIES_COUNT`. **Fehlt:** ein Klick „alle Stationen aus globalen Eckwerten / Archetyp-Muster füllen“, Profil-weite **Reset/Übernehmen**-Presets über alle Slots. | **Teilweise** — Ausbau siehe `COMBINATION_TIMING_PROFILE_PLAN.md` § 1 („Archetyp = Struktur + Defaults“). |
|
||||
| **Archetypbedingte Restriktionen & Server-Validierung** | Client führt geführte Felder; **keine** verbindliche Backend-Prüfung „Profil passt zu Archetyp“ (Pflichtschlüssel, Wertebereiche, unzulässige Slot-Kombinationen). | **Offen** — erhöht Datenqualität und Coach-Verlässlichkeit vor Stufe C. |
|
||||
| **Governance Archetyp ↔ offizielle Inhalte** | Noch keine getrennte Policy „nur Superadmin darf neue Archetyp-IDs einführen“ (derzeit ohnehin nur Code). | **Offen** — relevant sobald Archetypen konfigurierbar werden. |
|
||||
|
||||
**Hinweis:** § 13.1 nennt Stufe **A** als MVP-Pflicht und **B/C** als Ausbauschritte — die Tabelle oben präzisiert die **noch offenen** Arbeitspakete aus der Umsetzungspraxis.
|
||||
|
||||
---
|
||||
|
||||
## 11. Rahmenprogramm-Integration
|
||||
|
||||
Trainingsmodule und Kombinationsübungen müssen auch in Rahmenprogrammen nutzbar sein.
|
||||
|
||||
Regel:
|
||||
|
||||
> Was in einer konkreten Trainingseinheit geplant werden kann, sollte grundsätzlich auch in einem Rahmenprogramm oder Rahmen-Slot vorbereitet werden können, sofern es keine echte Durchführung voraussetzt.
|
||||
|
||||
Das betrifft insbesondere:
|
||||
|
||||
* Modul einfügen,
|
||||
* Kombinationsübung einfügen,
|
||||
* methodische Ausrichtung übernehmen,
|
||||
* Slot-Pools vorbelegen,
|
||||
* Dauer anpassen,
|
||||
* später konkrete Einheit daraus ableiten.
|
||||
|
||||
Nicht in den Rahmen gehört:
|
||||
|
||||
* echte Durchführung,
|
||||
* tatsächliche Dauer,
|
||||
* spontane Trainingsnotizen,
|
||||
* Nachbereitungsreflexion.
|
||||
|
||||
---
|
||||
|
||||
## 12. Governance
|
||||
|
||||
Für Methoden, Übungen, Kombinationsübungen und Module gelten abgestufte Sichtbarkeiten und Verantwortlichkeiten.
|
||||
|
||||
Empfohlene fachliche Ebenen:
|
||||
|
||||
* privat,
|
||||
* Verein,
|
||||
* offiziell,
|
||||
* archiviert,
|
||||
* Entwurf,
|
||||
* freigegeben.
|
||||
|
||||
Normale Trainer sollen Inhalte nutzen und lokal anpassen können. Offizielle oder vereinsweite Vorlagen sollen nicht ungeprüft überschrieben werden.
|
||||
|
||||
Für Methoden ist eine besondere Qualitätskontrolle sinnvoll, weil sie als fachlicher Katalog für viele Übungen und Planungen wirken.
|
||||
|
||||
---
|
||||
|
||||
## 13. MVP-Empfehlung
|
||||
|
||||
### 13.1 Muss enthalten sein
|
||||
|
||||
* Trainingsmodule anlegen und wiederverwenden,
|
||||
* Kombinationsübungen als fachliche Sonderform von Übungen,
|
||||
* Methodenbezug mit Hauptmethode und optionalen Nebenmethoden,
|
||||
* klare Trennung zwischen Methode, Archetyp und Ablaufprofil,
|
||||
* mindestens folgende Archetypen:
|
||||
|
||||
* lineare Sequenz,
|
||||
* rotierender Zirkel,
|
||||
* freier Methodenblock,
|
||||
* Planungsblöcke als fachliches Konzept,
|
||||
* lokale Anpassbarkeit nach Einfügen,
|
||||
* Coaching: mindestens **Stufe A** nach § 10.4 für alle Archetypen aus § 10.2.1 (strukturierte Slot-/Kombi-Darstellung; Archetyp-Hilfstexte); **zeitliche/mechanische Archetyp-Steuerung (Stufen B/C)** ausdrücklich als Ausbauschritte.
|
||||
|
||||
### 13.2 Sollte vorbereitet werden
|
||||
|
||||
* parallele Stationen,
|
||||
* Parcours,
|
||||
* Partner-/Paarwechsel,
|
||||
* Intervallblock,
|
||||
* Durchführungsdokumentation,
|
||||
* Rückfluss von Erfahrungswissen,
|
||||
* Offline-/PWA-Nutzung,
|
||||
* stärkere Suche nach Methoden und Archetypen.
|
||||
|
||||
### 13.3 Nicht im MVP
|
||||
|
||||
* vollständige technische Event-Historie jeder Planänderung,
|
||||
* automatische Synchronisation alter Einheiten bei Vorlagenänderung,
|
||||
* komplexe Verschachtelung von Modulen in Modulen,
|
||||
* individuelles Athleten-Tracking,
|
||||
* KI-generierte Trainingsplanung,
|
||||
* verbindliche technische Tabellen- oder API-Architektur.
|
||||
|
||||
---
|
||||
|
||||
## 14. Arbeitsauftrag an den Coding Agent — fachliche Leitplanken
|
||||
|
||||
Der Coding Agent soll die bestehende Codebasis prüfen und auf dieser Grundlage eine technische Umsetzungsplanung erstellen.
|
||||
|
||||
Dabei soll er ausdrücklich:
|
||||
|
||||
1. bestehende Strukturen wiederverwenden, soweit sinnvoll,
|
||||
2. keine unnötigen Refactorings auslösen,
|
||||
3. bestehende Trainingsplanung nicht destabilisieren,
|
||||
4. Migrationen schrittweise und rückwärtskompatibel planen,
|
||||
5. vorhandene Methodendomäne berücksichtigen,
|
||||
6. die Trennung zwischen Trainingsmethode, Archetyp und Ablaufprofil fachlich erhalten,
|
||||
7. technische Alternativen mit Vor- und Nachteilen darstellen,
|
||||
8. erst danach konkrete Tabellen, APIs und UI-Komponenten vorschlagen.
|
||||
|
||||
Die Spezifikation ist daher kein technisches Pflichtenheft, sondern ein fachlicher Rahmen.
|
||||
|
||||
---
|
||||
|
||||
## 15. Zusammenfassung der verbindlichen Produktlogik
|
||||
|
||||
1. Trainingsabschnitte sind die Makrostruktur der Einheit.
|
||||
2. Kombinationsübungen sind keine Abschnitte.
|
||||
3. Kombinationsübungen sind Sonderformen von Übungen.
|
||||
4. Trainingsmodule sind Planungsbausteine.
|
||||
5. Trainingsmethoden sind eigenständige fachliche Katalogobjekte.
|
||||
6. Eine Übung hat eine Hauptmethode und optional Nebenmethoden.
|
||||
7. Methoden-Archetypen beschreiben Ablaufmuster, nicht die Methode selbst.
|
||||
8. Ablaufprofile konkretisieren den Archetyp für Planung und Coaching (siehe § 10.5).
|
||||
9. Einfügen aus Bibliotheken erzeugt lokal bearbeitbare Planungsinhalte.
|
||||
10. Vorlagenänderungen verändern historische oder konkrete Planungen nicht automatisch.
|
||||
11. Rahmenprogramme sollen dieselbe Planungslogik nutzen wie konkrete Einheiten.
|
||||
12. Der Coding Agent entscheidet die technische Umsetzung anhand der bestehenden Codebasis.
|
||||
13. Archetyp-IDs und Coaching-Stufen (§ 10.2.1, § 10.4) sind die **Referenz gegen Code-Drift**; Änderungen nur mit Anhang A und technischer Doku.
|
||||
14. **Zeitliche Phasen** einer Kombination liegen vorrangig in **`method_profile`** und **Gesamtzeit am Planungseintrag**; **Übersteuerungen nur in der Planungsinstanz**, nicht still in der Bibliothek (§ 6.3, § 8.3, § 10.5.1).
|
||||
|
||||
---
|
||||
|
||||
## Anhang A — Implementierungsabgleich (Stand Code: App **0.8.110**)
|
||||
|
||||
Zweck: dieselbe Tabelle für **Produkt / Architekt / Agent** beim nächsten Schritt; verhindert „wir haben X gebaut, die Spec sagt aber Y“ ohne dass es dokumentiert wird.
|
||||
|
||||
| Thema (fachliche Headline aus dieser Spez) | Kurz beschrieben | Stand Code / UX (Referenz nur) | Lücke / nächste sinnvolle Schritte |
|
||||
|--------------------------------------------|-----------------|---------------------------------|-------------------------------------|
|
||||
| **Trainingsmodule (Bibliothek)** | Wiederverwendbare Blöcke, Kopier-Einfügen in Einheit | Bibliothek, API, Übernahme-Modal, Lineage-Spalte | **Phase 3** des Umsetzungsplans: erweiterter Übernahmemodus |
|
||||
| **Kombinationsübung im Katalog** | `exercise_kind=combination`, Slots, Pools (Kandidaten) | Migration 056, CRUD Übung mit `combination_slots`, GET liefert Slots + Kandidatentitel | Fachbezug Haupt-/Nebenmethoden aus § 4/§ 6 dort umsetzen, wo die Domäne es noch nicht abdeckt |
|
||||
| **Archetyp + Ablaufprofil am Katalogobjekt** | `method_archetype`, JSON `method_profile` + **`slot_profiles_v1`** | Geführtes Profil (`CombinationMethodProfileEditor`), `advance_mode` je Slot (Zeit / Ziel‑Wdh. / Coach), API-Build aus `ExerciseFormPage` | **Admin-UI für Archetypen** fehlt (nur Code-Konstanten); **serverseitige Validierung** Profil↔Archetyp offen; **volle Vorbelegung** aller Slots aus Preset/Archetyp nur teilweise (Schnellwahl) |
|
||||
| **Einplanbarkeit (normale Planung)** | Kombi in Sektionen; Overrides § 8.3 | `planning_method_profile` JSONB; Modal **„Ablauf bearbeiten“**; **Merge** Katalog+Planung im Frontend (`effectiveComboMethodProfile`); Payload-Sanitisierung; Backend `Json()` beim Insert | Planungsblöcke Phase 3; **serverseitige** Zusammenführung/Validierung optional (aktuell Merge nur Client) |
|
||||
| **Darstellung Planung / Lauf / Druck** | Konsistente Zeiten & Wdh. | `CombinationPlanBracket`, `effectiveStationTimingSummary`, Belastungs-Badge je Station; kompakte Kombi-Zeile in `TrainingUnitSectionsEditor` | Feintuning nach Nutzerfeedback |
|
||||
| **Zeitphasen (global / pro Slot)** | § 6.3 | `slot_profiles_v1`, globale Archetyp-Felder, `inferAdvanceModeFromStoredSlotRow` für Legacy-Zeilen | `timing_schema`-Konvergenz laut `COMBINATION_TIMING_PROFILE_PLAN.md` |
|
||||
| **Coaching Stufe A** | Slots + Kandidaten, Archetyp, Profil lesbar | `ExerciseFullContent` + `CombinationCoachSlots`: Merge Katalog+Planung; **globale Eckdaten mit fachlichen Labels** (`describeGlobalComboProfile`); Stationstexte inkl. „Wdh. ohne Wechsel zur nächsten Station“ / Pausen-Hinweis | Stufe **B/C** weiterhin **offen** (§ 10.6) |
|
||||
| **Coaching Stufe B** | Zeitleiste archetypnah | **Nein** — ein Coach‑Schritt = ein Planungsitem | Designentscheid: virtuelle Substeps vs. DB‑Materialisierung; Auswirkung auf Ist‑Zeit pro Item |
|
||||
| **Coaching Stufe C** | Timer/Wechsel/Abhaken nach Archetyp | Nur **generischer** Minuten-/Ist-Input pro Item; **kein** Stations-Timer-State | Pro Archetyp UI + `method_profile` — Haupt-Backlog |
|
||||
| **Rahmenprogramm** | Gleiche Inhalte wie Einheit | Slot‑Blueprint, `from-framework-slot` | Modul-/Kombi‑UX in Rahmen wie in Einheit konsolidieren (Phase 5) |
|
||||
| **Coaching-Vorschau im Editor** | § 9.3 Schritt 7 | **Peek** / Run nutzen `CombinationPlanBracket`; kein eigener „Coach-Sim“-Modus im Übungseditor | Optional: eingebettete read-only Coach-Ansicht |
|
||||
|
||||
**Pflege:** Bei jeder relevanten Codeänderung diese Tabelle **in demselben PR / derselben Session** anpassen (kein stiller Drift).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Gelieferte Features & technische Basis (Q2 2026)
|
||||
|
||||
**Stand:** 2026-05-08
|
||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.64**, **DB_SCHEMA_VERSION** siehe dort
|
||||
**Stand:** 2026-05-12
|
||||
**Referenz:** `backend/version.py` — aktuelle **APP_VERSION** / **DB_SCHEMA_VERSION** (Stand Code u. a. **0.8.96**)
|
||||
|
||||
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
|
||||
|
||||
@@ -170,4 +170,5 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| Fachlicher Nutzerüberblick | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` (Repo-Root) |
|
||||
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
||||
@@ -0,0 +1,130 @@
|
||||
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
|
||||
|
||||
**Status:** Entwurf · **Stand:** 2026-05-14
|
||||
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
|
||||
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand Analyse 2026-05-14): eine `training_unit` mit **`training_unit_sections`** und **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung **`TrainingUnitRunPage`** (sequentiell über Sektionen).
|
||||
|
||||
---
|
||||
|
||||
## 1. Ist-Stand (relevant)
|
||||
|
||||
| Bereich | Aktuell |
|
||||
|---------|---------|
|
||||
| Planstruktur | **Eine** lineare Liste `training_unit_sections` je `training_unit_id`; Items in `training_unit_section_items`. |
|
||||
| Rahmenprogramm | `training_framework_slots` verweisen auf **Blueprint**-`training_units` — Slots = **Serien-Spalten**, nicht simultane Breakouts in **einer** Halle. |
|
||||
| Kombinationsübung | Ein **Item** kann Kombi sein; `planning_method_profile` = Snapshot; Coaching-UI teilweise (`CombinationPlanBracket` in Run/Peek). |
|
||||
| Trainer-Zuweisung | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am **`training_units`**-Kopf; **keine** Zuordnung zu „welcher parallelen Spur“. |
|
||||
| Run-Modus | `TrainingUnitRunPage`: sortierte Sektionen/Items, Checkliste, Fortschritt in `sessionStorage` pro Einheit. |
|
||||
|
||||
**Konsequenz:** Parallele Streams erfordern ein **erweitertes konzeptionelles „Gefäß“** unterhalb der Einheit (Phasen und/oder Streams) und eine **Verknüpfung** bestehender Sektionen mit diesem Gefäß — oder eine **Migration** zu einem neuen Pflicht-Container (siehe §3).
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielarchitektur (logisch)
|
||||
|
||||
```
|
||||
training_unit (Kalender-Einheit)
|
||||
├── phase (order, kind: whole_group | parallel, optional Metadaten)
|
||||
│ ├── [whole_group] → sections[] → items[] (wie heute)
|
||||
│ └── [parallel] → stream (order, label, optional trainer_ids[])
|
||||
│ └── sections[] → items[]
|
||||
```
|
||||
|
||||
**Abwärtskompatibilität:** Einheiten **ohne** explizite Phasen/Streams verhalten sich wie heute: **implizit** eine einzige „Gemeinschaftsphase“ mit den vorhandenen Sektionen (Migration: alle bestehenden Sektionen an diese Default-Hülle hängen).
|
||||
|
||||
---
|
||||
|
||||
## 3. Datenmodell — Optionen
|
||||
|
||||
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
|
||||
|
||||
Neue Tabellen (Namen bei Implementierung final festlegen):
|
||||
|
||||
| Tabelle | Zweck |
|
||||
|---------|--------|
|
||||
| `training_unit_phases` | `training_unit_id`, `order_index`, `phase_kind` (`whole_group` \| `parallel`), optional `title`, `guidance_notes`, optional `planned_duration_min` |
|
||||
| `training_unit_parallel_streams` | `phase_id` (FK, nur wenn parent parallel), `order_index`, `title`/`label`, optional `notes`, optional `assigned_trainer_profile_ids` JSONB (oder 1:n-Hilfstabelle) |
|
||||
|
||||
**Anpassung `training_unit_sections`:** Zusätzliche FK-Spalte(n), z. B.:
|
||||
|
||||
- `phase_id` **NULL** und `parallel_stream_id` **NULL** → **Legacy / Default-Einheitsphase** (Migration setzt Default-Phase); oder
|
||||
- genau einer von `phase_id` (whole group) oder `parallel_stream_id` gesetzt.
|
||||
|
||||
**Constraints:** CHECK: nicht beide gesetzt; bei `phase_kind = parallel` Sektionen nur unter `parallel_stream_id`; bei `whole_group` nur unter `phase_id`.
|
||||
|
||||
**Vorteil:** Klare Semantik, Reporting, API-Shape konsistent.
|
||||
|
||||
### 3.2 Minimalvariante (nicht ideal fachlich)
|
||||
|
||||
Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; Phasen implizit durch „Marker“-Sektionen oder Konvention. **Nicht empfohlen**, erschwert UI und Erklärbarkeit.
|
||||
|
||||
---
|
||||
|
||||
## 4. API
|
||||
|
||||
- **`GET /api/training-units/:id`** (und Listen-Payloads wo vollständiger Plan nötig): verschachtelte Struktur **Phasen → Streams → sections → items** oder flache `sections` mit ausgefüllten `phase_id` / `parallel_stream_id` (Frontend kann normalisieren).
|
||||
- **`PUT/PATCH`:** Atomares Ersetzen der Phasen/Streams/Sektionen analog zu bestehendem `_replace_unit_sections`-Muster; **Validierung** der CHECK-Regeln serverseitig.
|
||||
- **Blueprint / Rahmen:** Blueprint-`training_units` dürfen dieselbe Struktur tragen; `GET` Kalenderliste blendet Blueprints weiter aus (`framework_slot_id IS NOT NULL`).
|
||||
|
||||
**Governance / Mandant:** Unverändert über Einheit → `group_id`; keine neuen Mandanten-Entitäten.
|
||||
|
||||
---
|
||||
|
||||
## 5. Frontend
|
||||
|
||||
### 5.1 Planung (`TrainingPlanningPage`)
|
||||
|
||||
- Darstellung als **vertikale Phasen**: Gemeinschaftsblöcke + Parallelphase mit **N Spalten** (Streams).
|
||||
- **Wiederverwendung:** `TrainingUnitSectionsEditor` **pro Stream** und pro Gemeinschaftsphase — analog zur Wiederverwendung **pro Rahmen-Slot** in `TrainingFrameworkProgramEditPage`.
|
||||
- **Co-Trainer:** UI pro Stream (`assigned_trainer_profile_ids`); Regel zur **Kopfliste** `assistant_trainer_profile_ids` festlegen (z. B. Union aller Stream-Zuweisungen für „Wer ist heute dabei“ + Rückwärtskompatibilität wenn Stream-Felder leer).
|
||||
|
||||
### 5.2 Durchführung (`TrainingUnitRunPage`)
|
||||
|
||||
- Gemeinschaftsphasen: heutiges **lineares** Verhalten.
|
||||
- Parallelphase: **Tabs, Akkordeon oder Swipe** zwischen Streams; Fortschritt **pro Stream** (Storage-Key z. B. `${unitId}:${streamId}`).
|
||||
- Kombi-Items: unverändert `CombinationPlanBracket` / `effectiveComboMethodProfile`.
|
||||
- Optional später: Filter „nur meine Spur“ anhand Session-Profil vs. Stream-Zuweisung.
|
||||
|
||||
### 5.3 Vorlagen (`training_plan_templates`)
|
||||
|
||||
- Erweiterung um **dieselbe** Phasen/Streams-Semantik (Kindtabellen oder serialisiertes JSON — Abgleich mit Kopierlogik aus Vorlage in Einheit).
|
||||
- **Kein** Live-Spiegel: weiterhin Materialisierung beim Anwenden.
|
||||
|
||||
---
|
||||
|
||||
## 6. Bezug Kombinationsübungen
|
||||
|
||||
- **Variante A** (Rotation innerhalb einer Teilstrecke): ein oder mehrere **Items** vom Typ Kombi im jeweiligen Stream; Archetyp und Parameter wie in `TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`.
|
||||
- **Variante B** (synchron Hallenweit): erweiterte **Phasen-** oder **Stream-übergreifende** Metadaten — **nicht** in MVP-Zwang; eigenes Teilpaket nach fachlicher Freigabe (`PARALLEL_TRAINING_STREAMS_CONCEPT.md` §5.2).
|
||||
|
||||
---
|
||||
|
||||
## 7. Migration und Risiken
|
||||
|
||||
1. **Datenmigration:** Alle existierenden `training_unit_sections` einer Einheit einer **Default-Phase** `whole_group` zuordnen.
|
||||
2. **API-Versionierung:** Clients, die nur flache `sections` erwarten, müssen angepasst werden (oder Server liefert **beides** kurzzeitig — nur wenn nötig).
|
||||
3. **Performance:** Tiefe Kopien (Rahmen-Slot, Duplikat Einheit) müssen rekursiv Phasen/Streams mitsamt Sektionen/Items kopieren.
|
||||
4. **Tests:** pytest für PUT/GET mit gemischten Phasen; ggf. Playwright-Smoke für Planung/Run.
|
||||
|
||||
---
|
||||
|
||||
## 8. Implementierungsphasen (Vorschlag)
|
||||
|
||||
| Phase | Inhalt |
|
||||
|-------|--------|
|
||||
| **P1** | Schema Phasen + Streams; Migration; GET/PATCH Einheit verschachtelt; Planungs-UI; Run-UI mit Stream-Tabs |
|
||||
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert |
|
||||
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) |
|
||||
|
||||
---
|
||||
|
||||
## 9. Verwandte Dokumente
|
||||
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md` | Fachziele, Begriffe, Entscheidungsfragen |
|
||||
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
|
||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
|
||||
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
|
||||
| `frontend/src/pages/TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Ist-UI |
|
||||
@@ -15,6 +15,7 @@
|
||||
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
|
||||
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
|
||||
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | **Parallele Streams / Breakout innerhalb einer Einheit** — orthogonale Domäne zu **Rahmen‑Slots** (Serien‑Sessions). |
|
||||
|
||||
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
# Trainingsmodule und Kombinationsübungen — Spezifikation (Entwurf)
|
||||
|
||||
**Status:** Entwurf zur fachlichen und technischen Abstimmung · **Stand:** 2026-05-12 (Code **0.8.110**, siehe `backend/version.py`)
|
||||
**Zweck:** Rahmen für Umsetzung, Integration in Planung/Rahmenprogramm und Durchführung im assistierten Training (Coaching-Modus). Dieses Dokument ist **nicht** implementierungsbindend, bis die markierten **offenen Entscheidungen** geschlossen und der Status angehoben wurde.
|
||||
|
||||
**Abgleich mit Code (Drift vermeiden):**
|
||||
|
||||
- **Kanonische Archetyp-IDs:** fest in `backend/routers/exercises.py` (`COMBINATION_ARCHETYPE_IDS`); fachliche Tabelle und UI-Labels in `frontend/src/constants/combinationArchetypes.js` — die **fachliche Master-Zuordnung** Name↔ID steht in `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` § 10.2.1. **Administrierbare Archetypen** (DB/UI) gibt es **nicht**; Erweiterungen nur per Code-Release — Fachspez **§ 10.6**.
|
||||
- **Planungs-Override:** `planning_method_profile` (Migration **057**) speichert einen **Snapshot**; **Merge** mit Katalogprofil erfolgt im Frontend (`frontend/src/utils/comboPlanningMethodProfile.js` — `effectiveComboMethodProfile`), nicht als serverseitiger Join. Payload-Sanitisierung vor PUT; Backend speichert JSONB zuverlässig (`Json()`).
|
||||
- **Coaching:** Stufe **A** — Slots, Kandidaten, Archetyp-Hilfstext, **Label** für globale Eckdaten (`describeGlobalComboProfile` in `combinationMethodProfileUi.js`), visuelle Klammer (`CombinationPlanBracket`) in Peek/Run; Stufen **B/C** (archetypgesteuerte Zeitleiste/Takt) **offen** — Fachspez § 10.4, **§ 10.6**, **Anhang A**.
|
||||
- **Umsetzungsplan:** `working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase 2/4 „teilweise“; Pakete **4e–4g** für Admin, Vorbelegung, Validierung).
|
||||
|
||||
**Verwandte Dokumente:**
|
||||
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Bibliothek, Slot-Blueprint, Kopiersemantik (`from-framework-slot`) |
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | Parallele Teilstrecken **innerhalb einer Einheit**; Kombi-Übungen weiter nutzbar **pro Stream** für Stationsrotation |
|
||||
| `DATABASE_SCHEMA.md` | Aktueller Stand `training_units`, Sektionen, Items |
|
||||
| `functional/DOMAIN_MODEL.md` | Domänenbegriffe (bei Bedarf zu erweitern) |
|
||||
| `EXERCISES_*` (Katalog) | Einzelübungen, Varianten |
|
||||
| `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` | Sichtbarkeit, Mandant, Rollen bei neuen Bibliotheks-Entitäten |
|
||||
|
||||
---
|
||||
|
||||
## 1. Zielbild und Abgrenzung
|
||||
|
||||
### 1.1 Problem
|
||||
|
||||
Die Trainingsplanung unterstützt Einheiten mit Sektionen und einzelnen Übungen (inkl. Notizen) sowie Rahmenprogramme mit Blueprint-Einheiten pro Slot. Es fehlen:
|
||||
|
||||
- **Wiederverwendbare Übungsfolgen** („Trainingsmodule“), die sich wie Bausteine in eine Einheit einfügen lassen (ganze Sektion oder Block innerhalb einer Sektion), inkl. kopierbasierter Integration analog zum Rahmen.
|
||||
- **Strukturierte Kombinationsformen** (z. B. Zirkel mit Stationstausch, Parcour), bei denen **mehrere Einzelübungen** Slots oder Rollen einnehmen und die **Trainingsmethode** den Ablauf (Rotation, parallele Stationen, Zeitmodell) bestimmt.
|
||||
- Ein durchgängiges Konzept für den **Coaching- bzw. Assistenzmodus**, in dem derselbe Plan je nach Archetyp **unterschiedlich gesteuert** wird (Beispiel Zirkel: Erklärphase vs. parallele Nutzung aller Stationen).
|
||||
|
||||
### 1.2 Nicht-Ziele (für erste Ausbaustufe)
|
||||
|
||||
- **Individuelles Athleten-Tracking** oder Leistungsmessung pro Person (außerhalb Shinkan-MVP, siehe Produktabgrenzung).
|
||||
- Automatische **Synchronisation** zwischen Bibliotheksexemplar und bereits geplanten historischen Einheiten (bewusst: **Kopie** statt Live-Spiegel, konsistent mit Rahmen-Konzept).
|
||||
|
||||
### 1.3 Zwei Bausteine (fachliche Trennung)
|
||||
|
||||
| Baustein | Kurzname | Einordnung | Kurzbeschreibung |
|
||||
|----------|-----------|------------|------------------|
|
||||
| **Typ 1** | **Kombinationsübung** | Übungskatalog (Sonderform einer **Übung**) | Eine logische Übung mit **1–n Slots**; Slots können einzelne Übungen oder **Pools** auswählbarer Übungen tragen; **Methodenprofil / Archetyp** steuert später den Durchlauf. |
|
||||
| **Typ 2** | **Trainingsmodul** | Planung / Bibliothek | Gespeicherte, wiederverwendbare **Sequenz** von Elementen (Einzelübungen, optional Kombinationsübungen, Notizen); Einbindung per **Kopie** in konkrete `training_units` oder in Rahmen-Slot-Blueprints. |
|
||||
|
||||
**Abgrenzung Rahmenprogramm:** Das Rahmenprogramm strukturiert **mehrere Einheiten** (Slots) auf Programm-Ebene. Ein Trainingsmodul strukturiert typischerweise **Inhalt einer Einheit** oder eines Teils davon, nicht den Wochen-/Periodenrahmen.
|
||||
|
||||
---
|
||||
|
||||
## 2. Begriffe
|
||||
|
||||
| Begriff | Definition |
|
||||
|---------|------------|
|
||||
| **Bibliotheksexemplar** | Gespeicherte Vorlage (Modul oder Kombinationsübung-Definition) mit Governance (z. B. global, Verein, privat). |
|
||||
| **Instanz in der Planung** | In `training_unit_section_items` (und ggf. ergänzende Tabellen) materialisierter Ablauf für einen **konkreten Termin** bzw. eine **geplante Einheit**. |
|
||||
| **Slot (Typ 1)** | Position innerhalb einer Kombinationsübung; kann genau eine gewählte Übung oder einen **Pool** (mehrere Kandidaten) referenzieren. |
|
||||
| **Methodenprofil / Archetyp** | Maschinenlesbare Semantik **wie** trainiert wird (Zeit, Rotation, Parallelität), ergänzend zum bestehenden Katalog `training_methods` (Beschreibung **was** für eine Didaktik/Kondition gilt). |
|
||||
| **Coaching-Modus** | UI- und Zustandslogik zur Durchführung einer geplanten Einheit (Timer, Phasen, Stationen). |
|
||||
|
||||
---
|
||||
|
||||
## 3. Trainingsmethoden und Archetypen (Typ 1)
|
||||
|
||||
### 3.1 Bestehende Basis
|
||||
|
||||
Der Katalog `training_methods` (Migration 003) enthält u. a. **Zirkeltraining** (`category` u. a. `zirkel`, `kondition`). Er beschreibt die Methode **inhaltlich**, nicht aber Parameter wie Wechselintervalle oder parallele vs. rotierende Nutzung.
|
||||
|
||||
### 3.2 Erweiterung: Archetyp
|
||||
|
||||
Jede Kombinationsübung (und optional der Methodendatensatz als Default) erhält ein Feld **`method_archetype`** (Enum/Wertliste). Der Archetyp legt fest, welche **Parameter** am Methodenprofil relevant sind und wie der **Coaching-Modus** den Ablauf interpretiert.
|
||||
|
||||
**Vorschlagsliste (erweiterbar, zu verbindlich machen):**
|
||||
|
||||
| Archetyp-ID (Vorschlag) | Beschreibung Planungslogik | Coaching (Intent) |
|
||||
|-------------------------|----------------------------|---------------------|
|
||||
| `circuit_rotate_time` | n Stationen; Wechsel nach Ablaufzeit, optional globale Rundenanzahl | Rotierender oder gemeinsamer Takt; Umlauf zur nächsten Station |
|
||||
| `circuit_all_parallel` | n Stationen; **kein** Umlauf als fachlicher Kern, alle Stationen gleichzeitig aktiv | Erklärphase (alle Inhalte vorher), dann **parallel** alle Stationen |
|
||||
| `sequence_linear` | feste Reihenfolge; Aufbau, keine Kreisrotation | Schrittliste / Timer optional pro Schritt |
|
||||
| `station_parcour` | Stationsbezogener Pfad, Reihenfolge kann variieren | Navigation / Abhaken eher als ein globaler Umlauf-Takt |
|
||||
| `pair_superset` | zwei (oder wenige) Blöcke im Wechsel | Partnerlogik, gekoppelte Timer |
|
||||
| `time_domain_interval` | AMRAP/EMOM-ähnliche Zeitdomäne | Globale Uhr, Runden-/Intervallzähler |
|
||||
|
||||
### 3.3 Parameter des Methodenprofils
|
||||
|
||||
Zu präzisieren (JSON-Dokument vs. normalisierte Spalten):
|
||||
|
||||
- Zeit: `work_seconds`, `rest_seconds`, `transition_seconds`, `rounds`
|
||||
- Organisation: `station_count`, `rotation_direction`, Flags `explain_all_before_start`, `stations_operate_simultaneously`
|
||||
- ggf. `intensity_profile` (skalar oder Enum), nur wenn für MVP nötig
|
||||
|
||||
**Offen:** Welche Parameter sind **Pflicht pro Archetyp** (Validierung).
|
||||
|
||||
---
|
||||
|
||||
## 4. Datenmodell (Zielarchitektur, Entwurf)
|
||||
|
||||
### 4.1 Typ 2 — Trainingsmodule
|
||||
|
||||
**Entwurfstabellen (Namen können bei Implementierung angeglichen werden):**
|
||||
|
||||
- `training_modules` — Kopf: Titel, Beschreibung, Metadaten, `visibility`, `club_id`, `created_by`, Timestamps
|
||||
- optional `training_module_sections` — falls ein Modul mehrere semantische Blöcke abbilden soll
|
||||
- `training_module_items` — Reihenfolge, Verweis auf:
|
||||
- Einzelübung (`exercise_id`, `exercise_variant_id`)
|
||||
- Kombinationsübung (`combination_exercise_id` / `exercise_id` mit `kind=combination`)
|
||||
- Freitext-Notiz (analog `note` bei Einheiten)
|
||||
|
||||
Semantik: **Bibliotheksbaum**, keine Bindung an Kalender oder Gruppe.
|
||||
|
||||
### 4.2 Typ 1 — Kombinationsübungen
|
||||
|
||||
**Option A (Embedding in `exercises`):** Spalte `exercise_kind` = `simple` | `combination` und Kindtabellen für Slots/Pools.
|
||||
|
||||
**Option B (Separate Kopf-Tabelle):** 1:1-Beziehung zwischen `exercises` und `combination_exercises`.
|
||||
|
||||
**Slot-Pools:** mindestens M:N **Pool-Kandidat** pro Slot; die **konkret geplante Auswahl** gehört zur **Instanz** (geplante Einheit), nicht zwingend zum Bibliotheksexemplar.
|
||||
|
||||
### 4.3 Integration in geplante Einheiten
|
||||
|
||||
Heute: `training_unit_section_items` mit `item_type` in (`exercise`, `note`).
|
||||
|
||||
**Erweiterungsoptionen (Entscheidung offen):**
|
||||
|
||||
1. **Expansion beim Einfügen:** Modul wird in Items „aufgeklappt“; optional `source_module_id` an Items für Herkunft (Lineage-Light).
|
||||
2. **Block-Item:** neuer `item_type` `module_reference` oder `combination` mit ID und eingebetteter Bearbeitungssemantik (komplexer, aber „Modul als Einheit“ editierbar).
|
||||
|
||||
Empfehlung zur Abstimmung: MVP oft mit **Expansion** + optionaler Markierung; später Block-Knoten.
|
||||
|
||||
**Rahmenprogramm:** Blueprint-`training_units` pro Slot nutzen dieselbe Sektions-/Item-Struktur — Module müssen **dort** ebenfalls einfügbar sein, wenn Rahmen und konkrete Planung konsistent bleiben sollen.
|
||||
|
||||
---
|
||||
|
||||
## 5. API (Skizze)
|
||||
|
||||
Verbindliche Pfade und Payloads folgen nach Freigabe dieses Dokuments.
|
||||
|
||||
| Richtung | Beispielpfad / Funktion | Zweck |
|
||||
|----------|-------------------------|--------|
|
||||
| CRUD | `GET/POST/PUT/DELETE …/training-modules` | Bibliothek Trainingsmodule |
|
||||
| Anwendung | `POST …/training-units/{id}/apply-module` | Modulinhalt in Sektion kopieren (tiefe Kopie) |
|
||||
| Übungen | Erweiterung `GET/POST/PUT …/exercises` oder Unterressource `…/exercises/{id}/combination` | Kombinationsübung inkl. Slots |
|
||||
| optional | `POST …/training-units/from-module` | Neue Einheit aus Modul (falls produktrelevant) |
|
||||
|
||||
**AuthZ:** analog andere Bibliotheks- und Planungsobjekte; Abgleich mit `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` und Endpoint-Audit.
|
||||
|
||||
---
|
||||
|
||||
## 6. Frontend
|
||||
|
||||
- **Bibliothek:** Verwaltung Trainingsmodule (Liste, Editor, Sortierung, Vorschau).
|
||||
- **Übungsbereich:** Editor für Kombinationsübungen (Slots, Pools, Methodenprofil/Archetyp).
|
||||
- **Planungs-UI:** Aktion „Modul einfügen“, Ziel-Sektion und Position; Hinweis **Kopie** und Editierbarkeit pro Termin.
|
||||
|
||||
---
|
||||
|
||||
## 7. Coaching- / Assistenzmodus (Durchlauf)
|
||||
|
||||
### 7.1 Phasenmodell (konzeptionell)
|
||||
|
||||
- **Briefing / Erklärung:** insbesondere für `circuit_all_parallel` und Varianten mit `explain_all_before_start`
|
||||
- **Arbeitsphase(n):** timer- und stationsgetrieben
|
||||
- **Übergänge:** Pausen, Wechsel, Rundenzähler
|
||||
|
||||
### 7.2 Persistenz während Durchführung
|
||||
|
||||
**Offen:** Ob ein **`training_session_run`** (Snapshot der aufgelösten Einheit zum Startzeitpunkt) für Nachvollziehbarkeit und Offline-Fähigkeit nötig ist.
|
||||
|
||||
### 7.3 Ausbaustufen
|
||||
|
||||
1. Read-only **Durchführungsansicht** (Archetyp + Zeiten, keine komplexe State Machine)
|
||||
2. **Aktiver Modus** mit State Machine und Archetyp-spezifischer UI
|
||||
3. Optional: Offline/PWA-Verhalten
|
||||
|
||||
---
|
||||
|
||||
## 8. Umsetzungsphasen (Vorschlag)
|
||||
|
||||
| Phase | Inhalt |
|
||||
|-------|--------|
|
||||
| **A** | Dieses Dokument verbindlich machen; Archetypen und Parameter final; Governance-Regeln |
|
||||
| **B** | Typ 2: `training_modules` + API + „Modul in Einheit einfügen“ (Expansion) |
|
||||
| **C** | Typ 1: Kombinationsübung im Katalog + Slots/Pools + Methodenprofil |
|
||||
| **D** | Einbindung in Rahmen-Slot-Blueprints (Editor-Flow) |
|
||||
| **E** | Coaching-Modus gemäß Archetyp |
|
||||
|
||||
---
|
||||
|
||||
## 9. Offene Entscheidungen (Checkliste)
|
||||
|
||||
- [ ] Modul-Einfügung: nur **Expansion** vs. **Block-Knoten** vs. beides
|
||||
- [ ] Normalisierung vs. JSON für **Methodenprofil-Parameter**
|
||||
- [ ] Globale vs. vereinsbezogene vs. private **Trainingsmodule** (Governance-Matrix)
|
||||
- [ ] Pflichtbinding: muss jede Kombinationsübung einen **Default-Archetyp** aus `training_methods` erben dürfen?
|
||||
- [ ] Coaching: Mindestumfang MVP (nur Ansicht vs. interaktive Timer)
|
||||
- [ ] Verweise in `DOMAIN_MODEL.md` und `DATABASE_SCHEMA.md` nach Implementierung pflegen
|
||||
|
||||
---
|
||||
|
||||
## 10. Changelog
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-12 | Erstversion (Entwurf) angelegt |
|
||||
@@ -15,6 +15,8 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
|
||||
| exercise_progression_graphs | `/api/exercise-progression-graphs*` | ja | `get_tenant_context` | Liste wie Bibliothek; Schreiben Ersteller/Plattform-Admin | Kanten: Lesen wenn Graph lesbar |
|
||||
| training_planning | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Vorlagen-Liste wie Übungen; POST Vorlage Default club_id |
|
||||
| dashboard | `GET /api/dashboard/kpis` | ja | `get_tenant_context` | wie `GET /api/exercises` + `GET /api/training-units` | Aggregat für Dashboard-Kurzüberblick (ein Roundtrip) |
|
||||
| training_modules | `/api/training-modules*` | ja | `get_tenant_context` | ja | Bibliotheks-Module wie Vorlagen/Rahmen; POST Default `club_id` bei `visibility=club` |
|
||||
| training_framework_programs | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Liste + POST Default club_id |
|
||||
| admin_users | `GET /api/admin/users` | Plattform | `require_auth` | Admin-Rolle | EXEMPT `check_access_layer_hints.py` |
|
||||
| platform_media_storage | `GET/PUT /api/admin/platform-media-storage` | Plattform | `require_auth` | GET: `is_platform_admin`; PUT: nur `superadmin` | Relativer Pfad unter `MEDIA_ROOT`; keine Secrets; EXEMPT wie admin_users |
|
||||
@@ -36,12 +38,13 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
|
||||
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
||||
|
||||
Letzte Änderung: 2026-05-07 — Upload-Dedupe Papierkorb 409 + `reactivate`; DELETE …/media nur Verknüpfung.
|
||||
Letzte Änderung: 2026-05-13 — `GET /api/dashboard/kpis` (Kurzüberblick-Aggregat).
|
||||
|
||||
---
|
||||
|
||||
### Changelog (Fortführung)
|
||||
|
||||
- **2026-05-13:** Dashboard-KPI-Endpunkt dokumentiert.
|
||||
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Kombinations‑Ablaufprofil — Zeitmodell, Archetyp‑Vorgaben, Umsetzung
|
||||
|
||||
**Zweck:** Fach-/Technik-Brücke zwischen Wunschbild („kein Nutzer‑JSON“, globale und slotbezogene Eckwerte, Archetyp‑Strukturen) und bestehendem Speicher **`method_profile` (JSON)** + **`planning_method_profile`** auf Planungszeilen.
|
||||
|
||||
**Bezüge:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (§ 6.3 / § 8.3); Frontend `CombinationMethodProfileEditor`, `combinationMethodProfileUi.js`; Archetyp‑IDs siehe Backend `COMBINATION_ARCHETYPE_IDS` / Frontend `COMBINATION_ARCHETYPE_OPTIONS`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Grundprinzipien
|
||||
|
||||
| Prinzip | Beschreibung |
|
||||
|--------|--------------|
|
||||
| **Kein Pflicht‑JSON für Trainer** | Alle trainertypischen Pflegepfade nur über geführte Felder + Archetyp‑Vorschlagsknöpfe. |
|
||||
| **JSON bleibt Transport** | Persistenz geschieht weiter in `method_profile` / Kopie in `planning_method_profile`; **kanonische Schlüssel** werden hier und in Codekommentaren festgehalten. |
|
||||
| **Archetyp = Struktur + Defaults** | Wechsel des Archetyps soll (optional/togglebar) Grundwerte oder typische Relationen vorbelegen können — keine stillen Überschreibungen ohne Hinweis. |
|
||||
| **`free_method_block` = Maximale Freiheit** | Entspricht „maximaler Konfiguration“: alle relevanten Timing‑Dimensionen über UI, insbesondere **pro Slot**; keine impliziten stationären Constraints. |
|
||||
|
||||
---
|
||||
|
||||
## 2. Kanonisches Zeit‑Schema (`timing_schema`)
|
||||
|
||||
**Empfohlene Versionierung im Objekt:**
|
||||
|
||||
- **`timing_schema: 1`** — sobald neue globale/strukturierte Felder aktiv genutzt werden (Pilot; UI kann ohne Migration starten durch parallele Schlüssel).
|
||||
|
||||
### 2.1 Globalebene (`method_profile`)
|
||||
|
||||
| Feld (Pilot) | Semantik |
|
||||
|----------------|----------|
|
||||
| `timing_schema` | `1` wenn Block unten aktiv |
|
||||
| `intro_sec` oder bestehend `block_intro_sec` | einmalige Einführung/Demo am Block |
|
||||
| `rounds` (bzw. bei Intervallen `interval_rounds` — Angleich später) | komplette Durchläufe des Musters |
|
||||
| *Planned totals* nur **berechnete Anzeige** in UI, optional persistiert z. B. `planned_total_duration_min_hint` später |
|
||||
|
||||
Relationen **Zwischen Arbeit und Pause** können als Schnellwahl gesetzt werden (kein eigener Persist‑Erzwing‑Typ nötig), indem konkrete Sekunden geschrieben werden.
|
||||
|
||||
### 2.2 Slots (`slot_profiles_v1`)
|
||||
|
||||
Array synchron zu `slot_index`; fehlende Einträge = „nicht gefüllt / aus globalen Eckdaten ableiten wo sinnvoll“.
|
||||
|
||||
Objekt‑Shape (Sekunden, ganze Zahlen ≥ 0):
|
||||
|
||||
```json
|
||||
{
|
||||
"slot_index": 0,
|
||||
"load_sec": 40,
|
||||
"consecutive_reps": 1,
|
||||
"intra_rep_rest_sec": 10,
|
||||
"transition_after_sec": 15
|
||||
}
|
||||
```
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|------|------------|
|
||||
| `load_sec` | Belastungsdauer „an der Station“. |
|
||||
| `consecutive_reps` | Wiederholungen pro „Serie“ bzw. ohne Wechsel zu **neuem** Stationsinhalt (oft 1). |
|
||||
| `rep_series_count` | Anzahl Serien à `consecutive_reps` bei rep/manual; Standard **1**, Archetyp‑Vorgabe möglich (**`ARCHETYPE_DEFAULT_REP_SERIES_COUNT`**). Persistiert für rep/manual ab 1. |
|
||||
| `intra_rep_rest_sec` | Pause zwischen den Folge‑Wiederholungen bzw. **zwischen Serien** (nur sinnvoll, wenn `rep_series_count` ≥ 2 im Modus `rep`/`manual`; sonst Wechselzeit `transition_after_sec` nutzen). |
|
||||
| `transition_after_sec` | Pause / Wechsel **zur nächsten** Station oder zum nächsten logischen Block. |
|
||||
|
||||
**Hinweis:** Bestehende Archetyp‑„flachen“ Schlüssel (`work_seconds`, `transition_seconds`, …) werden schrittweise **nicht zerstört**, sondern Slots ergänzen; Konvergenz (eine Darstellung zu v1) kann Phase 4 sein.
|
||||
|
||||
---
|
||||
|
||||
## 3. Archetyp → typische Schnellwahl (Überblicks‑Matrix)
|
||||
|
||||
| Archetyp | Globale Schnellwahl (Beispiele) | Slots |
|
||||
|----------|---------------------------------|-------|
|
||||
| `circuit_rotate_time` | Arbeit; Rotation „≈ Arbeit“ oder „Pause 2/3 Arbeit“ bezogen auf Rund‑Pausen/Rotation wo im UI dokumentiert | sinnvoll ab **timing_schema** geführt |
|
||||
| `time_domain_interval` | Pause = Arbeit; Pause = 2/3 Arbeit (auf `rest_seconds`↔`work_seconds`) | optional |
|
||||
| `sequence_linear` | Einführung + grobe Sek./Station | **slot_profiles_v1** priorisiert |
|
||||
| `circuit_all_parallel` | Erklärzeit, gemeinsamer Start | Slots optional |
|
||||
| `pair_superset` | Wechsel A↔B, Arbeit je Seite (+ später erweiterbar) | 2‑Slot‑Fokus |
|
||||
| `free_method_block` | alle globalen Slots optional | **Pfad für maximale Flex** |
|
||||
| `station_parcour` | Reihenfolge frei‑Flag bestehend | pro Station Verweilen sinnvoll |
|
||||
|
||||
**Pyramidal (später):** neue Archetyp‑ID **`pyramid_interval`** o. ä. oder Flag `pyramid_recovery_rule` mit Regelwerk „Pause abhängig von letzter Belastung“ — **explizit out of scope** bis Regeln feststehen.
|
||||
|
||||
---
|
||||
|
||||
## 4. UX‑Normen
|
||||
|
||||
- **Trainingsplanung** (`plannerMode`): **keine** Roh‑JSON‑Oberfläche.
|
||||
- **Übungsformular**: Roh‑JSON nur wenn `allowExpertJson === true` (Default false; später z. B. Superadmin/Dev).
|
||||
- **Coaching‑Ansicht**: nur **wirksame** Zahlen aus Snapshot/Katalog (Merge wie in `comboPlanningMethodProfile.js`); **globale** Profilwerte mit **fachlichen Labels** (`describeGlobalComboProfile`), nicht nur Rohschlüsseln.
|
||||
|
||||
### 4.1 Stand Umsetzung (App **0.8.110**, Kurz)
|
||||
|
||||
- **`slot_profiles_v1`** und Schnellwahlen Zirkel/Intervall im geführten Editor umgesetzt; **`advance_mode`** je Slot (Zeit / Ziel‑Wdh. / Coach).
|
||||
- **Phase 2** dieses Plans (Modal „Archetyp‑Vorlage anwenden?“, nicht‑destruktives Merge über alle Slots) — **noch offen** (Fachspez § 10.6, Umsetzungsplan Paket **4f**).
|
||||
|
||||
---
|
||||
|
||||
## 5. Phasen (Implementierung)
|
||||
|
||||
| Phase | Inhalt |
|
||||
|-------|--------|
|
||||
| **1 (jetzt)** | Slot‑Zeilen‑UI über `slot_profiles_v1`; Schnellwahl‑Ratios für `circuit_rotate_time` + `time_domain_interval`; `plannerMode` ohne JSON; `allowExpertJson` default false |
|
||||
| **2** | Beim Archetypwechsel **optionales** Modal „Archetyp‑Vorlage anwenden?“ mit nicht‑destruktivem Merge |
|
||||
| **3** | Geplante **Gesamtzeit** konsistent rechnerisch (Summe Slots × Runden + Global) mit Transparenz in UI |
|
||||
| **4** | Konsolidierung flacher Schlüssel → **`timing_schema`** v1‑only im Editor |
|
||||
| **5** | Pyramide / adaptive Recovery |
|
||||
|
||||
---
|
||||
|
||||
**Pflege:** Änderungen an Schlüsseln oder Phasen hier und in Anhang A der Fachspez mitziehen.
|
||||
@@ -0,0 +1,125 @@
|
||||
# Parallele Trainingsstreams — Ist-Analyse und risikoarmer Umsetzungsplan
|
||||
|
||||
**Status:** Stufe A (Analyse/Plan, ohne produktive Umsetzung in jener Session)
|
||||
**Stand:** 2026-05-14
|
||||
**Verbindliche fachliche Basis:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
|
||||
Dieses Dokument **persistiert** die strukturierte Prüfung der realen Codebasis (`training_planning.py`, `training_framework_programs.py`, `training_unit_sections`/`items`, Frontend Planung/Run/Coach) und den empfohlenen Implementierungspfad.
|
||||
|
||||
---
|
||||
|
||||
## 1. Zusammenfassung
|
||||
|
||||
- Plan-Inhalt pro Einheit ist heute **eine flache Liste** `training_unit_sections` mit **`UNIQUE (training_unit_id, order_index)`** (Migration 031) und `training_unit_section_items`; zentral: **`_fetch_sections`**, **`_replace_unit_sections`**, **`_hydrate_training_unit_payload`** in `backend/routers/training_planning.py`.
|
||||
- Parallele Phasen/Streams **passen** zu den Produktregeln (ein Kalendertermin, N Streams, je Miniplan), sind im Schema aber **nicht** abbildbar ohne Erweiterung und **ohne Auflösung** des globalen `order_index`-Modells.
|
||||
- **Empfehlung:** **Normalisierte** Tabellen `training_unit_phases`, `training_unit_parallel_streams`, erweiterte `training_unit_sections` mit FK auf Phase bzw. Stream, **partielle Unique-Indizes** statt `UNIQUE (training_unit_id, order_index)` für alle Sektionen.
|
||||
- **Blocker im Code:** u. a. `POST /api/training-units/{id}/apply-training-module` mit **`section_order_index` global pro Einheit** (`_resolve_training_unit_section_id`).
|
||||
- **Nicht persistiert an anderer Stelle:** Erste Fassung existierte nur als Chat-Antwort; dieses File ist die **kanonische** Arbeitskopie im Repo.
|
||||
|
||||
---
|
||||
|
||||
## 2. Ist-Analyse (kurz)
|
||||
|
||||
### Datenbank
|
||||
|
||||
- `training_unit_sections`: u. a. `training_unit_id`, `order_index`, `UNIQUE (training_unit_id, order_index)`.
|
||||
- `training_unit_section_items`: Übung/Notiz, `planning_method_profile` (Kombi), `source_training_module_id`.
|
||||
|
||||
### Backend (`training_planning.py`)
|
||||
|
||||
- `_replace_unit_sections`: DELETE aller Sektionen der Einheit + INSERT (vollständiger Ersetzungsbaum).
|
||||
- `_sections_clone_payload` + `_copy_blueprint_into_scheduled_unit`: tiefe Kopie für `from-framework-slot`.
|
||||
- `_flatten_exercises_from_sections`: flaches `exercises` am Unit-Payload.
|
||||
- `apply_training_module_to_training_unit`: Sektion per **`section_order_index`** global.
|
||||
|
||||
### Rahmen (`training_framework_programs.py`)
|
||||
|
||||
- Blueprint-`training_units` pro Slot; gleiche `_replace_unit_sections`-Semantik.
|
||||
|
||||
### Frontend
|
||||
|
||||
- Planung: `TrainingPlanningPageRoot.jsx`, `TrainingUnitSectionsEditor`, `buildSectionsPayload` / `normalizeUnitToForm`.
|
||||
- Run: `TrainingUnitRunPage.jsx` — Fortschritt `sessionStorage` Key `sj_training_run_checked_${unitId}`.
|
||||
- Coach: `TrainingCoachPage.jsx` — `flattenPlanTimeline` (linearer Ablauf).
|
||||
|
||||
### Tests
|
||||
|
||||
- Kaum Abdeckung für Plan-Inhalt; vorhanden u. a. `test_training_unit_assignments.py` (Merge Co-Trainer, ohne DB), `test_training_units_list_keyset.py` (Keyset-Validierung).
|
||||
|
||||
---
|
||||
|
||||
## 3. Technische Optionen und Empfehlung
|
||||
|
||||
| Option | Kurz |
|
||||
|--------|------|
|
||||
| A JSONB nur auf `training_units` | Niedriges DDL-Risiko, hohes Drift-/Wartungsrisiko — **nicht empfohlen** |
|
||||
| B Normalisiert Phasen/Streams | **Empfohlen** — eine Wahrheit, saubere Kopie, Rahmen kompatibel |
|
||||
| C Nur UI-Konvention ohne DB | Widerspricht Produkt — **abgelehnt** |
|
||||
|
||||
---
|
||||
|
||||
## 4. Migrations- und Kompatibilitätsstrategie
|
||||
|
||||
- Default **`whole_group`‑Phase** für alle bestehenden Einheiten; alle bisherigen Sektionen erhalten `phase_id`.
|
||||
- Unique-Regel: **pro Phase** bzw. **pro Stream** `order_index` eindeutig (partielle Unique-Indizes).
|
||||
- API optional: zusätzlich abgeleitetes flaches `sections` für Übergang — Entscheidung je nach Consumer (praktisch nur dieses Frontend).
|
||||
|
||||
---
|
||||
|
||||
## 5. API- / Frontend-Hotspots
|
||||
|
||||
- `GET`/`PUT` `/api/training-units/{id}`: verschachtelte `phases` / `streams` / `sections` / `items`.
|
||||
- `POST .../apply-training-module`: Kontext **Phase/Stream + Sektionsindex im Träger**.
|
||||
- Run/Coach: stream-spezifischer Fortschritt; `flattenPlanTimeline` phase-aware oder pro Stream.
|
||||
|
||||
---
|
||||
|
||||
## 6. Implementierungspakete (Überblick)
|
||||
|
||||
0. Spike DDL + Contract-Doku
|
||||
1. **Erledigt (2026-05-14):** Migration **063** + `training_planning`: Phasen/Streams-Schema, Backfill whole_group, `GET` mit `phases`, Legacy-`sections`-PUT unverändert (eine whole_group-Phase).
|
||||
2. PUT mit echten Parallelphasen / Streams, `apply-training-module` mit Stream-Kontext, `from-framework-slot`-Kopie
|
||||
3. Planung UI
|
||||
4. Run + Coach
|
||||
5. Co-Trainer pro Stream
|
||||
6. MVP+ (Duplizieren, Verschieben, „nur meine Spur“)
|
||||
|
||||
---
|
||||
|
||||
## 7. Risiken
|
||||
|
||||
- Migration Unique-Constraint / bestehende Daten.
|
||||
- Regression Run/Coach / Dashboard-Joins (meist unkritisch, solange `training_unit_id` auf Sektionen bleibt).
|
||||
- Rahmen-Blueprints: gleiche Struktur wie Kalender-Einheiten anstreben (oder bewusst zweite Phase nur Kalender).
|
||||
|
||||
---
|
||||
|
||||
## 8. Offene Produkt-/Technikfragen
|
||||
|
||||
- Rahmen-Blueprint parallel im MVP oder erst nach Kalender-Einheit?
|
||||
- Semantik `exercises`-Flatlist bei Parallelität.
|
||||
- Merge-Regel `assistant_trainer_profile_ids` Kopf vs. Stream-Zuweisungen.
|
||||
|
||||
---
|
||||
|
||||
## 9. Verweise
|
||||
|
||||
- Fachkonzept: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
- Technische Spec (Entwurf): `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
- Domänenüberblick: `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||
- `./PARALLEL_TRAINING_STREAMS_PREREQ_PROMPT.md` — **Prompt** für Folgesession (Performance/Wartung/Vorbereitung)
|
||||
|
||||
---
|
||||
|
||||
## 10. Vorbereitende Arbeiten (Session 2026-05-13)
|
||||
|
||||
Ohne produktives Parallel-Feature, nur Risikoabbau und Transparenz:
|
||||
|
||||
- **`training_planning.py`:** Lesepfad `_fetch_sections` in SQL-Konstanten + `_fetch_section_items_for_section` / `_hydrate_section_item_combination_slots` strukturiert; `_replace_unit_sections` delegiert an `_insert_one_replacement_section`; `_hydrate_training_unit_payload` dokumentiert.
|
||||
- **Tests:** `tests/test_training_planning_sections_pure.py` (flatten, ohne DB); `tests/test_training_planning_sections_integration.py` (Roundtrip replace↔fetch bei `TRAINING_PLANNING_INTEGRATION=1`).
|
||||
- **Frontend:** Kurzkommentare an Planung (`TrainingPlanningPageRoot`, `buildSectionsPayload`), Run, Coach, `flattenPlanTimeline` — Anbindungspunkte für spätere Phase/Stream-Logik.
|
||||
- **DOMAIN_MODEL:** UNIQUE-Hinweis und „keine Migration ohne Freigabe“.
|
||||
|
||||
**Empfohlene nächste Schritte:** Pakete **0** (DDL/Contract festzurren) und **1** (Schema + Migration + hydrate/replace laut Plan Abschnitt 4–6) in einer dedizierten Feature-Session; danach Paket **2** (PUT/Module/Clone).
|
||||
|
||||
---
|
||||
@@ -0,0 +1,41 @@
|
||||
# Prompt: Vorbereitungs- / Vorarbeit-Session (Performance & Wartung) für „Parallele Trainingsstreams“
|
||||
|
||||
**Kontext:** Du arbeitest in **Shinkan Jinkendo** (`c:\Dev\shinkan-jinkendo`). Das Feature **Parallele Trainingsstreams / Breakout** ist **inhaltlich** spezifiziert; eine **Ist-Analyse und ein risikoarmer Umsetzungsplan** liegen **persistiert** in:
|
||||
|
||||
- `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`
|
||||
- Fachlich: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
- Technik-Entwurf: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
|
||||
**Deine Rolle:** Du hast bereits **Refaktorierungs- und Wartungsaufgaben** mit Fokus **Performance, Lesbarkeit und Testbarkeit** durchgeführt. In **dieser** Session geht es **nicht** darum, das komplette Parallel-Feature zu bauen, sondern um **Vorarbeiten („Prerequisites“)**, die die geplante Komplexitätsauflösung **sicherer und billiger** machen.
|
||||
|
||||
## Ziele
|
||||
|
||||
1. **Lesepfad Planung vereinheitlichen:** `backend/routers/training_planning.py` ist zentral für `_fetch_sections`, `_replace_unit_sections`, `_hydrate_training_unit_payload`, Klonen, Blueprint-Kopie, `apply-training-module`. Prüfe, ob klar abgegrenzte Hilfsfunktionen (ohne Verhaltensänderung) die **nächste** große Änderung erleichtern — **keine** Feature-Logik für Phasen/Streams hinzufügen, nur Struktur/Tests/Docs wenn nötig.
|
||||
|
||||
2. **Test-Lücken schließen (minimal, hoher Nutzen):** Heute fehlen **DB/API-Tests** für kritische Pfade (`_replace_unit_sections` Roundtrip, `from-framework-slot` Struktur-Kopie, optional `apply-training-module`). Ergänze **kleine, deterministische** Tests (pytest mit DB, falls im Projekt üblich), ohne riesige Fixtures.
|
||||
|
||||
3. **Frontend-Schneidstellen markieren:** kurze Kommentare oder ein **Working-Doc-Update**, wo `TrainingPlanningPageRoot`, `buildSectionsPayload`, `TrainingUnitRunPage`, `TrainingCoachPage` + `trainingPlanUtils.flattenPlanTimeline` später angebunden werden — **kein** großes UI-Rewrite.
|
||||
|
||||
4. **Migrations-Sicherheit:** Dokumentiere in **einem Absatz** im `ANALYSIS`-Dokument oder hier, welche **Unique-Constraints** (`training_unit_sections`: `UNIQUE (training_unit_id, order_index)`) die Parallelität blockieren — **ohne** sie schon zu ändern, außer es ist Teil einer **explizit** freigegebenen ersten Migration.
|
||||
|
||||
5. **Performance nur berührensensible Stellen:** Einzelabruf `GET /api/training-units/{id}` wird mit mehr JOINs kommen. Falls du **jetzt** N+1 oder redundante Arbeit in `_fetch_sections` siehst und das **risikoarm** verbesserbar ist, nur mit **Messpunkt/Messvorstellung** (kein unnötiger Micro-Optimismus).
|
||||
|
||||
## Leitplanken
|
||||
|
||||
- **Stabilität vor Geschwindigkeit:** Keine Änderung, die bestehende Einheiten, Rahmen-Blueprints oder Run-Modus bricht.
|
||||
- **Keine pauschalen Refactors:** Nur Änderungen mit **klarem** Träger für das Parallel-Feature oder mit **Test-Regression-Schutz**.
|
||||
- **Regeln:** `.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht wo relevant.
|
||||
|
||||
## Erwartete Ausgabe
|
||||
|
||||
1. Kurze **Liste erledigter Vorarbeiten** (Dateien, was warum).
|
||||
2. **Empfohlene Reihenfolge** für die **nächste** Session, die Phasen/Streams **implementiert** (verweis auf `PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md` Pakete 0–2).
|
||||
3. Falls nichts Sinnvolles ohne Feature-Branch riskiert werden kann: **explizit** „keine Code-Änderung“, nur Risiko-Notiz.
|
||||
|
||||
## Optionaler Startbefehl
|
||||
|
||||
```
|
||||
Lies zuerst:
|
||||
.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md
|
||||
dann backend/routers/training_planning.py (Abschnitte um _fetch_sections, _replace_unit_sections).
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
# Umsetzungsplan: Trainingsmodule & Kombinationsübungen
|
||||
|
||||
**Bezug:** `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (Kopf „V3“, inkl. **§ 10.2.1**, **§ 10.4 Coaching-Stufen**, **Anhang A** Implementierungsabgleich — Drift-Schutz)
|
||||
**Technische Entwurfsspezifikation:** `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`
|
||||
**Stand dieses Dokuments:** 2026-05-12 (Abgleich mit Code App **0.8.110**, siehe `backend/version.py`)
|
||||
|
||||
## Ziele
|
||||
|
||||
Umsetzung der MVP-Punkte aus der Fachspezifikation ohne die bestehende Planung zu destabilisieren: schrittweise Migrationen, bestehende Sektions-/Item-Struktur (`training_unit_sections`, `training_unit_section_items`) beibehalten, Kopiersemantik bei Übernahmen.
|
||||
|
||||
## Phasenüberblick
|
||||
|
||||
| Phase | Inhalt | Status |
|
||||
|-------|--------|--------|
|
||||
| **1** | **Trainingsmodule (Bibliothek):** Tabellen `training_modules`, `training_module_items`; REST CRUD mit Governance wie andere Bibliotheken; Übernahme in eine bestehende Einheit per `POST /api/training-units/{id}/apply-training-module` (Anfügen ans Ende eines Abschnitts via `section_order_index`); optionale Lineage-Spalte `source_training_module_id` auf Planungsitems; UI: Liste/Editor unter `/planning/training-modules`, Link von der Planung, Modal „Modul übernehmen“ | **umgesetzt (MVP Schritt 1)** |
|
||||
| **2** | Kombinationsübungen: `exercise_kind`/`combination_*`, Slots, Pools, `method_archetype`, `method_profile` (JSON) | **teilweise** — wie links; zusätzlich **057** `planning_method_profile`; Planungs-Merge Client (`effectiveComboMethodProfile`); Archetypen weiterhin **nur Code-Konstanten** (kein Admin) | **Offen:** Archetyp-Admin-UI; Profil↔Archetyp-Validierung Backend; „alle Slots vorbelegen“ / Presets (siehe Fachspez **§ 10.6**); Haupt-/Nebenmethoden an Kombi wo Spec es verlangt |
|
||||
| **3** | Planungsblöcke: Gruppierung, Auflösen, „als Modul speichern“, erweiterter Übernahmemodus (Zwischenposition) | geplant |
|
||||
| **4** | Coaching: Archetyp-Support | **teilweise:** **Stufe A** — Merge Katalog+Planung; `CombinationPlanBracket` in Peek/Run; globale Profilzahlen mit Labels (`describeGlobalComboProfile`); Stations-/Timing-Zusammenfassung inkl. Wdh.-Hinweise. **Stufe B/C** — **offen** (§ 10.6, Anhang A) |
|
||||
| **5** | Rahmenprogramm: Modulübernahme UX in Slot-Blueprint-Editor konsolidieren | geplant |
|
||||
|
||||
## Coaching — verbindliche Arbeitspakete (gegen Spec-Drift)
|
||||
|
||||
| Paket | Spec-Referenz | Kurzinhalt |
|
||||
|-------|----------------|-----------|
|
||||
| **4a (Ist/Ziel)** | § 10.2.1 | Archetyp-Schlüssel bleiben identisch zu `backend/routers/exercises.py` (`COMBINATION_ARCHETYPE_IDS`) und `frontend/src/constants/combinationArchetypes.js`. |
|
||||
| **4b** | § 10.4 Stufe A | **Erreicht (0.8.110):** Slots + Kandidaten; Archetyp-Hilfstext; wirksames Profil lesend mit **fachlichen Labels**; Klammerdarstellung konsistent (`CombinationPlanBracket`, `comboPlanningMethodProfile.js`). |
|
||||
| **4c** | § 10.4 Stufe B | Entscheidung: virtuelle Substeps vs. persistierte Items; Konsistenz `sectionsToPutPayload`/Ist-Zeit. |
|
||||
| **4d** | § 10.4 Stufe C | Archetyp-spezifische Timer/Wechsel/Abhaken an `method_profile` — nach 4c. |
|
||||
| **4e** | § 10.6 | **Archetyp-Verwaltung:** DB/UI oder Konfiguration statt nur Release — Labels, Defaults, ggf. Vereins-/Rollen-Sichtbarkeit. |
|
||||
| **4f** | § 10.6 · `COMBINATION_TIMING_PROFILE_PLAN.md` | **Massen-Vorbelegung:** ein Klick alle Slot-Zeiten/Anzahlen aus Archetyp/Global; Modal „Archetyp-Vorlage anwenden?“ (Phase 2 des Timing-Plans). |
|
||||
| **4g** | § 10.6 | **Backend-Validierung:** Pflichtfelder/Wertebereiche je `method_archetype`; optional serverseitiger Merge mit Katalog (aktuell nur Client). |
|
||||
|
||||
## Phase 1 (technische Notizen)
|
||||
|
||||
- **Governance:** `visibility`/`club_id`/`created_by` analog `training_plan_templates`; Listenfilter `library_content_visibility_sql`.
|
||||
- **Übernahme:** Keine Live-Verknüpfung; Items werden kopiert; `source_training_module_id` dokumentiert Herkunft.
|
||||
- **Schnittstelle Übernahme:** `section_order_index` entspricht der Reihenfolge der Abschnitte in der gespeicherten Einheit (0-basiert), konsistent zur Planungs-API.
|
||||
|
||||
## Pflege nach Merge
|
||||
|
||||
- `DATABASE_SCHEMA.md` bei größeren Schema-Erweiterungen ergänzen.
|
||||
- `ACCESS_LAYER_ENDPOINT_AUDIT.md` bei neuen mandantenbezogenen Endpunkten fortpflegen.
|
||||
- **Nach jeder Kombi-/Coach-Änderung:** `functional/… Spezifikation V2.md` **Anhang A** und diese Tabelle Phasen 2/4 abstimmen.
|
||||
@@ -10,7 +10,7 @@ on:
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
# Wie Mitai-Jinkendo: pytest im laufenden backend-Container (Python aus Image, gleiche DB wie Deploy).
|
||||
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
||||
pytest-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
cd /app &&
|
||||
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
|
||||
python scripts/security_release_checks.py &&
|
||||
ACCESS_LAYER_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
ACCESS_LAYER_INTEGRATION=1 TRAINING_PLANNING_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
"
|
||||
|
||||
lint-backend:
|
||||
@@ -88,6 +88,90 @@ jobs:
|
||||
npm run build
|
||||
echo "✓ Frontend build OK"
|
||||
|
||||
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
||||
k6-health-baseline:
|
||||
name: k6 /health Baseline
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||
id: e2e
|
||||
run: |
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Prod-Basis."
|
||||
else
|
||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Dev (${DEV_BASE})."
|
||||
fi
|
||||
|
||||
- name: Dev /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Prod /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "Timeout: Prod /health nicht erreichbar"
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Install k6
|
||||
run: |
|
||||
set -e
|
||||
K6_VER="v0.55.0"
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64) K6_ARCH=amd64 ;;
|
||||
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
|
||||
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||
tar -xzf /tmp/k6.tgz -C /tmp
|
||||
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||
k6 version
|
||||
|
||||
- name: k6 Health-Baseline (parallele /health)
|
||||
env:
|
||||
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
||||
run: |
|
||||
set -e
|
||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||
k6 run scripts/load/k6-health-baseline.js
|
||||
echo "✓ k6 Health-Baseline passed"
|
||||
|
||||
playwright-tests:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
||||
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
|
||||
> | Fachlicher Nutzerüberblick (Design/Product) | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
||||
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
@@ -83,7 +86,7 @@ frontend/src/
|
||||
|
||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||
|
||||
Kurz (Stand 2026-05-08): App **0.8.64**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll), Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (§11 umgesetzt).
|
||||
Kurz (Stand 2026-05-12): App **0.8.96**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
|
||||
|
||||
### Log (Auszug)
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Hilfen für direkte Python-Aufrufe von FastAPI-Route-Handlern (ohne Request-Kontext)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def unwrap_query_default(value: Any) -> Any:
|
||||
"""
|
||||
Parameter mit Annotation ``= Query(default=…)`` sind im Funktionskörper ``fastapi.params.Query``-Instanzen,
|
||||
solange FastAPI sie nicht durch echte Werte ersetzt hat (interne Aufrufe, Aggregat-Endpunkte).
|
||||
"""
|
||||
try:
|
||||
from fastapi.params import Query
|
||||
except ImportError:
|
||||
return value
|
||||
return value.default if isinstance(value, Query) else value
|
||||
+9
-3
@@ -82,8 +82,8 @@ app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
||||
allow_headers=["Content-Type", "X-Auth-Token", "X-Active-Club-Id"],
|
||||
)
|
||||
|
||||
|
||||
@@ -193,7 +193,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -205,14 +205,20 @@ app.include_router(club_join_requests.router)
|
||||
app.include_router(admin_users.router)
|
||||
app.include_router(platform_media_storage.router)
|
||||
app.include_router(media_assets.router)
|
||||
app.include_router(media_assets.admin_rights_router)
|
||||
app.include_router(media_assets.admin_legal_hold_router)
|
||||
app.include_router(skills.router)
|
||||
app.include_router(training_planning.router)
|
||||
app.include_router(dashboard.router)
|
||||
app.include_router(training_modules.router)
|
||||
app.include_router(training_framework_programs.router)
|
||||
app.include_router(catalogs.router)
|
||||
app.include_router(maturity_models.router)
|
||||
app.include_router(matrix_stack_bundle.router)
|
||||
app.include_router(import_wiki.router)
|
||||
app.include_router(import_wiki_admin.router)
|
||||
app.include_router(legal_documents.router)
|
||||
app.include_router(content_reports.router)
|
||||
|
||||
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""P-11: Legal-Hold-Services fuer Medien-Assets.
|
||||
|
||||
Sofortsperrung bei Rechtsverletzungen (Compliance-Paket P-11).
|
||||
|
||||
Klare Trennung:
|
||||
- P-06: Rechteerklaerungs-/Deklarationsstatus (rights_status='declared'/'legacy_unreviewed')
|
||||
- P-11: Legal-Hold-Sperre (legal_hold_active + Metadaten)
|
||||
- P-03: Normaler Papierkorb-Lifecycle (lifecycle_state)
|
||||
- P-13: Meldeverfahren (spaeter; nutzt denselben set_legal_hold-Service)
|
||||
|
||||
Berechtigungen:
|
||||
- Setzen und Aufheben: ausschliesslich Superadmin.
|
||||
- Lesezugriff auf Legal-Hold-Status: Superadmin und Plattform-Admin.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from club_tenancy import is_superadmin
|
||||
from media_rights import write_audit_log_entry
|
||||
|
||||
LEGAL_HOLD_REASON_CODES = {
|
||||
"rights_dispute",
|
||||
"consent_withdrawn",
|
||||
"privacy_complaint",
|
||||
"copyright_complaint",
|
||||
"youth_protection",
|
||||
"illegal_content",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
def assert_superadmin_for_legal_hold(role: Optional[str]) -> None:
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Legal-Hold-Aktionen sind nur fuer Superadmins verfuegbar.",
|
||||
)
|
||||
|
||||
|
||||
def is_media_available_for_normal_use(asset: dict) -> bool:
|
||||
"""True wenn das Medium fuer normale Nutzerpfade verfuegbar ist.
|
||||
|
||||
Ein Medium ist NICHT verfuegbar wenn legal_hold_active = True,
|
||||
unabhaengig vom lifecycle_state.
|
||||
"""
|
||||
return not bool(asset.get("legal_hold_active"))
|
||||
|
||||
|
||||
def assert_not_under_legal_hold(asset: dict) -> None:
|
||||
"""Wirft HTTPException 403 wenn das Medium unter Legal Hold steht."""
|
||||
if bool(asset.get("legal_hold_active")):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail={
|
||||
"code": "LEGAL_HOLD_ACTIVE",
|
||||
"message": (
|
||||
"Dieses Medium ist durch einen Administrator sofort gesperrt und "
|
||||
"kann nicht verwendet werden."
|
||||
),
|
||||
"asset_id": asset.get("id"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def set_legal_hold(
|
||||
cur: Any,
|
||||
conn: Any,
|
||||
asset_id: int,
|
||||
acting_profile_id: int,
|
||||
reason_code: str,
|
||||
reason_note: Optional[str],
|
||||
) -> dict:
|
||||
"""Setzt Legal Hold auf ein Medium. Nur Superadmin.
|
||||
|
||||
Wirkung:
|
||||
- legal_hold_active = TRUE
|
||||
- legal_hold_reason_code, legal_hold_reason_note, legal_hold_set_by_profile_id, legal_hold_set_at
|
||||
- rights_status = 'blocked' (Spiegel fuer schnelle Checks)
|
||||
- Audit-Log-Eintrag 'legal_hold_set'
|
||||
|
||||
Gibt das aktualisierte Asset-Dict zurueck.
|
||||
"""
|
||||
if reason_code not in LEGAL_HOLD_REASON_CODES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Ungueltiger reason_code. Erlaubt: {sorted(LEGAL_HOLD_REASON_CODES)}",
|
||||
)
|
||||
if not reason_note or not reason_note.strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="reason_note (Begruendung) ist Pflicht beim Setzen eines Legal Holds.",
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id, legal_hold_active, rights_status, lifecycle_state, visibility
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
from db import r2d
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(row)
|
||||
|
||||
if bool(asset.get("legal_hold_active")):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Dieses Medium befindet sich bereits unter Legal Hold.",
|
||||
)
|
||||
|
||||
old_rights_status = asset.get("rights_status") or "legacy_unreviewed"
|
||||
|
||||
cur.execute(
|
||||
"""UPDATE media_assets
|
||||
SET legal_hold_active = TRUE,
|
||||
legal_hold_reason_code = %s,
|
||||
legal_hold_reason_note = %s,
|
||||
legal_hold_set_by_profile_id = %s,
|
||||
legal_hold_set_at = NOW(),
|
||||
legal_hold_released_by_profile_id = NULL,
|
||||
legal_hold_released_at = NULL,
|
||||
legal_hold_release_note = NULL,
|
||||
rights_status = 'blocked',
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, legal_hold_active, legal_hold_reason_code, legal_hold_reason_note,
|
||||
legal_hold_set_by_profile_id, legal_hold_set_at, rights_status,
|
||||
lifecycle_state, visibility""",
|
||||
(reason_code, reason_note.strip()[:2000], acting_profile_id, asset_id),
|
||||
)
|
||||
updated_row = cur.fetchone()
|
||||
updated = r2d(updated_row)
|
||||
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
asset_id=asset_id,
|
||||
acting_profile_id=acting_profile_id,
|
||||
event_type="legal_hold_set",
|
||||
old_values={"rights_status": old_rights_status, "legal_hold_active": False},
|
||||
new_values={
|
||||
"rights_status": "blocked",
|
||||
"legal_hold_active": True,
|
||||
"reason_code": reason_code,
|
||||
"reason_note": reason_note.strip()[:2000] if reason_note else None,
|
||||
},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return updated
|
||||
|
||||
|
||||
def release_legal_hold(
|
||||
cur: Any,
|
||||
conn: Any,
|
||||
asset_id: int,
|
||||
acting_profile_id: int,
|
||||
release_note: Optional[str],
|
||||
) -> dict:
|
||||
"""Hebt Legal Hold auf. Nur Superadmin.
|
||||
|
||||
Wirkung:
|
||||
- legal_hold_active = FALSE
|
||||
- legal_hold_released_by_profile_id, legal_hold_released_at, legal_hold_release_note
|
||||
- rights_status: zurueck auf 'declared' wenn vorher declared war, sonst 'legacy_unreviewed'
|
||||
(Entscheidungslogik: war vor dem Hold ein Deklarations-Eintrag vorhanden?)
|
||||
- Audit-Log-Eintrag 'legal_hold_released'
|
||||
|
||||
Gibt das aktualisierte Asset-Dict zurueck.
|
||||
"""
|
||||
if not release_note or not release_note.strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="release_note (Freigabe-Begruendung) ist Pflicht.",
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id, legal_hold_active, rights_status, lifecycle_state, visibility,
|
||||
legal_hold_reason_code, legal_hold_reason_note
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
from db import r2d
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(row)
|
||||
|
||||
if not bool(asset.get("legal_hold_active")):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Dieses Medium befindet sich nicht unter Legal Hold.",
|
||||
)
|
||||
|
||||
# Bestimme den rights_status nach Freigabe:
|
||||
# Gibt es eine gueltige Deklaration? → 'declared', sonst 'legacy_unreviewed'
|
||||
cur.execute(
|
||||
"""SELECT COUNT(*) AS cnt FROM media_asset_rights_declarations
|
||||
WHERE media_asset_id = %s
|
||||
AND action_type NOT IN ('correction')
|
||||
AND rights_holder_confirmed = TRUE""",
|
||||
(asset_id,),
|
||||
)
|
||||
decl_row = cur.fetchone()
|
||||
decl_count = int(decl_row[0] if not hasattr(decl_row, "keys") else decl_row["cnt"])
|
||||
restored_rights_status = "declared" if decl_count > 0 else "legacy_unreviewed"
|
||||
|
||||
cur.execute(
|
||||
"""UPDATE media_assets
|
||||
SET legal_hold_active = FALSE,
|
||||
legal_hold_released_by_profile_id = %s,
|
||||
legal_hold_released_at = NOW(),
|
||||
legal_hold_release_note = %s,
|
||||
rights_status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, legal_hold_active, rights_status, lifecycle_state, visibility,
|
||||
legal_hold_reason_code, legal_hold_reason_note,
|
||||
legal_hold_set_by_profile_id, legal_hold_set_at,
|
||||
legal_hold_released_by_profile_id, legal_hold_released_at,
|
||||
legal_hold_release_note""",
|
||||
(acting_profile_id, release_note.strip()[:2000], restored_rights_status, asset_id),
|
||||
)
|
||||
updated_row = cur.fetchone()
|
||||
updated = r2d(updated_row)
|
||||
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
asset_id=asset_id,
|
||||
acting_profile_id=acting_profile_id,
|
||||
event_type="legal_hold_released",
|
||||
old_values={
|
||||
"rights_status": "blocked",
|
||||
"legal_hold_active": True,
|
||||
"reason_code": asset.get("legal_hold_reason_code"),
|
||||
},
|
||||
new_values={
|
||||
"rights_status": restored_rights_status,
|
||||
"legal_hold_active": False,
|
||||
"release_note": release_note.strip()[:2000] if release_note else None,
|
||||
},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
return updated
|
||||
@@ -21,7 +21,8 @@ LC_TRASH_SOFT = "trash_soft"
|
||||
LC_TRASH_HIDDEN = "trash_hidden"
|
||||
|
||||
SOFT_TO_HIDDEN_DAYS = max(1, int(os.getenv("MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS", "30")))
|
||||
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "90")))
|
||||
# P-03b: Default gemaess fachlichem Loeschkonzept (Audit 2026-05-09): 30+30 Tage.
|
||||
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "30")))
|
||||
|
||||
|
||||
def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
@@ -278,6 +279,10 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
|
||||
"""
|
||||
Automatik: trash_soft älter als SOFT_TO_HIDDEN_DAYS → trash_hidden;
|
||||
trash_hidden mit purge_after_at in der Vergangenheit → purge.
|
||||
|
||||
P-11: Medien unter aktivem Legal Hold werden NICHT gerpurged (legal_hold_active = TRUE).
|
||||
Die Retention verschiebt sie auch nicht automatisch von trash_soft nach trash_hidden —
|
||||
Legal-Hold-Status hat Vorrang vor dem Papierkorb-Lifecycle.
|
||||
"""
|
||||
cutoff_soft = datetime.now(timezone.utc) - timedelta(days=SOFT_TO_HIDDEN_DAYS)
|
||||
cur.execute(
|
||||
@@ -285,6 +290,7 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
|
||||
SET lifecycle_state = %s, trash_hidden_at = NOW(), updated_at = NOW(),
|
||||
purge_after_at = NOW() + (%s * INTERVAL '1 day')
|
||||
WHERE lifecycle_state = %s AND trash_soft_at IS NOT NULL AND trash_soft_at <= %s
|
||||
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)
|
||||
RETURNING id""",
|
||||
(LC_TRASH_HIDDEN, HIDDEN_TO_PURGE_DAYS, LC_TRASH_SOFT, cutoff_soft),
|
||||
)
|
||||
@@ -293,7 +299,8 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id FROM media_assets
|
||||
WHERE lifecycle_state = %s AND purge_after_at IS NOT NULL AND purge_after_at <= NOW()""",
|
||||
WHERE lifecycle_state = %s AND purge_after_at IS NOT NULL AND purge_after_at <= NOW()
|
||||
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)""",
|
||||
(LC_TRASH_HIDDEN,),
|
||||
)
|
||||
purge_ids = [r2d(r)["id"] for r in cur.fetchall()]
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
"""P-06: Zentrale Rechte-Policy fuer Medien-Uploads und Promotionen.
|
||||
|
||||
Konservative Erstannahmen (p06-v1-conservative):
|
||||
- Alle Uploads (inkl. private) erfordern vollstaendige Erklaerung
|
||||
- Personenfragen bei allen Sichtbarkeiten Pflicht zu beantworten
|
||||
- Promotion zu hoeherem Niveau erfordert neue Erklaerung
|
||||
- Altmedien ('legacy_unreviewed') duerfen nicht promoted werden
|
||||
|
||||
VORLAEUTIG: Juristische Validierung der Felder und Texte steht aus.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json as _json
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
DECLARATION_VERSION = "p06-v1-conservative"
|
||||
|
||||
# Sichtbarkeits-Hierarchie: private(1) < club(2) < official(3)
|
||||
VISIBILITY_LEVELS: dict[str, int] = {
|
||||
"private": 1,
|
||||
"club": 2,
|
||||
"official": 3,
|
||||
}
|
||||
|
||||
|
||||
def visibility_level(vis: str) -> int:
|
||||
return VISIBILITY_LEVELS.get((vis or "").strip().lower(), 0)
|
||||
|
||||
|
||||
def rights_covers_target(declared_for: Optional[str], target_vis: str) -> bool:
|
||||
"""True wenn die vorhandene Erklaerung die Ziel-Sichtbarkeit abdeckt."""
|
||||
if not declared_for:
|
||||
return False
|
||||
return visibility_level(declared_for) >= visibility_level(target_vis)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Validierung einer eingehenden Erklaerung
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def validate_rights_declaration(decl: dict[str, Any], target_visibility: str) -> None:
|
||||
"""Pruefen ob alle Pflichtfelder der konservativen Erstannahme vorliegen.
|
||||
|
||||
Wirft HTTPException 400 mit maschinenlesbarem code bei Verstoss.
|
||||
Gilt fuer alle Sichtbarkeiten (private/club/official) identisch.
|
||||
"""
|
||||
# 1. rights_holder_confirmed ist immer Pflicht
|
||||
if not decl.get("rights_holder_confirmed"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": (
|
||||
"Bitte bestaetigen, dass du die erforderlichen Rechte an diesem Medium besitzt."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
# 2. contains_identifiable_persons muss explizit beantwortet sein
|
||||
if decl.get("contains_identifiable_persons") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": "Bitte angeben, ob erkennbare Personen abgebildet sind.",
|
||||
},
|
||||
)
|
||||
|
||||
# 3. Wenn Personen vorhanden: Einwilligung Pflicht
|
||||
if decl.get("contains_identifiable_persons") is True:
|
||||
if not decl.get("person_consent_confirmed"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "PERSON_CONSENT_REQUIRED",
|
||||
"message": (
|
||||
"Bitte bestaetigen, dass die Einwilligungen aller erkennbaren Personen vorliegen."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
# 4. contains_minors muss explizit beantwortet sein
|
||||
if decl.get("contains_minors") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": "Bitte angeben, ob Minderjaehrige abgebildet sind.",
|
||||
},
|
||||
)
|
||||
|
||||
# 5. Wenn Minderjaehrige: Elterneinwilligung Pflicht
|
||||
if decl.get("contains_minors") is True:
|
||||
if not decl.get("parental_consent_confirmed"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "PARENTAL_CONSENT_REQUIRED",
|
||||
"message": (
|
||||
"Bitte bestaetigen, dass die Einwilligungen der Sorgeberechtigten vorliegen."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
# 6. contains_music muss explizit beantwortet sein
|
||||
if decl.get("contains_music") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": "Bitte angeben, ob das Medium Musik enthaelt.",
|
||||
},
|
||||
)
|
||||
|
||||
# 7. Wenn Musik: Musikrechte Pflicht
|
||||
if decl.get("contains_music") is True:
|
||||
if not decl.get("music_rights_confirmed"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "MUSIC_RIGHTS_REQUIRED",
|
||||
"message": (
|
||||
"Bitte bestaetigen, dass die erforderlichen Musikrechte vorliegen."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
# 8. contains_third_party_content muss explizit beantwortet sein
|
||||
if decl.get("contains_third_party_content") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": "Bitte angeben, ob fremde geschuetzte Inhalte (Logos, Grafiken etc.) enthalten sind.",
|
||||
},
|
||||
)
|
||||
|
||||
# 9. Wenn Fremdmaterial: Rechte Pflicht
|
||||
if decl.get("contains_third_party_content") is True:
|
||||
if not decl.get("third_party_rights_confirmed"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "THIRD_PARTY_RIGHTS_REQUIRED",
|
||||
"message": (
|
||||
"Bitte bestaetigen, dass die Rechte an allen enthaltenen Fremdmaterialien vorliegen."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Pruefen ob vorhandene Erklaerung Zielsichtbarkeit abdeckt
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def check_rights_coverage(cur: Any, asset_id: int, target_visibility: str) -> str:
|
||||
"""Status der Rechteabdeckung fuer ein Asset und eine Zielsichtbarkeit.
|
||||
|
||||
Returns:
|
||||
'ok' - vorhandene Erklaerung reicht aus
|
||||
'legacy' - Altmedium ohne Erklaerung (legacy_unreviewed)
|
||||
'blocked' - durch Admin gesperrt
|
||||
'no_declaration' - neues Medium ohne Erklaerung (sollte nicht vorkommen)
|
||||
|
||||
Hinweis: Eine P-06-Erklaerung beschreibt den Inhalt (Rechteinhaber, Personen, Musik etc.)
|
||||
und ist sichtbarkeitsunabhaengig. rights_status='declared' gilt daher fuer alle
|
||||
Sichtbarkeits-Stufen ohne Levelvergleich.
|
||||
"""
|
||||
cur.execute(
|
||||
"SELECT rights_status FROM media_assets WHERE id = %s",
|
||||
(asset_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return "no_declaration"
|
||||
|
||||
rs = (row[0] if not hasattr(row, "keys") else row["rights_status"] or "").strip().lower()
|
||||
|
||||
if rs == "blocked":
|
||||
return "blocked"
|
||||
if rs == "legacy_unreviewed":
|
||||
return "legacy"
|
||||
if rs == "declared":
|
||||
return "ok"
|
||||
return "no_declaration"
|
||||
|
||||
|
||||
def assert_rights_for_promotion(cur: Any, asset_id: int, target_visibility: str) -> None:
|
||||
"""Wirft HTTPException wenn das Asset keine gueltige Erklaerung fuer target_visibility hat."""
|
||||
status = check_rights_coverage(cur, asset_id, target_visibility)
|
||||
if status == "ok":
|
||||
return
|
||||
if status == "legacy":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "LEGACY_REDECLARATION_REQUIRED",
|
||||
"message": (
|
||||
"Dieses Medium wurde vor Einfuehrung der Einwilligungspflicht hochgeladen. "
|
||||
"Bitte eine Rechterklaerung nachreichen, bevor die Sichtbarkeit erhoeht wird."
|
||||
),
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
if status == "blocked":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail={
|
||||
"code": "RIGHTS_BLOCKED",
|
||||
"message": "Dieses Medium ist durch einen Administrator gesperrt.",
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
# no_declaration (neues Medium ohne Erklaerung)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||
"message": "Fuer dieses Medium liegt keine Rechterklaerung vor.",
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def assert_rights_for_exercise_link(cur: Any, asset_id: int, exercise_visibility: str) -> None:
|
||||
"""Pruefen ob das Asset in eine Uebung mit dieser Sichtbarkeit eingebunden werden darf."""
|
||||
status = check_rights_coverage(cur, asset_id, exercise_visibility)
|
||||
if status == "ok":
|
||||
return
|
||||
if status == "legacy" and exercise_visibility == "private":
|
||||
# Altmedien duerfen in private Uebungen eingebunden bleiben (kein Upgrade-Risiko)
|
||||
return
|
||||
if status == "legacy":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "LEGACY_REDECLARATION_REQUIRED",
|
||||
"message": (
|
||||
"Das gewahlte Archiv-Medium hat noch keine Rechterklaerung nach neuem Standard. "
|
||||
"Bitte zuerst eine Erklaerung fuer dieses Medium abgeben."
|
||||
),
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
if status == "insufficient":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_SCOPE_INSUFFICIENT",
|
||||
"message": (
|
||||
f"Das Archiv-Medium hat keine Erklaerung fuer Sichtbarkeit '{exercise_visibility}'. "
|
||||
"Bitte zuerst eine neue Erklaerung fuer dieses Medium abgeben."
|
||||
),
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
if status == "blocked":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail={
|
||||
"code": "RIGHTS_BLOCKED",
|
||||
"message": "Dieses Medium ist gesperrt und kann nicht verwendet werden.",
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Declaration-Log schreiben + Schnellfelder aktualisieren
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _clean_context(val: Any) -> Optional[str]:
|
||||
"""Leere Strings → None, sonst auf 2000 Zeichen kuerzen."""
|
||||
s = (val or "").strip()
|
||||
return s[:2000] if s else None
|
||||
|
||||
|
||||
def write_rights_declaration(
|
||||
cur: Any,
|
||||
asset_id: int,
|
||||
profile_id: int,
|
||||
action_type: str,
|
||||
target_visibility: str,
|
||||
decl: dict[str, Any],
|
||||
) -> int:
|
||||
"""Schreibt einen neuen Eintrag in media_asset_rights_declarations (append-only).
|
||||
|
||||
Returns: id des neuen Eintrags
|
||||
"""
|
||||
cur.execute(
|
||||
"""INSERT INTO media_asset_rights_declarations (
|
||||
media_asset_id, declared_by_profile_id, action_type, target_visibility,
|
||||
declaration_version,
|
||||
rights_holder_confirmed,
|
||||
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
|
||||
contains_minors, parental_consent_confirmed, parental_consent_context,
|
||||
contains_music, music_rights_confirmed, music_rights_context,
|
||||
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id""",
|
||||
(
|
||||
asset_id,
|
||||
profile_id,
|
||||
action_type,
|
||||
target_visibility,
|
||||
DECLARATION_VERSION,
|
||||
bool(decl.get("rights_holder_confirmed")),
|
||||
decl.get("contains_identifiable_persons"),
|
||||
decl.get("person_consent_confirmed"),
|
||||
_clean_context(decl.get("person_consent_context")),
|
||||
decl.get("contains_minors"),
|
||||
decl.get("parental_consent_confirmed"),
|
||||
_clean_context(decl.get("parental_consent_context")),
|
||||
decl.get("contains_music"),
|
||||
decl.get("music_rights_confirmed"),
|
||||
_clean_context(decl.get("music_rights_context")),
|
||||
decl.get("contains_third_party_content"),
|
||||
decl.get("third_party_rights_confirmed"),
|
||||
_clean_context(decl.get("third_party_rights_context")),
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if hasattr(row, "keys"):
|
||||
return int(row["id"])
|
||||
return int(row[0])
|
||||
|
||||
|
||||
def write_audit_log_entry(
|
||||
cur: Any,
|
||||
asset_id: int,
|
||||
acting_profile_id: Optional[int],
|
||||
event_type: str,
|
||||
old_values: dict,
|
||||
new_values: dict,
|
||||
) -> None:
|
||||
"""Schreibt einen Eintrag in media_asset_audit_log (append-only)."""
|
||||
cur.execute(
|
||||
"""INSERT INTO media_asset_audit_log
|
||||
(media_asset_id, acting_profile_id, event_type, old_values, new_values)
|
||||
VALUES (%s, %s, %s, %s, %s)""",
|
||||
(
|
||||
asset_id,
|
||||
acting_profile_id,
|
||||
event_type,
|
||||
_json.dumps(old_values, default=str),
|
||||
_json.dumps(new_values, default=str),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def write_rights_correction_declaration(
|
||||
cur: Any,
|
||||
asset_id: int,
|
||||
profile_id: int,
|
||||
target_visibility: str,
|
||||
decl: dict[str, Any],
|
||||
correction_note: Optional[str],
|
||||
) -> int:
|
||||
"""Schreibt eine Korrektur-Deklaration (action_type='correction', append-only)."""
|
||||
cur.execute(
|
||||
"""INSERT INTO media_asset_rights_declarations (
|
||||
media_asset_id, declared_by_profile_id, action_type, target_visibility,
|
||||
declaration_version,
|
||||
rights_holder_confirmed,
|
||||
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
|
||||
contains_minors, parental_consent_confirmed, parental_consent_context,
|
||||
contains_music, music_rights_confirmed, music_rights_context,
|
||||
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context,
|
||||
correction_note
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id""",
|
||||
(
|
||||
asset_id,
|
||||
profile_id,
|
||||
"correction",
|
||||
target_visibility,
|
||||
DECLARATION_VERSION,
|
||||
bool(decl.get("rights_holder_confirmed")),
|
||||
decl.get("contains_identifiable_persons"),
|
||||
decl.get("person_consent_confirmed"),
|
||||
_clean_context(decl.get("person_consent_context")),
|
||||
decl.get("contains_minors"),
|
||||
decl.get("parental_consent_confirmed"),
|
||||
_clean_context(decl.get("parental_consent_context")),
|
||||
decl.get("contains_music"),
|
||||
decl.get("music_rights_confirmed"),
|
||||
_clean_context(decl.get("music_rights_context")),
|
||||
decl.get("contains_third_party_content"),
|
||||
decl.get("third_party_rights_confirmed"),
|
||||
_clean_context(decl.get("third_party_rights_context")),
|
||||
_clean_context(correction_note),
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if hasattr(row, "keys"):
|
||||
return int(row["id"])
|
||||
return int(row[0])
|
||||
|
||||
|
||||
def update_rights_quick_fields(cur: Any, asset_id: int, target_visibility: str) -> None:
|
||||
"""Setzt die Schnellfelder in media_assets nach erfolgreicher Deklaration."""
|
||||
cur.execute(
|
||||
"""UPDATE media_assets
|
||||
SET rights_status = 'declared',
|
||||
rights_declared_for_visibility = %s,
|
||||
rights_declared_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = %s""",
|
||||
(target_visibility, asset_id),
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
-- Migration 047: Admin-konfigurierbare Rechtstexte
|
||||
-- Tabellen: legal_documents (versioniert), legal_document_audit (Änderungslog)
|
||||
-- document_type: impressum | privacy_policy | terms_of_use | media_policy
|
||||
-- status: draft | published | archived
|
||||
-- Partial unique index: nur genau ein published-Dokument pro document_type erlaubt.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS legal_documents (
|
||||
id SERIAL PRIMARY KEY,
|
||||
document_type VARCHAR(50) NOT NULL
|
||||
CHECK (document_type IN ('impressum', 'privacy_policy', 'terms_of_use', 'media_policy')),
|
||||
version INT NOT NULL DEFAULT 1,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
content_sections JSONB NOT NULL DEFAULT '[]',
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'draft'
|
||||
CHECK (status IN ('draft', 'published', 'archived')),
|
||||
change_note TEXT,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
created_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
published_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
published_at TIMESTAMP
|
||||
);
|
||||
|
||||
-- Sicherstellt: pro document_type maximal ein published-Datensatz
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS legal_documents_unique_published
|
||||
ON legal_documents (document_type)
|
||||
WHERE status = 'published';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS legal_document_audit (
|
||||
id SERIAL PRIMARY KEY,
|
||||
legal_document_id INT NOT NULL REFERENCES legal_documents(id) ON DELETE CASCADE,
|
||||
action VARCHAR(50) NOT NULL,
|
||||
changed_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
change_note TEXT,
|
||||
previous_status VARCHAR(20),
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
@@ -0,0 +1,75 @@
|
||||
-- Migration 048: P-06 Upload-Einwilligungsdialog
|
||||
-- Append-only Deklarations-Log + Schnellfelder in media_assets
|
||||
-- Alle bestehenden Medien erhalten rights_status = 'legacy_unreviewed'
|
||||
|
||||
-- Deklarations-Log (append-only, wird nie geaendert oder geloescht)
|
||||
CREATE TABLE IF NOT EXISTS media_asset_rights_declarations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||
declared_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
declared_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
-- Kontext der Erklaerung
|
||||
action_type VARCHAR(50) NOT NULL
|
||||
CHECK (action_type IN (
|
||||
'upload', -- Erstupload
|
||||
'promote_club', -- Promotion zu club
|
||||
'promote_official', -- Promotion zu official
|
||||
're_declaration', -- Freiwillige Nacherklaerung
|
||||
'legacy_re_declaration' -- Altmedium: erste Erklaerung nachgereicht
|
||||
)),
|
||||
target_visibility VARCHAR(32) NOT NULL
|
||||
CHECK (target_visibility IN ('private', 'club', 'official')),
|
||||
-- Textversion der Erklaerung; 'p06-v1-conservative' = konservative Erstannahmen
|
||||
-- VORLAEUTIG: Texte noch nicht juristisch geprueft
|
||||
declaration_version VARCHAR(40) NOT NULL DEFAULT 'p06-v1-conservative',
|
||||
|
||||
-- Pflichtfeld (alle Sichtbarkeiten, alle Aktionen)
|
||||
rights_holder_confirmed BOOLEAN NOT NULL,
|
||||
|
||||
-- Personen (konservative Annahme: immer abgefragt, auch bei 'private')
|
||||
contains_identifiable_persons BOOLEAN,
|
||||
person_consent_confirmed BOOLEAN, -- Pflicht wenn contains_identifiable_persons = true
|
||||
|
||||
-- Minderjaehrige
|
||||
contains_minors BOOLEAN,
|
||||
parental_consent_confirmed BOOLEAN, -- Pflicht wenn contains_minors = true
|
||||
|
||||
-- Drittmaterial
|
||||
contains_music BOOLEAN,
|
||||
music_rights_confirmed BOOLEAN, -- Pflicht wenn contains_music = true
|
||||
contains_third_party_content BOOLEAN,
|
||||
third_party_rights_confirmed BOOLEAN, -- Pflicht wenn contains_third_party_content = true
|
||||
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mard_asset
|
||||
ON media_asset_rights_declarations (media_asset_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_mard_profile
|
||||
ON media_asset_rights_declarations (declared_by_profile_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_mard_action_type
|
||||
ON media_asset_rights_declarations (action_type);
|
||||
|
||||
-- Schnellfelder in media_assets (kein Ersatz fuer den Log, nur fuer effiziente Abfragen)
|
||||
ALTER TABLE media_assets
|
||||
ADD COLUMN IF NOT EXISTS rights_status VARCHAR(32)
|
||||
NOT NULL DEFAULT 'legacy_unreviewed'
|
||||
CHECK (rights_status IN ('legacy_unreviewed', 'declared', 'blocked')),
|
||||
ADD COLUMN IF NOT EXISTS rights_declared_for_visibility VARCHAR(32)
|
||||
CHECK (rights_declared_for_visibility IN ('private', 'club', 'official')),
|
||||
ADD COLUMN IF NOT EXISTS rights_declared_at TIMESTAMPTZ;
|
||||
|
||||
-- Bestehende Medien: explicit legacy_unreviewed setzen (redundant zum DEFAULT, zur Klarheit)
|
||||
UPDATE media_assets
|
||||
SET rights_status = 'legacy_unreviewed'
|
||||
WHERE rights_status = 'legacy_unreviewed'; -- no-op, setzt Default explizit
|
||||
|
||||
COMMENT ON TABLE media_asset_rights_declarations IS
|
||||
'P-06: Append-only Erklaerungslog fuer Upload-Einwilligungen. '
|
||||
'Eintraege werden nie geaendert. Juristische Validierung der Felder und Texte steht aus.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.rights_status IS
|
||||
'P-06: legacy_unreviewed = Altbestand ohne P-06-Erklaerung; '
|
||||
'declared = gueltige Erklaerung fuer rights_declared_for_visibility; '
|
||||
'blocked = durch Admin gesperrt (P-11-Schnittstelle).';
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Migration 049: P-06 Erweiterung – Einwilligungskontext-Felder und Copyright im Upload-Dialog
|
||||
-- Optionale Freitextfelder fuer den Kontext der Einwilligung (z.B. "Schriftliche Einwilligung
|
||||
-- vom 2026-05-01 liegt vor") sowie copyright_notice direkt beim Upload erfassbar.
|
||||
|
||||
ALTER TABLE media_asset_rights_declarations
|
||||
ADD COLUMN IF NOT EXISTS person_consent_context TEXT,
|
||||
ADD COLUMN IF NOT EXISTS parental_consent_context TEXT,
|
||||
ADD COLUMN IF NOT EXISTS music_rights_context TEXT,
|
||||
ADD COLUMN IF NOT EXISTS third_party_rights_context TEXT;
|
||||
|
||||
COMMENT ON COLUMN media_asset_rights_declarations.person_consent_context IS
|
||||
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der abgebildeten Personen vor?';
|
||||
COMMENT ON COLUMN media_asset_rights_declarations.parental_consent_context IS
|
||||
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der Sorgeberechtigten vor?';
|
||||
COMMENT ON COLUMN media_asset_rights_declarations.music_rights_context IS
|
||||
'Optionaler Freitext: Welche Lizenz / GEMA-Regelung liegt fuer die Musik vor?';
|
||||
COMMENT ON COLUMN media_asset_rights_declarations.third_party_rights_context IS
|
||||
'Optionaler Freitext: Auf welcher Grundlage duerfen die enthaltenen Fremdinhalte verwendet werden?';
|
||||
@@ -0,0 +1,47 @@
|
||||
-- Migration 050: Medien-Volljournal – Audit-Log für alle Änderungen + Korrektur-Deklarationen
|
||||
|
||||
-- Vollständiger Audit-Log: Sichtbarkeitsänderungen, Copyright, Metadaten, Lifecycle
|
||||
CREATE TABLE IF NOT EXISTS media_asset_audit_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||
acting_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
event_type VARCHAR(50) NOT NULL
|
||||
CHECK (event_type IN (
|
||||
'visibility_change',
|
||||
'copyright_change',
|
||||
'metadata_change',
|
||||
'lifecycle_change'
|
||||
)),
|
||||
old_values JSONB,
|
||||
new_values JSONB
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_maal_asset ON media_asset_audit_log (media_asset_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_maal_asset_occurred ON media_asset_audit_log (media_asset_id, occurred_at);
|
||||
|
||||
COMMENT ON TABLE media_asset_audit_log IS
|
||||
'Append-only Protokoll aller Aenderungen an Medien-Assets (Sichtbarkeit, Copyright, Metadaten, Lifecycle). '
|
||||
'Wird nie aktualisiert oder geloescht (ausser ON DELETE CASCADE des Assets).';
|
||||
|
||||
-- Korrektur-Notiz für nachtraegliche Deklarations-Korrekturen
|
||||
ALTER TABLE media_asset_rights_declarations
|
||||
ADD COLUMN IF NOT EXISTS correction_note TEXT;
|
||||
|
||||
COMMENT ON COLUMN media_asset_rights_declarations.correction_note IS
|
||||
'Optionale Begruendung fuer action_type=correction: Warum wurde die Erklaerung korrigiert?';
|
||||
|
||||
-- ''correction'' action_type hinzufuegen (bestehende CHECK-Constraint ersetzen)
|
||||
ALTER TABLE media_asset_rights_declarations
|
||||
DROP CONSTRAINT IF EXISTS media_asset_rights_declarations_action_type_check;
|
||||
|
||||
ALTER TABLE media_asset_rights_declarations
|
||||
ADD CONSTRAINT media_asset_rights_declarations_action_type_check
|
||||
CHECK (action_type IN (
|
||||
'upload',
|
||||
'promote_club',
|
||||
'promote_official',
|
||||
're_declaration',
|
||||
'legacy_re_declaration',
|
||||
'correction'
|
||||
));
|
||||
@@ -0,0 +1,73 @@
|
||||
-- Migration 051: P-11 Legal-Hold Lifecycle-Status
|
||||
-- Sofortsperrung fuer rechtlich problematische Medien (Compliance-Paket P-11)
|
||||
--
|
||||
-- Architekturentscheidung:
|
||||
-- rights_status='blocked' bleibt als Spiegel-Schnellstatus (P-06-Kompatibilitaet).
|
||||
-- Primaere Wahrheit: legal_hold_active + dedizierte Metadaten-Felder in media_assets.
|
||||
-- Dies ermoeglicht klare Trennung: P-06 Deklarationsstatus / P-11 Legal Hold / P-03 Lifecycle.
|
||||
-- P-13 kann spaeter denselben set_legal_hold-Service nutzen.
|
||||
|
||||
ALTER TABLE media_assets
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_active BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_reason_code VARCHAR(50)
|
||||
CHECK (legal_hold_reason_code IN (
|
||||
'rights_dispute',
|
||||
'consent_withdrawn',
|
||||
'privacy_complaint',
|
||||
'copyright_complaint',
|
||||
'youth_protection',
|
||||
'illegal_content',
|
||||
'other'
|
||||
)),
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_reason_note TEXT,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_set_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_set_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_released_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_released_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS legal_hold_release_note TEXT;
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_active IS
|
||||
'P-11: TRUE = Medium unter Legal Hold; sofortige Sperrung fuer alle normalen Nutzerpfade. '
|
||||
'Retention-Job darf dieses Medium nicht purgen. '
|
||||
'rights_status wird bei Aktivierung auf ''blocked'' gespiegelt.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_reason_code IS
|
||||
'P-11: Kategorie des Legal Holds. Pflicht beim Setzen.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_reason_note IS
|
||||
'P-11: Freitext-Begruendung fuer den Legal Hold.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_set_by_profile_id IS
|
||||
'P-11: Profil das den Legal Hold gesetzt hat (Superadmin).';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_set_at IS
|
||||
'P-11: Zeitpunkt der Legal-Hold-Aktivierung.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_released_by_profile_id IS
|
||||
'P-11: Profil das den Legal Hold aufgehoben hat.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_released_at IS
|
||||
'P-11: Zeitpunkt der Legal-Hold-Freigabe.';
|
||||
|
||||
COMMENT ON COLUMN media_assets.legal_hold_release_note IS
|
||||
'P-11: Begruendung fuer die Aufhebung des Legal Holds.';
|
||||
|
||||
-- Index fuer Admin-Liste aktiver Legal Holds
|
||||
CREATE INDEX IF NOT EXISTS idx_media_assets_legal_hold_active
|
||||
ON media_assets (legal_hold_active)
|
||||
WHERE legal_hold_active = TRUE;
|
||||
|
||||
-- Neue event_types fuer media_asset_audit_log
|
||||
ALTER TABLE media_asset_audit_log
|
||||
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
|
||||
|
||||
ALTER TABLE media_asset_audit_log
|
||||
ADD CONSTRAINT media_asset_audit_log_event_type_check
|
||||
CHECK (event_type IN (
|
||||
'visibility_change',
|
||||
'copyright_change',
|
||||
'metadata_change',
|
||||
'lifecycle_change',
|
||||
'legal_hold_set',
|
||||
'legal_hold_released'
|
||||
));
|
||||
@@ -0,0 +1,73 @@
|
||||
-- P-13: Content-Melde-Backend
|
||||
-- Meldungen rechtswidriger Inhalte (DSA-konformes Meldeverfahren, KRIT-03)
|
||||
--
|
||||
-- Architektur: Diese Tabelle traegt alle fachlichen Report-Daten.
|
||||
-- Die bestehende Admin-Inbox (InboxPage.jsx, GET /api/me/inbox/join-requests)
|
||||
-- wird um einen zweiten Abschnitt erweitert, der Content-Reports anzeigt.
|
||||
-- Keine separate Admin-Queue, keine generische inbox_items-Tabelle.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS content_reports (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
-- Ziel der Meldung (erweiterbar auf weitere Typen)
|
||||
target_type VARCHAR(20) NOT NULL DEFAULT 'media_asset'
|
||||
CHECK (target_type IN ('media_asset', 'exercise')),
|
||||
target_id INTEGER NOT NULL,
|
||||
|
||||
-- Meldungsinhalt
|
||||
report_reason VARCHAR(50) NOT NULL
|
||||
CHECK (report_reason IN (
|
||||
'copyright',
|
||||
'image_rights',
|
||||
'privacy',
|
||||
'minors',
|
||||
'illegal_content',
|
||||
'youth_protection',
|
||||
'offensive_content',
|
||||
'other'
|
||||
)),
|
||||
report_description TEXT NOT NULL,
|
||||
|
||||
-- Meldende Person (Name + E-Mail Pflicht; Profil optional bei eingeloggten Nutzern)
|
||||
reporter_name VARCHAR(200) NOT NULL,
|
||||
reporter_email VARCHAR(200) NOT NULL,
|
||||
reporter_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
|
||||
-- Gutglaubenserklärung (Pflicht)
|
||||
good_faith_confirmed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
|
||||
-- Automatische Priorisierung (high fuer minors/youth_protection/illegal_content)
|
||||
priority VARCHAR(20) NOT NULL DEFAULT 'normal'
|
||||
CHECK (priority IN ('high', 'normal')),
|
||||
|
||||
-- Workflow-Status
|
||||
status VARCHAR(30) NOT NULL DEFAULT 'submitted'
|
||||
CHECK (status IN (
|
||||
'submitted',
|
||||
'under_review',
|
||||
'resolved_no_action',
|
||||
'resolved_legal_hold',
|
||||
'rejected_invalid'
|
||||
)),
|
||||
|
||||
-- Bearbeitung
|
||||
assigned_to_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
reviewed_by_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
reviewed_at TIMESTAMP,
|
||||
resolution_note TEXT,
|
||||
|
||||
-- Zeitstempel
|
||||
submitted_at TIMESTAMP DEFAULT NOW(),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Indices fuer Admin-Liste
|
||||
CREATE INDEX IF NOT EXISTS idx_content_reports_status_created
|
||||
ON content_reports (status, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_content_reports_target
|
||||
ON content_reports (target_type, target_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_content_reports_priority
|
||||
ON content_reports (priority, status, created_at DESC);
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Migration 053: Audit-Log event_type-Constraint korrigieren + 'content_report_filed' hinzufuegen
|
||||
--
|
||||
-- Hintergrund: Die Tabelle media_asset_audit_log wurde per CREATE TABLE IF NOT EXISTS angelegt.
|
||||
-- Da die Tabelle bereits existierte, wurde die CHECK-Constraint aus Migration 050 nie angewendet.
|
||||
-- In der DB existieren Zeilen mit legal_hold_set und legal_hold_released (aus P-11).
|
||||
-- Diese Migration setzt die Constraint erstmalig mit allen gueltigen Werten.
|
||||
|
||||
ALTER TABLE media_asset_audit_log
|
||||
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
|
||||
|
||||
ALTER TABLE media_asset_audit_log
|
||||
ADD CONSTRAINT media_asset_audit_log_event_type_check
|
||||
CHECK (event_type IN (
|
||||
'visibility_change',
|
||||
'copyright_change',
|
||||
'metadata_change',
|
||||
'lifecycle_change',
|
||||
'legal_hold_set',
|
||||
'legal_hold_released',
|
||||
'content_report_filed'
|
||||
));
|
||||
@@ -0,0 +1,60 @@
|
||||
-- Migration 054: Trainingsmodule (Bibliothek / Planung) — Phase 1 MVP
|
||||
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_modules (
|
||||
id SERIAL PRIMARY KEY,
|
||||
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
summary TEXT,
|
||||
goal TEXT,
|
||||
recommended_duration_min INT,
|
||||
target_group_notes TEXT,
|
||||
deployment_context_notes TEXT,
|
||||
primary_method_id INT REFERENCES training_methods(id) ON DELETE SET NULL,
|
||||
visibility VARCHAR(50) NOT NULL DEFAULT 'club'
|
||||
CHECK (visibility IN ('private', 'club', 'official')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_modules_club ON training_modules(club_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_modules_creator ON training_modules(created_by);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_modules_visibility ON training_modules(visibility);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_modules_method ON training_modules(primary_method_id)
|
||||
WHERE primary_method_id IS NOT NULL;
|
||||
|
||||
DROP TRIGGER IF EXISTS training_modules_update ON training_modules;
|
||||
CREATE TRIGGER training_modules_update
|
||||
BEFORE UPDATE ON training_modules
|
||||
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_module_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
module_id INT NOT NULL REFERENCES training_modules(id) ON DELETE CASCADE,
|
||||
order_index INT NOT NULL,
|
||||
item_type VARCHAR(20) NOT NULL CHECK (item_type IN ('exercise', 'note')),
|
||||
exercise_id INT REFERENCES exercises(id) ON DELETE SET NULL,
|
||||
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
|
||||
planned_duration_min INT,
|
||||
notes TEXT,
|
||||
note_body TEXT,
|
||||
UNIQUE (module_id, order_index),
|
||||
CHECK (
|
||||
(item_type = 'exercise' AND exercise_id IS NOT NULL AND note_body IS NULL)
|
||||
OR
|
||||
(item_type = 'note' AND exercise_id IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_module_items_module ON training_module_items(module_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_module_items_exercise ON training_module_items(exercise_id)
|
||||
WHERE exercise_id IS NOT NULL;
|
||||
|
||||
-- Herkunft bei Übernahme aus Modul-Bibliothek (Kopie, keine Live-Verknüpfung)
|
||||
ALTER TABLE training_unit_section_items
|
||||
ADD COLUMN IF NOT EXISTS source_training_module_id INT REFERENCES training_modules(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_section_items_source_module
|
||||
ON training_unit_section_items(source_training_module_id)
|
||||
WHERE source_training_module_id IS NOT NULL;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Persönliche Planungs-UI-Präferenzen (JSONB, selbst vom Nutzer setzbar)
|
||||
ALTER TABLE profiles
|
||||
ADD COLUMN IF NOT EXISTS training_planning_prefs JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Migration 056: Kombinationsübungen (Phase 2 MVP) — Slots + Pool-Kandidaten
|
||||
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md §6
|
||||
|
||||
ALTER TABLE exercises
|
||||
ADD COLUMN IF NOT EXISTS exercise_kind VARCHAR(20) NOT NULL DEFAULT 'simple'
|
||||
CHECK (exercise_kind IN ('simple', 'combination')),
|
||||
ADD COLUMN IF NOT EXISTS method_archetype VARCHAR(80),
|
||||
ADD COLUMN IF NOT EXISTS method_profile JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_exercise_kind ON exercises(exercise_kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_method_archetype ON exercises(method_archetype)
|
||||
WHERE method_archetype IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS combination_exercise_slots (
|
||||
id SERIAL PRIMARY KEY,
|
||||
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||
slot_index INT NOT NULL,
|
||||
title VARCHAR(200),
|
||||
UNIQUE (exercise_id, slot_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_combination_exercise_slots_exercise ON combination_exercise_slots(exercise_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS combination_slot_candidates (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slot_id INT NOT NULL REFERENCES combination_exercise_slots(id) ON DELETE CASCADE,
|
||||
candidate_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
UNIQUE (slot_id, candidate_exercise_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_slot ON combination_slot_candidates(slot_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_exercise ON combination_slot_candidates(candidate_exercise_id);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- 057: Terminspezifisches Ablaufprofil fuer Kombinationsuebungen in der Planung
|
||||
-- NULL = method_profile vom Katalog (exercises) verwenden; sonst dieser JSONB-Stand gilt fuer diese Platzierung.
|
||||
|
||||
ALTER TABLE training_unit_section_items
|
||||
ADD COLUMN IF NOT EXISTS planning_method_profile JSONB NULL;
|
||||
|
||||
COMMENT ON COLUMN training_unit_section_items.planning_method_profile IS
|
||||
'Snapshots des Ablaufprofils fuer diese Einheit/Zeile; NULL = exercises.method_profile.';
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Unterstützung für GET /api/exercises: ORDER BY e.updated_at DESC
|
||||
-- und häufiger Pfad created_by_me (= e.created_by = Profil) mit derselben Sortierung.
|
||||
-- Hinweis: idx_exercises_created_at (014) betrifft created_at, nicht updated_at.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_updated_at_desc ON exercises (updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_created_by_updated_at_desc ON exercises (created_by, updated_at DESC);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- GET /api/training-units: Liste nutzt immer tu.framework_slot_id IS NULL (keine Rahmen-Blueprints)
|
||||
-- und sortiert nach planned_date, planned_time_start (ASC/DESC mit NULLS LAST).
|
||||
-- Teilindex verkleinert die Menge und unterstützt die Sortierung.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_scheduled_order
|
||||
ON training_units (planned_date DESC, planned_time_start DESC NULLS LAST)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Migration 060: Übungslisten bei großem Bestand (Ziel: Tausende Übungen, viele Filterkombinationen).
|
||||
-- Ergänzt 058 (globale Sortierung / created_by): kleinere Partial-Indizes für häufige
|
||||
-- Sichtbarkeits-Pfade der Bibliothek sowie Junction-Indizes für die List-Subqueries
|
||||
-- (primary_focus_name / JSON-Aggregate mit is_primary).
|
||||
--
|
||||
-- Bereits vorhanden und sinnvoll: UNIQUE(exercise_id, …) auf den M:N-Tabellen für EXISTS-Joins;
|
||||
-- GIN auf exercises.search_vector (014); idx_exercises_exercise_kind (056).
|
||||
|
||||
-- Official: OR-Zweig der Bibliothek — kompakter als Full-Table-Scan bei BitmapOr mit anderen Partial-Indizes
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_list_official_updated
|
||||
ON exercises (updated_at DESC)
|
||||
WHERE visibility = 'official'
|
||||
AND COALESCE(status, '') <> 'archived';
|
||||
|
||||
-- Club: häufig club_id + Sortierung nach updated_at (Mandanten-Bibliothek)
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_list_club_updated
|
||||
ON exercises (club_id, updated_at DESC)
|
||||
WHERE visibility = 'club'
|
||||
AND club_id IS NOT NULL
|
||||
AND COALESCE(status, '') <> 'archived';
|
||||
|
||||
-- List-SELECT: Subqueries / json_agg sortieren zuerst nach is_primary (siehe exercises.py)
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_exercise_primary
|
||||
ON exercise_focus_areas (exercise_id, is_primary DESC NULLS LAST, focus_area_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_style_directions_exercise_primary
|
||||
ON exercise_style_directions (exercise_id, is_primary DESC NULLS LAST, style_direction_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_training_types_exercise_primary
|
||||
ON exercise_training_types (exercise_id, is_primary DESC NULLS LAST, training_type_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_exercise_primary
|
||||
ON exercise_target_groups (exercise_id, is_primary DESC NULLS LAST, target_group_id);
|
||||
@@ -0,0 +1,22 @@
|
||||
-- GET /api/training-units: Keyset über (planned_date, planned_time_start NULLS LAST per Sort, id)
|
||||
-- Ersetzt den reinen Datum/Uhrzeit-Teilindex 059 durch zwei Richtungen mit Tie-Break id.
|
||||
|
||||
DROP INDEX IF EXISTS idx_training_units_scheduled_order;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_desc
|
||||
ON training_units (
|
||||
planned_date DESC,
|
||||
(planned_time_start IS NULL) ASC,
|
||||
planned_time_start DESC NULLS LAST,
|
||||
id DESC
|
||||
)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_asc
|
||||
ON training_units (
|
||||
planned_date ASC,
|
||||
(planned_time_start IS NULL) ASC,
|
||||
planned_time_start ASC NULLS LAST,
|
||||
id ASC
|
||||
)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
@@ -0,0 +1,41 @@
|
||||
-- list_exercises mit skill_min_level / skill_max_level: EXISTS auf exercise_skills mit numerischem Stufen-Rang.
|
||||
-- Ausdruck muss mit backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL (Alias „es“) übereinstimmen.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_skills_exercise_level_rank
|
||||
ON exercise_skills (
|
||||
exercise_id,
|
||||
(CASE COALESCE(
|
||||
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||
)
|
||||
WHEN 'basis' THEN 1
|
||||
WHEN 'grundlagen' THEN 2
|
||||
WHEN 'aufbau' THEN 3
|
||||
WHEN 'fortgeschritten' THEN 4
|
||||
WHEN 'optimierung' THEN 5
|
||||
WHEN 'einsteiger' THEN 1
|
||||
WHEN 'experte' THEN 5
|
||||
WHEN '1' THEN 1
|
||||
WHEN '2' THEN 2
|
||||
WHEN '3' THEN 3
|
||||
WHEN '4' THEN 4
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END)
|
||||
)
|
||||
WHERE (CASE COALESCE(
|
||||
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||
)
|
||||
WHEN 'basis' THEN 1
|
||||
WHEN 'grundlagen' THEN 2
|
||||
WHEN 'aufbau' THEN 3
|
||||
WHEN 'fortgeschritten' THEN 4
|
||||
WHEN 'optimierung' THEN 5
|
||||
WHEN 'einsteiger' THEN 1
|
||||
WHEN 'experte' THEN 5
|
||||
WHEN '1' THEN 1
|
||||
WHEN '2' THEN 2
|
||||
WHEN '3' THEN 3
|
||||
WHEN '4' THEN 4
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END) IS NOT NULL;
|
||||
@@ -0,0 +1,85 @@
|
||||
-- Migration 063: Phasen und parallele Streams pro Trainingseinheit (Grundlage Breakout).
|
||||
-- Bestehende Sektionen werden einer Default-whole_group-Phase zugeordnet.
|
||||
-- UNIQUE (training_unit_id, order_index) auf Sektionen entfällt zugunsten
|
||||
-- eindeutiger order_index je Phase bzw. je parallel_stream.
|
||||
|
||||
-- ── Phasen ───────────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_unit_phases (
|
||||
id SERIAL PRIMARY KEY,
|
||||
training_unit_id INT NOT NULL REFERENCES training_units(id) ON DELETE CASCADE,
|
||||
order_index INT NOT NULL,
|
||||
phase_kind VARCHAR(20) NOT NULL CHECK (phase_kind IN ('whole_group', 'parallel')),
|
||||
title VARCHAR(200),
|
||||
guidance_notes TEXT,
|
||||
UNIQUE (training_unit_id, order_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_phases_unit ON training_unit_phases(training_unit_id);
|
||||
|
||||
-- ── Streams innerhalb einer Parallelphase ──────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_unit_parallel_streams (
|
||||
id SERIAL PRIMARY KEY,
|
||||
phase_id INT NOT NULL REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||
order_index INT NOT NULL,
|
||||
title VARCHAR(200),
|
||||
notes TEXT,
|
||||
assigned_trainer_profile_ids JSONB,
|
||||
UNIQUE (phase_id, order_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_parallel_streams_phase
|
||||
ON training_unit_parallel_streams(phase_id);
|
||||
|
||||
COMMENT ON COLUMN training_unit_parallel_streams.assigned_trainer_profile_ids IS
|
||||
'Optionale Co-Trainer-IDs (JSON-Array von Profil-IDs) für diese Teilstrecke; MVP+';
|
||||
|
||||
-- ── Sektionen: Zuordnung zu Phase (gemeinsam) oder Stream (parallel) ─────
|
||||
ALTER TABLE training_unit_sections
|
||||
ADD COLUMN IF NOT EXISTS phase_id INT REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||
ADD COLUMN IF NOT EXISTS parallel_stream_id INT REFERENCES training_unit_parallel_streams(id) ON DELETE CASCADE;
|
||||
|
||||
-- Backfill: je Einheit mit Sektionen eine whole_group-Phase, alle Sektionen dorthin
|
||||
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title)
|
||||
SELECT tu.id, 0, 'whole_group', NULL
|
||||
FROM training_units tu
|
||||
WHERE EXISTS (SELECT 1 FROM training_unit_sections s WHERE s.training_unit_id = tu.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM training_unit_phases p
|
||||
WHERE p.training_unit_id = tu.id AND p.order_index = 0 AND p.phase_kind = 'whole_group'
|
||||
);
|
||||
|
||||
UPDATE training_unit_sections tus
|
||||
SET phase_id = p.id
|
||||
FROM training_unit_phases p
|
||||
WHERE tus.phase_id IS NULL
|
||||
AND p.training_unit_id = tus.training_unit_id
|
||||
AND p.order_index = 0
|
||||
AND p.phase_kind = 'whole_group';
|
||||
|
||||
-- Alte globale Reihenfolge-Eindeutigkeit pro Einheit entfernen
|
||||
ALTER TABLE training_unit_sections
|
||||
DROP CONSTRAINT IF EXISTS training_unit_sections_training_unit_id_order_index_key;
|
||||
|
||||
-- Genau eine Zielspalte gesetzt: gemeinsame Phase ODER paralleler Stream
|
||||
ALTER TABLE training_unit_sections
|
||||
DROP CONSTRAINT IF EXISTS training_unit_sections_phase_or_stream_chk;
|
||||
|
||||
ALTER TABLE training_unit_sections
|
||||
ADD CONSTRAINT training_unit_sections_phase_or_stream_chk CHECK (
|
||||
(phase_id IS NOT NULL AND parallel_stream_id IS NULL)
|
||||
OR (phase_id IS NULL AND parallel_stream_id IS NOT NULL)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_phase_order
|
||||
ON training_unit_sections (phase_id, order_index)
|
||||
WHERE phase_id IS NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_stream_order
|
||||
ON training_unit_sections (parallel_stream_id, order_index)
|
||||
WHERE parallel_stream_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_phase
|
||||
ON training_unit_sections(phase_id) WHERE phase_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_parallel_stream
|
||||
ON training_unit_sections(parallel_stream_id) WHERE parallel_stream_id IS NOT NULL;
|
||||
+5
-1
@@ -26,7 +26,7 @@ class PasswordResetRequest(BaseModel):
|
||||
|
||||
class PasswordResetConfirm(BaseModel):
|
||||
token: str
|
||||
new_password: str
|
||||
new_password: str = Field(min_length=8, max_length=128)
|
||||
|
||||
class ProfileCreate(BaseModel):
|
||||
"""Nur für POST /api/profiles (Plattform-Admin): neues Nutzerprofil ohne Self-Registration."""
|
||||
@@ -47,6 +47,10 @@ class ProfileUpdate(BaseModel):
|
||||
default=None,
|
||||
description="JSON: gespeicherte Standardfilter für die Übungsliste",
|
||||
)
|
||||
training_planning_prefs: Optional[Dict[str, Any]] = Field(
|
||||
default=None,
|
||||
description="JSON: UI-Optionen Trainingsplanung (z.B. Darstellung kopierter Module)",
|
||||
)
|
||||
|
||||
class ProfileResponse(BaseModel):
|
||||
id: int
|
||||
|
||||
+1
-1
@@ -6,5 +6,5 @@ python_functions = test_*
|
||||
addopts = -q --tb=short
|
||||
markers =
|
||||
smoke: Schnelle Kern-Regression.
|
||||
integration: PostgreSQL-Mandanten-Integration (ACCESS_LAYER_INTEGRATION=1).
|
||||
integration: PostgreSQL-Integration (z. B. ACCESS_LAYER_INTEGRATION=1, TRAINING_PLANNING_INTEGRATION=1).
|
||||
slow: Lange/schwere Tests; in CI wie Mitai-Jinkendo ausgeschlossen (Auswahl: not slow).
|
||||
@@ -98,8 +98,8 @@ def change_pin(req: dict, session: dict=Depends(require_auth)):
|
||||
"""Change PIN/password for current user."""
|
||||
pid = session['profile_id']
|
||||
new_pin = req.get('pin', '')
|
||||
if len(new_pin) < 4:
|
||||
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
|
||||
if len(new_pin) < 8:
|
||||
raise HTTPException(400, "Passwort muss mind. 8 Zeichen haben")
|
||||
|
||||
new_hash = hash_pin(new_pin)
|
||||
with get_db() as conn:
|
||||
|
||||
@@ -0,0 +1,931 @@
|
||||
"""
|
||||
P-13: Content-Melde-Backend
|
||||
|
||||
Meldeverfahren fuer moeglicherweise rechtswidrige Inhalte (DSA-Grundlage, KRIT-03).
|
||||
|
||||
Architektur:
|
||||
- Fachliche Daten in 'content_reports' Tabelle (Migration 052)
|
||||
- Integration in bestehende Admin-Inbox (GET /api/me/inbox/content-reports)
|
||||
- Keine separate Admin-Queue; die InboxPage.jsx zeigt beide Vorgangstypen
|
||||
- P-11-Anschluss: Superadmin kann aus Meldung heraus Legal Hold setzen
|
||||
|
||||
Berechtigungen:
|
||||
- Meldung einreichen: optional Auth (ohne Auth nur fuer official-Medien erlaubt)
|
||||
- Liste/Detail: Plattform-Admin (alle Meldungen) oder Club-Admin (nur eigene Vereinsmedien)
|
||||
- Status-Bearbeitung: Plattform-Admin
|
||||
- Legal Hold aus Meldung: ausschliesslich Superadmin
|
||||
|
||||
E-Mail-Benachrichtigungen:
|
||||
- Nach Eingang: Bestaetigung an Melder
|
||||
- Nach Eingang: Benachrichtigung aller Plattform-Admins (best-effort, kein Fehler wenn SMTP fehlt)
|
||||
|
||||
Audit-Log (Migration 053):
|
||||
- Bei media_asset-Meldungen: Eintrag in media_asset_audit_log (event_type='content_report_filed')
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from club_tenancy import is_platform_admin, is_superadmin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from media_legal_hold import (
|
||||
LEGAL_HOLD_REASON_CODES,
|
||||
assert_superadmin_for_legal_hold,
|
||||
set_legal_hold,
|
||||
)
|
||||
from media_rights import write_audit_log_entry
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["content_reports"])
|
||||
|
||||
# Erlaubte Meldungsgruende
|
||||
REPORT_REASONS = frozenset({
|
||||
"copyright",
|
||||
"image_rights",
|
||||
"privacy",
|
||||
"minors",
|
||||
"illegal_content",
|
||||
"youth_protection",
|
||||
"offensive_content",
|
||||
"other",
|
||||
})
|
||||
|
||||
REASON_LABELS_DE = {
|
||||
"copyright": "Urheberrecht",
|
||||
"image_rights": "Bildrechte",
|
||||
"privacy": "Datenschutz / Persönlichkeitsrecht",
|
||||
"minors": "Minderjährige",
|
||||
"illegal_content": "Rechtswidriger Inhalt",
|
||||
"youth_protection": "Jugendschutz",
|
||||
"offensive_content": "Beleidigender Inhalt",
|
||||
"other": "Sonstiges",
|
||||
}
|
||||
|
||||
# Gruende mit hoher Prioritaet (illegal, Minderjaehrigenschutz)
|
||||
HIGH_PRIORITY_REASONS = frozenset({
|
||||
"minors",
|
||||
"illegal_content",
|
||||
"youth_protection",
|
||||
})
|
||||
|
||||
# Mapping: report_reason -> legal_hold reason_code
|
||||
_REASON_TO_HOLD_CODE = {
|
||||
"copyright": "copyright_complaint",
|
||||
"image_rights": "rights_dispute",
|
||||
"privacy": "privacy_complaint",
|
||||
"minors": "youth_protection",
|
||||
"illegal_content": "illegal_content",
|
||||
"youth_protection": "youth_protection",
|
||||
"offensive_content": "illegal_content",
|
||||
"other": "other",
|
||||
}
|
||||
|
||||
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
|
||||
|
||||
# ─── Pydantic-Modelle ────────────────────────────────────────────────────────
|
||||
|
||||
class ContentReportCreate(BaseModel):
|
||||
target_type: str = Field(default="media_asset")
|
||||
target_id: int = Field(..., ge=1)
|
||||
report_reason: str
|
||||
report_description: str = Field(..., min_length=10, max_length=8000)
|
||||
reporter_name: str = Field(..., min_length=1, max_length=200)
|
||||
reporter_email: str = Field(..., min_length=5, max_length=200)
|
||||
good_faith_confirmed: bool
|
||||
|
||||
@field_validator("target_type")
|
||||
@classmethod
|
||||
def validate_target_type(cls, v: str) -> str:
|
||||
if v not in ("media_asset", "exercise"):
|
||||
raise ValueError("target_type muss 'media_asset' oder 'exercise' sein")
|
||||
return v
|
||||
|
||||
@field_validator("report_reason")
|
||||
@classmethod
|
||||
def validate_reason(cls, v: str) -> str:
|
||||
if v not in REPORT_REASONS:
|
||||
raise ValueError(f"Ungueltiger report_reason. Erlaubt: {sorted(REPORT_REASONS)}")
|
||||
return v
|
||||
|
||||
@field_validator("reporter_email")
|
||||
@classmethod
|
||||
def validate_email(cls, v: str) -> str:
|
||||
if not _EMAIL_RE.match(v.strip()):
|
||||
raise ValueError("Ungueltige E-Mail-Adresse")
|
||||
return v.strip().lower()
|
||||
|
||||
@field_validator("reporter_name")
|
||||
@classmethod
|
||||
def validate_name(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("Name darf nicht leer sein")
|
||||
return v
|
||||
|
||||
|
||||
class ContentReportPatch(BaseModel):
|
||||
status: Optional[str] = None
|
||||
resolution_note: Optional[str] = Field(None, max_length=4000)
|
||||
assigned_to_profile_id: Optional[int] = None
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def validate_status(cls, v: Optional[str]) -> Optional[str]:
|
||||
if v is None:
|
||||
return v
|
||||
allowed = {"submitted", "under_review", "resolved_no_action",
|
||||
"resolved_legal_hold", "rejected_invalid"}
|
||||
if v not in allowed:
|
||||
raise ValueError(f"Ungueltiger status. Erlaubt: {sorted(allowed)}")
|
||||
return v
|
||||
|
||||
|
||||
class ContentReportLegalHoldBody(BaseModel):
|
||||
reason_note: str = Field(..., min_length=5, max_length=2000)
|
||||
|
||||
|
||||
# ─── Hilfsfunktionen ────────────────────────────────────────────────────────
|
||||
|
||||
def _assert_can_manage_report(cur, role: Optional[str], pid: int, report: dict) -> None:
|
||||
"""Platform-Admins: jede Meldung. Club-Admin: nur Meldungen zu Medien ihres Vereins."""
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if report.get("target_type") != "media_asset":
|
||||
raise HTTPException(status_code=403, detail="Nur Plattform-Admins können Meldungen zu Übungen bearbeiten")
|
||||
cur.execute("SELECT club_id FROM media_assets WHERE id = %s", (int(report["target_id"]),))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
club_id = r2d(row).get("club_id")
|
||||
if not club_id:
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff – Medium ohne Vereinszugehörigkeit")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||
AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||
""",
|
||||
(pid, club_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff auf diese Meldung")
|
||||
|
||||
|
||||
def _assert_can_set_legal_hold_from_report(cur, role: Optional[str], pid: int, asset_id: int) -> None:
|
||||
"""Superadmin: immer. Club-Admin: nur für Vereinsmedien mit visibility != 'official'."""
|
||||
if is_superadmin(role):
|
||||
return
|
||||
cur.execute("SELECT club_id, visibility FROM media_assets WHERE id = %s", (asset_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(row)
|
||||
if asset.get("visibility") == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Legal Hold auf offiziellen Medien erfordert Superadmin-Rechte",
|
||||
)
|
||||
club_id = asset.get("club_id")
|
||||
if not club_id:
|
||||
raise HTTPException(status_code=403, detail="Legal Hold erfordert Superadmin-Rechte für Medien ohne Vereinszugehörigkeit")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||
AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||
""",
|
||||
(pid, club_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff – Superadmin oder Vereinsadmin des Vereins erforderlich")
|
||||
|
||||
|
||||
def _is_media_asset_visible_anonymous(cur, asset_id: int) -> bool:
|
||||
"""True wenn das Medium als 'official' und aktiv gilt (fuer anonyme Meldung zugaenglich)."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM media_assets
|
||||
WHERE id = %s
|
||||
AND visibility = 'official'
|
||||
AND lifecycle_state = 'active'
|
||||
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)
|
||||
""",
|
||||
(asset_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _is_media_asset_visible_to_profile(cur, asset_id: int, profile_id: int, global_role: Optional[str]) -> bool:
|
||||
"""Prueft ob ein eingeloggter Nutzer das Medium sehen darf."""
|
||||
if is_platform_admin(global_role):
|
||||
cur.execute("SELECT 1 FROM media_assets WHERE id = %s", (asset_id,))
|
||||
return cur.fetchone() is not None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT ma.id, ma.visibility, ma.club_id, ma.uploaded_by_profile_id
|
||||
FROM media_assets ma
|
||||
WHERE ma.id = %s
|
||||
AND ma.lifecycle_state = 'active'
|
||||
AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL)
|
||||
""",
|
||||
(asset_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
asset = r2d(row)
|
||||
visibility = asset.get("visibility")
|
||||
if visibility == "official":
|
||||
return True
|
||||
if visibility == "club":
|
||||
club_id = asset.get("club_id")
|
||||
if not club_id:
|
||||
return False
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||
""",
|
||||
(profile_id, club_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
if visibility == "private":
|
||||
if asset.get("uploaded_by_profile_id") == profile_id:
|
||||
return True
|
||||
club_id = asset.get("club_id")
|
||||
if club_id:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.profile_id = %s AND cm.club_id = %s AND cm.status = 'active'
|
||||
AND r.role_code = 'club_admin'
|
||||
""",
|
||||
(profile_id, club_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
return False
|
||||
|
||||
|
||||
def _is_exercise_visible_to_profile(cur, exercise_id: int, profile_id: Optional[int], global_role: Optional[str]) -> bool:
|
||||
"""Vereinfachte Sichtbarkeitspruefung fuer Uebungen (fuer Meldungen)."""
|
||||
if profile_id and is_platform_admin(global_role):
|
||||
cur.execute("SELECT 1 FROM exercises WHERE id = %s AND status != 'deleted'", (exercise_id,))
|
||||
return cur.fetchone() is not None
|
||||
if profile_id is None:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM exercises WHERE id = %s AND visibility = 'official' AND status = 'active'",
|
||||
(exercise_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT e.visibility, e.club_id, e.created_by_profile_id
|
||||
FROM exercises e WHERE e.id = %s AND e.status != 'deleted'
|
||||
""",
|
||||
(exercise_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
ex = r2d(row)
|
||||
if ex.get("visibility") == "official":
|
||||
return True
|
||||
if ex.get("visibility") == "club":
|
||||
club_id = ex.get("club_id")
|
||||
if not club_id:
|
||||
return False
|
||||
cur.execute(
|
||||
"SELECT 1 FROM club_members WHERE profile_id = %s AND club_id = %s AND status = 'active'",
|
||||
(profile_id, club_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
if ex.get("visibility") == "private":
|
||||
return ex.get("created_by_profile_id") == profile_id
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_optional_auth(cur, x_auth_token: Optional[str]) -> tuple[Optional[int], Optional[str]]:
|
||||
"""Gibt (profile_id, global_role) zurueck wenn Token gueltig, sonst (None, None)."""
|
||||
if not x_auth_token:
|
||||
return None, None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id AS profile_id, p.role
|
||||
FROM sessions s
|
||||
INNER JOIN profiles p ON p.id = s.profile_id
|
||||
WHERE s.token = %s
|
||||
AND (s.expires_at IS NULL OR s.expires_at > NOW())
|
||||
""",
|
||||
(x_auth_token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None, None
|
||||
d = r2d(row)
|
||||
return d.get("profile_id"), d.get("role")
|
||||
|
||||
|
||||
def _get_platform_admin_emails(cur) -> list[str]:
|
||||
"""Gibt E-Mail-Adressen aller aktiven Plattform-Admins zurueck."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT email FROM profiles
|
||||
WHERE role IN ('admin', 'superadmin')
|
||||
AND email IS NOT NULL AND email <> ''
|
||||
"""
|
||||
)
|
||||
return [r2d(row)["email"] for row in cur.fetchall()]
|
||||
|
||||
|
||||
def _send_email(to: str, subject: str, body: str) -> None:
|
||||
"""SMTP-Versand (best-effort, ignoriert Fehler und nicht konfiguriertes SMTP)."""
|
||||
try:
|
||||
import smtplib, ssl
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
smtp_host = (os.getenv("SMTP_HOST") or "").strip()
|
||||
smtp_user = (os.getenv("SMTP_USER") or "").strip()
|
||||
smtp_pass = os.getenv("SMTP_PASS") or ""
|
||||
if not smtp_host or not smtp_user or not smtp_pass:
|
||||
return
|
||||
smtp_port = int(os.getenv("SMTP_PORT") or "587")
|
||||
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
|
||||
force_ssl = (os.getenv("SMTP_SSL", "").strip().lower() in ("1", "true", "yes")) or smtp_port == 465
|
||||
use_tls = os.getenv("SMTP_STARTTLS", "true").strip().lower() not in ("0", "false", "no")
|
||||
|
||||
msg = MIMEText(body, "plain", "utf-8")
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = smtp_from
|
||||
msg["To"] = to
|
||||
ctx = ssl.create_default_context()
|
||||
if force_ssl:
|
||||
with smtplib.SMTP_SSL(smtp_host, smtp_port, context=ctx, timeout=30) as srv:
|
||||
srv.login(smtp_user, smtp_pass)
|
||||
srv.send_message(msg)
|
||||
else:
|
||||
with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as srv:
|
||||
srv.ehlo()
|
||||
if use_tls:
|
||||
srv.starttls(context=ctx)
|
||||
srv.ehlo()
|
||||
srv.login(smtp_user, smtp_pass)
|
||||
srv.send_message(msg)
|
||||
except Exception as exc:
|
||||
print(f"[SMTP content_reports] Fehler: {exc}")
|
||||
|
||||
|
||||
def _notify_report_submitted(
|
||||
*,
|
||||
report_id: int,
|
||||
reporter_name: str,
|
||||
reporter_email: str,
|
||||
reason: str,
|
||||
priority: str,
|
||||
target_type: str,
|
||||
target_id: int,
|
||||
target_label: str,
|
||||
admin_emails: list[str],
|
||||
) -> None:
|
||||
"""Sendet Bestaetigungs-Mail an Melder + Benachrichtigung an alle Plattform-Admins (best-effort)."""
|
||||
app_url = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
reason_label = REASON_LABELS_DE.get(reason, reason)
|
||||
prio_label = "DRINGEND" if priority == "high" else "normal"
|
||||
|
||||
# Bestaetigungs-Mail an Melder
|
||||
confirmation_body = (
|
||||
f"Hallo {reporter_name},\n\n"
|
||||
f"Ihre Meldung (#{report_id}) wurde entgegengenommen.\n\n"
|
||||
f"Meldegrund: {reason_label}\n"
|
||||
f"Gemeldeter Inhalt: {target_label}\n\n"
|
||||
f"Ein Administrator wird Ihre Meldung zeitnah prüfen. Sie müssen nichts weiter tun.\n\n"
|
||||
f"Shinkan Jinkendo\n"
|
||||
f"{app_url}"
|
||||
)
|
||||
_send_email(reporter_email, f"Meldung #{report_id} eingegangen – Shinkan Jinkendo", confirmation_body)
|
||||
|
||||
# Admin-Benachrichtigung
|
||||
admin_body = (
|
||||
f"Neue Inhaltsmeldung #{report_id} [{prio_label}]\n\n"
|
||||
f"Meldegrund: {reason_label}\n"
|
||||
f"Gemeldeter Inhalt: {target_label}\n"
|
||||
f"Gemeldet von: {reporter_name} <{reporter_email}>\n\n"
|
||||
f"Posteingang öffnen: {app_url}/inbox\n"
|
||||
)
|
||||
subject = f"Inhaltsmeldung #{report_id} [{prio_label}] – Shinkan Jinkendo"
|
||||
for email in admin_emails:
|
||||
_send_email(email, subject, admin_body)
|
||||
|
||||
|
||||
def _report_row_to_dict(row) -> dict:
|
||||
return r2d(row)
|
||||
|
||||
|
||||
# ─── Endpoints ──────────────────────────────────────────────────────────────
|
||||
|
||||
@router.post("/content-reports", status_code=201)
|
||||
def submit_content_report(
|
||||
body: ContentReportCreate,
|
||||
x_auth_token: Optional[str] = Header(default=None),
|
||||
):
|
||||
"""
|
||||
Meldung einreichen (optionale Authentifizierung).
|
||||
|
||||
- Ohne Login: nur fuer 'official'-Medien erlaubt (öffentlich erreichbare Inhalte)
|
||||
- Mit Login: fuer alle Inhalte, die der Nutzer laut Sichtbarkeitslogik sehen darf
|
||||
- Gutglaubenserklärung (good_faith_confirmed=true) ist Pflicht
|
||||
- Journaleintrag im Medien-Audit-Log (wenn target_type=media_asset)
|
||||
- E-Mail-Bestaetigung an Melder + Benachrichtigung an Plattform-Admins (best-effort)
|
||||
"""
|
||||
if not body.good_faith_confirmed:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
|
||||
)
|
||||
|
||||
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
|
||||
|
||||
report_id: int
|
||||
admin_emails: list[str] = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Optionale Auth aufloesen
|
||||
profile_id, global_role = _resolve_optional_auth(cur, x_auth_token)
|
||||
|
||||
# Sichtbarkeit pruefen
|
||||
if body.target_type == "media_asset":
|
||||
if profile_id:
|
||||
visible = _is_media_asset_visible_to_profile(cur, body.target_id, profile_id, global_role)
|
||||
else:
|
||||
visible = _is_media_asset_visible_anonymous(cur, body.target_id)
|
||||
if not visible:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Das gemeldete Medium existiert nicht oder ist nicht zugänglich.",
|
||||
)
|
||||
elif body.target_type == "exercise":
|
||||
visible = _is_exercise_visible_to_profile(cur, body.target_id, profile_id, global_role)
|
||||
if not visible:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Die gemeldete Übung existiert nicht oder ist nicht zugänglich.",
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO content_reports (
|
||||
target_type, target_id, report_reason, report_description,
|
||||
reporter_name, reporter_email, reporter_profile_id,
|
||||
good_faith_confirmed, priority, status,
|
||||
submitted_at, created_at, updated_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'submitted', NOW(), NOW(), NOW())
|
||||
RETURNING id, status, priority, submitted_at
|
||||
""",
|
||||
(
|
||||
body.target_type,
|
||||
body.target_id,
|
||||
body.report_reason,
|
||||
body.report_description.strip(),
|
||||
body.reporter_name,
|
||||
body.reporter_email,
|
||||
profile_id,
|
||||
body.good_faith_confirmed,
|
||||
priority,
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
result = r2d(row)
|
||||
report_id = int(result["id"])
|
||||
|
||||
# Dateinamen / Zielbezeichnung fuer E-Mail abfragen
|
||||
target_label_for_email = f"{'Medium' if body.target_type == 'media_asset' else 'Übung'} #{body.target_id}"
|
||||
if body.target_type == "media_asset":
|
||||
cur.execute("SELECT original_filename FROM media_assets WHERE id = %s", (body.target_id,))
|
||||
fn_row = cur.fetchone()
|
||||
if fn_row:
|
||||
fn = r2d(fn_row).get("original_filename") or ""
|
||||
if fn:
|
||||
target_label_for_email = f"{fn} (Medium #{body.target_id})"
|
||||
|
||||
elif body.target_type == "exercise":
|
||||
cur.execute("SELECT title FROM exercises WHERE id = %s", (body.target_id,))
|
||||
ex_row = cur.fetchone()
|
||||
if ex_row:
|
||||
ex_name = r2d(ex_row).get("title") or ""
|
||||
if ex_name:
|
||||
target_label_for_email = f"{ex_name} (Übung #{body.target_id})"
|
||||
|
||||
# Audit-Log-Eintrag (nur fuer media_asset-Meldungen)
|
||||
if body.target_type == "media_asset":
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
body.target_id,
|
||||
profile_id,
|
||||
"content_report_filed",
|
||||
{},
|
||||
{
|
||||
"content_report_id": report_id,
|
||||
"report_reason": REASON_LABELS_DE.get(body.report_reason, body.report_reason),
|
||||
"priority": "hoch" if priority == "high" else "normal",
|
||||
},
|
||||
)
|
||||
|
||||
# Admin-E-Mails vor Commit abfragen (Verbindung noch offen)
|
||||
admin_emails = _get_platform_admin_emails(cur)
|
||||
|
||||
conn.commit()
|
||||
|
||||
# E-Mails nach Commit senden (best-effort, kein Rollback-Risiko)
|
||||
_notify_report_submitted(
|
||||
report_id=report_id,
|
||||
reporter_name=body.reporter_name,
|
||||
reporter_email=body.reporter_email,
|
||||
reason=body.report_reason,
|
||||
priority=priority,
|
||||
target_type=body.target_type,
|
||||
target_id=body.target_id,
|
||||
target_label=target_label_for_email,
|
||||
admin_emails=admin_emails,
|
||||
)
|
||||
|
||||
return {
|
||||
"id": report_id,
|
||||
"status": result["status"],
|
||||
"priority": result["priority"],
|
||||
"submitted_at": str(result["submitted_at"]),
|
||||
"message": "Ihre Meldung wurde entgegengenommen. Ein Administrator wird sie prüfen.",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/me/inbox/content-reports")
|
||||
def list_inbox_content_reports(
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Meldungen fuer die Inbox.
|
||||
- Plattform-Admins (admin/superadmin): alle Meldungen
|
||||
- Club-Admins: nur Meldungen ueber Medien ihres Vereins
|
||||
"""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
is_padmin = is_platform_admin(role)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
if is_padmin:
|
||||
# Plattform-Admin: alle Meldungen
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
cr.id,
|
||||
cr.target_type,
|
||||
cr.target_id,
|
||||
cr.report_reason,
|
||||
cr.report_description,
|
||||
cr.reporter_name,
|
||||
cr.reporter_email,
|
||||
cr.reporter_profile_id,
|
||||
cr.priority,
|
||||
cr.status,
|
||||
cr.assigned_to_profile_id,
|
||||
cr.reviewed_by_profile_id,
|
||||
cr.reviewed_at,
|
||||
cr.resolution_note,
|
||||
cr.submitted_at,
|
||||
cr.created_at,
|
||||
cr.updated_at,
|
||||
ma.original_filename AS target_filename,
|
||||
ma.visibility AS target_visibility,
|
||||
ma.mime_type AS target_mime_type,
|
||||
ma.legal_hold_active AS target_legal_hold_active,
|
||||
ex.title AS target_exercise_name,
|
||||
rev.name AS reviewed_by_name,
|
||||
asgn.name AS assigned_to_name
|
||||
FROM content_reports cr
|
||||
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||
ORDER BY
|
||||
CASE WHEN cr.status = 'submitted' THEN 0
|
||||
WHEN cr.status = 'under_review' THEN 1
|
||||
ELSE 2 END ASC,
|
||||
cr.priority DESC,
|
||||
cr.created_at ASC
|
||||
LIMIT 500
|
||||
""",
|
||||
)
|
||||
else:
|
||||
# Club-Admin: Meldungen ueber Medien der eigenen Vereine
|
||||
# Zuerst pruefen ob ueberhaupt Club-Admin-Rolle vorhanden
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS cnt
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
cnt_row = r2d(cur.fetchone())
|
||||
if int(cnt_row.get("cnt", 0)) == 0:
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff auf Inhaltsmeldungen")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
cr.id,
|
||||
cr.target_type,
|
||||
cr.target_id,
|
||||
cr.report_reason,
|
||||
cr.report_description,
|
||||
cr.reporter_name,
|
||||
cr.reporter_email,
|
||||
cr.reporter_profile_id,
|
||||
cr.priority,
|
||||
cr.status,
|
||||
cr.assigned_to_profile_id,
|
||||
cr.reviewed_by_profile_id,
|
||||
cr.reviewed_at,
|
||||
cr.resolution_note,
|
||||
cr.submitted_at,
|
||||
cr.created_at,
|
||||
cr.updated_at,
|
||||
ma.original_filename AS target_filename,
|
||||
ma.visibility AS target_visibility,
|
||||
ma.mime_type AS target_mime_type,
|
||||
ma.legal_hold_active AS target_legal_hold_active,
|
||||
ex.title AS target_exercise_name,
|
||||
rev.name AS reviewed_by_name,
|
||||
asgn.name AS assigned_to_name
|
||||
FROM content_reports cr
|
||||
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||
WHERE cr.target_type = 'media_asset'
|
||||
AND ma.club_id IN (
|
||||
SELECT cm.club_id
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||
)
|
||||
ORDER BY
|
||||
CASE WHEN cr.status = 'submitted' THEN 0
|
||||
WHEN cr.status = 'under_review' THEN 1
|
||||
ELSE 2 END ASC,
|
||||
cr.priority DESC,
|
||||
cr.created_at ASC
|
||||
LIMIT 200
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
|
||||
return [_report_row_to_dict(row) for row in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/content-reports/{report_id}")
|
||||
def get_content_report(
|
||||
report_id: int,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Detail-Ansicht einer Meldung fuer Plattform-Admins und zustaendige Club-Admins."""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
cr.*,
|
||||
ma.original_filename AS target_filename,
|
||||
ma.visibility AS target_visibility,
|
||||
ma.mime_type AS target_mime_type,
|
||||
ma.legal_hold_active AS target_legal_hold_active,
|
||||
ma.legal_hold_reason_code AS target_legal_hold_reason_code,
|
||||
ex.title AS target_exercise_name,
|
||||
ex.visibility AS target_exercise_visibility,
|
||||
rev.name AS reviewed_by_name,
|
||||
asgn.name AS assigned_to_name,
|
||||
rep.name AS reporter_profile_name
|
||||
FROM content_reports cr
|
||||
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||
LEFT JOIN profiles rep ON rep.id = cr.reporter_profile_id
|
||||
WHERE cr.id = %s
|
||||
""",
|
||||
(report_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||
report_dict = _report_row_to_dict(row)
|
||||
_assert_can_manage_report(cur, role, pid, report_dict)
|
||||
return report_dict
|
||||
|
||||
|
||||
@router.patch("/content-reports/{report_id}")
|
||||
def patch_content_report(
|
||||
report_id: int,
|
||||
body: ContentReportPatch,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Status und Bearbeitungsnotiz einer Meldung aktualisieren.
|
||||
Abschluss ohne Massnahme (resolved_no_action, rejected_invalid) erfordert resolution_note.
|
||||
Plattform-Admins: jede Meldung. Club-Admins: nur Meldungen zu Medien ihres Vereins.
|
||||
"""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
if body.status in ("resolved_no_action", "rejected_invalid") and not (body.resolution_note or "").strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Bei Abschluss ohne Massnahme ist eine Begründung (resolution_note) Pflicht.",
|
||||
)
|
||||
|
||||
STATUS_LABELS_DE = {
|
||||
"submitted": "Eingegangen",
|
||||
"under_review": "In Bearbeitung",
|
||||
"resolved_no_action": "Abgeschlossen (kein Handlungsbedarf)",
|
||||
"resolved_legal_hold": "Abgeschlossen (Legal Hold)",
|
||||
"rejected_invalid": "Abgewiesen (ungültig)",
|
||||
}
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, status, resolution_note, target_type, target_id FROM content_reports WHERE id = %s",
|
||||
(report_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||
old_report = r2d(row)
|
||||
_assert_can_manage_report(cur, role, pid, old_report)
|
||||
old_status = old_report["status"]
|
||||
old_note = (old_report.get("resolution_note") or "").strip()
|
||||
|
||||
updates = ["updated_at = NOW()"]
|
||||
params = []
|
||||
|
||||
if body.status is not None:
|
||||
updates.append("status = %s")
|
||||
params.append(body.status)
|
||||
if body.status in ("resolved_no_action", "resolved_legal_hold", "rejected_invalid"):
|
||||
updates.append("reviewed_by_profile_id = %s")
|
||||
updates.append("reviewed_at = NOW()")
|
||||
params.append(pid)
|
||||
elif body.status == "submitted":
|
||||
# Wieder öffnen: Prüferfelder zurücksetzen
|
||||
updates.append("reviewed_by_profile_id = NULL")
|
||||
updates.append("reviewed_at = NULL")
|
||||
|
||||
if body.resolution_note is not None:
|
||||
updates.append("resolution_note = %s")
|
||||
params.append(body.resolution_note.strip() or None)
|
||||
|
||||
if body.assigned_to_profile_id is not None:
|
||||
updates.append("assigned_to_profile_id = %s")
|
||||
params.append(body.assigned_to_profile_id)
|
||||
|
||||
if len(updates) == 1:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren angegeben")
|
||||
|
||||
params.append(report_id)
|
||||
cur.execute(
|
||||
f"UPDATE content_reports SET {', '.join(updates)} WHERE id = %s RETURNING id, status",
|
||||
params,
|
||||
)
|
||||
updated = r2d(cur.fetchone())
|
||||
new_status = updated["status"]
|
||||
|
||||
is_media = old_report["target_type"] == "media_asset"
|
||||
if is_media:
|
||||
new_note = (body.resolution_note or "").strip() if body.resolution_note is not None else old_note
|
||||
|
||||
# Audit-Log: Statuswechsel
|
||||
if body.status is not None and old_status != new_status:
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
int(old_report["target_id"]),
|
||||
pid,
|
||||
"content_report_filed",
|
||||
{"status": STATUS_LABELS_DE.get(old_status, old_status)},
|
||||
{
|
||||
"content_report_id": report_id,
|
||||
"status": STATUS_LABELS_DE.get(new_status, new_status),
|
||||
**({"begründung": new_note} if new_note else {}),
|
||||
},
|
||||
)
|
||||
# Audit-Log: reine Notizänderung (ohne Statuswechsel)
|
||||
elif body.resolution_note is not None and new_note != old_note:
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
int(old_report["target_id"]),
|
||||
pid,
|
||||
"content_report_filed",
|
||||
{"content_report_id": report_id, "begründung": old_note or None},
|
||||
{"content_report_id": report_id, "begründung": new_note or None},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True, "id": updated["id"], "status": updated["status"]}
|
||||
|
||||
|
||||
@router.post("/content-reports/{report_id}/legal-hold")
|
||||
def set_legal_hold_from_report(
|
||||
report_id: int,
|
||||
body: ContentReportLegalHoldBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Legal Hold (P-11) aus einer Meldung heraus setzen.
|
||||
Superadmin: immer. Club-Admin: nur fuer Vereinsmedien (visibility != 'official').
|
||||
Nur fuer Meldungen mit target_type='media_asset'.
|
||||
|
||||
Der Reason-Code wird automatisch aus dem report_reason der Meldung abgeleitet.
|
||||
Nach dem Setzen wird der Report-Status auf 'resolved_legal_hold' gesetzt.
|
||||
"""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
# Plattform-Admin ohne Superadmin hat keine Legal-Hold-Rechte (fruehzeitig ablehnen)
|
||||
if is_platform_admin(role) and not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Legal Hold erfordert Superadmin oder Vereinsadmin-Rechte",
|
||||
)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, target_type, target_id, report_reason, status FROM content_reports WHERE id = %s",
|
||||
(report_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||
report = r2d(row)
|
||||
|
||||
if report["target_type"] != "media_asset":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Legal Hold ist nur fuer Meldungen mit target_type='media_asset' verfügbar.",
|
||||
)
|
||||
|
||||
asset_id = int(report["target_id"])
|
||||
_assert_can_set_legal_hold_from_report(cur, role, pid, asset_id)
|
||||
reason_code = _REASON_TO_HOLD_CODE.get(report["report_reason"], "other")
|
||||
|
||||
# P-11-Service aufrufen
|
||||
set_legal_hold(
|
||||
cur=cur,
|
||||
conn=conn,
|
||||
asset_id=asset_id,
|
||||
acting_profile_id=pid,
|
||||
reason_code=reason_code,
|
||||
reason_note=f"[P-13 Meldung #{report_id}] {body.reason_note.strip()}",
|
||||
)
|
||||
|
||||
# set_legal_hold committed bereits — neue Transaktion fuer Report-Update
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE content_reports
|
||||
SET status = 'resolved_legal_hold',
|
||||
reviewed_by_profile_id = %s,
|
||||
reviewed_at = NOW(),
|
||||
resolution_note = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, status
|
||||
""",
|
||||
(pid, f"Legal Hold gesetzt auf Asset #{asset_id} (reason_code: {reason_code})", report_id),
|
||||
)
|
||||
updated = r2d(cur.fetchone())
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"report_id": updated["id"],
|
||||
"report_status": updated["status"],
|
||||
"asset_id": asset_id,
|
||||
"legal_hold_reason_code": reason_code,
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
Dashboard: zusammengefasste Kennzahlen (ein Roundtrip statt mehrerer Listen).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
from routers.exercises import list_exercises_like_get
|
||||
from routers.training_planning import list_training_units
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["dashboard"])
|
||||
|
||||
|
||||
def _slice_training_home_notes(planned_pool: List[Dict[str, Any]], max_notes: int = 5) -> List[Dict[str, Any]]:
|
||||
out = []
|
||||
for u in planned_pool:
|
||||
tn = (u.get("trainer_notes") or "").strip()
|
||||
n = (u.get("notes") or "").strip()
|
||||
if tn or n:
|
||||
out.append(u)
|
||||
if len(out) >= max_notes:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/dashboard/kpis")
|
||||
def get_dashboard_kpis(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""
|
||||
Kurzüberblick: Übungs-KPIs + YTD-Einheiten + Trainings-Home (nächste Termine, Vermerke, offene Rückschau)
|
||||
in einem Roundtrip — gleiche Filter wie zuvor im Dashboard (mehrere Client-Calls).
|
||||
"""
|
||||
year = date.today().year
|
||||
year_start = f"{year}-01-01"
|
||||
year_end = f"{year}-12-31"
|
||||
today = date.today().isoformat()
|
||||
|
||||
draft_list = list_exercises_like_get(
|
||||
tenant, created_by_me=True, status="draft", limit=100
|
||||
)
|
||||
mine_list = list_exercises_like_get(
|
||||
tenant, created_by_me=True, status=None, limit=100
|
||||
)
|
||||
ytd_completed = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=year_start,
|
||||
end_date=year_end,
|
||||
status="completed",
|
||||
assigned_to_me=True,
|
||||
debrief_pending=False,
|
||||
sort="desc",
|
||||
limit=250,
|
||||
tenant=tenant,
|
||||
)
|
||||
planned_pool = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=today,
|
||||
end_date=None,
|
||||
status="planned",
|
||||
assigned_to_me=True,
|
||||
debrief_pending=False,
|
||||
sort="asc",
|
||||
limit=40,
|
||||
tenant=tenant,
|
||||
)
|
||||
review_pending = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=None,
|
||||
end_date=None,
|
||||
status=None,
|
||||
assigned_to_me=True,
|
||||
debrief_pending=True,
|
||||
sort="desc",
|
||||
limit=8,
|
||||
tenant=tenant,
|
||||
)
|
||||
|
||||
draft_preview = [
|
||||
{"id": int(ex["id"]), "title": ex.get("title") or f"Übung #{ex['id']}"}
|
||||
for ex in draft_list[:8]
|
||||
]
|
||||
|
||||
return {
|
||||
"year": year,
|
||||
"draft_count": len(draft_list),
|
||||
"draft_capped": len(draft_list) >= 100,
|
||||
"draft_preview": draft_preview,
|
||||
"mine_count": len(mine_list),
|
||||
"mine_capped": len(mine_list) >= 100,
|
||||
"ytd_completed_count": len(ytd_completed),
|
||||
"ytd_capped": len(ytd_completed) >= 250,
|
||||
"training_home": {
|
||||
"upcoming": planned_pool[:8],
|
||||
"planned_with_notes": _slice_training_home_notes(planned_pool),
|
||||
"review_pending": review_pending,
|
||||
},
|
||||
}
|
||||
+530
-12
@@ -9,13 +9,17 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
||||
from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Request, UploadFile, File, Form
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from fastapi_param_unwrap import unwrap_query_default
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from club_tenancy import (
|
||||
@@ -29,6 +33,8 @@ from club_tenancy import (
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
|
||||
from media_rights import assert_rights_for_exercise_link, validate_rights_declaration, write_rights_declaration, update_rights_quick_fields
|
||||
from media_legal_hold import assert_not_under_legal_hold
|
||||
from exercise_rich_text import (
|
||||
RICH_HTML_EXERCISE_FIELDS,
|
||||
assert_no_inline_media_references_on_create,
|
||||
@@ -93,6 +99,7 @@ CASE COALESCE(
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END
|
||||
""".strip()
|
||||
# Bei Änderung: Migration 062 idx_exercise_skills_exercise_level_rank (SQL-Ausdruck) synchron halten.
|
||||
|
||||
|
||||
def normalize_exercise_skill_level(value) -> Optional[str]:
|
||||
@@ -196,6 +203,26 @@ def _upload_limit_bytes(tenant: TenantContext) -> int:
|
||||
# Pydantic Models
|
||||
# ============================================================================
|
||||
|
||||
# Archetyp-IDs (Maschinenlesbare Ablaufmuster) — konsistent zur technischen Entwurfsspezifikation
|
||||
COMBINATION_ARCHETYPE_IDS = frozenset(
|
||||
{
|
||||
"circuit_rotate_time",
|
||||
"circuit_all_parallel",
|
||||
"sequence_linear",
|
||||
"station_parcour",
|
||||
"pair_superset",
|
||||
"time_domain_interval",
|
||||
"free_method_block",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class CombinationSlotIn(BaseModel):
|
||||
slot_index: int = Field(ge=0, le=99)
|
||||
title: Optional[str] = Field(None, max_length=200)
|
||||
candidate_exercise_ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ExerciseCreate(BaseModel):
|
||||
# Basis-Felder (goal/execution: DB-Constraint mind. eines; Wiki oft nur eines)
|
||||
title: str = Field(..., min_length=3, max_length=300)
|
||||
@@ -229,6 +256,12 @@ class ExerciseCreate(BaseModel):
|
||||
status: str = "draft"
|
||||
club_id: Optional[int] = None
|
||||
|
||||
# Kombinationsübung (Phase 2)
|
||||
exercise_kind: Literal["simple", "combination"] = "simple"
|
||||
method_archetype: Optional[str] = Field(None, max_length=80)
|
||||
method_profile: Dict[str, Any] = Field(default_factory=dict)
|
||||
combination_slots: list[CombinationSlotIn] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_goal_execution(self):
|
||||
g = (self.goal or "").strip() or None
|
||||
@@ -268,6 +301,11 @@ class ExerciseUpdate(BaseModel):
|
||||
# Vereins-Übung: fehlende Copyrights an Datei-Assets nach Prompt-Text setzen (PUT-Retry)
|
||||
default_club_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
||||
|
||||
exercise_kind: Optional[Literal["simple", "combination"]] = None
|
||||
method_archetype: Optional[str] = Field(None, max_length=80)
|
||||
method_profile: Optional[Dict[str, Any]] = None
|
||||
combination_slots: Optional[list[CombinationSlotIn]] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_goal_execution(self):
|
||||
if self.goal is not None:
|
||||
@@ -809,6 +847,174 @@ def _resolve_local_media_file(
|
||||
return path_under_media_root(media_root, asset_storage_key)
|
||||
return _abs_media_path(file_path_db or "", media_root) if file_path_db else None
|
||||
|
||||
|
||||
def _normalize_method_profile_store(raw: Any) -> Dict[str, Any]:
|
||||
if raw is None:
|
||||
return {}
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
raise HTTPException(status_code=400, detail="method_profile muss ein JSON-Objekt sein")
|
||||
|
||||
|
||||
def _validate_archetype_for_kind(kind: str, archetype: Optional[str]) -> None:
|
||||
if kind != "combination":
|
||||
return
|
||||
if archetype is None or not str(archetype).strip():
|
||||
return
|
||||
a = str(archetype).strip()
|
||||
if a not in COMBINATION_ARCHETYPE_IDS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Unbekannter method_archetype. Erlaubt: "
|
||||
+ ", ".join(sorted(COMBINATION_ARCHETYPE_IDS))
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _assert_candidate_exercises_for_combination(cur, tenant: TenantContext, ids: List[int]) -> None:
|
||||
if not ids:
|
||||
return
|
||||
seen: set[int] = set()
|
||||
for cid_raw in ids:
|
||||
cid = int(cid_raw)
|
||||
if cid in seen:
|
||||
continue
|
||||
seen.add(cid)
|
||||
cur.execute(
|
||||
"""SELECT id, exercise_kind, visibility, club_id, created_by
|
||||
FROM exercises WHERE id = %s""",
|
||||
(cid,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=400, detail=f"Slot-Verweis: Übung #{cid} nicht gefunden")
|
||||
rd = r2d(row)
|
||||
k = str(rd.get("exercise_kind") or "simple").strip().lower()
|
||||
if k != "simple":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Slot-Verweis: Übung #{cid} ist eine Kombinationsübung — nur Einzelübungen erlaubt",
|
||||
)
|
||||
if not library_content_visible_to_profile(
|
||||
cur,
|
||||
tenant.profile_id,
|
||||
rd.get("visibility"),
|
||||
rd.get("club_id"),
|
||||
rd.get("created_by"),
|
||||
tenant.global_role,
|
||||
):
|
||||
raise HTTPException(status_code=403, detail=f"Slot-Verweis: keine Leserechte für Übung #{cid}")
|
||||
|
||||
|
||||
def _validate_and_normalize_combination_slots_payload(
|
||||
cur,
|
||||
tenant: TenantContext,
|
||||
slots: Optional[List[CombinationSlotIn]],
|
||||
) -> List[Tuple[int, Optional[str], List[int]]]:
|
||||
if slots is None:
|
||||
return []
|
||||
normalized: Dict[int, Tuple[Optional[str], List[int]]] = {}
|
||||
for s in sorted(slots, key=lambda x: x.slot_index):
|
||||
cid_list_raw = list(s.candidate_exercise_ids or [])
|
||||
cid_list: List[int] = []
|
||||
for x in cid_list_raw:
|
||||
cid_list.append(int(x))
|
||||
title = ((s.title or "").strip()) or None
|
||||
normalized[int(s.slot_index)] = (title, cid_list)
|
||||
out: List[Tuple[int, Optional[str], List[int]]] = []
|
||||
for idx in sorted(normalized.keys()):
|
||||
title, cands = normalized[idx]
|
||||
if not cands:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Station (Index {idx}): mindestens eine Einzelübung (Pool) ist erforderlich",
|
||||
)
|
||||
out.append((idx, title, cands))
|
||||
return out
|
||||
|
||||
|
||||
def replace_combination_slots(
|
||||
cur,
|
||||
tenant: TenantContext,
|
||||
exercise_id: int,
|
||||
slots_norm: List[Tuple[int, Optional[str], List[int]]],
|
||||
) -> None:
|
||||
flat_ids = [cid for _, __, xs in slots_norm for cid in xs]
|
||||
_assert_candidate_exercises_for_combination(cur, tenant, flat_ids)
|
||||
cur.execute("DELETE FROM combination_exercise_slots WHERE exercise_id = %s", (exercise_id,))
|
||||
for slot_index, title, cand_ids in slots_norm:
|
||||
cur.execute(
|
||||
"""INSERT INTO combination_exercise_slots (exercise_id, slot_index, title)
|
||||
VALUES (%s, %s, %s) RETURNING id""",
|
||||
(exercise_id, slot_index, title),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
sid = row["id"] if isinstance(row, dict) else row[0]
|
||||
for so, cid in enumerate(cand_ids):
|
||||
cur.execute(
|
||||
"""INSERT INTO combination_slot_candidates (slot_id, candidate_exercise_id, sort_order)
|
||||
VALUES (%s, %s, %s)""",
|
||||
(sid, int(cid), int(so)),
|
||||
)
|
||||
|
||||
|
||||
def wipe_combination_structure(cur, exercise_id: int) -> None:
|
||||
cur.execute("DELETE FROM combination_exercise_slots WHERE exercise_id = %s", (exercise_id,))
|
||||
|
||||
|
||||
def assert_exercise_not_combination(cur, exercise_id: int) -> None:
|
||||
cur.execute(
|
||||
"SELECT COALESCE(exercise_kind, 'simple') AS exercise_kind FROM exercises WHERE id = %s",
|
||||
(exercise_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
if str(r2d(row).get("exercise_kind") or "simple").strip().lower() == "combination":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Kombinationsübungen unterstützen keine Varianten.",
|
||||
)
|
||||
|
||||
|
||||
def load_combination_slots_for_exercise(cur, exercise_id: int) -> List[dict]:
|
||||
"""Stationsliste einer Kombinationsübung (gleiches Format wie GET /api/exercises/:id)."""
|
||||
cur.execute(
|
||||
"""SELECT id, slot_index, title FROM combination_exercise_slots
|
||||
WHERE exercise_id = %s ORDER BY slot_index ASC, id ASC""",
|
||||
(exercise_id,),
|
||||
)
|
||||
slot_rows = [r2d(r) for r in cur.fetchall()]
|
||||
slots_out: List[dict] = []
|
||||
for sr in slot_rows:
|
||||
slot_pk = sr["id"]
|
||||
cur.execute(
|
||||
"""SELECT candidate_exercise_id FROM combination_slot_candidates
|
||||
WHERE slot_id = %s ORDER BY sort_order ASC, id ASC""",
|
||||
(slot_pk,),
|
||||
)
|
||||
crows = cur.fetchall()
|
||||
cids = [int(r2d(c)["candidate_exercise_id"]) for c in crows]
|
||||
cand_meta: Dict[int, Optional[str]] = {}
|
||||
if cids:
|
||||
ph = ",".join(["%s"] * len(cids))
|
||||
cur.execute(
|
||||
f"SELECT id, title FROM exercises WHERE id IN ({ph})",
|
||||
tuple(cids),
|
||||
)
|
||||
cand_meta = {int(r2d(x)["id"]): r2d(x).get("title") for x in cur.fetchall()}
|
||||
slots_out.append(
|
||||
{
|
||||
"slot_index": sr["slot_index"],
|
||||
"title": sr.get("title"),
|
||||
"candidate_exercise_ids": cids,
|
||||
"candidates": [{"exercise_id": cid, "title": cand_meta.get(cid)} for cid in cids],
|
||||
}
|
||||
)
|
||||
return slots_out
|
||||
|
||||
|
||||
def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
"""
|
||||
Lädt alle M:N Relations für eine Übung und gibt ein vollständiges
|
||||
@@ -921,7 +1127,8 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
"""SELECT em.id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
|
||||
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context,
|
||||
em.media_asset_id, ma.copyright_notice AS asset_copyright_notice,
|
||||
ma.lifecycle_state AS asset_lifecycle_state
|
||||
ma.lifecycle_state AS asset_lifecycle_state,
|
||||
ma.legal_hold_active AS asset_legal_hold_active
|
||||
FROM exercise_media em
|
||||
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
|
||||
WHERE em.exercise_id = %s
|
||||
@@ -930,6 +1137,14 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
)
|
||||
exercise["media"] = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
mp_raw = exercise.get("method_profile")
|
||||
exercise["method_profile"] = mp_raw if isinstance(mp_raw, dict) else {}
|
||||
exercise["exercise_kind"] = str(exercise.get("exercise_kind") or "simple").strip().lower()
|
||||
|
||||
exercise["combination_slots"] = []
|
||||
if exercise["exercise_kind"] == "combination":
|
||||
exercise["combination_slots"] = load_combination_slots_for_exercise(cur, exercise_id)
|
||||
|
||||
return exercise
|
||||
|
||||
|
||||
@@ -1442,6 +1657,20 @@ def bulk_patch_exercises_metadata(
|
||||
}
|
||||
|
||||
|
||||
def _parse_cursor_updated_at_list(raw: Optional[str]) -> datetime:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
raise HTTPException(status_code=400, detail="cursor_updated_at leer")
|
||||
if s.endswith("Z"):
|
||||
s = s[:-1] + "+00:00"
|
||||
try:
|
||||
return datetime.fromisoformat(s)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="cursor_updated_at ungültig (ISO-8601 erwartet)"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises")
|
||||
def list_exercises(
|
||||
focus_area_ids: list[int] = Query(default=[], description="ODER: mind. einer dieser Fokusbereiche"),
|
||||
@@ -1467,6 +1696,15 @@ def list_exercises(
|
||||
),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
cursor_updated_at: Optional[str] = Query(
|
||||
default=None,
|
||||
description="Keyset: ISO-8601 von updated_at der letzten Zeile; zusammen mit cursor_id (offset dann 0)",
|
||||
),
|
||||
cursor_id: Optional[int] = Query(
|
||||
default=None,
|
||||
ge=1,
|
||||
description="Keyset: id der letzten Zeile (Tie‑break bei gleichem updated_at); mit cursor_updated_at",
|
||||
),
|
||||
include_variants: bool = Query(
|
||||
default=False,
|
||||
description="Wenn true: Feld variants[] pro Übung (id, variant_name, sequence_order) für Planung/UI",
|
||||
@@ -1525,15 +1763,41 @@ def list_exercises(
|
||||
default=False,
|
||||
description="Nur Übungen, die vom aktuellen Profil angelegt wurden (created_by = Profil)",
|
||||
),
|
||||
exercise_kind_any: list[str] = Query(
|
||||
default=[],
|
||||
description="ODER: mind. einer dieser Übungsarten — simple oder combination",
|
||||
),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Liste aller Übungen mit Filtern.
|
||||
Lightweight Response (ohne M:N Details, nur IDs und Namen).
|
||||
Optional include_variants für Variantenauswahl in der Trainingsplanung.
|
||||
Keyset: cursor_updated_at + cursor_id ersetzt große OFFSET-Werte (Sortierung: updated_at DESC, id DESC).
|
||||
"""
|
||||
cursor_updated_at = unwrap_query_default(cursor_updated_at)
|
||||
cursor_id = unwrap_query_default(cursor_id)
|
||||
limit = unwrap_query_default(limit)
|
||||
offset = unwrap_query_default(offset)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
|
||||
c_ts_raw = (cursor_updated_at or "").strip() or None
|
||||
use_keyset = c_ts_raw is not None and cursor_id is not None
|
||||
if (c_ts_raw is not None) != (cursor_id is not None):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="cursor_updated_at und cursor_id müssen zusammen gesetzt werden",
|
||||
)
|
||||
if use_keyset and offset != 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Keyset-Pagination: offset nicht kombinieren (nur cursor_* oder nur offset)",
|
||||
)
|
||||
cursor_ts_val: Optional[datetime] = None
|
||||
if use_keyset:
|
||||
cursor_ts_val = _parse_cursor_updated_at_list(c_ts_raw)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
@@ -1555,6 +1819,21 @@ def list_exercises(
|
||||
where.append("e.created_by = %s")
|
||||
params.append(profile_id)
|
||||
|
||||
ek_filtered: List[str] = []
|
||||
if exercise_kind_any:
|
||||
for raw in exercise_kind_any:
|
||||
s = str(raw or "").strip().lower()
|
||||
if not s:
|
||||
continue
|
||||
if s not in ("simple", "combination"):
|
||||
raise HTTPException(status_code=400, detail="exercise_kind_any: nur simple oder combination")
|
||||
if s not in ek_filtered:
|
||||
ek_filtered.append(s)
|
||||
if ek_filtered:
|
||||
ph = ",".join(["%s"] * len(ek_filtered))
|
||||
where.append(f"(LOWER(TRIM(COALESCE(e.exercise_kind::text,''))) IN ({ph}))")
|
||||
params.extend(ek_filtered)
|
||||
|
||||
vis_list = _merge_str_any(visibility_any, visibility)
|
||||
if vis_list:
|
||||
ph = ",".join(["%s"] * len(vis_list))
|
||||
@@ -1751,6 +2030,12 @@ def list_exercises(
|
||||
where.append("e.search_vector @@ plainto_tsquery('german', %s)")
|
||||
params.append(qtext)
|
||||
|
||||
if cursor_ts_val is not None and cursor_id is not None:
|
||||
where.append(
|
||||
"(e.updated_at < %s OR (e.updated_at = %s AND e.id < %s))"
|
||||
)
|
||||
params.extend([cursor_ts_val, cursor_ts_val, cursor_id])
|
||||
|
||||
variants_sql = ""
|
||||
if include_variants:
|
||||
variants_sql = """,
|
||||
@@ -1773,6 +2058,7 @@ def list_exercises(
|
||||
# Query (primary_focus_name für Listen-Ansicht gemäß Spec-Beispiel „focus_area“-Label)
|
||||
query = f"""
|
||||
SELECT e.id, e.title, e.summary, e.visibility, e.status,
|
||||
e.exercise_kind, e.method_archetype,
|
||||
e.created_by, p.name as creator_name,
|
||||
e.club_id, c.name as club_name,
|
||||
e.created_at, e.updated_at,
|
||||
@@ -1815,10 +2101,10 @@ def list_exercises(
|
||||
LEFT JOIN profiles p ON e.created_by = p.id
|
||||
LEFT JOIN clubs c ON e.club_id = c.id
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY e.updated_at DESC
|
||||
ORDER BY e.updated_at DESC, e.id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
"""
|
||||
params.extend([limit, offset])
|
||||
params.extend([limit, 0 if use_keyset else offset])
|
||||
|
||||
cur.execute(query, params)
|
||||
rows = cur.fetchall()
|
||||
@@ -1826,6 +2112,7 @@ def list_exercises(
|
||||
out = []
|
||||
for r in rows:
|
||||
d = r2d(r)
|
||||
d["exercise_kind"] = str(d.get("exercise_kind") or "simple").strip().lower()
|
||||
pfn = d.get("primary_focus_name")
|
||||
d["focus_area"] = pfn
|
||||
d["focus_area_names"] = _coerce_json_str_list(d.get("focus_area_names"))
|
||||
@@ -1844,6 +2131,58 @@ def list_exercises(
|
||||
return out
|
||||
|
||||
|
||||
def list_exercises_like_get(
|
||||
tenant: TenantContext,
|
||||
*,
|
||||
created_by_me: bool,
|
||||
status: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Programmatischer Aufruf mit gleicher Semantik wie GET /api/exercises
|
||||
(ohne FastAPI-Query-Default-Objekte an list_exercises zu übergeben).
|
||||
"""
|
||||
return list_exercises(
|
||||
focus_area_ids=[],
|
||||
focus_area=None,
|
||||
visibility_any=[],
|
||||
visibility=None,
|
||||
status_any=[],
|
||||
status=status,
|
||||
skill_ids=[],
|
||||
skill_id=None,
|
||||
style_direction_ids=[],
|
||||
style_direction_id=None,
|
||||
training_type_ids=[],
|
||||
training_type_id=None,
|
||||
target_group_ids=[],
|
||||
target_group_id=None,
|
||||
skill_min_level=None,
|
||||
skill_max_level=None,
|
||||
search=None,
|
||||
ai_search=None,
|
||||
limit=limit,
|
||||
offset=0,
|
||||
include_variants=False,
|
||||
visibility_exclude_any=[],
|
||||
status_exclude_any=[],
|
||||
exclude_without_focus=False,
|
||||
focus_only_without_focus_areas=False,
|
||||
focus_area_must_include_ids=[],
|
||||
focus_area_must_exclude_ids=[],
|
||||
style_direction_must_include_ids=[],
|
||||
style_direction_must_exclude_ids=[],
|
||||
training_type_must_include_ids=[],
|
||||
training_type_must_exclude_ids=[],
|
||||
target_group_must_include_ids=[],
|
||||
target_group_must_exclude_ids=[],
|
||||
include_archived=False,
|
||||
created_by_me=created_by_me,
|
||||
exercise_kind_any=[],
|
||||
tenant=tenant,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises/{exercise_id}")
|
||||
def get_exercise(
|
||||
exercise_id: int,
|
||||
@@ -1910,16 +2249,39 @@ def create_exercise(
|
||||
cur, profile_id, tenant.global_role, body.visibility, club_id
|
||||
)
|
||||
|
||||
kind_clean = str(body.exercise_kind or "simple").strip().lower()
|
||||
if kind_clean not in ("simple", "combination"):
|
||||
raise HTTPException(status_code=400, detail="exercise_kind: simple oder combination")
|
||||
|
||||
prof_dict = _normalize_method_profile_store(body.method_profile)
|
||||
arch_raw = body.method_archetype
|
||||
arch_val = (arch_raw.strip() if isinstance(arch_raw, str) and arch_raw.strip() else None)
|
||||
_validate_archetype_for_kind(kind_clean, arch_val)
|
||||
|
||||
slots_norm: List[Tuple[int, Optional[str], List[int]]] = []
|
||||
if kind_clean == "combination":
|
||||
slots_norm = _validate_and_normalize_combination_slots_payload(
|
||||
cur, tenant, body.combination_slots or []
|
||||
)
|
||||
if not slots_norm:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Kombinationsübung: mindestens eine Station mit Übungen nötig",
|
||||
)
|
||||
|
||||
mp_json = Json(prof_dict if kind_clean == "combination" else {})
|
||||
arch_db = arch_val if kind_clean == "combination" else None
|
||||
|
||||
# Equipment als JSONB
|
||||
equipment_json = json.dumps(body.equipment) if body.equipment else None
|
||||
|
||||
# INSERT
|
||||
cur.execute(
|
||||
"""INSERT INTO exercises
|
||||
(title, summary, goal, execution, preparation, trainer_notes,
|
||||
duration_min, duration_max, group_size_min, group_size_max,
|
||||
equipment, visibility, status, created_by, club_id)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
equipment, visibility, status, created_by, club_id,
|
||||
exercise_kind, method_archetype, method_profile)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id""",
|
||||
(
|
||||
body.title, body.summary, body.goal, body.execution,
|
||||
@@ -1928,11 +2290,15 @@ def create_exercise(
|
||||
body.group_size_min, body.group_size_max,
|
||||
equipment_json,
|
||||
body.visibility, body.status, profile_id, club_id,
|
||||
)
|
||||
kind_clean, arch_db, mp_json,
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
exercise_id = row['id'] if isinstance(row, dict) else row[0]
|
||||
|
||||
if kind_clean == "combination":
|
||||
replace_combination_slots(cur, tenant, exercise_id, slots_norm)
|
||||
|
||||
data = body.dict()
|
||||
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
||||
if (body.visibility or "").strip().lower() == "club":
|
||||
@@ -1960,7 +2326,7 @@ def update_exercise(
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute(
|
||||
f"""SELECT created_by, visibility, club_id,
|
||||
f"""SELECT created_by, visibility, club_id, exercise_kind, method_archetype, method_profile,
|
||||
{", ".join(sorted(RICH_HTML_EXERCISE_FIELDS))}
|
||||
FROM exercises WHERE id = %s""",
|
||||
(exercise_id,),
|
||||
@@ -1990,6 +2356,84 @@ def update_exercise(
|
||||
default_official_copy = data.pop("default_official_media_copyright", None)
|
||||
default_club_copy = data.pop("default_club_media_copyright", None)
|
||||
|
||||
combo_slots_provided = "combination_slots" in data
|
||||
combo_slots_payload = data.pop("combination_slots", None)
|
||||
|
||||
ec_kind_was = str(rd_full.get("exercise_kind") or "simple").strip().lower()
|
||||
ek_provided = "exercise_kind" in data
|
||||
next_kind = ec_kind_was
|
||||
if ek_provided:
|
||||
next_kind = str(data.pop("exercise_kind") or "simple").strip().lower()
|
||||
|
||||
arche_provided = "method_archetype" in data
|
||||
meth_prof_provided = "method_profile" in data
|
||||
|
||||
next_ma_db = rd_full.get("method_archetype")
|
||||
if isinstance(next_ma_db, str):
|
||||
next_ma_db = next_ma_db.strip() or None
|
||||
else:
|
||||
next_ma_db = None
|
||||
|
||||
mp_row = rd_full.get("method_profile")
|
||||
next_mp_db = mp_row if isinstance(mp_row, dict) else {}
|
||||
|
||||
if ek_provided and next_kind not in ("simple", "combination"):
|
||||
raise HTTPException(status_code=400, detail="exercise_kind: simple oder combination")
|
||||
|
||||
if arche_provided:
|
||||
va = data.pop("method_archetype")
|
||||
if va is None or (isinstance(va, str) and not va.strip()):
|
||||
next_ma_db = None
|
||||
elif isinstance(va, str):
|
||||
next_ma_db = va.strip() or None
|
||||
else:
|
||||
next_ma_db = None
|
||||
|
||||
if meth_prof_provided:
|
||||
next_mp_db = _normalize_method_profile_store(data.pop("method_profile"))
|
||||
|
||||
if next_kind == "simple":
|
||||
next_ma_db = None
|
||||
next_mp_db = {}
|
||||
|
||||
_validate_archetype_for_kind(next_kind, next_ma_db)
|
||||
|
||||
if ec_kind_was == "simple" and next_kind == "combination":
|
||||
if not combo_slots_provided:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail='Umschalten auf Kombinationsübung: Feld "combination_slots" ist erforderlich',
|
||||
)
|
||||
|
||||
combo_slots_normalized: Optional[List[Tuple[int, Optional[str], List[int]]]] = None
|
||||
if combo_slots_provided:
|
||||
if next_kind != "combination":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="combination_slots nur bei exercise_kind=combination erlaubt",
|
||||
)
|
||||
slots_in_raw = combo_slots_payload if combo_slots_payload is not None else []
|
||||
slots_in: List[CombinationSlotIn] = []
|
||||
for s in slots_in_raw:
|
||||
if isinstance(s, CombinationSlotIn):
|
||||
slots_in.append(s)
|
||||
elif isinstance(s, dict):
|
||||
slots_in.append(CombinationSlotIn(**s))
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Ungültige combination_slots Payload-Struktur")
|
||||
combo_slots_normalized = _validate_and_normalize_combination_slots_payload(
|
||||
cur, tenant, slots_in
|
||||
)
|
||||
if not combo_slots_normalized:
|
||||
raise HTTPException(status_code=400, detail="Kombinationsübung: mindestens eine Station mit Übungen")
|
||||
|
||||
update_combo_cols = (
|
||||
ek_provided
|
||||
or arche_provided
|
||||
or meth_prof_provided
|
||||
or (next_kind == "simple" and ec_kind_was != "simple")
|
||||
)
|
||||
|
||||
merged_rich = {fld: rich_row.get(fld) for fld in RICH_HTML_EXERCISE_FIELDS}
|
||||
for fld in RICH_HTML_EXERCISE_FIELDS:
|
||||
if fld not in data:
|
||||
@@ -2061,11 +2505,27 @@ def update_exercise(
|
||||
fields.append("equipment = %s")
|
||||
params.append(json.dumps(data["equipment"]) if data["equipment"] else None)
|
||||
|
||||
if update_combo_cols:
|
||||
if ek_provided:
|
||||
fields.append("exercise_kind = %s")
|
||||
params.append(next_kind)
|
||||
fields.append("method_archetype = %s")
|
||||
params.append(next_ma_db)
|
||||
fields.append("method_profile = %s")
|
||||
params.append(Json(next_mp_db))
|
||||
|
||||
if fields:
|
||||
fields.append("updated_at = NOW()")
|
||||
params.append(exercise_id)
|
||||
query = f"UPDATE exercises SET {', '.join(fields)} WHERE id = %s"
|
||||
cur.execute(query, params)
|
||||
elif combo_slots_normalized is not None:
|
||||
cur.execute("UPDATE exercises SET updated_at = NOW() WHERE id = %s", (exercise_id,))
|
||||
|
||||
if combo_slots_normalized is not None:
|
||||
replace_combination_slots(cur, tenant, exercise_id, combo_slots_normalized)
|
||||
elif ec_kind_was == "combination" and next_kind == "simple":
|
||||
wipe_combination_structure(cur, exercise_id)
|
||||
|
||||
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
||||
try:
|
||||
@@ -2141,6 +2601,7 @@ def reorder_exercise_variants(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
|
||||
cur.execute(
|
||||
"SELECT id FROM exercise_variants WHERE exercise_id = %s",
|
||||
@@ -2175,6 +2636,7 @@ def create_exercise_variant(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
_validate_variant_prerequisite(cur, exercise_id, body.prerequisite_variant_id)
|
||||
|
||||
eq_json = _variant_equipment_json(body.equipment_changes)
|
||||
@@ -2239,6 +2701,7 @@ def update_exercise_variant(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
old = _fetch_variant_row(cur, exercise_id, variant_id)
|
||||
|
||||
if "variant_name" in data and data["variant_name"] is not None:
|
||||
@@ -2320,6 +2783,7 @@ def delete_exercise_variant(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
_fetch_variant_row(cur, exercise_id, variant_id)
|
||||
|
||||
cur.execute(
|
||||
@@ -2464,7 +2928,8 @@ def _fetch_media_row(cur, exercise_id: int, media_id: int) -> Optional[dict]:
|
||||
"""SELECT em.id, em.exercise_id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
|
||||
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context, em.created_at,
|
||||
em.media_asset_id, ma.storage_key AS asset_storage_key,
|
||||
ma.lifecycle_state AS asset_lifecycle_state
|
||||
ma.lifecycle_state AS asset_lifecycle_state,
|
||||
ma.legal_hold_active AS asset_legal_hold_active
|
||||
FROM exercise_media em
|
||||
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
|
||||
WHERE em.id = %s AND em.exercise_id = %s""",
|
||||
@@ -2494,6 +2959,12 @@ def download_exercise_media_file(
|
||||
if (media.get("embed_url") or "").strip():
|
||||
raise HTTPException(status_code=400, detail="Embed-Medien haben keine Datei-URL")
|
||||
|
||||
if bool(media.get("asset_legal_hold_active")):
|
||||
raise HTTPException(
|
||||
status_code=451,
|
||||
detail={"code": "LEGAL_HOLD_ACTIVE", "message": "Dieses Medium ist gesperrt und steht nicht zur Verfügung."}
|
||||
)
|
||||
|
||||
lc = (media.get("asset_lifecycle_state") or "active").strip().lower()
|
||||
if lc == "trash_hidden":
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
@@ -2526,6 +2997,21 @@ async def upload_exercise_media(
|
||||
description: str = Form(""),
|
||||
context: str = Form("ablauf"),
|
||||
is_primary: bool = Form(False),
|
||||
copyright_notice: Optional[str] = Form(None),
|
||||
# P-06: Rechte-Erklaerung (Pflicht bei Datei-Upload mit neuem media_asset)
|
||||
rights_holder_confirmed: Optional[bool] = Form(None),
|
||||
contains_identifiable_persons: Optional[bool] = Form(None),
|
||||
person_consent_confirmed: Optional[bool] = Form(None),
|
||||
person_consent_context: Optional[str] = Form(None),
|
||||
contains_minors: Optional[bool] = Form(None),
|
||||
parental_consent_confirmed: Optional[bool] = Form(None),
|
||||
parental_consent_context: Optional[str] = Form(None),
|
||||
contains_music: Optional[bool] = Form(None),
|
||||
music_rights_confirmed: Optional[bool] = Form(None),
|
||||
music_rights_context: Optional[str] = Form(None),
|
||||
contains_third_party_content: Optional[bool] = Form(None),
|
||||
third_party_rights_confirmed: Optional[bool] = Form(None),
|
||||
third_party_rights_context: Optional[str] = Form(None),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
if media_type not in ("image", "video", "document", "sketch"):
|
||||
@@ -2764,11 +3250,12 @@ async def upload_exercise_media(
|
||||
if not dest_path.is_file():
|
||||
dest_path.write_bytes(raw)
|
||||
|
||||
clean_cr = (copyright_notice or "").strip() or None
|
||||
cur.execute(
|
||||
"""INSERT INTO media_assets (
|
||||
mime_type, byte_size, sha256, original_filename, visibility, club_id,
|
||||
uploaded_by_profile_id, copyright_notice, storage_backend, storage_key, lifecycle_state
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, NULL, 'local', %s, 'active')
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'local', %s, 'active')
|
||||
RETURNING id""",
|
||||
(
|
||||
mime,
|
||||
@@ -2778,11 +3265,31 @@ async def upload_exercise_media(
|
||||
ex_vis,
|
||||
dedupe_club,
|
||||
profile_id,
|
||||
clean_cr,
|
||||
storage_key,
|
||||
),
|
||||
)
|
||||
ar = cur.fetchone()
|
||||
aid = r2d(ar)["id"]
|
||||
# P-06: Rechterklaerung fuer neues Media-Asset validieren und schreiben
|
||||
p06_decl = {
|
||||
"rights_holder_confirmed": rights_holder_confirmed,
|
||||
"contains_identifiable_persons": contains_identifiable_persons,
|
||||
"person_consent_confirmed": person_consent_confirmed,
|
||||
"person_consent_context": person_consent_context,
|
||||
"contains_minors": contains_minors,
|
||||
"parental_consent_confirmed": parental_consent_confirmed,
|
||||
"parental_consent_context": parental_consent_context,
|
||||
"contains_music": contains_music,
|
||||
"music_rights_confirmed": music_rights_confirmed,
|
||||
"music_rights_context": music_rights_context,
|
||||
"contains_third_party_content": contains_third_party_content,
|
||||
"third_party_rights_confirmed": third_party_rights_confirmed,
|
||||
"third_party_rights_context": third_party_rights_context,
|
||||
}
|
||||
validate_rights_declaration(p06_decl, ex_vis)
|
||||
write_rights_declaration(cur, aid, profile_id, "upload", ex_vis, p06_decl)
|
||||
update_rights_quick_fields(cur, aid, ex_vis)
|
||||
db_path = f"/media/{storage_key}"
|
||||
cur.execute(
|
||||
f"""INSERT INTO exercise_media (
|
||||
@@ -2843,7 +3350,7 @@ def attach_exercise_media_from_asset(
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id, mime_type, byte_size, original_filename, visibility, club_id,
|
||||
uploaded_by_profile_id, storage_key, lifecycle_state
|
||||
uploaded_by_profile_id, storage_key, lifecycle_state, legal_hold_active
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(body.media_asset_id,),
|
||||
)
|
||||
@@ -2856,6 +3363,8 @@ def attach_exercise_media_from_asset(
|
||||
status_code=400,
|
||||
detail="Nur aktive Archiv-Medien können verknüpft werden",
|
||||
)
|
||||
# P-11: Legal Hold verhindert neue Einbindung in Übungen
|
||||
assert_not_under_legal_hold(asset)
|
||||
|
||||
if not library_content_visible_to_profile(
|
||||
cur,
|
||||
@@ -2867,6 +3376,15 @@ def attach_exercise_media_from_asset(
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Archiv-Medium")
|
||||
|
||||
# P-06: Rechtspruefung — Asset muss Einwilligung fuer Sichtbarkeit der Uebung haben
|
||||
cur.execute(
|
||||
"SELECT visibility FROM exercises WHERE id = %s",
|
||||
(exercise_id,),
|
||||
)
|
||||
ex_row = cur.fetchone()
|
||||
ex_vis = (r2d(ex_row).get("visibility") or "private").strip().lower() if ex_row else "private"
|
||||
assert_rights_for_exercise_link(cur, body.media_asset_id, ex_vis)
|
||||
|
||||
cur.execute(
|
||||
"SELECT 1 FROM exercise_media WHERE exercise_id = %s AND media_asset_id = %s",
|
||||
(exercise_id, body.media_asset_id),
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
"""
|
||||
Rechtstexte (Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie).
|
||||
|
||||
Öffentlich (kein Auth):
|
||||
GET /api/legal-documents/{document_type}/published
|
||||
|
||||
Superadmin only:
|
||||
GET /api/admin/legal-documents – Liste aller Versionen
|
||||
POST /api/admin/legal-documents – Neuen Entwurf anlegen
|
||||
GET /api/admin/legal-documents/{id} – Einzelnes Dokument
|
||||
PUT /api/admin/legal-documents/{id} – Entwurf bearbeiten
|
||||
POST /api/admin/legal-documents/{id}/publish – Veröffentlichen
|
||||
POST /api/admin/legal-documents/{id}/archive – Archivieren
|
||||
GET /api/admin/legal-documents/{id}/audit – Änderungslog
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
# ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug.
|
||||
# Öffentlicher GET-Endpoint ohne jegliche Auth; Admin-Endpoints nutzen require_auth + is_superadmin().
|
||||
# Eingetragen in backend/scripts/check_access_layer_hints.py EXEMPT_ROUTERS.
|
||||
router = APIRouter(tags=["legal_documents"])
|
||||
|
||||
VALID_TYPES = {"impressum", "privacy_policy", "terms_of_use", "media_policy"}
|
||||
|
||||
|
||||
def _require_superadmin(session: dict):
|
||||
role = (session.get("role") or "").lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
class LegalDocumentCreate(BaseModel):
|
||||
document_type: str
|
||||
title: str
|
||||
content_sections: List[Dict[str, Any]] = []
|
||||
change_note: Optional[str] = None
|
||||
|
||||
|
||||
class LegalDocumentUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
content_sections: Optional[List[Dict[str, Any]]] = None
|
||||
change_note: Optional[str] = None
|
||||
|
||||
|
||||
class PublishRequest(BaseModel):
|
||||
change_note: Optional[str] = None
|
||||
|
||||
|
||||
# ─── Public endpoint ────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/api/legal-documents/{document_type}/published")
|
||||
def get_published_legal_document(document_type: str):
|
||||
"""Liefert das aktuell veröffentlichte Dokument oder null. Kein Auth erforderlich."""
|
||||
if document_type not in VALID_TYPES:
|
||||
raise HTTPException(status_code=404, detail="Unbekannter Dokumententyp")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, document_type, version, title, content_sections,
|
||||
status, change_note, published_at, updated_at
|
||||
FROM legal_documents
|
||||
WHERE document_type = %s AND status = 'published'
|
||||
LIMIT 1
|
||||
""",
|
||||
(document_type,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
return None
|
||||
|
||||
doc = r2d(row)
|
||||
return doc
|
||||
|
||||
|
||||
# ─── Superadmin endpoints ────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/api/admin/legal-documents")
|
||||
def list_legal_documents(
|
||||
document_type: Optional[str] = None,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Alle Versionen aller Rechtstexte (oder gefiltert nach document_type)."""
|
||||
_require_superadmin(session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if document_type:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.id, d.document_type, d.version, d.title, d.status,
|
||||
d.change_note, d.created_at, d.updated_at, d.published_at,
|
||||
p.name AS created_by_name
|
||||
FROM legal_documents d
|
||||
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
|
||||
WHERE d.document_type = %s
|
||||
ORDER BY d.document_type, d.version DESC
|
||||
""",
|
||||
(document_type,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.id, d.document_type, d.version, d.title, d.status,
|
||||
d.change_note, d.created_at, d.updated_at, d.published_at,
|
||||
p.name AS created_by_name
|
||||
FROM legal_documents d
|
||||
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
|
||||
ORDER BY d.document_type, d.version DESC
|
||||
"""
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [r2d(r) for r in rows]
|
||||
|
||||
|
||||
@router.post("/api/admin/legal-documents", status_code=201)
|
||||
def create_legal_document(
|
||||
body: LegalDocumentCreate,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Neuen Entwurf anlegen. Versionsnummer = max(vorherige) + 1."""
|
||||
_require_superadmin(session)
|
||||
|
||||
if body.document_type not in VALID_TYPES:
|
||||
raise HTTPException(status_code=422, detail="Ungültiger document_type")
|
||||
|
||||
profile_id = session["profile_id"]
|
||||
|
||||
import json as _json
|
||||
sections_json = _json.dumps(body.content_sections, ensure_ascii=False)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT COALESCE(MAX(version), 0) FROM legal_documents WHERE document_type = %s",
|
||||
(body.document_type,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
next_version = list(row.values())[0] + 1
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_documents
|
||||
(document_type, version, title, content_sections, status, change_note, created_by_profile_id)
|
||||
VALUES (%s, %s, %s, %s::jsonb, 'draft', %s, %s)
|
||||
RETURNING id, document_type, version, title, content_sections,
|
||||
status, change_note, created_at, updated_at
|
||||
""",
|
||||
(body.document_type, next_version, body.title, sections_json, body.change_note, profile_id),
|
||||
)
|
||||
new_row = cur.fetchone()
|
||||
new_id = list(new_row.values())[0]
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_document_audit (legal_document_id, action, changed_by_profile_id, change_note)
|
||||
VALUES (%s, 'created', %s, %s)
|
||||
""",
|
||||
(new_id, profile_id, body.change_note),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return r2d(new_row)
|
||||
|
||||
|
||||
@router.get("/api/admin/legal-documents/{doc_id}")
|
||||
def get_legal_document(doc_id: int, session: dict = Depends(require_auth)):
|
||||
"""Einzelnes Dokument (alle Felder inkl. content_sections)."""
|
||||
_require_superadmin(session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.id, d.document_type, d.version, d.title, d.content_sections,
|
||||
d.status, d.change_note, d.created_at, d.updated_at,
|
||||
d.published_at, d.created_by_profile_id,
|
||||
p.name AS created_by_name,
|
||||
pb.name AS published_by_name
|
||||
FROM legal_documents d
|
||||
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
|
||||
LEFT JOIN profiles pb ON pb.id = d.published_by_profile_id
|
||||
WHERE d.id = %s
|
||||
""",
|
||||
(doc_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.put("/api/admin/legal-documents/{doc_id}")
|
||||
def update_legal_document(
|
||||
doc_id: int,
|
||||
body: LegalDocumentUpdate,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Entwurf bearbeiten. Nur status='draft' kann bearbeitet werden."""
|
||||
_require_superadmin(session)
|
||||
|
||||
profile_id = session["profile_id"]
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, status, title, content_sections, change_note FROM legal_documents WHERE id = %s",
|
||||
(doc_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
doc = r2d(row)
|
||||
if doc["status"] != "draft":
|
||||
raise HTTPException(status_code=409, detail="Nur Entwürfe können bearbeitet werden")
|
||||
|
||||
import json as _json
|
||||
|
||||
new_title = body.title if body.title is not None else doc["title"]
|
||||
new_sections = body.content_sections if body.content_sections is not None else doc["content_sections"]
|
||||
new_note = body.change_note if body.change_note is not None else doc["change_note"]
|
||||
sections_json = _json.dumps(new_sections, ensure_ascii=False)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE legal_documents
|
||||
SET title = %s, content_sections = %s::jsonb, change_note = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, document_type, version, title, content_sections,
|
||||
status, change_note, created_at, updated_at
|
||||
""",
|
||||
(new_title, sections_json, new_note, doc_id),
|
||||
)
|
||||
updated = cur.fetchone()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_document_audit (legal_document_id, action, changed_by_profile_id, change_note)
|
||||
VALUES (%s, 'updated', %s, %s)
|
||||
""",
|
||||
(doc_id, profile_id, new_note),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return r2d(updated)
|
||||
|
||||
|
||||
@router.post("/api/admin/legal-documents/{doc_id}/publish")
|
||||
def publish_legal_document(
|
||||
doc_id: int,
|
||||
body: PublishRequest = PublishRequest(),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Veröffentlicht dieses Dokument. Ein bisher veröffentlichtes Dokument desselben
|
||||
Typs wird automatisch auf 'archived' gesetzt (partial unique index erzwingt dies).
|
||||
"""
|
||||
_require_superadmin(session)
|
||||
|
||||
profile_id = session["profile_id"]
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, document_type, status FROM legal_documents WHERE id = %s",
|
||||
(doc_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
doc = r2d(row)
|
||||
if doc["status"] == "published":
|
||||
raise HTTPException(status_code=409, detail="Dokument ist bereits veröffentlicht")
|
||||
if doc["status"] == "archived":
|
||||
raise HTTPException(status_code=409, detail="Archivierte Dokumente können nicht veröffentlicht werden")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
# Vorheriges published-Dokument desselben Typs archivieren
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE legal_documents
|
||||
SET status = 'archived', updated_at = NOW()
|
||||
WHERE document_type = %s AND status = 'published' AND id != %s
|
||||
""",
|
||||
(doc["document_type"], doc_id),
|
||||
)
|
||||
# Dieses Dokument veröffentlichen
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE legal_documents
|
||||
SET status = 'published', published_at = NOW(),
|
||||
published_by_profile_id = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, document_type, version, title, content_sections,
|
||||
status, change_note, published_at, updated_at
|
||||
""",
|
||||
(profile_id, doc_id),
|
||||
)
|
||||
updated = cur.fetchone()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_document_audit
|
||||
(legal_document_id, action, changed_by_profile_id, change_note, previous_status)
|
||||
VALUES (%s, 'published', %s, %s, %s)
|
||||
""",
|
||||
(doc_id, profile_id, body.change_note, doc["status"]),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return r2d(updated)
|
||||
|
||||
|
||||
@router.post("/api/admin/legal-documents/{doc_id}/archive")
|
||||
def archive_legal_document(
|
||||
doc_id: int,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Archiviert ein Dokument. Veröffentlichte Dokumente dürfen nur archiviert werden wenn kein anderes published ist."""
|
||||
_require_superadmin(session)
|
||||
|
||||
profile_id = session["profile_id"]
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, status FROM legal_documents WHERE id = %s",
|
||||
(doc_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
doc = r2d(row)
|
||||
if doc["status"] == "archived":
|
||||
raise HTTPException(status_code=409, detail="Dokument ist bereits archiviert")
|
||||
|
||||
prev_status = doc["status"]
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE legal_documents
|
||||
SET status = 'archived', updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, document_type, version, title, status, updated_at
|
||||
""",
|
||||
(doc_id,),
|
||||
)
|
||||
updated = cur.fetchone()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_document_audit
|
||||
(legal_document_id, action, changed_by_profile_id, previous_status)
|
||||
VALUES (%s, 'archived', %s, %s)
|
||||
""",
|
||||
(doc_id, profile_id, prev_status),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return r2d(updated)
|
||||
|
||||
|
||||
@router.post("/api/admin/legal-documents/{doc_id}/copy-as-draft", status_code=201)
|
||||
def copy_legal_document_as_draft(
|
||||
doc_id: int,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Kopiert ein beliebiges Dokument (egal welcher Status) als neuen Entwurf mit
|
||||
nächster Versionsnummer. Inhalt und Titel werden übernommen.
|
||||
"""
|
||||
_require_superadmin(session)
|
||||
|
||||
profile_id = session["profile_id"]
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, document_type, title, content_sections FROM legal_documents WHERE id = %s",
|
||||
(doc_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
src = r2d(row)
|
||||
|
||||
import json as _json
|
||||
sections_json = _json.dumps(src["content_sections"], ensure_ascii=False)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT COALESCE(MAX(version), 0) FROM legal_documents WHERE document_type = %s",
|
||||
(src["document_type"],),
|
||||
)
|
||||
row2 = cur.fetchone()
|
||||
next_version = list(row2.values())[0] + 1
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_documents
|
||||
(document_type, version, title, content_sections, status, change_note, created_by_profile_id)
|
||||
VALUES (%s, %s, %s, %s::jsonb, 'draft', NULL, %s)
|
||||
RETURNING id, document_type, version, title, content_sections,
|
||||
status, change_note, created_at, updated_at
|
||||
""",
|
||||
(src["document_type"], next_version, src["title"], sections_json, profile_id),
|
||||
)
|
||||
new_row = cur.fetchone()
|
||||
new_id = list(new_row.values())[0]
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO legal_document_audit
|
||||
(legal_document_id, action, changed_by_profile_id, change_note)
|
||||
VALUES (%s, 'created', %s, %s)
|
||||
""",
|
||||
(new_id, profile_id, f"Kopie von Version {src.get('version', '?')} (ID {doc_id})"),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return r2d(new_row)
|
||||
|
||||
|
||||
@router.get("/api/admin/legal-documents/{doc_id}/audit")
|
||||
def get_legal_document_audit(doc_id: int, session: dict = Depends(require_auth)):
|
||||
"""Änderungslog für ein Dokument."""
|
||||
_require_superadmin(session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM legal_documents WHERE id = %s", (doc_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.id, a.action, a.change_note, a.previous_status, a.created_at,
|
||||
p.name AS changed_by_name
|
||||
FROM legal_document_audit a
|
||||
LEFT JOIN profiles p ON p.id = a.changed_by_profile_id
|
||||
WHERE a.legal_document_id = %s
|
||||
ORDER BY a.created_at DESC
|
||||
""",
|
||||
(doc_id,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [r2d(r) for r in rows]
|
||||
+797
-15
@@ -13,6 +13,7 @@ from club_tenancy import (
|
||||
assert_club_member,
|
||||
assert_valid_governance_visibility,
|
||||
club_ids_for_profile_with_roles,
|
||||
has_club_role,
|
||||
is_platform_admin,
|
||||
is_superadmin,
|
||||
library_content_visible_to_profile,
|
||||
@@ -37,6 +38,24 @@ from media_lifecycle import (
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root, relocate_local_media_file
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible
|
||||
|
||||
from media_rights import (
|
||||
assert_rights_for_promotion,
|
||||
update_rights_quick_fields,
|
||||
validate_rights_declaration,
|
||||
write_rights_declaration,
|
||||
write_audit_log_entry,
|
||||
write_rights_correction_declaration,
|
||||
check_rights_coverage,
|
||||
VISIBILITY_LEVELS,
|
||||
)
|
||||
from media_legal_hold import (
|
||||
LEGAL_HOLD_REASON_CODES,
|
||||
assert_not_under_legal_hold,
|
||||
assert_superadmin_for_legal_hold,
|
||||
is_media_available_for_normal_use,
|
||||
set_legal_hold,
|
||||
release_legal_hold,
|
||||
)
|
||||
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
|
||||
|
||||
router = APIRouter(prefix="/api/media-assets", tags=["media-assets"])
|
||||
@@ -70,6 +89,57 @@ class MediaAssetPatch(BaseModel):
|
||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
tags: Optional[list[str]] = None
|
||||
# P-06: optionale Rechte-Erklaerung (wird Pflicht wenn Promotion zu hoeherer Sichtbarkeit)
|
||||
rights_holder_confirmed: Optional[bool] = None
|
||||
contains_identifiable_persons: Optional[bool] = None
|
||||
person_consent_confirmed: Optional[bool] = None
|
||||
person_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_minors: Optional[bool] = None
|
||||
parental_consent_confirmed: Optional[bool] = None
|
||||
parental_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_music: Optional[bool] = None
|
||||
music_rights_confirmed: Optional[bool] = None
|
||||
music_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_third_party_content: Optional[bool] = None
|
||||
third_party_rights_confirmed: Optional[bool] = None
|
||||
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
|
||||
|
||||
class RightsDeclarationBody(BaseModel):
|
||||
"""P-06: Explizite Re-Deklaration / Nachdeklaration fuer ein bestehendes Medium."""
|
||||
target_visibility: str = Field(..., pattern="^(private|club|official)$")
|
||||
rights_holder_confirmed: bool
|
||||
contains_identifiable_persons: bool
|
||||
person_consent_confirmed: Optional[bool] = None
|
||||
person_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_minors: bool
|
||||
parental_consent_confirmed: Optional[bool] = None
|
||||
parental_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_music: bool
|
||||
music_rights_confirmed: Optional[bool] = None
|
||||
music_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_third_party_content: bool
|
||||
third_party_rights_confirmed: Optional[bool] = None
|
||||
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
|
||||
|
||||
class RightsCorrectionBody(BaseModel):
|
||||
"""P-06: Nachtraegliche Korrektur einer Erklaerung (append-only, neueste gilt)."""
|
||||
target_visibility: str = Field(..., pattern="^(private|club|official)$")
|
||||
rights_holder_confirmed: bool
|
||||
contains_identifiable_persons: bool
|
||||
person_consent_confirmed: Optional[bool] = None
|
||||
person_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_minors: bool
|
||||
parental_consent_confirmed: Optional[bool] = None
|
||||
parental_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_music: bool
|
||||
music_rights_confirmed: Optional[bool] = None
|
||||
music_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
contains_third_party_content: bool
|
||||
third_party_rights_confirmed: Optional[bool] = None
|
||||
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
correction_note: Optional[str] = Field(None, max_length=2000)
|
||||
|
||||
|
||||
class MediaBulkLifecycleBody(BaseModel):
|
||||
@@ -100,7 +170,22 @@ class MediaBulkPatchBody(BaseModel):
|
||||
original_filename: Optional[str] = Field(None, max_length=300)
|
||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
# P-06 Kontext (bei Promotion)
|
||||
person_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
parental_consent_context: Optional[str] = Field(None, max_length=2000)
|
||||
music_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
|
||||
tags: Optional[list[str]] = None
|
||||
# P-06: Rechterklaerung (gilt fuer alle Assets des Batches bei Promotion)
|
||||
rights_holder_confirmed: Optional[bool] = None
|
||||
contains_identifiable_persons: Optional[bool] = None
|
||||
person_consent_confirmed: Optional[bool] = None
|
||||
contains_minors: Optional[bool] = None
|
||||
parental_consent_confirmed: Optional[bool] = None
|
||||
contains_music: Optional[bool] = None
|
||||
music_rights_confirmed: Optional[bool] = None
|
||||
contains_third_party_content: Optional[bool] = None
|
||||
third_party_rights_confirmed: Optional[bool] = None
|
||||
|
||||
|
||||
_LIFECYCLE_LIST_FILTERS = frozenset({"active", "trash_soft", "trash_hidden", "all"})
|
||||
@@ -379,8 +464,16 @@ def _relocate_asset_file_if_governance_changed(
|
||||
|
||||
|
||||
|
||||
def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str, list[Any]]:
|
||||
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL."""
|
||||
def _list_active_visibility_clause(
|
||||
is_plat: bool,
|
||||
profile_id: int,
|
||||
include_legal_hold: bool = False,
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL.
|
||||
|
||||
P-11: Legal-Hold-Medien sind für normale Nutzer nicht sichtbar.
|
||||
is_plat/is_sup können include_legal_hold=True übergeben, um sie weiterhin zu sehen.
|
||||
"""
|
||||
parts = ["lower(trim(ma.visibility)) = 'official'"]
|
||||
vals: list[Any] = []
|
||||
|
||||
@@ -414,8 +507,13 @@ def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str,
|
||||
)
|
||||
vals.append(profile_id)
|
||||
|
||||
sql = "(" + " OR ".join(parts) + ")"
|
||||
return sql, vals
|
||||
vis_sql = "(" + " OR ".join(parts) + ")"
|
||||
|
||||
# P-11: Legal-Hold-Medien für normale Nutzer ausblenden
|
||||
if not include_legal_hold:
|
||||
vis_sql = f"({vis_sql} AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL))"
|
||||
|
||||
return vis_sql, vals
|
||||
|
||||
|
||||
def _list_trash_visibility_clause(
|
||||
@@ -453,12 +551,15 @@ def _list_main_visibility_where(
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""
|
||||
Kombiniert lifecycle mit Leserechten. Papierkorb-Stufen für normale Nutzer stark eingeschränkt.
|
||||
P-11: Plattform-Admins und Superadmins sehen Legal-Hold-Medien in der aktiven Liste.
|
||||
"""
|
||||
lc = (lifecycle or "active").strip().lower()
|
||||
if lc not in _LIFECYCLE_LIST_FILTERS:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger lifecycle-Filter")
|
||||
|
||||
active_sql, active_params = _list_active_visibility_clause(is_plat, profile_id)
|
||||
active_sql, active_params = _list_active_visibility_clause(
|
||||
is_plat, profile_id, include_legal_hold=is_sup
|
||||
)
|
||||
trash_sql, trash_params = _list_trash_visibility_clause(
|
||||
is_plat, is_sup, profile_id, admin_club_ids
|
||||
)
|
||||
@@ -572,6 +673,7 @@ def _apply_lifecycle_action(
|
||||
|
||||
action = body.action
|
||||
role_raw = tenant.global_role
|
||||
old_lc = (asset.get("lifecycle_state") or LC_ACTIVE).strip()
|
||||
|
||||
if action == "superadmin_hard_delete":
|
||||
if not is_superadmin(role_raw):
|
||||
@@ -586,7 +688,13 @@ def _apply_lifecycle_action(
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmin")
|
||||
tl = body.target_lifecycle or "active"
|
||||
mp = {"active": LC_ACTIVE, "trash_soft": LC_TRASH_SOFT, "trash_hidden": LC_TRASH_HIDDEN}
|
||||
return superadmin_force_lifecycle_state(cur, conn, asset_id, mp[tl])
|
||||
new_lc = mp[tl]
|
||||
result = superadmin_force_lifecycle_state(cur, conn, asset_id, new_lc)
|
||||
if old_lc != new_lc:
|
||||
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
|
||||
{"lifecycle_state": old_lc}, {"lifecycle_state": new_lc})
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
if action == "purge":
|
||||
if not is_superadmin(role_raw):
|
||||
@@ -603,16 +711,32 @@ def _apply_lifecycle_action(
|
||||
|
||||
if action == "trash_soft":
|
||||
assert_can_trash_soft(cur, tenant, asset)
|
||||
return transition_to_trash_soft(cur, conn, asset_id)
|
||||
result = transition_to_trash_soft(cur, conn, asset_id)
|
||||
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
|
||||
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_SOFT})
|
||||
conn.commit()
|
||||
return result
|
||||
if action == "trash_hidden":
|
||||
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
|
||||
return transition_to_trash_hidden(cur, conn, asset_id)
|
||||
result = transition_to_trash_hidden(cur, conn, asset_id)
|
||||
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
|
||||
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_HIDDEN})
|
||||
conn.commit()
|
||||
return result
|
||||
if action == "recover":
|
||||
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
|
||||
return transition_recover_from_hidden(cur, conn, asset_id)
|
||||
result = transition_recover_from_hidden(cur, conn, asset_id)
|
||||
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
|
||||
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_SOFT})
|
||||
conn.commit()
|
||||
return result
|
||||
if action == "reactivate":
|
||||
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
|
||||
return reactivate_media_asset_from_trash(cur, conn, asset_id)
|
||||
result = reactivate_media_asset_from_trash(cur, conn, asset_id)
|
||||
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
|
||||
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_ACTIVE})
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
raise HTTPException(status_code=500, detail="Interner Fehler: lifecycle action")
|
||||
|
||||
@@ -628,8 +752,14 @@ def _ingest_library_media_file(
|
||||
content_type: Optional[str],
|
||||
visibility: str,
|
||||
club_id_form: Optional[int],
|
||||
decl: Optional[dict] = None,
|
||||
copyright_notice: Optional[str] = None,
|
||||
) -> dict:
|
||||
"""Neues Archiv-Medium oder aktiver Dedupe-Treffer (sha256 + Sichtbarkeit + Verein). Kein exercise_media."""
|
||||
"""Neues Archiv-Medium oder aktiver Dedupe-Treffer (sha256 + Sichtbarkeit + Verein). Kein exercise_media.
|
||||
|
||||
decl: P-06 Rechterklaerung (bereits validiert). Bei Dedupe-Treffer wird eine neue Erklaerung
|
||||
fuer die aktuelle Aktion geschrieben falls decl uebergeben wird.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role or ""
|
||||
vis = (visibility or "private").strip().lower()
|
||||
@@ -762,11 +892,12 @@ def _ingest_library_media_file(
|
||||
if not dest_path.is_file():
|
||||
dest_path.write_bytes(raw)
|
||||
|
||||
clean_cr = (copyright_notice or "").strip() or None
|
||||
cur.execute(
|
||||
"""INSERT INTO media_assets (
|
||||
mime_type, byte_size, sha256, original_filename, visibility, club_id,
|
||||
uploaded_by_profile_id, copyright_notice, storage_backend, storage_key, lifecycle_state
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, NULL, 'local', %s, 'active')
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'local', %s, 'active')
|
||||
RETURNING id""",
|
||||
(
|
||||
mime,
|
||||
@@ -776,11 +907,16 @@ def _ingest_library_media_file(
|
||||
vis,
|
||||
next_cid,
|
||||
profile_id,
|
||||
clean_cr,
|
||||
storage_key,
|
||||
),
|
||||
)
|
||||
ar = cur.fetchone()
|
||||
aid = int(r2d(ar)["id"])
|
||||
# P-06: Erklaerung schreiben und Schnellfelder setzen
|
||||
if decl is not None:
|
||||
write_rights_declaration(cur, aid, tenant.profile_id, "upload", vis, decl)
|
||||
update_rights_quick_fields(cur, aid, vis)
|
||||
return {"status": "created", "media_asset_id": aid, "original_filename": filename or storage_key}
|
||||
|
||||
|
||||
@@ -790,8 +926,27 @@ async def bulk_upload_media_assets(
|
||||
files: list[UploadFile] = File(..., description="Mehrere Dateien (jpeg, png, gif, mp4, pdf)"),
|
||||
visibility: str = Form("private"),
|
||||
club_id: Optional[int] = Form(None),
|
||||
copyright_notice: Optional[str] = Form(None),
|
||||
# P-06 Rechterklaerung (gilt fuer alle Dateien des Batches)
|
||||
rights_holder_confirmed: bool = Form(...),
|
||||
contains_identifiable_persons: bool = Form(...),
|
||||
person_consent_confirmed: Optional[bool] = Form(None),
|
||||
person_consent_context: Optional[str] = Form(None),
|
||||
contains_minors: bool = Form(...),
|
||||
parental_consent_confirmed: Optional[bool] = Form(None),
|
||||
parental_consent_context: Optional[str] = Form(None),
|
||||
contains_music: bool = Form(...),
|
||||
music_rights_confirmed: Optional[bool] = Form(None),
|
||||
music_rights_context: Optional[str] = Form(None),
|
||||
contains_third_party_content: bool = Form(...),
|
||||
third_party_rights_confirmed: Optional[bool] = Form(None),
|
||||
third_party_rights_context: Optional[str] = Form(None),
|
||||
):
|
||||
"""Mehrere Dateien ins Archiv; Dedupe wie Übungs-Upload. Pro Datei eigene DB-Transaktion."""
|
||||
"""Mehrere Dateien ins Archiv; Dedupe wie Übungs-Upload. Pro Datei eigene DB-Transaktion.
|
||||
|
||||
P-06: Eine Rechterklaerung gilt fuer alle Dateien des Batches.
|
||||
VORLAEUTIG: Texte und Pflichtfelder noch nicht juristisch geprueft (p06-v1-conservative).
|
||||
"""
|
||||
if not files:
|
||||
raise HTTPException(status_code=400, detail="Keine Dateien übermittelt")
|
||||
if len(files) > _MAX_BULK_LIBRARY_FILES:
|
||||
@@ -800,6 +955,24 @@ async def bulk_upload_media_assets(
|
||||
detail=f"Maximal {_MAX_BULK_LIBRARY_FILES} Dateien pro Anfrage",
|
||||
)
|
||||
|
||||
decl = {
|
||||
"rights_holder_confirmed": rights_holder_confirmed,
|
||||
"contains_identifiable_persons": contains_identifiable_persons,
|
||||
"person_consent_confirmed": person_consent_confirmed,
|
||||
"person_consent_context": person_consent_context,
|
||||
"contains_minors": contains_minors,
|
||||
"parental_consent_confirmed": parental_consent_confirmed,
|
||||
"parental_consent_context": parental_consent_context,
|
||||
"contains_music": contains_music,
|
||||
"music_rights_confirmed": music_rights_confirmed,
|
||||
"music_rights_context": music_rights_context,
|
||||
"contains_third_party_content": contains_third_party_content,
|
||||
"third_party_rights_confirmed": third_party_rights_confirmed,
|
||||
"third_party_rights_context": third_party_rights_context,
|
||||
}
|
||||
target_vis = (visibility or "private").strip().lower()
|
||||
validate_rights_declaration(decl, target_vis)
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
created = duplicate = failed = 0
|
||||
|
||||
@@ -821,7 +994,10 @@ async def bulk_upload_media_assets(
|
||||
uf.content_type,
|
||||
visibility,
|
||||
club_id,
|
||||
decl=decl,
|
||||
copyright_notice=copyright_notice,
|
||||
)
|
||||
conn.commit()
|
||||
results.append({"filename": fn, "ok": True, **r})
|
||||
if r["status"] == "created":
|
||||
created += 1
|
||||
@@ -969,7 +1145,10 @@ def list_media_assets(
|
||||
cur.execute(
|
||||
f"""SELECT ma.id, ma.mime_type, ma.byte_size, ma.original_filename, ma.visibility, ma.club_id,
|
||||
ma.uploaded_by_profile_id, ma.lifecycle_state, ma.created_at, ma.sha256,
|
||||
ma.copyright_notice, ma.storage_key, {tags_select}
|
||||
ma.copyright_notice, ma.storage_key, ma.rights_status,
|
||||
ma.legal_hold_active, ma.legal_hold_reason_code, ma.legal_hold_reason_note,
|
||||
ma.legal_hold_set_at, ma.legal_hold_set_by_profile_id,
|
||||
{tags_select}
|
||||
pr.name AS uploader_name,
|
||||
pr.email AS uploader_email,
|
||||
cl.name AS club_name
|
||||
@@ -989,10 +1168,26 @@ def list_media_assets(
|
||||
show_club = sup or is_adm or bool(admin_club_ids)
|
||||
asset_ids = [int(r["id"]) for r in rows]
|
||||
usage_map = _usage_for_media_assets(cur, asset_ids)
|
||||
# open_report_count: nur für Admins relevant; immer befüllen (0 für normale Nutzer ok)
|
||||
report_count_map: dict[int, int] = {}
|
||||
if asset_ids and (is_adm or bool(admin_club_ids)):
|
||||
cur.execute(
|
||||
"""SELECT target_id, COUNT(*) AS cnt
|
||||
FROM content_reports
|
||||
WHERE target_type = 'media_asset'
|
||||
AND target_id = ANY(%s)
|
||||
AND status IN ('submitted', 'under_review')
|
||||
GROUP BY target_id""",
|
||||
(asset_ids,),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
rd = r2d(row)
|
||||
report_count_map[int(rd["target_id"])] = int(rd["cnt"])
|
||||
for r in rows:
|
||||
r["permissions"] = _item_permissions(r, tenant, admin_club_ids)
|
||||
tid = int(r["id"])
|
||||
r["usage"] = usage_map.get(tid, {"exercises": [], "training_units": []})
|
||||
r["open_report_count"] = report_count_map.get(tid, 0)
|
||||
tags_val = r.get("tags")
|
||||
if tags_val is None:
|
||||
r["tags"] = []
|
||||
@@ -1035,9 +1230,30 @@ def download_media_asset_file(
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
asset = _fetch_asset_file_row(cur, asset_id)
|
||||
# _fetch_asset_file_row wird erweitert um legal_hold_active
|
||||
cur.execute(
|
||||
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
|
||||
storage_key, mime_type, original_filename, legal_hold_active
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
asset = r2d(row) if row else None
|
||||
if not asset:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
|
||||
# P-11: Legal Hold blockiert normalen Dateizugriff (nicht für Superadmin)
|
||||
if bool(asset.get("legal_hold_active")):
|
||||
role = tenant.global_role if hasattr(tenant, "global_role") else None
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail={
|
||||
"code": "LEGAL_HOLD_ACTIVE",
|
||||
"message": "Dieses Medium ist sofort gesperrt und nicht verfügbar.",
|
||||
},
|
||||
)
|
||||
|
||||
lc = (asset.get("lifecycle_state") or "").strip().lower()
|
||||
if lc == "active":
|
||||
_assert_can_view_archive_asset(cur, tenant, asset)
|
||||
@@ -1158,6 +1374,56 @@ def bulk_media_patch(
|
||||
)
|
||||
continue
|
||||
|
||||
if next_vis in ("club", "official"):
|
||||
effective_copyright = (
|
||||
patch_fields.get("copyright_notice") or asset.get("copyright_notice") or ""
|
||||
)
|
||||
if not str(effective_copyright).strip():
|
||||
failed.append(
|
||||
{
|
||||
"id": asset_id,
|
||||
"detail": (
|
||||
"Für Vereins- oder offizielle Medien ist eine "
|
||||
"Urheberrechtsangabe (copyright_notice) Pflicht."
|
||||
),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# P-06: Rechteprüfung bei Promotion
|
||||
cur_vis = (asset.get("visibility") or "private").strip().lower()
|
||||
bulk_p06_decl: Optional[dict] = None
|
||||
bulk_p06_action: Optional[str] = None
|
||||
if VISIBILITY_LEVELS.get(next_vis, 0) > VISIBILITY_LEVELS.get(cur_vis, 0):
|
||||
coverage = check_rights_coverage(cur, asset_id, next_vis)
|
||||
if coverage != "ok":
|
||||
p06_fields = {
|
||||
"rights_holder_confirmed": patch_fields.get("rights_holder_confirmed"),
|
||||
"contains_identifiable_persons": patch_fields.get("contains_identifiable_persons"),
|
||||
"person_consent_confirmed": patch_fields.get("person_consent_confirmed"),
|
||||
"contains_minors": patch_fields.get("contains_minors"),
|
||||
"parental_consent_confirmed": patch_fields.get("parental_consent_confirmed"),
|
||||
"contains_music": patch_fields.get("contains_music"),
|
||||
"music_rights_confirmed": patch_fields.get("music_rights_confirmed"),
|
||||
"contains_third_party_content": patch_fields.get("contains_third_party_content"),
|
||||
"third_party_rights_confirmed": patch_fields.get("third_party_rights_confirmed"),
|
||||
}
|
||||
if p06_fields.get("rights_holder_confirmed") is None:
|
||||
code = "LEGACY_REDECLARATION_REQUIRED" if coverage == "legacy" else "RIGHTS_SCOPE_INSUFFICIENT"
|
||||
failed.append({
|
||||
"id": asset_id,
|
||||
"detail": f"{code}: Rechterklaerung fuer '{next_vis}' erforderlich.",
|
||||
})
|
||||
continue
|
||||
try:
|
||||
validate_rights_declaration(p06_fields, next_vis)
|
||||
except HTTPException as p06e:
|
||||
d = p06e.detail
|
||||
failed.append({"id": asset_id, "detail": d.get("message") if isinstance(d, dict) else str(d)})
|
||||
continue
|
||||
bulk_p06_decl = p06_fields
|
||||
bulk_p06_action = "legacy_re_declaration" if coverage == "legacy" else "promote_club" if next_vis == "club" else "promote_official"
|
||||
|
||||
new_sk: Optional[str] = None
|
||||
if "visibility" in patch_fields or "club_id" in patch_fields:
|
||||
next_club_param: Optional[int] = None
|
||||
@@ -1196,6 +1462,12 @@ def bulk_media_patch(
|
||||
f"UPDATE media_assets SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
# P-06: Declaration-Log schreiben wenn neue Erklaerung bei Promotion
|
||||
if bulk_p06_decl is not None and bulk_p06_action is not None:
|
||||
write_rights_declaration(
|
||||
cur, asset_id, profile_id, bulk_p06_action, next_vis, bulk_p06_decl
|
||||
)
|
||||
update_rights_quick_fields(cur, asset_id, next_vis)
|
||||
conn.commit()
|
||||
updated.append(asset_id)
|
||||
except HTTPException as he:
|
||||
@@ -1239,6 +1511,8 @@ def patch_media_asset(
|
||||
eff = _effective_media_patch_fields(data, asset)
|
||||
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
|
||||
next_cid = eff.get("club_id", asset.get("club_id"))
|
||||
_p06_pending_decl: Optional[dict] = None
|
||||
_p06_action: Optional[str] = None
|
||||
if "visibility" in data or "club_id" in data:
|
||||
assert_valid_governance_visibility(
|
||||
cur,
|
||||
@@ -1256,6 +1530,75 @@ def patch_media_asset(
|
||||
),
|
||||
)
|
||||
|
||||
if next_vis in ("club", "official"):
|
||||
effective_copyright = (
|
||||
data.get("copyright_notice") or asset.get("copyright_notice") or ""
|
||||
)
|
||||
if not str(effective_copyright).strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Für Vereins- oder offizielle Medien ist eine Urheberrechtsangabe "
|
||||
"(copyright_notice) Pflicht. Bitte vor oder zusammen mit der "
|
||||
"Freigabe angeben."
|
||||
),
|
||||
)
|
||||
|
||||
# P-06: Rechteprüfung bei Sichtbarkeits-Promotion
|
||||
cur_vis = (asset.get("visibility") or "private").strip().lower()
|
||||
if VISIBILITY_LEVELS.get(next_vis, 0) > VISIBILITY_LEVELS.get(cur_vis, 0):
|
||||
coverage = check_rights_coverage(cur, asset_id, next_vis)
|
||||
if coverage != "ok":
|
||||
# Neue Erklaerung muss im Body mitgeliefert werden
|
||||
p06_fields = {
|
||||
"rights_holder_confirmed": data.get("rights_holder_confirmed"),
|
||||
"contains_identifiable_persons": data.get("contains_identifiable_persons"),
|
||||
"person_consent_confirmed": data.get("person_consent_confirmed"),
|
||||
"contains_minors": data.get("contains_minors"),
|
||||
"parental_consent_confirmed": data.get("parental_consent_confirmed"),
|
||||
"contains_music": data.get("contains_music"),
|
||||
"music_rights_confirmed": data.get("music_rights_confirmed"),
|
||||
"contains_third_party_content": data.get("contains_third_party_content"),
|
||||
"third_party_rights_confirmed": data.get("third_party_rights_confirmed"),
|
||||
}
|
||||
if coverage == "legacy":
|
||||
if p06_fields.get("rights_holder_confirmed") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "LEGACY_REDECLARATION_REQUIRED",
|
||||
"message": (
|
||||
"Dieses Medium wurde vor Einfuehrung der Einwilligungspflicht "
|
||||
"hochgeladen. Bitte eine vollstaendige Rechterklaerung (P-06-Felder) "
|
||||
"zusammen mit dem PATCH uebergeben."
|
||||
),
|
||||
"asset_id": asset_id,
|
||||
},
|
||||
)
|
||||
else:
|
||||
if p06_fields.get("rights_holder_confirmed") is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "RIGHTS_SCOPE_INSUFFICIENT",
|
||||
"message": (
|
||||
f"Die vorhandene Erklaerung deckt '{next_vis}' nicht ab. "
|
||||
"Bitte eine neue Erklaerung (P-06-Felder) mitschicken."
|
||||
),
|
||||
"asset_id": asset_id,
|
||||
"target_visibility": next_vis,
|
||||
},
|
||||
)
|
||||
validate_rights_declaration(p06_fields, next_vis)
|
||||
_p06_pending_decl = p06_fields
|
||||
_p06_action = "legacy_re_declaration" if coverage == "legacy" else "promote_club" if next_vis == "club" else "promote_official"
|
||||
else:
|
||||
_p06_pending_decl = None
|
||||
_p06_action = None
|
||||
else:
|
||||
_p06_pending_decl = None
|
||||
_p06_action = None
|
||||
|
||||
new_sk: Optional[str] = None
|
||||
if "visibility" in data or "club_id" in data:
|
||||
next_club_param: Optional[int] = None
|
||||
@@ -1292,6 +1635,38 @@ def patch_media_asset(
|
||||
f"UPDATE media_assets SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
# P-06: Declaration-Log schreiben wenn neue Erklaerung bei Promotion
|
||||
if _p06_pending_decl is not None and _p06_action is not None:
|
||||
write_rights_declaration(
|
||||
cur, asset_id, profile_id, _p06_action, next_vis, _p06_pending_decl
|
||||
)
|
||||
update_rights_quick_fields(cur, asset_id, next_vis)
|
||||
# Audit-Log: Änderungen protokollieren (gleiche Transaktion)
|
||||
if "visibility" in data or "club_id" in data:
|
||||
_old_vis = (asset.get("visibility") or "").strip()
|
||||
_old_cid = asset.get("club_id")
|
||||
if next_vis != _old_vis or next_cid != _old_cid:
|
||||
write_audit_log_entry(
|
||||
cur, asset_id, profile_id, "visibility_change",
|
||||
{"visibility": _old_vis, "club_id": _old_cid},
|
||||
{"visibility": next_vis, "club_id": next_cid},
|
||||
)
|
||||
if "copyright_notice" in data:
|
||||
_old_cr = (asset.get("copyright_notice") or "").strip()
|
||||
_new_cr = (data.get("copyright_notice") or "").strip()
|
||||
if _new_cr != _old_cr:
|
||||
write_audit_log_entry(
|
||||
cur, asset_id, profile_id, "copyright_change",
|
||||
{"copyright_notice": asset.get("copyright_notice")},
|
||||
{"copyright_notice": data["copyright_notice"]},
|
||||
)
|
||||
_meta_old: dict = {}
|
||||
_meta_new: dict = {}
|
||||
if "original_filename" in data:
|
||||
_meta_old["original_filename"] = asset.get("original_filename")
|
||||
_meta_new["original_filename"] = data["original_filename"]
|
||||
if _meta_new:
|
||||
write_audit_log_entry(cur, asset_id, profile_id, "metadata_change", _meta_old, _meta_new)
|
||||
conn.commit()
|
||||
has_tags = _media_assets_tags_column_present(cur)
|
||||
if has_tags:
|
||||
@@ -1312,3 +1687,410 @@ def patch_media_asset(
|
||||
if not has_tags:
|
||||
out["tags"] = []
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# P-06: Re-Deklaration / Nachdeklaration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/{asset_id}/rights-declarations")
|
||||
def create_rights_declaration(
|
||||
asset_id: int,
|
||||
body: RightsDeclarationBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-06: Explizite Rechte-Erklaerung fuer ein bestehendes Medium.
|
||||
|
||||
Verwendung:
|
||||
- Altmedium ('legacy_unreviewed'): Erste Erklaerung nach P-06 (action_type='legacy_re_declaration')
|
||||
- Medium mit Erklaerung fuer niedrigere Sichtbarkeit: Neue Erklaerung fuer Zielsichtbarkeit
|
||||
(action_type='re_declaration')
|
||||
|
||||
Die Erklaerung aendert NICHT die Sichtbarkeit des Mediums; dafuer PATCH verwenden.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
decl = body.model_dump() if hasattr(body, "model_dump") else body.dict()
|
||||
target_vis = decl.pop("target_visibility")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, uploaded_by_profile_id, lifecycle_state, rights_status FROM media_assets WHERE id = %s",
|
||||
(asset_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(row)
|
||||
assert_can_edit_media_asset_metadata(cur, tenant, asset)
|
||||
|
||||
validate_rights_declaration(decl, target_vis)
|
||||
|
||||
rs = (asset.get("rights_status") or "legacy_unreviewed").strip().lower()
|
||||
action_type = "legacy_re_declaration" if rs == "legacy_unreviewed" else "re_declaration"
|
||||
decl_id = write_rights_declaration(cur, asset_id, profile_id, action_type, target_vis, decl)
|
||||
update_rights_quick_fields(cur, asset_id, target_vis)
|
||||
conn.commit()
|
||||
return {
|
||||
"declaration_id": decl_id,
|
||||
"asset_id": asset_id,
|
||||
"action_type": action_type,
|
||||
"target_visibility": target_vis,
|
||||
"rights_status": "declared",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# P-06: Admin – Legacy-Übersicht
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
admin_rights_router = APIRouter(prefix="/api/admin/media-rights", tags=["admin", "media-rights"])
|
||||
|
||||
|
||||
@admin_rights_router.get("/legacy-summary")
|
||||
def get_legacy_rights_summary(
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-06 Admin: Zusammenfassung wie viele Medien noch im legacy_unreviewed-Status sind."""
|
||||
role = tenant.global_role
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung (Plattform-Admin erforderlich)")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT rights_status, COUNT(*) AS cnt
|
||||
FROM media_assets
|
||||
WHERE lifecycle_state = 'active'
|
||||
GROUP BY rights_status
|
||||
ORDER BY rights_status
|
||||
"""
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
totals = {r["rights_status"]: int(r["cnt"]) for r in rows}
|
||||
total_active = sum(totals.values())
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS cnt FROM media_asset_rights_declarations"
|
||||
)
|
||||
decl_count_row = cur.fetchone()
|
||||
total_declarations = int(r2d(decl_count_row)["cnt"]) if decl_count_row else 0
|
||||
return {
|
||||
"total_active_assets": total_active,
|
||||
"legacy_unreviewed": totals.get("legacy_unreviewed", 0),
|
||||
"declared": totals.get("declared", 0),
|
||||
"blocked": totals.get("blocked", 0),
|
||||
"total_declarations_logged": total_declarations,
|
||||
}
|
||||
|
||||
|
||||
@admin_rights_router.get("/legacy-assets")
|
||||
def get_legacy_rights_assets(
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
offset: int = Query(0, ge=0),
|
||||
visibility: Optional[str] = Query(None, pattern="^(private|club|official)$"),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-06 Admin: Liste der Medien mit rights_status = 'legacy_unreviewed' oder 'blocked'."""
|
||||
role = tenant.global_role
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung (Plattform-Admin erforderlich)")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
conditions = ["ma.lifecycle_state = 'active'", "ma.rights_status != 'declared'"]
|
||||
params: list[Any] = []
|
||||
if visibility:
|
||||
conditions.append("ma.visibility = %s")
|
||||
params.append(visibility)
|
||||
where = " AND ".join(conditions)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT ma.id, ma.original_filename, ma.visibility, ma.rights_status,
|
||||
ma.created_at, ma.uploaded_by_profile_id,
|
||||
p.name AS uploader_name
|
||||
FROM media_assets ma
|
||||
LEFT JOIN profiles p ON p.id = ma.uploaded_by_profile_id
|
||||
WHERE {where}
|
||||
ORDER BY ma.created_at DESC
|
||||
LIMIT %s OFFSET %s
|
||||
""",
|
||||
(*params, limit, offset),
|
||||
)
|
||||
assets = [r2d(r) for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS cnt
|
||||
FROM media_assets ma
|
||||
WHERE {where}
|
||||
""",
|
||||
tuple(params),
|
||||
)
|
||||
total_row = cur.fetchone()
|
||||
total = int(r2d(total_row)["cnt"]) if total_row else 0
|
||||
return {"total": total, "limit": limit, "offset": offset, "assets": assets}
|
||||
|
||||
|
||||
@admin_rights_router.get("/assets/{asset_id}/journal")
|
||||
def get_media_asset_journal(
|
||||
asset_id: int,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Vollständiges Medien-Journal: Einwilligungen + alle Änderungen chronologisch.
|
||||
|
||||
Zugriff: Superadmin, ursprünglicher Uploader oder Vereins-Admin des betreffenden Mediums.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, original_filename, visibility, club_id, rights_status,
|
||||
rights_declared_for_visibility, rights_declared_at,
|
||||
copyright_notice, mime_type, lifecycle_state,
|
||||
uploaded_by_profile_id, created_at
|
||||
FROM media_assets
|
||||
WHERE id = %s
|
||||
""",
|
||||
(asset_id,),
|
||||
)
|
||||
asset_row = cur.fetchone()
|
||||
if not asset_row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(asset_row)
|
||||
|
||||
is_sup = is_superadmin(role)
|
||||
is_uploader = asset.get("uploaded_by_profile_id") == profile_id
|
||||
is_club_adm = False
|
||||
if asset.get("club_id"):
|
||||
is_club_adm = has_club_role(cur, profile_id, asset["club_id"], "club_admin")
|
||||
|
||||
if not (is_sup or is_uploader or is_club_adm):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung (Superadmin, Uploader oder Vereinsadmin)")
|
||||
|
||||
can_correct = is_sup or is_uploader or is_club_adm
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.id, d.declared_at, d.action_type, d.target_visibility,
|
||||
d.declaration_version,
|
||||
d.rights_holder_confirmed,
|
||||
d.contains_identifiable_persons, d.person_consent_confirmed,
|
||||
d.person_consent_context,
|
||||
d.contains_minors, d.parental_consent_confirmed,
|
||||
d.parental_consent_context,
|
||||
d.contains_music, d.music_rights_confirmed,
|
||||
d.music_rights_context,
|
||||
d.contains_third_party_content, d.third_party_rights_confirmed,
|
||||
d.third_party_rights_context,
|
||||
d.declared_by_profile_id, d.correction_note,
|
||||
p.name AS declared_by_name,
|
||||
p.email AS declared_by_email
|
||||
FROM media_asset_rights_declarations d
|
||||
LEFT JOIN profiles p ON p.id = d.declared_by_profile_id
|
||||
WHERE d.media_asset_id = %s
|
||||
ORDER BY d.declared_at ASC
|
||||
""",
|
||||
(asset_id,),
|
||||
)
|
||||
events: list[dict] = []
|
||||
for r in cur.fetchall():
|
||||
d = r2d(r)
|
||||
d["kind"] = "declaration"
|
||||
d["at"] = str(d.get("declared_at", ""))
|
||||
events.append(d)
|
||||
|
||||
# Audit-Log (Migration 050 – Tabelle darf noch nicht existieren)
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.id, a.occurred_at, a.event_type, a.old_values, a.new_values,
|
||||
a.acting_profile_id,
|
||||
p.name AS acting_name,
|
||||
p.email AS acting_email
|
||||
FROM media_asset_audit_log a
|
||||
LEFT JOIN profiles p ON p.id = a.acting_profile_id
|
||||
WHERE a.media_asset_id = %s
|
||||
ORDER BY a.occurred_at ASC
|
||||
""",
|
||||
(asset_id,),
|
||||
)
|
||||
for r in cur.fetchall():
|
||||
a = r2d(r)
|
||||
a["kind"] = "audit"
|
||||
a["at"] = str(a.get("occurred_at", ""))
|
||||
events.append(a)
|
||||
except Exception:
|
||||
pass # Tabelle noch nicht migriert
|
||||
|
||||
events.sort(key=lambda e: e.get("at", ""))
|
||||
|
||||
return {"asset": asset, "events": events, "can_correct": can_correct}
|
||||
|
||||
|
||||
@admin_rights_router.post("/assets/{asset_id}/correction")
|
||||
def add_rights_correction(
|
||||
asset_id: int,
|
||||
body: RightsCorrectionBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Nachträgliche Korrektur einer P-06-Einwilligungserklärung (append-only, neueste gilt).
|
||||
|
||||
Zugriff: Superadmin, ursprünglicher Uploader oder Vereins-Admin.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id, uploaded_by_profile_id, club_id, rights_status, lifecycle_state FROM media_assets WHERE id = %s",
|
||||
(asset_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
asset = r2d(row)
|
||||
|
||||
is_sup = is_superadmin(role)
|
||||
is_uploader = asset.get("uploaded_by_profile_id") == profile_id
|
||||
is_club_adm = False
|
||||
if asset.get("club_id"):
|
||||
is_club_adm = has_club_role(cur, profile_id, asset["club_id"], "club_admin")
|
||||
|
||||
if not (is_sup or is_uploader or is_club_adm):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Keine Berechtigung (Superadmin, ursprünglicher Uploader oder Vereinsadmin erforderlich)",
|
||||
)
|
||||
|
||||
decl = body.model_dump(exclude_unset=False) if hasattr(body, "model_dump") else body.dict()
|
||||
target_vis = decl.pop("target_visibility")
|
||||
correction_note = decl.pop("correction_note", None)
|
||||
|
||||
validate_rights_declaration(decl, target_vis)
|
||||
write_rights_correction_declaration(cur, asset_id, profile_id, target_vis, decl, correction_note)
|
||||
update_rights_quick_fields(cur, asset_id, target_vis)
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True, "asset_id": asset_id}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# P-11: Legal-Hold-Endpoints (Superadmin only)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
admin_legal_hold_router = APIRouter(prefix="/api/admin/media-assets", tags=["admin", "legal-hold"])
|
||||
|
||||
|
||||
class LegalHoldSetBody(BaseModel):
|
||||
reason_code: str = Field(..., description="Kategorie des Legal Holds")
|
||||
reason_note: str = Field(..., min_length=5, max_length=2000, description="Pflichtbegründung")
|
||||
|
||||
|
||||
class LegalHoldReleaseBody(BaseModel):
|
||||
release_note: str = Field(..., min_length=5, max_length=2000, description="Freigabe-Begründung")
|
||||
|
||||
|
||||
@admin_legal_hold_router.post("/{asset_id}/legal-hold")
|
||||
def post_legal_hold_set(
|
||||
asset_id: int,
|
||||
body: LegalHoldSetBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-11: Legal Hold auf ein Medium setzen. Nur Superadmin.
|
||||
|
||||
Wirkung: Sofortige Unsichtbarkeit in normalen Nutzerpfaden, rights_status='blocked',
|
||||
Audit-Log-Eintrag. Keine automatische physische Löschung. Keine Löschfristen.
|
||||
"""
|
||||
assert_superadmin_for_legal_hold(tenant.global_role)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = set_legal_hold(
|
||||
cur, conn,
|
||||
asset_id=asset_id,
|
||||
acting_profile_id=int(tenant.profile_id),
|
||||
reason_code=body.reason_code,
|
||||
reason_note=body.reason_note,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"asset_id": asset_id,
|
||||
"legal_hold_active": result.get("legal_hold_active"),
|
||||
"rights_status": result.get("rights_status"),
|
||||
"legal_hold_reason_code": result.get("legal_hold_reason_code"),
|
||||
"legal_hold_set_at": str(result.get("legal_hold_set_at", "")),
|
||||
}
|
||||
|
||||
|
||||
@admin_legal_hold_router.post("/{asset_id}/legal-hold/release")
|
||||
def post_legal_hold_release(
|
||||
asset_id: int,
|
||||
body: LegalHoldReleaseBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-11: Legal Hold aufheben. Nur Superadmin.
|
||||
|
||||
Wirkung: legal_hold_active=FALSE, rights_status wiederhergestellt,
|
||||
Audit-Log-Eintrag. Vorheriger Lifecycle-Zustand bleibt erhalten.
|
||||
"""
|
||||
assert_superadmin_for_legal_hold(tenant.global_role)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = release_legal_hold(
|
||||
cur, conn,
|
||||
asset_id=asset_id,
|
||||
acting_profile_id=int(tenant.profile_id),
|
||||
release_note=body.release_note,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"asset_id": asset_id,
|
||||
"legal_hold_active": result.get("legal_hold_active"),
|
||||
"rights_status": result.get("rights_status"),
|
||||
"legal_hold_released_at": str(result.get("legal_hold_released_at", "")),
|
||||
}
|
||||
|
||||
|
||||
@admin_legal_hold_router.get("/legal-hold")
|
||||
def list_legal_hold_assets(
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
offset: int = Query(0, ge=0),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""P-11: Admin-Liste aller Medien unter aktivem Legal Hold. Superadmin oder Plattform-Admin."""
|
||||
if not is_platform_admin(tenant.global_role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Keine Berechtigung (Plattform-Admin oder Superadmin erforderlich)",
|
||||
)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT ma.id, ma.original_filename, ma.visibility, ma.club_id,
|
||||
ma.lifecycle_state, ma.rights_status,
|
||||
ma.legal_hold_active, ma.legal_hold_reason_code,
|
||||
ma.legal_hold_reason_note, ma.legal_hold_set_at,
|
||||
ma.legal_hold_set_by_profile_id,
|
||||
p_set.name AS set_by_name,
|
||||
ma.uploaded_by_profile_id,
|
||||
p_upl.name AS uploader_name,
|
||||
cl.name AS club_name,
|
||||
ma.created_at
|
||||
FROM media_assets ma
|
||||
LEFT JOIN profiles p_set ON p_set.id = ma.legal_hold_set_by_profile_id
|
||||
LEFT JOIN profiles p_upl ON p_upl.id = ma.uploaded_by_profile_id
|
||||
LEFT JOIN clubs cl ON cl.id = ma.club_id
|
||||
WHERE ma.legal_hold_active = TRUE
|
||||
ORDER BY ma.legal_hold_set_at DESC NULLS LAST, ma.id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
""",
|
||||
(limit, offset),
|
||||
)
|
||||
assets = [r2d(r) for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS cnt FROM media_assets WHERE legal_hold_active = TRUE"
|
||||
)
|
||||
total_row = cur.fetchone()
|
||||
total = int(r2d(total_row)["cnt"]) if total_row else 0
|
||||
return {"total": total, "limit": limit, "offset": offset, "assets": assets}
|
||||
@@ -384,6 +384,15 @@ def _run_profile_update(pid: str, p: ProfileUpdate, tenant: TenantContext) -> di
|
||||
else:
|
||||
raise HTTPException(400, "exercise_list_prefs muss ein JSON-Objekt sein")
|
||||
|
||||
if "training_planning_prefs" in patch:
|
||||
tp = patch.pop("training_planning_prefs")
|
||||
if tp is None:
|
||||
data["training_planning_prefs"] = Json({})
|
||||
elif isinstance(tp, dict):
|
||||
data["training_planning_prefs"] = Json(tp)
|
||||
else:
|
||||
raise HTTPException(400, "training_planning_prefs muss ein JSON-Objekt sein")
|
||||
|
||||
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||
for k, v in patch.items():
|
||||
if k == "email":
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
"""
|
||||
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
|
||||
|
||||
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
|
||||
Liste/Detail über `library_content_visibility_sql`; Schreiben: Ersteller oder Plattform‑Admin.
|
||||
|
||||
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
from club_tenancy import (
|
||||
assert_valid_governance_visibility,
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["training_modules"])
|
||||
|
||||
|
||||
def _has_planning_role(role: Optional[str]) -> bool:
|
||||
return role in ("admin", "superadmin", "trainer", "user")
|
||||
|
||||
|
||||
def _fetch_training_module_row(cur, mid: int) -> Dict[str, Any]:
|
||||
cur.execute("SELECT * FROM training_modules WHERE id = %s", (mid,))
|
||||
r = cur.fetchone()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Trainingsmodul nicht gefunden")
|
||||
return r2d(r)
|
||||
|
||||
|
||||
def _module_assert_readable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if not library_content_visible_to_profile(
|
||||
cur,
|
||||
profile_id,
|
||||
row.get("visibility") or "club",
|
||||
row.get("club_id"),
|
||||
row.get("created_by"),
|
||||
role,
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
|
||||
|
||||
|
||||
def _module_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if row.get("created_by") != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Nur der Ersteller darf dieses Modul ändern")
|
||||
|
||||
|
||||
def _module_access(cur, mid: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||
row = _fetch_training_module_row(cur, mid)
|
||||
_module_assert_readable(cur, row, profile_id, role)
|
||||
return row
|
||||
|
||||
|
||||
def _validate_variant_for_exercise(cur, exercise_id: Optional[int], variant_id: Optional[int]):
|
||||
if not variant_id:
|
||||
return
|
||||
if not exercise_id:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="exercise_variant_id nur zusammen mit exercise_id erlaubt"
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT 1 FROM exercise_variants WHERE id = %s AND exercise_id = %s",
|
||||
(variant_id, exercise_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=400, detail="Variante passt nicht zur gewählten Übung")
|
||||
|
||||
|
||||
def _optional_positive_int(val, field_name: str) -> Optional[int]:
|
||||
if val is None or val == "":
|
||||
return None
|
||||
try:
|
||||
i = int(val)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"Ungültige {field_name}")
|
||||
if i < 1:
|
||||
raise HTTPException(status_code=400, detail=f"Ungültige {field_name}")
|
||||
return i
|
||||
|
||||
|
||||
def _replace_module_items(cur, module_id: int, items_in: Optional[List[Any]]) -> None:
|
||||
cur.execute("DELETE FROM training_module_items WHERE module_id = %s", (module_id,))
|
||||
items_in = items_in or []
|
||||
for i, raw in enumerate(items_in):
|
||||
itype = raw.get("item_type")
|
||||
if not itype:
|
||||
itype = "exercise" if raw.get("exercise_id") else "note"
|
||||
order_ix = raw.get("order_index")
|
||||
if order_ix is None:
|
||||
order_ix = i
|
||||
order_ix = int(order_ix)
|
||||
|
||||
if itype == "note":
|
||||
body = raw.get("note_body")
|
||||
if body is None:
|
||||
body = ""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_module_items (
|
||||
module_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, notes, note_body
|
||||
) VALUES (%s, %s, 'note',
|
||||
NULL, NULL, NULL, NULL, %s)
|
||||
""",
|
||||
(module_id, order_ix, body),
|
||||
)
|
||||
continue
|
||||
|
||||
eid = raw.get("exercise_id")
|
||||
if not eid:
|
||||
continue
|
||||
eid = int(eid)
|
||||
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
|
||||
_validate_variant_for_exercise(cur, eid, vid)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_module_items (
|
||||
module_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, notes, note_body
|
||||
) VALUES (%s, %s, 'exercise',
|
||||
%s, %s, %s, %s, NULL)
|
||||
""",
|
||||
(
|
||||
module_id,
|
||||
order_ix,
|
||||
eid,
|
||||
vid,
|
||||
raw.get("planned_duration_min"),
|
||||
raw.get("notes"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def load_training_module_for_apply(
|
||||
cur, module_id: int, profile_id: int, role: Optional[str]
|
||||
) -> Tuple[List[Dict[str, Any]], int]:
|
||||
"""
|
||||
Liest Modul inkl. Items für Übernahme in eine Trainingseinheit.
|
||||
Returns (items_ordered, module_id).
|
||||
Raises HTTPException bei 403/404.
|
||||
"""
|
||||
row = _fetch_training_module_row(cur, module_id)
|
||||
_module_assert_readable(cur, row, profile_id, role or "")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT item_type, exercise_id, exercise_variant_id,
|
||||
planned_duration_min, notes, note_body
|
||||
FROM training_module_items
|
||||
WHERE module_id = %s
|
||||
ORDER BY order_index ASC
|
||||
""",
|
||||
(module_id,),
|
||||
)
|
||||
raw_items = [r2d(x) for x in cur.fetchall()]
|
||||
items: List[Dict[str, Any]] = []
|
||||
for r in raw_items:
|
||||
items.append(dict(r))
|
||||
return items, int(module_id)
|
||||
|
||||
|
||||
@router.get("/training-modules")
|
||||
def list_training_modules(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="m",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT m.*,
|
||||
(SELECT COUNT(*) FROM training_module_items i WHERE i.module_id = m.id)
|
||||
AS items_count
|
||||
FROM training_modules m
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY m.updated_at DESC NULLS LAST, m.title
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/training-modules/{module_id}")
|
||||
def get_training_module(module_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = _module_access(cur, module_id, profile_id, role)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM training_module_items
|
||||
WHERE module_id = %s
|
||||
ORDER BY order_index ASC
|
||||
""",
|
||||
(module_id,),
|
||||
)
|
||||
row["items"] = [r2d(r) for r in cur.fetchall()]
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/training-modules")
|
||||
def create_training_module(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Trainingsmodule anlegen")
|
||||
|
||||
title = (data.get("title") or "").strip()
|
||||
if not title:
|
||||
raise HTTPException(status_code=400, detail="title ist Pflicht")
|
||||
|
||||
vis_raw = data.get("visibility")
|
||||
visibility = (vis_raw if isinstance(vis_raw, str) else "club").strip() or "club"
|
||||
club_id = data.get("club_id")
|
||||
if club_id in ("", []):
|
||||
club_id = None
|
||||
if visibility == "club" and club_id is None:
|
||||
club_id = tenant.effective_club_id
|
||||
|
||||
primary_method_id = data.get("primary_method_id")
|
||||
if primary_method_id in ("", []):
|
||||
primary_method_id = None
|
||||
if primary_method_id is not None:
|
||||
primary_method_id = int(primary_method_id)
|
||||
|
||||
items_in = data.get("items") or []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, visibility, club_id)
|
||||
if primary_method_id is not None:
|
||||
cur.execute("SELECT 1 FROM training_methods WHERE id = %s", (primary_method_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=400, detail="Trainingsmethode nicht gefunden")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_modules (
|
||||
club_id, created_by, title, summary, goal,
|
||||
recommended_duration_min, target_group_notes, deployment_context_notes,
|
||||
primary_method_id, visibility
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
profile_id,
|
||||
title,
|
||||
(data.get("summary") or "").strip() or None,
|
||||
data.get("goal"),
|
||||
data.get("recommended_duration_min"),
|
||||
data.get("target_group_notes"),
|
||||
data.get("deployment_context_notes"),
|
||||
primary_method_id,
|
||||
visibility,
|
||||
),
|
||||
)
|
||||
mid = cur.fetchone()["id"]
|
||||
_replace_module_items(cur, mid, items_in if isinstance(items_in, list) else [])
|
||||
conn.commit()
|
||||
|
||||
return get_training_module(mid, tenant)
|
||||
|
||||
|
||||
@router.put("/training-modules/{module_id}")
|
||||
def update_training_module(
|
||||
module_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_prev = _fetch_training_module_row(cur, module_id)
|
||||
_module_assert_writable(cur, row_prev, profile_id, role)
|
||||
|
||||
merged_vis = row_prev.get("visibility") or "club"
|
||||
merged_club = row_prev.get("club_id")
|
||||
|
||||
if "visibility" in data:
|
||||
v_in = data.get("visibility")
|
||||
if not isinstance(v_in, str) or v_in not in ("private", "club", "official"):
|
||||
raise HTTPException(status_code=400, detail="visibility ungültig")
|
||||
merged_vis = v_in
|
||||
|
||||
if "club_id" in data:
|
||||
merged_club = data.get("club_id")
|
||||
if merged_club in ("", []):
|
||||
merged_club = None
|
||||
|
||||
if "visibility" in data or "club_id" in data:
|
||||
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
||||
|
||||
fields: List[str] = []
|
||||
params: List[Any] = []
|
||||
|
||||
if "title" in data:
|
||||
t = data.get("title")
|
||||
t = t.strip() if isinstance(t, str) else ""
|
||||
if not t:
|
||||
raise HTTPException(status_code=400, detail="title ist Pflicht")
|
||||
fields.append("title = %s")
|
||||
params.append(t)
|
||||
|
||||
for col in ("summary", "goal", "target_group_notes", "deployment_context_notes"):
|
||||
if col in data:
|
||||
fields.append(f"{col} = %s")
|
||||
v = data.get(col)
|
||||
if col == "summary" and isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
params.append(v)
|
||||
|
||||
if "recommended_duration_min" in data:
|
||||
fields.append("recommended_duration_min = %s")
|
||||
params.append(data.get("recommended_duration_min"))
|
||||
|
||||
if "primary_method_id" in data:
|
||||
pm = data.get("primary_method_id")
|
||||
if pm in ("", [], None):
|
||||
fields.append("primary_method_id = %s")
|
||||
params.append(None)
|
||||
else:
|
||||
pm = int(pm)
|
||||
cur.execute("SELECT 1 FROM training_methods WHERE id = %s", (pm,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=400, detail="Trainingsmethode nicht gefunden")
|
||||
fields.append("primary_method_id = %s")
|
||||
params.append(pm)
|
||||
|
||||
if "club_id" in data:
|
||||
fields.append("club_id = %s")
|
||||
params.append(merged_club)
|
||||
|
||||
if "visibility" in data:
|
||||
fields.append("visibility = %s")
|
||||
params.append(merged_vis)
|
||||
|
||||
if fields:
|
||||
fields.append("updated_at = NOW()")
|
||||
params.append(module_id)
|
||||
cur.execute(
|
||||
f"UPDATE training_modules SET {', '.join(fields)} WHERE id = %s",
|
||||
tuple(params),
|
||||
)
|
||||
|
||||
if "items" in data:
|
||||
items_in = data["items"]
|
||||
_replace_module_items(cur, module_id, items_in if isinstance(items_in, list) else [])
|
||||
|
||||
conn.commit()
|
||||
|
||||
return get_training_module(module_id, tenant)
|
||||
|
||||
|
||||
@router.delete("/training-modules/{module_id}")
|
||||
def delete_training_module(module_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_del = _fetch_training_module_row(cur, module_id)
|
||||
_module_assert_writable(cur, row_del, profile_id, role)
|
||||
cur.execute("DELETE FROM training_modules WHERE id = %s", (module_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
@@ -4,10 +4,13 @@ und wiederverwendbare Trainingsvorlagen (Sektions-Gliederung).
|
||||
|
||||
Governance: Sichtbarkeit wie Übungen (private / club / official); Schreiben nur Ersteller oder Plattform-Admin.
|
||||
"""
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
from datetime import date, datetime, time as dt_time, timedelta
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from psycopg2.extras import Json as PsycopgJson
|
||||
|
||||
from fastapi_param_unwrap import unwrap_query_default
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
@@ -17,6 +20,9 @@ from club_tenancy import (
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
from routers.training_modules import load_training_module_for_apply
|
||||
|
||||
from routers.exercises import load_combination_slots_for_exercise
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["training_planning"])
|
||||
|
||||
@@ -38,13 +44,101 @@ def _optional_positive_int(val, field_name: str) -> Optional[int]:
|
||||
return i
|
||||
|
||||
|
||||
def _parse_cursor_planned_date(raw: Optional[str]) -> date:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
raise HTTPException(status_code=400, detail="cursor_planned_date ungültig (YYYY-MM-DD)")
|
||||
try:
|
||||
return date.fromisoformat(s[:10])
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="cursor_planned_date ungültig (YYYY-MM-DD)")
|
||||
|
||||
|
||||
def _parse_cursor_planned_time_optional(raw: Optional[str]) -> Optional[dt_time]:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ("%H:%M:%S", "%H:%M"):
|
||||
try:
|
||||
return datetime.strptime(s, fmt).time()
|
||||
except ValueError:
|
||||
continue
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="cursor_planned_time ungültig (HH:MM oder HH:MM:SS)",
|
||||
)
|
||||
|
||||
|
||||
def _training_units_keyset_sql(
|
||||
order_dir: str,
|
||||
cursor_date: date,
|
||||
cursor_time_null: bool,
|
||||
cursor_time: Optional[dt_time],
|
||||
cursor_id: int,
|
||||
) -> Tuple[str, List[Any]]:
|
||||
"""WHERE-Zusatz für Keyset; sort=asc|desc muss zu order_dir passen."""
|
||||
d = cursor_date
|
||||
cid = cursor_id
|
||||
if order_dir == "ASC":
|
||||
if cursor_time_null:
|
||||
frag = (
|
||||
"(tu.planned_date > %s OR (tu.planned_date = %s AND "
|
||||
"tu.planned_time_start IS NULL AND tu.id > %s))"
|
||||
)
|
||||
return frag, [d, d, cid]
|
||||
assert cursor_time is not None
|
||||
ct = cursor_time
|
||||
frag = (
|
||||
"(tu.planned_date > %s OR (tu.planned_date = %s AND ("
|
||||
"(tu.planned_time_start IS NOT NULL AND (tu.planned_time_start > %s OR "
|
||||
"(tu.planned_time_start = %s AND tu.id > %s))) OR "
|
||||
"(tu.planned_time_start IS NULL)"
|
||||
")))"
|
||||
)
|
||||
return frag, [d, d, ct, ct, cid]
|
||||
if order_dir == "DESC":
|
||||
if cursor_time_null:
|
||||
frag = (
|
||||
"(tu.planned_date < %s OR (tu.planned_date = %s AND "
|
||||
"tu.planned_time_start IS NULL AND tu.id < %s))"
|
||||
)
|
||||
return frag, [d, d, cid]
|
||||
assert cursor_time is not None
|
||||
ct = cursor_time
|
||||
frag = (
|
||||
"(tu.planned_date < %s OR (tu.planned_date = %s AND ("
|
||||
"(tu.planned_time_start IS NOT NULL AND (tu.planned_time_start < %s OR "
|
||||
"(tu.planned_time_start = %s AND tu.id < %s))) OR "
|
||||
"(tu.planned_time_start IS NULL)"
|
||||
")))"
|
||||
)
|
||||
return frag, [d, d, ct, ct, cid]
|
||||
raise HTTPException(status_code=400, detail="sort: nur asc oder desc")
|
||||
|
||||
|
||||
def _validate_variant_for_exercise(cur, exercise_id: Optional[int], variant_id: Optional[int]):
|
||||
if not exercise_id:
|
||||
if variant_id:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="exercise_variant_id nur zusammen mit exercise_id erlaubt"
|
||||
)
|
||||
return
|
||||
cur.execute(
|
||||
"SELECT COALESCE(exercise_kind, 'simple') AS exercise_kind FROM exercises WHERE id = %s",
|
||||
(int(exercise_id),),
|
||||
)
|
||||
ek_row = cur.fetchone()
|
||||
if not ek_row:
|
||||
raise HTTPException(status_code=400, detail="Übung nicht gefunden")
|
||||
if str(r2d(ek_row).get("exercise_kind") or "simple").strip().lower() == "combination":
|
||||
if variant_id:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Kombinationsübungen haben keine Varianten — bitte exercise_variant_id weglassen",
|
||||
)
|
||||
return
|
||||
if not variant_id:
|
||||
return
|
||||
if not exercise_id:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="exercise_variant_id nur zusammen mit exercise_id erlaubt"
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT 1 FROM exercise_variants WHERE id = %s AND exercise_id = %s",
|
||||
(variant_id, exercise_id),
|
||||
@@ -390,6 +484,18 @@ def _normalize_assistant_trainer_profile_ids(
|
||||
)
|
||||
return uniq
|
||||
|
||||
def _normalize_planning_method_profile_payload(raw) -> Optional[Dict[str, Any]]:
|
||||
"""None = Katalog wirksam; Dict = Snapshot fuer diese Platzierung."""
|
||||
if raw is None:
|
||||
return None
|
||||
if isinstance(raw, dict):
|
||||
return dict(raw)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="planning_method_profile muss ein JSON-Objekt oder null sein",
|
||||
)
|
||||
|
||||
|
||||
# Nachverfolgbarkeit: Übernahmen aus Rahmenprogramm über origin_framework_slot_id
|
||||
_ORIGIN_LINEAGE_JOIN = """
|
||||
LEFT JOIN training_framework_slots origin_slot ON origin_slot.id = tu.origin_framework_slot_id
|
||||
@@ -403,24 +509,71 @@ _ORIGIN_LINEAGE_FIELDS = """
|
||||
"""
|
||||
|
||||
|
||||
def _fetch_sections(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
def _optional_source_training_module_id_payload(raw_val) -> Optional[int]:
|
||||
"""Erlaubt None; sonst positives int (FK-Verletzung bei ungültigem Modul möglich)."""
|
||||
if raw_val is None or raw_val == "":
|
||||
return None
|
||||
try:
|
||||
i = int(raw_val)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if i < 1:
|
||||
return None
|
||||
return i
|
||||
|
||||
|
||||
# ── Sektionen laden / ersetzen (Kernpfad Planungsinhalt) ──────────────────
|
||||
# Hinweis: Pro Sektion ein Items-Query (N+1) — bewusst einfach; Batching später möglich.
|
||||
|
||||
|
||||
def _clear_unit_plan_content(cur, unit_id: int) -> None:
|
||||
"""Löscht alle Planungs-Phasen der Einheit (CASCADE: Streams, Sektionen, Items)."""
|
||||
cur.execute("DELETE FROM training_unit_phases WHERE training_unit_id = %s", (unit_id,))
|
||||
|
||||
|
||||
def _ensure_default_whole_group_phase(cur, unit_id: int, *, order_index: int = 0) -> int:
|
||||
"""Legt bei Bedarf eine whole_group-Phase an; gibt phase.id zurück."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, title, guidance_notes, source_template_section_id
|
||||
FROM training_unit_sections
|
||||
WHERE training_unit_id = %s
|
||||
ORDER BY order_index
|
||||
SELECT id FROM training_unit_phases
|
||||
WHERE training_unit_id = %s AND phase_kind = 'whole_group' AND order_index = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(unit_id,),
|
||||
(unit_id, order_index),
|
||||
)
|
||||
secs = []
|
||||
for sec_row in cur.fetchall():
|
||||
sec = r2d(sec_row)
|
||||
cur.execute(
|
||||
"""
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return int(row["id"])
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title, guidance_notes)
|
||||
VALUES (%s, %s, 'whole_group', NULL, NULL)
|
||||
RETURNING id
|
||||
""",
|
||||
(unit_id, order_index),
|
||||
)
|
||||
return int(cur.fetchone()["id"])
|
||||
|
||||
|
||||
_SECTION_ROWS_SQL = """
|
||||
SELECT tus.id, tus.training_unit_id, tus.order_index, tus.title, tus.guidance_notes,
|
||||
tus.source_template_section_id, tus.phase_id, tus.parallel_stream_id
|
||||
FROM training_unit_sections tus
|
||||
LEFT JOIN training_unit_phases ph ON ph.id = tus.phase_id
|
||||
LEFT JOIN training_unit_parallel_streams ps ON ps.id = tus.parallel_stream_id
|
||||
LEFT JOIN training_unit_phases ph_s ON ph_s.id = ps.phase_id
|
||||
WHERE tus.training_unit_id = %s
|
||||
ORDER BY COALESCE(ph.order_index, ph_s.order_index) ASC,
|
||||
ps.order_index ASC NULLS FIRST,
|
||||
tus.order_index ASC
|
||||
"""
|
||||
_SECTION_ITEMS_ROWS_SQL = """
|
||||
SELECT tusi.*,
|
||||
e.title AS exercise_title,
|
||||
e.exercise_kind AS exercise_kind,
|
||||
e.summary AS exercise_summary,
|
||||
e.method_archetype AS catalog_method_archetype,
|
||||
e.method_profile AS catalog_method_profile,
|
||||
(
|
||||
SELECT fa.name FROM exercise_focus_areas efa
|
||||
JOIN focus_areas fa ON fa.id = efa.focus_area_id
|
||||
@@ -428,20 +581,127 @@ def _fetch_sections(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC
|
||||
LIMIT 1
|
||||
) AS exercise_focus_area,
|
||||
ev.variant_name AS exercise_variant_name
|
||||
ev.variant_name AS exercise_variant_name,
|
||||
tm.title AS source_module_title
|
||||
FROM training_unit_section_items tusi
|
||||
LEFT JOIN exercises e ON tusi.exercise_id = e.id
|
||||
LEFT JOIN exercise_variants ev ON tusi.exercise_variant_id = ev.id
|
||||
LEFT JOIN training_modules tm ON tm.id = tusi.source_training_module_id
|
||||
WHERE tusi.section_id = %s
|
||||
ORDER BY tusi.order_index
|
||||
""",
|
||||
(sec["id"],),
|
||||
)
|
||||
sec["items"] = [r2d(r) for r in cur.fetchall()]
|
||||
"""
|
||||
|
||||
|
||||
def _hydrate_section_item_combination_slots(cur, it: Dict[str, Any]) -> None:
|
||||
"""Setzt `combination_slots` für Kombi‑Übungen; sonst leere Liste."""
|
||||
if it.get("item_type") != "exercise":
|
||||
return
|
||||
cmp_raw = it.get("catalog_method_profile")
|
||||
if not isinstance(cmp_raw, dict):
|
||||
it["catalog_method_profile"] = {}
|
||||
else:
|
||||
it["catalog_method_profile"] = dict(cmp_raw)
|
||||
ek = str(it.get("exercise_kind") or "simple").strip().lower()
|
||||
if ek == "combination" and it.get("exercise_id"):
|
||||
try:
|
||||
it["combination_slots"] = load_combination_slots_for_exercise(cur, int(it["exercise_id"]))
|
||||
except (TypeError, ValueError):
|
||||
it["combination_slots"] = []
|
||||
else:
|
||||
it["combination_slots"] = []
|
||||
|
||||
|
||||
def _fetch_section_items_for_section(cur, section_id: int) -> List[Dict[str, Any]]:
|
||||
cur.execute(_SECTION_ITEMS_ROWS_SQL, (section_id,))
|
||||
items = [r2d(r) for r in cur.fetchall()]
|
||||
for it in items:
|
||||
_hydrate_section_item_combination_slots(cur, it)
|
||||
return items
|
||||
|
||||
|
||||
def _fetch_sections(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
"""Lädt alle Sektionen inkl. Items und Katalog-Anreicherung für die Einheit."""
|
||||
cur.execute(_SECTION_ROWS_SQL, (unit_id,))
|
||||
secs = []
|
||||
for sec_row in cur.fetchall():
|
||||
sec = r2d(sec_row)
|
||||
sec["items"] = _fetch_section_items_for_section(cur, sec["id"])
|
||||
secs.append(sec)
|
||||
return secs
|
||||
|
||||
|
||||
def _fetch_phases_nested(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
"""Verschachtelte Phasen/Streams/Sektionen für GET (UI kann parallele Sp später nutzen)."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, phase_kind, title, guidance_notes
|
||||
FROM training_unit_phases
|
||||
WHERE training_unit_id = %s
|
||||
ORDER BY order_index
|
||||
""",
|
||||
(unit_id,),
|
||||
)
|
||||
out: List[Dict[str, Any]] = []
|
||||
for prow in cur.fetchall():
|
||||
p = r2d(prow)
|
||||
pk = str(p.get("phase_kind") or "").strip().lower()
|
||||
if pk == "whole_group":
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, title, guidance_notes,
|
||||
source_template_section_id, phase_id, parallel_stream_id
|
||||
FROM training_unit_sections
|
||||
WHERE phase_id = %s
|
||||
ORDER BY order_index
|
||||
""",
|
||||
(p["id"],),
|
||||
)
|
||||
secs: List[Dict[str, Any]] = []
|
||||
for srow in cur.fetchall():
|
||||
sec = r2d(srow)
|
||||
sec["items"] = _fetch_section_items_for_section(cur, sec["id"])
|
||||
secs.append(sec)
|
||||
p["sections"] = secs
|
||||
p["streams"] = []
|
||||
elif pk == "parallel":
|
||||
p["sections"] = []
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, phase_id, order_index, title, notes, assigned_trainer_profile_ids
|
||||
FROM training_unit_parallel_streams
|
||||
WHERE phase_id = %s
|
||||
ORDER BY order_index
|
||||
""",
|
||||
(p["id"],),
|
||||
)
|
||||
streams: List[Dict[str, Any]] = []
|
||||
for st_row in cur.fetchall():
|
||||
st = r2d(st_row)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, title, guidance_notes,
|
||||
source_template_section_id, phase_id, parallel_stream_id
|
||||
FROM training_unit_sections
|
||||
WHERE parallel_stream_id = %s
|
||||
ORDER BY order_index
|
||||
""",
|
||||
(st["id"],),
|
||||
)
|
||||
secs = []
|
||||
for sec_row in cur.fetchall():
|
||||
sec = r2d(sec_row)
|
||||
sec["items"] = _fetch_section_items_for_section(cur, sec["id"])
|
||||
secs.append(sec)
|
||||
st["sections"] = secs
|
||||
streams.append(st)
|
||||
p["streams"] = streams
|
||||
else:
|
||||
p["sections"] = []
|
||||
p["streams"] = []
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
|
||||
def _sections_clone_payload(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
"""Sektionen/Items für eine tiefe Kopie (ohne DB-IDs / Join-Felder)."""
|
||||
secs = _fetch_sections(cur, unit_id)
|
||||
@@ -452,28 +712,33 @@ def _sections_clone_payload(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
itype = it.get("item_type") or ("exercise" if it.get("exercise_id") else "note")
|
||||
oix = it.get("order_index")
|
||||
if itype == "note":
|
||||
items_clean.append(
|
||||
{
|
||||
"item_type": "note",
|
||||
"order_index": oix,
|
||||
"note_body": it.get("note_body") or "",
|
||||
}
|
||||
)
|
||||
note_item = {
|
||||
"item_type": "note",
|
||||
"order_index": oix,
|
||||
"note_body": it.get("note_body") or "",
|
||||
}
|
||||
sm = _optional_source_training_module_id_payload(it.get("source_training_module_id"))
|
||||
if sm is not None:
|
||||
note_item["source_training_module_id"] = sm
|
||||
items_clean.append(note_item)
|
||||
continue
|
||||
if itype != "exercise" or not it.get("exercise_id"):
|
||||
continue
|
||||
items_clean.append(
|
||||
{
|
||||
"item_type": "exercise",
|
||||
"order_index": oix,
|
||||
"exercise_id": it["exercise_id"],
|
||||
"exercise_variant_id": it.get("exercise_variant_id"),
|
||||
"planned_duration_min": it.get("planned_duration_min"),
|
||||
"actual_duration_min": it.get("actual_duration_min"),
|
||||
"notes": it.get("notes"),
|
||||
"modifications": it.get("modifications"),
|
||||
}
|
||||
)
|
||||
ex_item = {
|
||||
"item_type": "exercise",
|
||||
"order_index": oix,
|
||||
"exercise_id": it["exercise_id"],
|
||||
"exercise_variant_id": it.get("exercise_variant_id"),
|
||||
"planned_duration_min": it.get("planned_duration_min"),
|
||||
"actual_duration_min": it.get("actual_duration_min"),
|
||||
"notes": it.get("notes"),
|
||||
"modifications": it.get("modifications"),
|
||||
"planning_method_profile": it.get("planning_method_profile"),
|
||||
}
|
||||
sm = _optional_source_training_module_id_payload(it.get("source_training_module_id"))
|
||||
if sm is not None:
|
||||
ex_item["source_training_module_id"] = sm
|
||||
items_clean.append(ex_item)
|
||||
out.append(
|
||||
{
|
||||
"title": sec.get("title"),
|
||||
@@ -562,12 +827,110 @@ def _flatten_exercises_from_sections(unit: Dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _hydrate_training_unit_payload(cur, unit: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""GET-Payload: `phases` (verschachtelt), flache `sections` + abgeleitete `exercises` (Legacy)."""
|
||||
uid = unit["id"]
|
||||
unit["phases"] = _fetch_phases_nested(cur, uid)
|
||||
unit["sections"] = _fetch_sections(cur, uid)
|
||||
_flatten_exercises_from_sections(unit)
|
||||
return unit
|
||||
|
||||
|
||||
def _resolve_training_unit_section_id(cur, unit_id: int, section_order_index: int) -> int:
|
||||
"""Erste Sektion mit order_index in einer whole_group-Phase (Parallelstreams ausgeschlossen)."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tus.id
|
||||
FROM training_unit_sections tus
|
||||
INNER JOIN training_unit_phases p ON p.id = tus.phase_id
|
||||
WHERE tus.training_unit_id = %s
|
||||
AND tus.order_index = %s
|
||||
AND tus.parallel_stream_id IS NULL
|
||||
AND LOWER(TRIM(p.phase_kind)) = 'whole_group'
|
||||
ORDER BY p.order_index ASC, tus.id ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(unit_id, section_order_index),
|
||||
)
|
||||
r = cur.fetchone()
|
||||
if not r:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="Abschnitt für diese Reihenfolge nicht gefunden"
|
||||
)
|
||||
return int(r["id"])
|
||||
|
||||
|
||||
def _append_copied_module_items_to_section(
|
||||
cur,
|
||||
section_id: int,
|
||||
module_items: List[Dict[str, Any]],
|
||||
source_training_module_id: int,
|
||||
) -> None:
|
||||
"""Hängt kopierte Modul‑Items ans Ende eines Abschnitts (section_order_index in API)."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(order_index), -1) AS mo
|
||||
FROM training_unit_section_items
|
||||
WHERE section_id = %s
|
||||
""",
|
||||
(section_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
start = int(row["mo"]) + 1 if row and row["mo"] is not None else 0
|
||||
|
||||
for i, mi in enumerate(module_items):
|
||||
oi = start + i
|
||||
itype = mi.get("item_type")
|
||||
if itype == "note":
|
||||
body = mi.get("note_body")
|
||||
if body is None:
|
||||
body = ""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_section_items (
|
||||
section_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, actual_duration_min,
|
||||
notes, modifications, note_body, source_training_module_id
|
||||
) VALUES (%s, %s, 'note',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, %s, %s)
|
||||
""",
|
||||
(section_id, oi, body, source_training_module_id),
|
||||
)
|
||||
continue
|
||||
|
||||
eid = mi.get("exercise_id")
|
||||
if not eid:
|
||||
continue
|
||||
eid = int(eid)
|
||||
vid = mi.get("exercise_variant_id")
|
||||
if vid is not None:
|
||||
vid = int(vid)
|
||||
else:
|
||||
vid = None
|
||||
_validate_variant_for_exercise(cur, eid, vid)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_section_items (
|
||||
section_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, actual_duration_min,
|
||||
notes, modifications, note_body,
|
||||
source_training_module_id, planning_method_profile
|
||||
) VALUES (%s, %s, 'exercise',
|
||||
%s, %s, %s, NULL, %s, NULL, NULL, %s, NULL)
|
||||
""",
|
||||
(
|
||||
section_id,
|
||||
oi,
|
||||
eid,
|
||||
vid,
|
||||
mi.get("planned_duration_min"),
|
||||
mi.get("notes"),
|
||||
source_training_module_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _insert_section_items(cur, section_id: int, items_in: Optional[List[Any]], start_order: int = 0):
|
||||
if items_in is None:
|
||||
items_in = []
|
||||
@@ -582,18 +945,19 @@ def _insert_section_items(cur, section_id: int, items_in: Optional[List[Any]], s
|
||||
body = raw.get("note_body")
|
||||
if body is None:
|
||||
body = ""
|
||||
src_mod = _optional_source_training_module_id_payload(raw.get("source_training_module_id"))
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_section_items (
|
||||
section_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, actual_duration_min,
|
||||
notes, modifications, note_body
|
||||
notes, modifications, note_body, source_training_module_id
|
||||
) VALUES (%s, %s, 'note',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, %s
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, %s, %s
|
||||
)
|
||||
""",
|
||||
(section_id, order_ix, body),
|
||||
(section_id, order_ix, body, src_mod),
|
||||
)
|
||||
continue
|
||||
|
||||
@@ -603,16 +967,27 @@ def _insert_section_items(cur, section_id: int, items_in: Optional[List[Any]], s
|
||||
eid = int(eid)
|
||||
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
|
||||
_validate_variant_for_exercise(cur, eid, vid)
|
||||
cur.execute(
|
||||
"""SELECT COALESCE(exercise_kind, 'simple') AS k FROM exercises WHERE id = %s""",
|
||||
(eid,),
|
||||
)
|
||||
er = cur.fetchone()
|
||||
ek = str(er["k"] if er and er.get("k") is not None else "simple").strip().lower()
|
||||
planning_mp = _normalize_planning_method_profile_payload(raw.get("planning_method_profile"))
|
||||
if ek != "combination":
|
||||
planning_mp = None
|
||||
planning_sql_val = PsycopgJson(planning_mp) if planning_mp is not None else None
|
||||
src_mod = _optional_source_training_module_id_payload(raw.get("source_training_module_id"))
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_section_items (
|
||||
section_id, order_index, item_type,
|
||||
exercise_id, exercise_variant_id,
|
||||
planned_duration_min, actual_duration_min,
|
||||
notes, modifications, note_body
|
||||
notes, modifications, note_body,
|
||||
source_training_module_id, planning_method_profile
|
||||
) VALUES (%s, %s, 'exercise',
|
||||
%s, %s, %s, %s, %s, %s, NULL
|
||||
)
|
||||
%s, %s, %s, %s, %s, %s, NULL, %s, %s)
|
||||
""",
|
||||
(
|
||||
section_id,
|
||||
@@ -623,35 +998,60 @@ def _insert_section_items(cur, section_id: int, items_in: Optional[List[Any]], s
|
||||
raw.get("actual_duration_min"),
|
||||
raw.get("notes"),
|
||||
raw.get("modifications"),
|
||||
src_mod,
|
||||
planning_sql_val,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _insert_one_replacement_section(
|
||||
cur,
|
||||
unit_id: int,
|
||||
sec: Any,
|
||||
enumeration_index: int,
|
||||
*,
|
||||
phase_id: Optional[int] = None,
|
||||
parallel_stream_id: Optional[int] = None,
|
||||
) -> None:
|
||||
"""Eine Sektion inkl. Items (genau eines von phase_id / parallel_stream_id gesetzt)."""
|
||||
if (phase_id is None) == (parallel_stream_id is None):
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Intern: Sektion braucht phase_id oder parallel_stream_id"
|
||||
)
|
||||
title = (sec.get("title") or "").strip() or "Abschnitt"
|
||||
order_ix = sec.get("order_index")
|
||||
if order_ix is None:
|
||||
order_ix = enumeration_index
|
||||
src_tsec = _optional_positive_int(sec.get("source_template_section_id"), "source_template_section_id")
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes, source_template_section_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
unit_id,
|
||||
phase_id,
|
||||
parallel_stream_id,
|
||||
order_ix,
|
||||
title,
|
||||
sec.get("guidance_notes"),
|
||||
src_tsec,
|
||||
),
|
||||
)
|
||||
sid = cur.fetchone()["id"]
|
||||
_insert_section_items(cur, sid, sec.get("items"))
|
||||
|
||||
|
||||
def _replace_unit_sections(cur, unit_id: int, sections_in: List[Any]):
|
||||
cur.execute("DELETE FROM training_unit_sections WHERE training_unit_id = %s", (unit_id,))
|
||||
"""Ersetzt den gesamten Plan (Legacy): eine whole_group-Phase + Sektionen."""
|
||||
_clear_unit_plan_content(cur, unit_id)
|
||||
phase_id = _ensure_default_whole_group_phase(cur, unit_id, order_index=0)
|
||||
for si, sec in enumerate(sections_in):
|
||||
title = (sec.get("title") or "").strip() or "Abschnitt"
|
||||
order_ix = sec.get("order_index")
|
||||
if order_ix is None:
|
||||
order_ix = si
|
||||
src_tsec = _optional_positive_int(sec.get("source_template_section_id"), "source_template_section_id")
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, order_index, title, guidance_notes, source_template_section_id
|
||||
) VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
unit_id,
|
||||
order_ix,
|
||||
title,
|
||||
sec.get("guidance_notes"),
|
||||
src_tsec,
|
||||
),
|
||||
_insert_one_replacement_section(
|
||||
cur, unit_id, sec, si, phase_id=phase_id, parallel_stream_id=None
|
||||
)
|
||||
sid = cur.fetchone()["id"]
|
||||
_insert_section_items(cur, sid, sec.get("items"))
|
||||
|
||||
|
||||
def _distinct_exercise_ids_in_unit(cur, unit_id: int) -> List[int]:
|
||||
@@ -780,13 +1180,16 @@ def _promote_private_exercises_used_in_unit(cur, unit_id: int, profile_id: int,
|
||||
def _insert_sections_from_legacy_exercises(cur, unit_id: int, exercises_in: List[Any]):
|
||||
if not exercises_in:
|
||||
return
|
||||
pid = _ensure_default_whole_group_phase(cur, unit_id, order_index=0)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (training_unit_id, order_index, title, guidance_notes)
|
||||
VALUES (%s, 0, %s, NULL)
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes
|
||||
)
|
||||
VALUES (%s, %s, NULL, 0, %s, NULL)
|
||||
RETURNING id
|
||||
""",
|
||||
(unit_id, "Übungen"),
|
||||
(unit_id, pid, "Übungen"),
|
||||
)
|
||||
sid = cur.fetchone()["id"]
|
||||
slot = 0
|
||||
@@ -815,6 +1218,8 @@ def _insert_sections_from_legacy_exercises(cur, unit_id: int, exercises_in: List
|
||||
|
||||
|
||||
def _instantiate_from_template(cur, unit_id: int, template_id: int):
|
||||
_clear_unit_plan_content(cur, unit_id)
|
||||
pid = _ensure_default_whole_group_phase(cur, unit_id, order_index=0)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, title, guidance_text
|
||||
@@ -825,29 +1230,26 @@ def _instantiate_from_template(cur, unit_id: int, template_id: int):
|
||||
(template_id,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
for row in rows:
|
||||
for gi, row in enumerate(rows):
|
||||
r = r2d(row)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, order_index, title, guidance_notes, source_template_section_id
|
||||
) VALUES (%s, (
|
||||
SELECT COALESCE(MAX(order_index), -1) + 1 FROM training_unit_sections u2
|
||||
WHERE u2.training_unit_id = %s
|
||||
), %s, %s, %s)
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes, source_template_section_id
|
||||
) VALUES (%s, %s, NULL, %s, %s, %s, %s)
|
||||
""",
|
||||
(unit_id, unit_id, r["title"], r["guidance_text"], r["id"]),
|
||||
(unit_id, pid, gi, r["title"], r["guidance_text"], r["id"]),
|
||||
)
|
||||
|
||||
# Fallback: keine Sektionen in Vorlage → ein leerer Block
|
||||
if not rows:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (training_unit_id, order_index, title, guidance_notes)
|
||||
SELECT %s, 0, %s, NULL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM training_unit_sections WHERE training_unit_id = %s)
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes
|
||||
) VALUES (%s, %s, NULL, 0, 'Hauptteil', NULL)
|
||||
""",
|
||||
(unit_id, "Hauptteil", unit_id),
|
||||
(unit_id, pid),
|
||||
)
|
||||
|
||||
|
||||
@@ -1081,8 +1483,34 @@ def list_training_units(
|
||||
),
|
||||
sort: str = Query(default="desc"),
|
||||
limit: Optional[int] = Query(default=None),
|
||||
cursor_planned_date: Optional[str] = Query(
|
||||
default=None,
|
||||
description="Keyset: YYYY-MM-DD der letzten Zeile (mit cursor_id)",
|
||||
),
|
||||
cursor_planned_time: Optional[str] = Query(
|
||||
default=None,
|
||||
description="Keyset: HH:MM oder HH:MM:SS; weglassen/leer wenn planned_time_start NULL",
|
||||
),
|
||||
cursor_id: Optional[int] = Query(
|
||||
default=None,
|
||||
ge=1,
|
||||
description="Keyset: id der letzten Zeile (mit cursor_planned_date)",
|
||||
),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
group_id = unwrap_query_default(group_id)
|
||||
club_id = unwrap_query_default(club_id)
|
||||
start_date = unwrap_query_default(start_date)
|
||||
end_date = unwrap_query_default(end_date)
|
||||
status = unwrap_query_default(status)
|
||||
assigned_to_me = unwrap_query_default(assigned_to_me)
|
||||
debrief_pending = unwrap_query_default(debrief_pending)
|
||||
sort = unwrap_query_default(sort)
|
||||
limit = unwrap_query_default(limit)
|
||||
cursor_planned_date = unwrap_query_default(cursor_planned_date)
|
||||
cursor_planned_time = unwrap_query_default(cursor_planned_time)
|
||||
cursor_id = unwrap_query_default(cursor_id)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
@@ -1091,6 +1519,40 @@ def list_training_units(
|
||||
if gid and cid:
|
||||
raise HTTPException(status_code=400, detail="Nur eines der Parameter group_id oder club_id angeben")
|
||||
|
||||
order_dir = "ASC" if (sort or "").strip().lower() == "asc" else "DESC"
|
||||
lim: Optional[int] = None
|
||||
if limit is not None:
|
||||
try:
|
||||
lim = int(limit)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="limit ungültig")
|
||||
if lim < 1:
|
||||
raise HTTPException(status_code=400, detail="limit ungültig")
|
||||
lim = min(lim, 250)
|
||||
|
||||
c_id_q = cursor_id
|
||||
c_date_raw = (cursor_planned_date or "").strip() or None
|
||||
time_nonempty = (cursor_planned_time or "").strip() != ""
|
||||
has_cursor_partial = (
|
||||
(c_id_q is not None) != (c_date_raw is not None) or (time_nonempty and c_id_q is None)
|
||||
)
|
||||
if has_cursor_partial:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="cursor_planned_date und cursor_id müssen zusammen gesetzt werden",
|
||||
)
|
||||
use_keyset = c_id_q is not None
|
||||
if use_keyset and lim is None:
|
||||
raise HTTPException(status_code=400, detail="Keyset: Parameter limit ist erforderlich")
|
||||
cursor_d: Optional[date] = None
|
||||
cursor_t: Optional[dt_time] = None
|
||||
cursor_t_null = False
|
||||
if use_keyset:
|
||||
assert c_id_q is not None and c_date_raw is not None
|
||||
cursor_d = _parse_cursor_planned_date(c_date_raw)
|
||||
cursor_t = _parse_cursor_planned_time_optional(cursor_planned_time)
|
||||
cursor_t_null = cursor_t is None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
@@ -1113,17 +1575,6 @@ def list_training_units(
|
||||
if not (ok_staff or ok_org or ok_member):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diese Gruppe")
|
||||
|
||||
order_dir = "ASC" if (sort or "").strip().lower() == "asc" else "DESC"
|
||||
lim: Optional[int] = None
|
||||
if limit is not None:
|
||||
try:
|
||||
lim = int(limit)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="limit ungültig")
|
||||
if lim < 1:
|
||||
raise HTTPException(status_code=400, detail="limit ungültig")
|
||||
lim = min(lim, 250)
|
||||
|
||||
query = """
|
||||
SELECT tu.*,
|
||||
tg.name as group_name,
|
||||
@@ -1206,10 +1657,25 @@ def list_training_units(
|
||||
where.append("tu.status = %s")
|
||||
params.append(status)
|
||||
|
||||
if use_keyset:
|
||||
assert cursor_d is not None and c_id_q is not None
|
||||
ks_sql, ks_params = _training_units_keyset_sql(
|
||||
order_dir,
|
||||
cursor_d,
|
||||
cursor_t_null,
|
||||
cursor_t,
|
||||
int(c_id_q),
|
||||
)
|
||||
where.append(ks_sql)
|
||||
params.extend(ks_params)
|
||||
|
||||
if where:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
|
||||
query += f" ORDER BY tu.planned_date {order_dir}, tu.planned_time_start {order_dir} NULLS LAST"
|
||||
query += (
|
||||
f" ORDER BY tu.planned_date {order_dir}, (tu.planned_time_start IS NULL) ASC, "
|
||||
f"tu.planned_time_start {order_dir} NULLS LAST, tu.id {order_dir}"
|
||||
)
|
||||
if lim is not None:
|
||||
query += " LIMIT %s"
|
||||
params.append(lim)
|
||||
@@ -1443,6 +1909,46 @@ def get_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenant_c
|
||||
return unit
|
||||
|
||||
|
||||
@router.post("/training-units/{unit_id}/apply-training-module")
|
||||
def apply_training_module_to_training_unit(
|
||||
unit_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
|
||||
):
|
||||
"""Kopiert die Positionen eines Trainingsmoduls ans Ende eines Abschnitts (lokal bearbeitbar)."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Module übernehmen")
|
||||
|
||||
module_id_raw = data.get("module_id")
|
||||
if module_id_raw is None or module_id_raw == "":
|
||||
raise HTTPException(status_code=400, detail="module_id ist Pflicht")
|
||||
try:
|
||||
module_id = int(module_id_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="module_id ungültig")
|
||||
|
||||
soy = data.get("section_order_index")
|
||||
try:
|
||||
section_order_index = int(soy)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="section_order_index ist Pflicht (Ganzzahl)")
|
||||
if section_order_index < 0:
|
||||
raise HTTPException(status_code=400, detail="section_order_index ungültig")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
unit_row = _training_unit_guard_row(cur, unit_id)
|
||||
_assert_training_unit_permission(cur, unit_row, profile_id, role)
|
||||
|
||||
section_id = _resolve_training_unit_section_id(cur, unit_id, section_order_index)
|
||||
mod_items, src_mid = load_training_module_for_apply(cur, module_id, profile_id, role)
|
||||
_append_copied_module_items_to_section(cur, section_id, mod_items, src_mid)
|
||||
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
|
||||
conn.commit()
|
||||
|
||||
return get_training_unit(unit_id, tenant)
|
||||
|
||||
|
||||
@router.post("/training-units")
|
||||
def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
@@ -1512,6 +2018,7 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
|
||||
lead_ins,
|
||||
)
|
||||
if assistant_set:
|
||||
av_db = None if assistant_val is None else PsycopgJson(assistant_val)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
@@ -1523,7 +2030,7 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
base_params + (assistant_val,),
|
||||
base_params + (av_db,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
@@ -1662,7 +2169,7 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
eff_lead_for_co,
|
||||
)
|
||||
assist_sql = ", assistant_trainer_profile_ids = %s"
|
||||
assist_params.append(na)
|
||||
assist_params.append(None if na is None else PsycopgJson(na))
|
||||
|
||||
debrief_frag = ""
|
||||
if "debrief_completed" in data and not is_blueprint:
|
||||
@@ -1720,7 +2227,6 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
detail="reset_from_template erfordert plan_template_id auf der Einheit oder im Request",
|
||||
)
|
||||
_template_access(cur, tid, profile_id, role)
|
||||
cur.execute("DELETE FROM training_unit_sections WHERE training_unit_id = %s", (unit_id,))
|
||||
cur.execute(
|
||||
"UPDATE training_units SET plan_template_id = %s WHERE id = %s", (tid, unit_id)
|
||||
)
|
||||
@@ -1730,7 +2236,7 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
if not content_handled and "sections" in data:
|
||||
_replace_unit_sections(cur, unit_id, data["sections"] or [])
|
||||
elif not content_handled and "exercises" in data:
|
||||
cur.execute("DELETE FROM training_unit_sections WHERE training_unit_id = %s", (unit_id,))
|
||||
_clear_unit_plan_content(cur, unit_id)
|
||||
_insert_sections_from_legacy_exercises(cur, unit_id, data["exercises"] or [])
|
||||
|
||||
if content_handled or "sections" in data or "exercises" in data:
|
||||
|
||||
@@ -22,6 +22,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
||||
"auth.py",
|
||||
"admin_users.py",
|
||||
"platform_media_storage.py",
|
||||
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
||||
"catalogs.py",
|
||||
"skills.py",
|
||||
"maturity_models.py",
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
P-05b: POST /api/auth/reset-password muss Passwoerter unter 8 Zeichen ablehnen.
|
||||
Prueft Pydantic-Validierung (HTTP 422) BEVOR die DB befragt wird.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _mock_db_valid_token() -> MagicMock:
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = {"profile_id": 1}
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
return mock_cm, mock_cur
|
||||
|
||||
|
||||
# ── Mindestlaenge-Grenzwerte ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("short_pw", ["", "a", "1234567"])
|
||||
def test_reset_password_too_short_rejected(client: TestClient, short_pw: str) -> None:
|
||||
"""Passwort < 8 Zeichen muss mit 422 abgelehnt werden (Pydantic-Validierung)."""
|
||||
r = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": "sometoken", "new_password": short_pw},
|
||||
)
|
||||
assert r.status_code == 422, (
|
||||
f"Erwartet 422 fuer Passwort {short_pw!r} ({len(short_pw)} Zeichen), "
|
||||
f"erhalten {r.status_code}"
|
||||
)
|
||||
|
||||
|
||||
def test_reset_password_exactly_8_chars_accepted(client: TestClient) -> None:
|
||||
"""Passwort mit genau 8 Zeichen muss die Validierung passieren."""
|
||||
mock_cm, mock_cur = _mock_db_valid_token()
|
||||
with patch("routers.auth.get_db", return_value=mock_cm), patch(
|
||||
"routers.auth.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": "sometoken", "new_password": "12345678"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json().get("ok") is True
|
||||
|
||||
|
||||
def test_reset_password_long_password_accepted(client: TestClient) -> None:
|
||||
"""Langes Passwort (>= 8 Zeichen) muss akzeptiert werden."""
|
||||
mock_cm, mock_cur = _mock_db_valid_token()
|
||||
with patch("routers.auth.get_db", return_value=mock_cm), patch(
|
||||
"routers.auth.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": "sometoken", "new_password": "sicheresPasswort123!"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_reset_password_missing_field_rejected(client: TestClient) -> None:
|
||||
"""Fehlendes new_password-Feld muss mit 422 abgelehnt werden."""
|
||||
r = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": "sometoken"},
|
||||
)
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_reset_password_invalid_token_returns_400(client: TestClient) -> None:
|
||||
"""Gueltiges Passwort aber ungueltiger Token muss 400 liefern."""
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = None
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
with patch("routers.auth.get_db", return_value=mock_cm), patch(
|
||||
"routers.auth.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": "ungueltig", "new_password": "validesPw123"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
@@ -0,0 +1,69 @@
|
||||
"""GET /api/dashboard/kpis: Auth + interne Aufruf-Hilfen."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import Query
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from fastapi_param_unwrap import unwrap_query_default
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_unwrap_query_default_for_direct_route_calls() -> None:
|
||||
assert unwrap_query_default(Query(default=None)) is None
|
||||
assert unwrap_query_default("2026-01-01") == "2026-01-01"
|
||||
assert unwrap_query_default(7) == 7
|
||||
|
||||
|
||||
def test_dashboard_kpis_unauthenticated_401(client: TestClient) -> None:
|
||||
r = client.get("/api/dashboard/kpis")
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def _fake_tenant_for_kpis() -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=42,
|
||||
global_role="trainer",
|
||||
effective_club_id=7,
|
||||
club_ids=frozenset({7}),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
@patch("routers.dashboard.list_training_units")
|
||||
@patch("routers.dashboard.list_exercises_like_get")
|
||||
def test_dashboard_kpis_200_when_inner_lists_mocked(
|
||||
mock_list_ex: object,
|
||||
mock_list_tu: object,
|
||||
client: TestClient,
|
||||
) -> None:
|
||||
mock_list_ex.return_value = []
|
||||
mock_list_tu.return_value = []
|
||||
app.dependency_overrides[get_tenant_context] = _fake_tenant_for_kpis
|
||||
try:
|
||||
r = client.get("/api/dashboard/kpis")
|
||||
assert r.status_code == 200, r.text
|
||||
data = r.json()
|
||||
assert "year" in data
|
||||
assert data["draft_count"] == 0
|
||||
assert data["mine_count"] == 0
|
||||
assert data["ytd_completed_count"] == 0
|
||||
th = data["training_home"]
|
||||
assert th["upcoming"] == []
|
||||
assert th["planned_with_notes"] == []
|
||||
assert th["review_pending"] == []
|
||||
assert mock_list_ex.call_count == 2
|
||||
assert mock_list_tu.call_count == 3
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""GET /api/exercises: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides() -> None:
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def test_list_exercises_keyset_incomplete_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={"cursor_id": "42"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_updated_at" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_exercises_keyset_with_offset_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_updated_at": "2026-01-01T12:00:00.000Z",
|
||||
"offset": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "offset" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_exercises_keyset_bad_timestamp_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={"cursor_id": "1", "cursor_updated_at": "not-a-date"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
@@ -130,8 +130,8 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"c": 0},
|
||||
{"created_by": 1, "visibility": "private", "club_id": None}, # _assert_can_edit_exercise
|
||||
{"c": 0}, # _count_exercise_media
|
||||
{
|
||||
"id": 5,
|
||||
"mime_type": "image/jpeg",
|
||||
@@ -142,14 +142,15 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": _SK_OFF_A,
|
||||
},
|
||||
{"id": 1},
|
||||
}, # asset lookup
|
||||
{"visibility": "private"}, # P-06: exercise visibility
|
||||
{"id": 1}, # duplicate check -> 400
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
), patch("routers.exercises.assert_rights_for_exercise_link"):
|
||||
r = client.post(
|
||||
"/api/exercises/3/media/from-asset",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
@@ -196,8 +197,8 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
}
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"c": 0},
|
||||
{"created_by": 1, "visibility": "private", "club_id": None}, # _assert_can_edit_exercise
|
||||
{"c": 0}, # _count_exercise_media
|
||||
{
|
||||
"id": 5,
|
||||
"mime_type": "image/jpeg",
|
||||
@@ -208,15 +209,16 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": _SK_OFF_B,
|
||||
},
|
||||
None,
|
||||
inserted,
|
||||
}, # asset lookup
|
||||
{"visibility": "private"}, # P-06: exercise visibility
|
||||
None, # duplicate check -> None (no duplicate)
|
||||
inserted, # INSERT RETURNING
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
), patch("routers.exercises.assert_rights_for_exercise_link"):
|
||||
r = client.post(
|
||||
"/api/exercises/3/media/from-asset",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
P-04: Copyright-Pflicht bei Promotion auf club/official.
|
||||
PATCH /api/media-assets/{id} und POST /api/media-assets/bulk-patch
|
||||
lehnen eine Sichtbarkeits-Promotion auf club oder official ab,
|
||||
wenn keine copyright_notice vorhanden ist.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import ExitStack
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
_SUPERADMIN_TENANT = TenantContext(
|
||||
profile_id=1,
|
||||
global_role="superadmin",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
_PRIVATE_ASSET: dict = {
|
||||
"id": 42,
|
||||
"visibility": "private",
|
||||
"club_id": 7,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": None,
|
||||
"original_filename": "foto.jpg",
|
||||
"sha256": "a" * 64,
|
||||
"storage_key": f"library/verein-7/image/{'a' * 64}.jpg",
|
||||
"storage_backend": "local",
|
||||
"mime_type": "image/jpeg",
|
||||
"byte_size": 1024,
|
||||
"created_at": None,
|
||||
"tags": [],
|
||||
}
|
||||
|
||||
_ASSET_WITH_COPYRIGHT: dict = {**_PRIVATE_ASSET, "copyright_notice": "Verein 2026"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def _make_db_mocks(asset: dict) -> tuple[MagicMock, MagicMock]:
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = asset
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
return mock_cm, mock_cur
|
||||
|
||||
|
||||
_PERMISSION_PATCHES = [
|
||||
("routers.media_assets.assert_can_edit_media_asset_metadata", {}),
|
||||
("routers.media_assets.assert_valid_governance_visibility", {}),
|
||||
("routers.media_assets._media_assets_tags_column_present", {"return_value": False}),
|
||||
("routers.media_assets.get_effective_media_root", {"return_value": "/tmp/media"}),
|
||||
("routers.media_assets._relocate_asset_file_if_governance_changed", {"return_value": None}),
|
||||
# P-06: bestehende Tests testen Copyright, nicht Rechteerklaerung – "ok" mocken
|
||||
("routers.media_assets.check_rights_coverage", {"return_value": "ok"}),
|
||||
]
|
||||
|
||||
|
||||
def _enter_permission_patches(stack: ExitStack) -> None:
|
||||
for target, kwargs in _PERMISSION_PATCHES:
|
||||
stack.enter_context(patch(target, **kwargs))
|
||||
|
||||
|
||||
# ── Single PATCH ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_patch_promote_to_club_without_copyright_returns_400(client: TestClient) -> None:
|
||||
"""Promotion private -> club ohne copyright_notice muss 400 liefern."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"visibility": "club", "club_id": 7},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
detail = r.json()["detail"].lower()
|
||||
assert "copyright" in detail or "urheberrecht" in detail
|
||||
|
||||
|
||||
def test_patch_promote_to_official_without_copyright_returns_400(client: TestClient) -> None:
|
||||
"""Promotion private -> official ohne copyright_notice muss 400 liefern."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"visibility": "official"},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
detail = r.json()["detail"].lower()
|
||||
assert "copyright" in detail or "urheberrecht" in detail
|
||||
|
||||
|
||||
def test_patch_promote_to_club_with_copyright_in_body_allowed(client: TestClient) -> None:
|
||||
"""Promotion private -> club MIT copyright_notice im Body muss 200 liefern."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
updated_asset = {**_PRIVATE_ASSET, "visibility": "club", "copyright_notice": "Verein 2026"}
|
||||
mock_cur.fetchone.side_effect = [_PRIVATE_ASSET, updated_asset]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"visibility": "club", "club_id": 7, "copyright_notice": "Verein 2026"},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["id"] == 42
|
||||
assert body["visibility"] == "club"
|
||||
assert body["copyright_notice"] == "Verein 2026"
|
||||
|
||||
|
||||
def test_patch_promote_to_club_existing_copyright_allowed(client: TestClient) -> None:
|
||||
"""Asset hat bereits copyright_notice -> Promotion ohne Body-Copyright muss 200 liefern."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
promoted_asset = {**_ASSET_WITH_COPYRIGHT, "visibility": "club"}
|
||||
mock_cm, mock_cur = _make_db_mocks(_ASSET_WITH_COPYRIGHT)
|
||||
mock_cur.fetchone.side_effect = [_ASSET_WITH_COPYRIGHT, promoted_asset]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"visibility": "club", "club_id": 7},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["id"] == 42
|
||||
assert body["visibility"] == "club"
|
||||
assert body["copyright_notice"] == "Verein 2026"
|
||||
|
||||
|
||||
def test_patch_filename_only_no_copyright_check(client: TestClient) -> None:
|
||||
"""Kein Visibility-Wechsel -> keine Copyright-Prufung."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
mock_cur.fetchone.side_effect = [
|
||||
_PRIVATE_ASSET,
|
||||
{**_PRIVATE_ASSET, "original_filename": "neu.jpg"},
|
||||
]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"original_filename": "neu.jpg"},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
# ── Bulk PATCH ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_bulk_patch_promote_to_club_without_copyright_in_failed(client: TestClient) -> None:
|
||||
"""Bulk-Promotion ohne copyright_notice -> Asset in failed-Liste."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = _PRIVATE_ASSET
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.post(
|
||||
"/api/media-assets/bulk-patch",
|
||||
json={"media_asset_ids": [42], "visibility": "club", "club_id": 7},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["updated_count"] == 0
|
||||
assert body["failed_count"] == 1
|
||||
detail = body["failed"][0]["detail"].lower()
|
||||
assert "copyright" in detail or "urheberrecht" in detail
|
||||
|
||||
|
||||
def test_bulk_patch_promote_to_club_with_copyright_in_updated(client: TestClient) -> None:
|
||||
"""Bulk-Promotion MIT copyright_notice -> Asset in updated-Liste."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = _PRIVATE_ASSET
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.post(
|
||||
"/api/media-assets/bulk-patch",
|
||||
json={
|
||||
"media_asset_ids": [42],
|
||||
"visibility": "club",
|
||||
"club_id": 7,
|
||||
"copyright_notice": "Verein 2026",
|
||||
},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert 42 in body["updated"]
|
||||
assert body["updated_count"] == 1
|
||||
@@ -0,0 +1,430 @@
|
||||
"""
|
||||
P-06: Rechte-Erklaerung – Backend-Tests.
|
||||
|
||||
Abgedeckt:
|
||||
1. validate_rights_declaration – alle Pflichtfelder
|
||||
2. check_rights_coverage – ok / insufficient / legacy / blocked
|
||||
3. assert_rights_for_promotion – richtiges Fehlermuster
|
||||
4. PATCH /api/media-assets/{id} – Promotion mit und ohne P-06
|
||||
5. POST /api/media-assets/{id}/rights-declarations – Re-Deklaration
|
||||
6. POST /api/media-assets/bulk-patch – P-06-Pfad im Bulk
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import ExitStack
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import HTTPException
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from main import app
|
||||
from media_rights import (
|
||||
validate_rights_declaration,
|
||||
check_rights_coverage,
|
||||
assert_rights_for_promotion,
|
||||
rights_covers_target,
|
||||
visibility_level,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SUPERADMIN_TENANT = TenantContext(
|
||||
profile_id=1,
|
||||
global_role="superadmin",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
_FULL_DECL = {
|
||||
"rights_holder_confirmed": True,
|
||||
"contains_identifiable_persons": False,
|
||||
"person_consent_confirmed": None,
|
||||
"contains_minors": False,
|
||||
"parental_consent_confirmed": None,
|
||||
"contains_music": False,
|
||||
"music_rights_confirmed": None,
|
||||
"contains_third_party_content": False,
|
||||
"third_party_rights_confirmed": None,
|
||||
}
|
||||
|
||||
_PRIVATE_ASSET = {
|
||||
"id": 42,
|
||||
"visibility": "private",
|
||||
"club_id": 7,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "Rechteinhaber 2026",
|
||||
"original_filename": "foto.jpg",
|
||||
"sha256": "a" * 64,
|
||||
"storage_key": f"library/verein-7/image/{'a' * 64}.jpg",
|
||||
"storage_backend": "local",
|
||||
"mime_type": "image/jpeg",
|
||||
"byte_size": 1024,
|
||||
"created_at": None,
|
||||
"tags": [],
|
||||
"rights_status": "legacy_unreviewed",
|
||||
"rights_declared_for_visibility": None,
|
||||
}
|
||||
|
||||
_DECLARED_ASSET = {**_PRIVATE_ASSET, "rights_status": "declared", "rights_declared_for_visibility": "private"}
|
||||
_BLOCKED_ASSET = {**_PRIVATE_ASSET, "rights_status": "blocked", "rights_declared_for_visibility": None}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def _make_db_mocks(asset: dict) -> tuple[MagicMock, MagicMock]:
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = asset
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
return mock_cm, mock_cur
|
||||
|
||||
|
||||
_PERMISSION_PATCHES = [
|
||||
("routers.media_assets.assert_can_edit_media_asset_metadata", {}),
|
||||
("routers.media_assets.assert_valid_governance_visibility", {}),
|
||||
("routers.media_assets._media_assets_tags_column_present", {"return_value": False}),
|
||||
("routers.media_assets.get_effective_media_root", {"return_value": "/tmp/media"}),
|
||||
("routers.media_assets._relocate_asset_file_if_governance_changed", {"return_value": None}),
|
||||
]
|
||||
|
||||
|
||||
def _enter_permission_patches(stack: ExitStack) -> None:
|
||||
for target, kwargs in _PERMISSION_PATCHES:
|
||||
stack.enter_context(patch(target, **kwargs))
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 1. validate_rights_declaration – Unit-Tests (kein HTTP)
|
||||
# ===========================================================================
|
||||
|
||||
class TestValidateRightsDeclaration:
|
||||
|
||||
def test_missing_rights_holder_raises(self):
|
||||
decl = {**_FULL_DECL, "rights_holder_confirmed": False}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.status_code == 400
|
||||
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
|
||||
|
||||
def test_identifiable_persons_none_raises(self):
|
||||
decl = {**_FULL_DECL, "contains_identifiable_persons": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.status_code == 400
|
||||
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
|
||||
|
||||
def test_person_consent_required_when_persons_present(self):
|
||||
decl = {**_FULL_DECL, "contains_identifiable_persons": True, "person_consent_confirmed": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "club")
|
||||
assert exc.value.detail["code"] == "PERSON_CONSENT_REQUIRED"
|
||||
|
||||
def test_minors_none_raises(self):
|
||||
decl = {**_FULL_DECL, "contains_minors": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
|
||||
|
||||
def test_parental_consent_required_when_minors_present(self):
|
||||
decl = {**_FULL_DECL, "contains_minors": True, "parental_consent_confirmed": False}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "official")
|
||||
assert exc.value.detail["code"] == "PARENTAL_CONSENT_REQUIRED"
|
||||
|
||||
def test_music_none_raises(self):
|
||||
decl = {**_FULL_DECL, "contains_music": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
|
||||
|
||||
def test_music_rights_required_when_music_present(self):
|
||||
decl = {**_FULL_DECL, "contains_music": True, "music_rights_confirmed": False}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.detail["code"] == "MUSIC_RIGHTS_REQUIRED"
|
||||
|
||||
def test_third_party_none_raises(self):
|
||||
decl = {**_FULL_DECL, "contains_third_party_content": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "private")
|
||||
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
|
||||
|
||||
def test_third_party_rights_required_when_content_present(self):
|
||||
decl = {**_FULL_DECL, "contains_third_party_content": True, "third_party_rights_confirmed": None}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
validate_rights_declaration(decl, "official")
|
||||
assert exc.value.detail["code"] == "THIRD_PARTY_RIGHTS_REQUIRED"
|
||||
|
||||
def test_full_clean_decl_passes(self):
|
||||
validate_rights_declaration(_FULL_DECL, "official")
|
||||
|
||||
def test_full_decl_with_all_true_passes(self):
|
||||
decl = {
|
||||
"rights_holder_confirmed": True,
|
||||
"contains_identifiable_persons": True,
|
||||
"person_consent_confirmed": True,
|
||||
"contains_minors": True,
|
||||
"parental_consent_confirmed": True,
|
||||
"contains_music": True,
|
||||
"music_rights_confirmed": True,
|
||||
"contains_third_party_content": True,
|
||||
"third_party_rights_confirmed": True,
|
||||
}
|
||||
validate_rights_declaration(decl, "official")
|
||||
|
||||
def test_private_also_requires_full_declaration(self):
|
||||
"""Konservative Erstannahme: private erfordert dieselbe Erklaerung wie official."""
|
||||
decl = {**_FULL_DECL, "contains_identifiable_persons": None}
|
||||
with pytest.raises(HTTPException):
|
||||
validate_rights_declaration(decl, "private")
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 2. check_rights_coverage – Unit-Tests mit Mock-Cursor
|
||||
# ===========================================================================
|
||||
|
||||
class TestCheckRightsCoverage:
|
||||
|
||||
def _cur(self, row):
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = row
|
||||
return cur
|
||||
|
||||
def test_no_asset_returns_no_declaration(self):
|
||||
cur = self._cur(None)
|
||||
assert check_rights_coverage(cur, 1, "private") == "no_declaration"
|
||||
|
||||
def test_blocked_returns_blocked(self):
|
||||
cur = self._cur({"rights_status": "blocked"})
|
||||
assert check_rights_coverage(cur, 1, "private") == "blocked"
|
||||
|
||||
def test_legacy_returns_legacy(self):
|
||||
cur = self._cur({"rights_status": "legacy_unreviewed"})
|
||||
assert check_rights_coverage(cur, 1, "club") == "legacy"
|
||||
|
||||
def test_declared_covers_any_visibility(self):
|
||||
# Eine bestehende Erklaerung gilt sichtbarkeitsunabhaengig
|
||||
for target in ("private", "club", "official"):
|
||||
cur = self._cur({"rights_status": "declared"})
|
||||
assert check_rights_coverage(cur, 1, target) == "ok", f"failed for target={target}"
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 3. assert_rights_for_promotion – Fehlermuster
|
||||
# ===========================================================================
|
||||
|
||||
class TestAssertRightsForPromotion:
|
||||
|
||||
def _cur(self, row):
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = row
|
||||
return cur
|
||||
|
||||
def test_ok_passes_for_any_target(self):
|
||||
for target in ("private", "club", "official"):
|
||||
cur = self._cur({"rights_status": "declared"})
|
||||
assert_rights_for_promotion(cur, 1, target) # no raise
|
||||
|
||||
def test_legacy_raises_legacy_code(self):
|
||||
cur = self._cur({"rights_status": "legacy_unreviewed"})
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_rights_for_promotion(cur, 1, "club")
|
||||
assert exc.value.status_code == 400
|
||||
assert exc.value.detail["code"] == "LEGACY_REDECLARATION_REQUIRED"
|
||||
|
||||
def test_blocked_raises_403(self):
|
||||
cur = self._cur({"rights_status": "blocked"})
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_rights_for_promotion(cur, 1, "official")
|
||||
assert exc.value.status_code == 403
|
||||
assert exc.value.detail["code"] == "RIGHTS_BLOCKED"
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 4. PATCH /api/media-assets/{id} – P-06-Promotion via HTTP
|
||||
# ===========================================================================
|
||||
|
||||
class TestPatchP06Promotion:
|
||||
|
||||
def test_promote_legacy_without_decl_returns_400(self, client):
|
||||
"""PATCH private->club ohne P-06-Felder muss LEGACY_REDECLARATION_REQUIRED liefern."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
mock_cur.fetchone.side_effect = [_PRIVATE_ASSET, {"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None}]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={"visibility": "club", "club_id": 7, "copyright_notice": "Rechteinhaber 2026"},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
d = r.json()["detail"]
|
||||
assert d["code"] == "LEGACY_REDECLARATION_REQUIRED"
|
||||
|
||||
def test_promote_legacy_with_full_decl_calls_write_declaration(self, client):
|
||||
"""PATCH private->club mit vollstaendiger P-06-Erklaerung schreibt Declaration-Log."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
updated_asset = {**_PRIVATE_ASSET, "visibility": "club"}
|
||||
mock_cur.fetchone.side_effect = [
|
||||
_PRIVATE_ASSET,
|
||||
{"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None},
|
||||
updated_asset,
|
||||
]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
_enter_permission_patches(stack)
|
||||
wr = stack.enter_context(patch("routers.media_assets.write_rights_declaration", return_value=1))
|
||||
uq = stack.enter_context(patch("routers.media_assets.update_rights_quick_fields"))
|
||||
r = client.patch(
|
||||
"/api/media-assets/42",
|
||||
json={
|
||||
"visibility": "club",
|
||||
"club_id": 7,
|
||||
"copyright_notice": "Rechteinhaber 2026",
|
||||
**_FULL_DECL,
|
||||
},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
assert wr.called
|
||||
call_args = wr.call_args
|
||||
assert call_args.args[3] == "legacy_re_declaration"
|
||||
assert call_args.args[4] == "club"
|
||||
assert uq.called
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 5. POST /api/media-assets/{id}/rights-declarations – Re-Deklaration
|
||||
# ===========================================================================
|
||||
|
||||
class TestPostRightsDeclaration:
|
||||
|
||||
def test_redeclaration_for_legacy_asset_succeeds(self, client):
|
||||
"""Nachdeklaration fuer Altmedium setzt action_type='legacy_re_declaration'."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
mock_cur.fetchone.return_value = _PRIVATE_ASSET
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
|
||||
wr = stack.enter_context(patch("routers.media_assets.write_rights_declaration", return_value=99))
|
||||
stack.enter_context(patch("routers.media_assets.update_rights_quick_fields"))
|
||||
r = client.post(
|
||||
"/api/media-assets/42/rights-declarations",
|
||||
json={"target_visibility": "club", **_FULL_DECL},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["action_type"] == "legacy_re_declaration"
|
||||
assert data["declaration_id"] == 99
|
||||
assert wr.called
|
||||
|
||||
def test_redeclaration_incomplete_decl_returns_400_or_422(self, client):
|
||||
"""Fehlende Erklaerungsfelder fuehren zu 400 (business logic) oder 422 (Pydantic)."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
|
||||
r = client.post(
|
||||
"/api/media-assets/42/rights-declarations",
|
||||
# Fehlende Pflichtfelder (contains_identifiable_persons etc.) -> Pydantic 422 ODER
|
||||
# validate_rights_declaration 400 je nach welche Felder fehlen
|
||||
json={"target_visibility": "private", "rights_holder_confirmed": True},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code in (400, 422)
|
||||
|
||||
def test_redeclaration_asset_not_found_returns_404(self, client):
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(None)
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
|
||||
r = client.post(
|
||||
"/api/media-assets/999/rights-declarations",
|
||||
json={"target_visibility": "private", **_FULL_DECL},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 6. Bulk-Patch – P-06-Promotion im Batch
|
||||
# ===========================================================================
|
||||
|
||||
class TestBulkPatchP06:
|
||||
|
||||
def test_bulk_promote_legacy_without_decl_reports_failure(self, client):
|
||||
"""Bulk-Patch: Legacy-Asset ohne P-06-Felder landet in 'failed', nicht 422."""
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
|
||||
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
|
||||
mock_cur.fetchone.side_effect = [
|
||||
_PRIVATE_ASSET,
|
||||
{"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None},
|
||||
]
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
|
||||
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
|
||||
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
|
||||
stack.enter_context(patch("routers.media_assets.assert_valid_governance_visibility"))
|
||||
stack.enter_context(patch("routers.media_assets._media_assets_tags_column_present", return_value=False))
|
||||
stack.enter_context(patch("routers.media_assets.get_effective_media_root", return_value="/tmp"))
|
||||
stack.enter_context(patch("routers.media_assets._relocate_asset_file_if_governance_changed", return_value=None))
|
||||
r = client.post(
|
||||
"/api/media-assets/bulk-patch",
|
||||
json={
|
||||
"media_asset_ids": [42],
|
||||
"visibility": "club",
|
||||
"club_id": 7,
|
||||
"copyright_notice": "Rechteinhaber 2026",
|
||||
},
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["failed_count"] == 1
|
||||
assert data["updated_count"] == 0
|
||||
assert "LEGACY_REDECLARATION_REQUIRED" in data["failed"][0]["detail"] or \
|
||||
"RIGHTS_SCOPE_INSUFFICIENT" in data["failed"][0]["detail"]
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
P-11: Legal-Hold – Backend-Tests.
|
||||
|
||||
Abgedeckt (15 Faelle):
|
||||
1. assert_superadmin_for_legal_hold – Superadmin darf
|
||||
2. assert_superadmin_for_legal_hold – Nicht-Superadmin wird geblockt
|
||||
3. is_media_available_for_normal_use – ohne Hold True
|
||||
4. is_media_available_for_normal_use – mit Hold False
|
||||
5. assert_not_under_legal_hold – ohne Hold passiert nichts
|
||||
6. assert_not_under_legal_hold – mit Hold wirft 403 LEGAL_HOLD_ACTIVE
|
||||
7. set_legal_hold – ungueltige reason_code → 400
|
||||
8. set_legal_hold – leere reason_note → 400
|
||||
9. set_legal_hold – Asset bereits unter Hold → 409
|
||||
10. set_legal_hold – Erfolgspfad: DB-Update + Audit-Log
|
||||
11. release_legal_hold – leere release_note → 400
|
||||
12. release_legal_hold – Asset nicht unter Hold → 409
|
||||
13. release_legal_hold – Erfolgspfad ohne Deklaration → legacy_unreviewed
|
||||
14. release_legal_hold – Erfolgspfad mit Deklaration → declared
|
||||
15. Retention-Job ueberspringt Legal-Hold-Assets (run_retention_pass query)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from media_legal_hold import (
|
||||
LEGAL_HOLD_REASON_CODES,
|
||||
assert_not_under_legal_hold,
|
||||
assert_superadmin_for_legal_hold,
|
||||
is_media_available_for_normal_use,
|
||||
release_legal_hold,
|
||||
set_legal_hold,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _asset(legal_hold_active=False, rights_status="legacy_unreviewed", **kw) -> dict:
|
||||
base = {
|
||||
"id": 99,
|
||||
"visibility": "private",
|
||||
"lifecycle_state": "active",
|
||||
"rights_status": rights_status,
|
||||
"legal_hold_active": legal_hold_active,
|
||||
"legal_hold_reason_code": None,
|
||||
"legal_hold_reason_note": None,
|
||||
}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
|
||||
def _make_cur(fetchone_val, fetchone_seq=None):
|
||||
"""Erstellt einen Mock-Cursor.
|
||||
|
||||
fetchone_seq: wenn angegeben, wird fetchone() sequenziell diese Werte liefern.
|
||||
"""
|
||||
cur = MagicMock()
|
||||
if fetchone_seq is not None:
|
||||
cur.fetchone.side_effect = fetchone_seq
|
||||
else:
|
||||
cur.fetchone.return_value = fetchone_val
|
||||
return cur
|
||||
|
||||
|
||||
def _dict_row(d: dict):
|
||||
"""Simuliert ein psycopg2-DictRow-Objekt (keys() + Subscript)."""
|
||||
m = MagicMock()
|
||||
m.keys.return_value = list(d.keys())
|
||||
m.__getitem__ = lambda self, k: d[k]
|
||||
m.__iter__ = lambda self: iter(d.values())
|
||||
return m
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1–2: assert_superadmin_for_legal_hold
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAssertSuperadmin:
|
||||
def test_superadmin_passes(self):
|
||||
# kein Fehler
|
||||
assert_superadmin_for_legal_hold("superadmin")
|
||||
|
||||
def test_non_superadmin_raises_403(self):
|
||||
for role in ("admin", "user", "club_admin", None, ""):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_superadmin_for_legal_hold(role)
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3–4: is_media_available_for_normal_use
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestIsMediaAvailable:
|
||||
def test_no_hold_is_available(self):
|
||||
assert is_media_available_for_normal_use(_asset(legal_hold_active=False)) is True
|
||||
|
||||
def test_hold_active_is_not_available(self):
|
||||
assert is_media_available_for_normal_use(_asset(legal_hold_active=True)) is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5–6: assert_not_under_legal_hold
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAssertNotUnderLegalHold:
|
||||
def test_no_hold_does_not_raise(self):
|
||||
assert_not_under_legal_hold(_asset(legal_hold_active=False))
|
||||
|
||||
def test_hold_active_raises_403_with_code(self):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_not_under_legal_hold(_asset(legal_hold_active=True, id=55))
|
||||
assert exc.value.status_code == 403
|
||||
detail = exc.value.detail
|
||||
assert isinstance(detail, dict)
|
||||
assert detail["code"] == "LEGAL_HOLD_ACTIVE"
|
||||
assert detail["asset_id"] == 55
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7–10: set_legal_hold
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSetLegalHold:
|
||||
def test_invalid_reason_code_raises_400(self):
|
||||
cur = MagicMock()
|
||||
conn = MagicMock()
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
set_legal_hold(cur, conn, asset_id=1, acting_profile_id=1,
|
||||
reason_code="totally_made_up", reason_note="some reason")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
def test_empty_reason_note_raises_400(self):
|
||||
cur = MagicMock()
|
||||
conn = MagicMock()
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
set_legal_hold(cur, conn, asset_id=1, acting_profile_id=1,
|
||||
reason_code="rights_dispute", reason_note="")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
def test_already_under_hold_raises_409(self):
|
||||
asset = _asset(legal_hold_active=True)
|
||||
cur = _make_cur(_dict_row(asset))
|
||||
conn = MagicMock()
|
||||
with patch("db.r2d", return_value=asset), \
|
||||
patch("media_legal_hold.write_audit_log_entry"):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
set_legal_hold(cur, conn, asset_id=99, acting_profile_id=1,
|
||||
reason_code="rights_dispute", reason_note="Verletzung bestätigt")
|
||||
assert exc.value.status_code == 409
|
||||
|
||||
def test_success_sets_hold_and_writes_audit(self):
|
||||
asset_before = _asset(legal_hold_active=False, rights_status="declared")
|
||||
asset_after = {
|
||||
**asset_before,
|
||||
"legal_hold_active": True,
|
||||
"legal_hold_reason_code": "copyright_complaint",
|
||||
"legal_hold_reason_note": "Urheberrechtsverletzung gemeldet",
|
||||
"legal_hold_set_by_profile_id": 1,
|
||||
"legal_hold_set_at": "2026-05-11T12:00:00Z",
|
||||
"rights_status": "blocked",
|
||||
}
|
||||
cur = _make_cur(None)
|
||||
cur.fetchone.side_effect = [_dict_row(asset_before), _dict_row(asset_after)]
|
||||
conn = MagicMock()
|
||||
|
||||
with patch("db.r2d", side_effect=[asset_before, asset_after]), \
|
||||
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
|
||||
result = set_legal_hold(
|
||||
cur, conn,
|
||||
asset_id=99,
|
||||
acting_profile_id=1,
|
||||
reason_code="copyright_complaint",
|
||||
reason_note="Urheberrechtsverletzung gemeldet",
|
||||
)
|
||||
|
||||
assert result["legal_hold_active"] is True
|
||||
assert result["rights_status"] == "blocked"
|
||||
conn.commit.assert_called_once()
|
||||
mock_audit.assert_called_once()
|
||||
audit_call_kwargs = mock_audit.call_args
|
||||
assert audit_call_kwargs[1]["event_type"] == "legal_hold_set"
|
||||
assert audit_call_kwargs[1]["new_values"]["legal_hold_active"] is True
|
||||
assert audit_call_kwargs[1]["new_values"]["reason_code"] == "copyright_complaint"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 11–14: release_legal_hold
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestReleaseLegalHold:
|
||||
def test_empty_release_note_raises_400(self):
|
||||
cur = MagicMock()
|
||||
conn = MagicMock()
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
release_legal_hold(cur, conn, asset_id=99, acting_profile_id=1, release_note="")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
def test_not_under_hold_raises_409(self):
|
||||
asset = _asset(legal_hold_active=False)
|
||||
cur = _make_cur(_dict_row(asset))
|
||||
conn = MagicMock()
|
||||
with patch("db.r2d", return_value=asset):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
release_legal_hold(cur, conn, asset_id=99, acting_profile_id=1,
|
||||
release_note="Falschmeldung")
|
||||
assert exc.value.status_code == 409
|
||||
|
||||
def test_release_without_declaration_restores_legacy_unreviewed(self):
|
||||
asset = _asset(legal_hold_active=True, rights_status="blocked")
|
||||
asset_after = {**asset, "legal_hold_active": False, "rights_status": "legacy_unreviewed",
|
||||
"legal_hold_released_by_profile_id": 1, "legal_hold_release_note": "Klaerung abgeschlossen"}
|
||||
cur = _make_cur(None)
|
||||
# fetchone-Sequenz: 1) Asset (fuer r2d), 2) decl count row, 3) updated asset row (fuer r2d)
|
||||
decl_cnt_row = type("Row", (), {"__getitem__": staticmethod(lambda k: 0), "__iter__": staticmethod(lambda: iter([0]))})()
|
||||
cur.fetchone.side_effect = [_dict_row(asset), decl_cnt_row, _dict_row(asset_after)]
|
||||
conn = MagicMock()
|
||||
|
||||
with patch("db.r2d", side_effect=[asset, asset_after]), \
|
||||
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
|
||||
result = release_legal_hold(
|
||||
cur, conn, asset_id=99, acting_profile_id=1,
|
||||
release_note="Klaerung abgeschlossen",
|
||||
)
|
||||
|
||||
assert result["legal_hold_active"] is False
|
||||
assert result["rights_status"] == "legacy_unreviewed"
|
||||
conn.commit.assert_called_once()
|
||||
mock_audit.assert_called_once()
|
||||
assert mock_audit.call_args[1]["event_type"] == "legal_hold_released"
|
||||
|
||||
def test_release_with_declaration_restores_declared(self):
|
||||
asset = _asset(legal_hold_active=True, rights_status="blocked")
|
||||
asset_after = {**asset, "legal_hold_active": False, "rights_status": "declared",
|
||||
"legal_hold_released_by_profile_id": 1, "legal_hold_release_note": "Einigung erzielt"}
|
||||
cur = _make_cur(None)
|
||||
decl_cnt_row = type("Row", (), {"__getitem__": staticmethod(lambda k: 1), "__iter__": staticmethod(lambda: iter([1]))})()
|
||||
cur.fetchone.side_effect = [_dict_row(asset), decl_cnt_row, _dict_row(asset_after)]
|
||||
conn = MagicMock()
|
||||
|
||||
with patch("db.r2d", side_effect=[asset, asset_after]), \
|
||||
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
|
||||
result = release_legal_hold(
|
||||
cur, conn, asset_id=99, acting_profile_id=1,
|
||||
release_note="Einigung erzielt",
|
||||
)
|
||||
|
||||
assert result["legal_hold_active"] is False
|
||||
assert result["rights_status"] == "declared"
|
||||
mock_audit.assert_called_once()
|
||||
assert mock_audit.call_args[1]["new_values"]["rights_status"] == "declared"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 15: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRetentionJobSkipsLegalHold:
|
||||
def test_retention_queries_exclude_legal_hold(self):
|
||||
"""Prueft dass run_retention_pass keine Legal-Hold-Assets anfasst."""
|
||||
import inspect
|
||||
import media_lifecycle
|
||||
|
||||
source = inspect.getsource(media_lifecycle.run_retention_pass)
|
||||
|
||||
# Beide Queries (trash_soft→trash_hidden und trash_hidden→purge)
|
||||
# muessen den Legal-Hold-Filter enthalten
|
||||
assert "legal_hold_active" in source, (
|
||||
"run_retention_pass muss legal_hold_active in den Retention-Queries filtern"
|
||||
)
|
||||
# Sicherstellen, dass der Filter korrekt lautet (FALSE oder IS NULL)
|
||||
assert "legal_hold_active = FALSE" in source or "legal_hold_active IS NULL" in source, (
|
||||
"Filter muss 'legal_hold_active = FALSE' oder 'IS NULL' enthalten"
|
||||
)
|
||||
@@ -0,0 +1,344 @@
|
||||
"""
|
||||
P-13: Content-Melde-Backend – Backend-Tests.
|
||||
|
||||
Abgedeckt (15 Faelle):
|
||||
1. submit_report ohne good_faith_confirmed=False → 400
|
||||
2. submit_report mit leerem report_description → 422
|
||||
3. submit_report mit fehlender reporter_email → 422
|
||||
4. submit_report ohne Login fuer official-Medium – Erfolgspfad
|
||||
5. submit_report ohne Login fuer nicht-official-Medium → 404
|
||||
6. submit_report mit Login fuer sichtbares club-Medium – Erfolgspfad
|
||||
7. submit_report mit Login fuer nicht-sichtbares fremdes Medium → 404
|
||||
8. Prioritaet high fuer illegal_content/minors/youth_protection
|
||||
9. Prioritaet normal fuer copyright/other
|
||||
10. list_inbox als Nicht-Admin → 403
|
||||
11. list_inbox als Plattform-Admin – gibt Liste zurueck
|
||||
12. patch_report status 'under_review' – Erfolgspfad
|
||||
13. patch_report 'resolved_no_action' ohne resolution_note → 400
|
||||
14. set_legal_hold_from_report als Nicht-Superadmin → 403
|
||||
15. set_legal_hold_from_report als Superadmin – Erfolgspfad (reason_code-Mapping)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from routers.content_reports import (
|
||||
HIGH_PRIORITY_REASONS,
|
||||
_REASON_TO_HOLD_CODE,
|
||||
_is_media_asset_visible_anonymous,
|
||||
_is_media_asset_visible_to_profile,
|
||||
REPORT_REASONS,
|
||||
ContentReportCreate,
|
||||
ContentReportPatch,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hilfsfunktionen
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_cur(fetchone_val=None):
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = fetchone_val
|
||||
cur.fetchall.return_value = []
|
||||
return cur
|
||||
|
||||
|
||||
def _row(data: dict):
|
||||
"""Simuliert eine psycopg2-DictRow."""
|
||||
m = MagicMock()
|
||||
m.__getitem__ = lambda self, k: data[k]
|
||||
m.keys = lambda: data.keys()
|
||||
return m
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. good_faith_confirmed=False → 400
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_submit_requires_good_faith():
|
||||
body = ContentReportCreate(
|
||||
target_type="media_asset",
|
||||
target_id=1,
|
||||
report_reason="copyright",
|
||||
report_description="A" * 20,
|
||||
reporter_name="Max",
|
||||
reporter_email="max@example.com",
|
||||
good_faith_confirmed=False,
|
||||
)
|
||||
from routers.content_reports import submit_content_report
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
submit_content_report(body)
|
||||
assert exc.value.status_code == 400
|
||||
assert "Gutglauben" in exc.value.detail
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Leere report_description → 422 (Pydantic)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_submit_requires_description():
|
||||
with pytest.raises(Exception):
|
||||
ContentReportCreate(
|
||||
target_type="media_asset",
|
||||
target_id=1,
|
||||
report_reason="copyright",
|
||||
report_description="ab", # unter min_length=10
|
||||
reporter_name="Max",
|
||||
reporter_email="max@example.com",
|
||||
good_faith_confirmed=True,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Ungueltige E-Mail → 422 (Pydantic Validator)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_submit_requires_valid_email():
|
||||
with pytest.raises(Exception):
|
||||
ContentReportCreate(
|
||||
target_type="media_asset",
|
||||
target_id=1,
|
||||
report_reason="copyright",
|
||||
report_description="A" * 20,
|
||||
reporter_name="Max",
|
||||
reporter_email="kein-at-zeichen",
|
||||
good_faith_confirmed=True,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Anonym – official-Medium → sichtbar
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_anonymous_official_medium_visible():
|
||||
cur = _make_cur(fetchone_val={"1": 1})
|
||||
cur.fetchone.return_value = MagicMock()
|
||||
result = _is_media_asset_visible_anonymous(cur, asset_id=42)
|
||||
assert result is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Anonym – nicht-official-Medium → nicht sichtbar
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_anonymous_non_official_medium_not_visible():
|
||||
cur = _make_cur(fetchone_val=None)
|
||||
result = _is_media_asset_visible_anonymous(cur, asset_id=99)
|
||||
assert result is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Eingeloggter Nutzer – sichtbares club-Medium → True
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_logged_in_club_member_can_see_club_media():
|
||||
asset_row = MagicMock()
|
||||
asset_row.keys = lambda: ["id", "visibility", "club_id", "uploaded_by_profile_id"]
|
||||
asset_row.__getitem__ = lambda s, k: {
|
||||
"id": 7,
|
||||
"visibility": "club",
|
||||
"club_id": 3,
|
||||
"uploaded_by_profile_id": 99,
|
||||
}[k]
|
||||
|
||||
member_row = MagicMock() # Mitgliedschaft gefunden
|
||||
|
||||
cur = MagicMock()
|
||||
cur.fetchone.side_effect = [asset_row, member_row]
|
||||
|
||||
result = _is_media_asset_visible_to_profile(cur, asset_id=7, profile_id=1, global_role="trainer")
|
||||
assert result is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. Eingeloggter Nutzer – fremdes Medium → False
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_logged_in_non_member_cannot_see_club_media():
|
||||
asset_row = MagicMock()
|
||||
asset_row.keys = lambda: ["id", "visibility", "club_id", "uploaded_by_profile_id"]
|
||||
asset_row.__getitem__ = lambda s, k: {
|
||||
"id": 7,
|
||||
"visibility": "club",
|
||||
"club_id": 3,
|
||||
"uploaded_by_profile_id": 99,
|
||||
}[k]
|
||||
|
||||
cur = MagicMock()
|
||||
# Erster fetchone: Asset-Zeile, zweiter: kein Mitglied
|
||||
cur.fetchone.side_effect = [asset_row, None]
|
||||
|
||||
result = _is_media_asset_visible_to_profile(cur, asset_id=7, profile_id=5, global_role="trainer")
|
||||
assert result is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 8. Prioritaet high fuer kritische Gruende
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_high_priority_reasons():
|
||||
assert "illegal_content" in HIGH_PRIORITY_REASONS
|
||||
assert "minors" in HIGH_PRIORITY_REASONS
|
||||
assert "youth_protection" in HIGH_PRIORITY_REASONS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 9. Prioritaet normal fuer andere Gruende
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_normal_priority_reasons():
|
||||
normal_reasons = REPORT_REASONS - HIGH_PRIORITY_REASONS
|
||||
assert "copyright" in normal_reasons
|
||||
assert "other" in normal_reasons
|
||||
assert "privacy" in normal_reasons
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 10. list_inbox als Nicht-Admin → 403
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_list_inbox_requires_platform_admin():
|
||||
from routers.content_reports import list_inbox_content_reports
|
||||
tenant = MagicMock()
|
||||
tenant.global_role = "trainer"
|
||||
tenant.profile_id = 99
|
||||
|
||||
# COUNT-Abfrage fuer Club-Admin-Rollen → 0 → 403
|
||||
cnt_row = _row({"cnt": 0})
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = cnt_row
|
||||
|
||||
mock_conn = MagicMock()
|
||||
mock_conn_ctx = MagicMock()
|
||||
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
|
||||
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
|
||||
patch("routers.content_reports.get_cursor", return_value=mock_cur):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
list_inbox_content_reports(tenant=tenant)
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 11. list_inbox als Plattform-Admin – gibt Liste zurueck
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_list_inbox_as_admin_returns_list():
|
||||
from routers.content_reports import list_inbox_content_reports
|
||||
|
||||
tenant = MagicMock()
|
||||
tenant.global_role = "admin"
|
||||
|
||||
mock_conn = MagicMock()
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.return_value = []
|
||||
mock_conn.__enter__ = MagicMock(return_value=mock_conn)
|
||||
mock_conn.__exit__ = MagicMock(return_value=False)
|
||||
mock_conn_ctx = MagicMock()
|
||||
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
|
||||
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
|
||||
patch("routers.content_reports.get_cursor", return_value=mock_cur):
|
||||
result = list_inbox_content_reports(tenant=tenant)
|
||||
assert isinstance(result, list)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 12. patch_report status 'under_review' – Erfolgspfad
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_patch_report_under_review():
|
||||
from routers.content_reports import patch_content_report
|
||||
|
||||
tenant = MagicMock()
|
||||
tenant.global_role = "admin"
|
||||
tenant.profile_id = 1
|
||||
|
||||
body = ContentReportPatch(status="under_review")
|
||||
|
||||
existing_row = MagicMock()
|
||||
existing_row.__getitem__ = lambda s, k: {
|
||||
"id": 5, "status": "submitted",
|
||||
"target_type": "media_asset", "target_id": 42, "resolution_note": None,
|
||||
}[k]
|
||||
existing_row.keys = lambda: ["id", "status", "target_type", "target_id", "resolution_note"]
|
||||
|
||||
updated_row = MagicMock()
|
||||
updated_row.__getitem__ = lambda s, k: {"id": 5, "status": "under_review"}[k]
|
||||
updated_row.keys = lambda: ["id", "status"]
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [existing_row, updated_row]
|
||||
|
||||
mock_conn = MagicMock()
|
||||
mock_conn_ctx = MagicMock()
|
||||
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
|
||||
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
|
||||
patch("routers.content_reports.get_cursor", return_value=mock_cur):
|
||||
result = patch_content_report(5, body, tenant=tenant)
|
||||
|
||||
assert result["ok"] is True
|
||||
assert result["status"] == "under_review"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 13. patch_report 'resolved_no_action' ohne resolution_note → 400
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_patch_resolved_no_action_requires_note():
|
||||
from routers.content_reports import patch_content_report
|
||||
|
||||
tenant = MagicMock()
|
||||
tenant.global_role = "admin"
|
||||
tenant.profile_id = 1
|
||||
|
||||
body = ContentReportPatch(status="resolved_no_action", resolution_note=None)
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
patch_content_report(99, body, tenant=tenant)
|
||||
assert exc.value.status_code == 400
|
||||
assert "Begründung" in exc.value.detail
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 14. set_legal_hold_from_report als Nicht-Superadmin → 403
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_legal_hold_from_report_requires_superadmin():
|
||||
from routers.content_reports import set_legal_hold_from_report, ContentReportLegalHoldBody
|
||||
|
||||
tenant = MagicMock()
|
||||
tenant.global_role = "admin" # nur admin, nicht superadmin
|
||||
|
||||
body = ContentReportLegalHoldBody(reason_note="Test-Begruendung")
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
set_legal_hold_from_report(1, body, tenant=tenant)
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 15. Reason-Code-Mapping: copyright → copyright_complaint
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_reason_code_mapping():
|
||||
assert _REASON_TO_HOLD_CODE["copyright"] == "copyright_complaint"
|
||||
assert _REASON_TO_HOLD_CODE["minors"] == "youth_protection"
|
||||
assert _REASON_TO_HOLD_CODE["illegal_content"] == "illegal_content"
|
||||
assert _REASON_TO_HOLD_CODE["privacy"] == "privacy_complaint"
|
||||
assert _REASON_TO_HOLD_CODE["image_rights"] == "rights_dispute"
|
||||
assert _REASON_TO_HOLD_CODE["other"] == "other"
|
||||
# Alle Reason-Codes muessen gemappt sein
|
||||
for reason in REPORT_REASONS:
|
||||
assert reason in _REASON_TO_HOLD_CODE, f"{reason} fehlt im Mapping"
|
||||
@@ -124,3 +124,27 @@ def test_api_attachments_x_content_type_options_nosniff(client: TestClient) -> N
|
||||
r2 = client.get("/api/version")
|
||||
assert r2.status_code == 200
|
||||
assert r2.headers.get("x-content-type-options") == "nosniff"
|
||||
|
||||
|
||||
def test_public_media_static_not_mounted_by_default() -> None:
|
||||
"""/media/-StaticFiles-Mount darf ohne ALLOW_PUBLIC_MEDIA_STATIC nicht aktiv sein."""
|
||||
snippet = """
|
||||
from main import app
|
||||
mounted = [getattr(r, 'path', '') for r in app.routes]
|
||||
assert not any(p == '/media' for p in mounted), (
|
||||
"ALLOW_PUBLIC_MEDIA_STATIC aktiv – /media oeffentlich erreichbar. Vor Deploy entfernen."
|
||||
)
|
||||
"""
|
||||
proc = _run_fresh_import_int(snippet, {"ENVIRONMENT": "production"})
|
||||
assert proc.returncode == 0, proc.stderr + proc.stdout
|
||||
|
||||
|
||||
def test_allow_public_media_static_activates_media_mount() -> None:
|
||||
"""Dokumentiert: ALLOW_PUBLIC_MEDIA_STATIC=1 aktiviert /media ohne Authentifizierung."""
|
||||
snippet = """
|
||||
from main import app
|
||||
mounted = [getattr(r, 'path', '') for r in app.routes]
|
||||
assert any(p == '/media' for p in mounted), "/media-Mount wurde nicht aktiviert"
|
||||
"""
|
||||
proc = _run_fresh_import_int(snippet, {"ALLOW_PUBLIC_MEDIA_STATIC": "1"})
|
||||
assert proc.returncode == 0, proc.stderr + proc.stdout
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
PostgreSQL-Integration: Roundtrip _replace_unit_sections ↔ _fetch_sections.
|
||||
|
||||
Aktivierung:
|
||||
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
||||
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf (deployter Backend-Container + PostgreSQL).
|
||||
|
||||
Voraussetzung: migrierte DB, DB_* wie Docker-Compose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from routers.training_planning import _fetch_sections, _replace_unit_sections
|
||||
|
||||
|
||||
def _integration_enabled() -> bool:
|
||||
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.integration,
|
||||
pytest.mark.skipif(
|
||||
not _integration_enabled(),
|
||||
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _db_ping() -> bool:
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT 1 AS ok")
|
||||
row = cur.fetchone()
|
||||
return row is not None and row.get("ok") == 1
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def db_ready():
|
||||
if not _db_ping():
|
||||
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
|
||||
|
||||
|
||||
def test_replace_sections_roundtrip(db_ready):
|
||||
"""INSERT-Hilfsdaten, replace, fetch — gleiche Semantik wie produktiver PUT-Pfad."""
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
club_name = f"tpl_it_club_{suffix}"
|
||||
email = f"tpl_it_{suffix}@test.local"
|
||||
|
||||
from auth import hash_pin
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||
(club_name, "T", "active"),
|
||||
)
|
||||
club_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(email, hash_pin("x"), f"TP {suffix}", "trainer", club_id),
|
||||
)
|
||||
profile_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_groups (club_id, name, trainer_id, status)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(club_id, f"Gruppe {suffix}", profile_id, "active"),
|
||||
)
|
||||
group_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(f"Übung {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||
)
|
||||
ex_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date, status, created_by
|
||||
) VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(group_id, "2026-06-01", "planned", profile_id),
|
||||
)
|
||||
unit_id = int(cur.fetchone()["id"])
|
||||
|
||||
sections_in = [
|
||||
{
|
||||
"title": "A1",
|
||||
"order_index": 0,
|
||||
"guidance_notes": "gn",
|
||||
"items": [
|
||||
{
|
||||
"item_type": "note",
|
||||
"order_index": 0,
|
||||
"note_body": "Hinweis",
|
||||
},
|
||||
{
|
||||
"item_type": "exercise",
|
||||
"order_index": 1,
|
||||
"exercise_id": ex_id,
|
||||
"planned_duration_min": 5,
|
||||
"notes": "n1",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "B2",
|
||||
"order_index": 1,
|
||||
"items": [],
|
||||
},
|
||||
]
|
||||
_replace_unit_sections(cur, unit_id, sections_in)
|
||||
loaded = _fetch_sections(cur, unit_id)
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
assert len(loaded) == 2
|
||||
assert loaded[0]["title"] == "A1"
|
||||
assert loaded[0]["guidance_notes"] == "gn"
|
||||
assert loaded[0]["order_index"] == 0
|
||||
assert len(loaded[0]["items"]) == 2
|
||||
assert loaded[0]["items"][0]["item_type"] == "note"
|
||||
assert loaded[0]["items"][0]["note_body"] == "Hinweis"
|
||||
assert loaded[0]["items"][1]["item_type"] == "exercise"
|
||||
assert int(loaded[0]["items"][1]["exercise_id"]) == ex_id
|
||||
assert loaded[0]["items"][1]["planned_duration_min"] == 5
|
||||
assert loaded[1]["title"] == "B2"
|
||||
assert loaded[1]["items"] == []
|
||||
finally:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||
conn.commit()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Unit-Tests ohne DB: abgeleitete Trainingseinheit-Payload-Helfer."""
|
||||
import pytest
|
||||
|
||||
from routers.training_planning import _flatten_exercises_from_sections
|
||||
|
||||
|
||||
def test_flatten_exercises_from_sections_order():
|
||||
unit = {
|
||||
"sections": [
|
||||
{
|
||||
"order_index": 1,
|
||||
"items": [
|
||||
{"order_index": 1, "item_type": "exercise", "exercise_id": 10},
|
||||
{"order_index": 0, "item_type": "note"},
|
||||
{"order_index": 2, "item_type": "exercise", "exercise_id": 20},
|
||||
],
|
||||
},
|
||||
{
|
||||
"order_index": 0,
|
||||
"items": [{"order_index": 0, "item_type": "exercise", "exercise_id": 5}],
|
||||
},
|
||||
]
|
||||
}
|
||||
_flatten_exercises_from_sections(unit)
|
||||
# Sektionen nach order_index; innerhalb nur exercise-Items nach order_index
|
||||
assert [x["exercise_id"] for x in unit["exercises"]] == [5, 10, 20]
|
||||
|
||||
|
||||
def test_flatten_exercises_from_sections_empty():
|
||||
unit = {"sections": []}
|
||||
_flatten_exercises_from_sections(unit)
|
||||
assert unit["exercises"] == []
|
||||
@@ -0,0 +1,108 @@
|
||||
"""GET /api/training-units: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides() -> None:
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def _tenant() -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
def test_list_training_units_keyset_incomplete_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={"cursor_id": "42"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_planned_date" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_without_limit_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "2026-05-10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "limit" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_bad_date_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "not-a-date",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_list_training_units_keyset_bad_time_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "2026-05-10",
|
||||
"cursor_planned_time": "25:99",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_planned_time" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_time_without_id_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_planned_time": "18:00",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
+572
-9
@@ -1,34 +1,597 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.65"
|
||||
BUILD_DATE = "2026-05-08"
|
||||
DB_SCHEMA_VERSION = "20260508049"
|
||||
APP_VERSION = "0.8.137"
|
||||
BUILD_DATE = "2026-05-12"
|
||||
DB_SCHEMA_VERSION = "20260515063"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
|
||||
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
"auth": "1.2.3", # P-05b: reset-password min_length=8 via Pydantic PasswordResetConfirm
|
||||
"profiles": "1.8.0", # training_planning_prefs JSONB (Planungs-UI); Patch via ProfileUpdate + Json(), Migration 055
|
||||
"tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
|
||||
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
|
||||
"club_memberships": "1.0.1", # Depends(get_tenant_context)
|
||||
"club_join_requests": "1.0.1", # Depends(get_tenant_context)
|
||||
"admin_users": "1.0.0", # GET /api/admin/users
|
||||
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
|
||||
"media_assets": "1.12.1", # official: nur Superadmin Lifecycle/PATCH; UI Lesemodus; Superadmin Upload-Verein = aktiv
|
||||
"media_rights": "1.3.1", # acting_profile_id in write_audit_log_entry auf Optional[int] (P-13 anonyme Meldungen)
|
||||
"media_assets": "1.18.1", # P-13: open_report_count in Listendaten (fuer Admins)
|
||||
"media_legal_hold": "1.0.0", # P-11: Sofortsperre-Services (set_legal_hold, release_legal_hold)
|
||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
"groups": "0.1.0",
|
||||
"skills": "0.1.0",
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.19.1", # Verein: PUT default_club_media_copyright + Prompt beim Speichern (fehlende File-Asset-Copyrights)
|
||||
"training_units": "0.2.0",
|
||||
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
||||
"training_units": "0.3.0", # GET /api/training-units Keyset cursor_planned_date + cursor_id (+ optional cursor_planned_time); Sort mit id-Tiebreak
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||
"planning": "0.10.0", # Migration 063: training_unit_phases + parallel_streams; Sektionen phase_id|parallel_stream_id; GET phases + sections
|
||||
"dashboard": "1.1.0", # GET /api/dashboard/kpis inkl. training_home (ein Client-Roundtrip für KPIs + nächste Termine)
|
||||
"training_modules": "1.0.0",
|
||||
"import_wiki": "1.0.0",
|
||||
"admin": "1.0.0",
|
||||
"membership": "1.0.0",
|
||||
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
|
||||
"maturity_models": "1.4.0", # matrix_stack_bundle: vollständiger Katalog+Modelle+Bindings Export/Import
|
||||
"content_reports": "1.5.1", # P-13: Fruehzeitige 403 fuer plain Admin in set_legal_hold_from_report (CI-Fix)
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.137",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"DB 063: training_unit_phases, training_unit_parallel_streams; Sektionen mit phase_id oder parallel_stream_id; Default whole_group für Bestand.",
|
||||
"Planung: GET training_unit liefert phases (verschachtelt) + sections (flach sortiert); Legacy-PUT sections weiterhin eine whole_group-Phase.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.136",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: api/exercises.js — Mandanten-Header für Raw-fetch (PUT Übung, Medien-Upload, Bulk-Archiv) über lokale withActiveClubHeaders statt mergeActiveClubHeader-Import (ReferenceError beim Speichern).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.135",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 3: frontend/src/api/exercises.js (Übungen, Medien/Archiv, Progressionsgraphen, KI); client.js exportiert API_URL und mergeActiveClubHeader; utils/api.js re-exportiert Modul, api-Objekt spread exercises.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.134",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 2: frontend/src/api/planning.js (Trainingsplanung); utils/api.js re-exportiert Modul, api-Objekt spread planning.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.133",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 1: frontend/src/api/client.js (request, ACTIVE_CLUB_STORAGE_KEY); utils/api.js importiert Client, bleibt Facade. Roadmap Phase 4 gestartet.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.132",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 3 abgeschlossen: TrainingPlanningPageRoot, ExerciseFormPageRoot, ExercisesListPageRoot unter components/; pages/ nur Re-Export (Soft-Limit). Roadmap UMSETZUNGSPLAN Phase 3 / M3 aktualisiert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.131",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningUnitFormModal (Neu/Bearbeiten-Einheit); frameworkLineageText in trainingPlanningPageHelpers; BASELINE_SNAPSHOT §3.4 k6-Log-Mapping.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.130",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: PUT/POST training_units — assistant_trainer_profile_ids als JSONB mit psycopg2.extras.Json schreiben (rohe Python-Liste → ProgrammingError/500 bei Co-Zuweisung).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.129",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningTrainerAssignModal (Trainer zuweisen) aus Trainingsplanungsseite; Handler per useCallback.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.128",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningModuleApplyModal (Trainingsmodul einfügen) aus Trainingsplanungsseite; gemeinsamer Callback onModuleApplySectionIndexChange.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.126",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningFrameworkImportModal aus Trainingsplanungsseite; Playwright-Test 13 (Rahmen-Dialog, skip ohne Gruppe).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.125",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Tests: Playwright 11 (Übungsliste Bulk-Toolbar), 12 (Trainingsplanung); Dashboard-Test 8 prüft HTTP 200 auf /api/dashboard/kpis; pytest test_dashboard_kpis_200_when_inner_lists_mocked.",
|
||||
"Frontend Phase 3: trainingPlanningPageHelpers.js aus TrainingPlanningPage; ExerciseListBulkToolbar data-testid.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.124",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): ExerciseListBulkToolbar-Komponente; Übungsliste nur Verdrahtung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.123",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: GET /api/dashboard/kpis — interne Aufrufe von list_exercises / list_training_units erhielten FastAPI-Query-Defaults statt None; .strip() auf Query-Objekt → 500. unwrap_query_default in beiden Handlern (Hilfsmodul fastapi_param_unwrap.py).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.122",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): useExerciseListCatalogsAndQuery — Katalog-Fetch und Übungslisten-Laden/Keyset-Pagination aus ExercisesListPage in Hook ausgelagert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.121",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): Übungsliste — Suchleiste/Chips in ExerciseListSearchBar; API-Query-Bau und Filter-Chips in utils/exerciseListQuery.js bzw. exerciseListFilterChips.js.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.120",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend: Übungsliste — Filter- und Massenänderungs-Dialoge in ExerciseListFilterModal / ExerciseListBulkModal ausgelagert; Playwright-Test 10 (Filter-Dialog).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.119",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): Übungsliste — ExerciseListCard-Komponente, Progressions-Tab lazy (Suspense); Übungspicker-Modal mit @tanstack/react-virtual; content-visibility auf Karten im Übungs-Gitter; Playwright-Test 9 Übungsliste.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.118",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/dashboard/kpis liefert training_home (upcoming, planned_with_notes, review_pending) — gleiche Logik wie zuvor zwei listTrainingUnits-Calls; Dashboard-Frontend ein Request.",
|
||||
"Migration 062: Index exercise_skills(exercise_id, level_rank_expr) für list_exercises Stufenfilter; Ausdruck wie _EXERCISE_SKILL_LEVEL_RANK_SQL.",
|
||||
"Phase 2: Vorlagen EXPLAIN unter scripts/load/explain-readpaths.sql; Playwright-Test 8 erwartet 0× GET /api/training-units auf dem Dashboard.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.117",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/training-units: optionale Keyset-Pagination (cursor_planned_date YYYY-MM-DD, cursor_id, optional cursor_planned_time bei gesetzter Startzeit; bei Keyset ist limit erforderlich). Sortierung um stabile Tie-Breaks ergänzt: (planned_time_start IS NULL), id.",
|
||||
"Migration 061: Teilindizes training_units für ASC/DESC-Keyset inkl. id (ersetzt idx_training_units_scheduled_order).",
|
||||
"frontend api.listTrainingUnits: Query-Parameter für Cursor durchreichen.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.116",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend: Org-Posteingang lädt beim ersten Mount per requestIdleCallback (Fallback setTimeout), um parallele API-Aufrufe beim Dashboard-Start zu entzerren; refresh/Inbox-Seite unverändert sofort.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.115",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/exercises: optionale Keyset-Pagination (cursor_updated_at ISO-8601 + cursor_id), stabile Sortierung updated_at DESC, id DESC; „Mehr laden“ in Übungsliste und Picker nutzt Keyset statt OFFSET.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.114",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 060: Skalierung GET /api/exercises — Partial-Indizes official/club (+ updated_at, ohne archiviert); Junction-Indizes (exercise_id, is_primary) für List-Subqueries.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.113",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 059: Teilindex training_units(planned_date, planned_time_start) nur für Zeilen ohne framework_slot_id — list_training_units Sortierung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.112",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 058: Indizes exercises(updated_at DESC) und (created_by, updated_at DESC) für list_exercises-Sortierung und „meine Übungen“.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.111",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"GET /api/dashboard/kpis: Kurzüberblick (meine Entwürfe, meine Übungen, abgeschlossene Einheiten Kalenderjahr) in einem Aufruf; Dashboard-UI nutzt den Endpunkt.",
|
||||
"Hilfsfunktion list_exercises_like_get in exercises-Router für programmatische Listen ohne Query-Defaults.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.110",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"GET /api/training-units/:id: Bei Kombinationsübungen werden `combination_slots` inkl. Kandidaten-Titel mitgeliefert (für Plan & Ablauf / Druck).",
|
||||
"Hilfsfunktion `load_combination_slots_for_exercise` im exercises-Router; GET Übung nutzt dieselbe Ladelogik.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.109",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombination: „Serien“ standardmäßig 1 (Formular/API); Archetyp kann via `ARCHETYPE_DEFAULT_REP_SERIES_COUNT` andere Vorgaben setzen; Profil‑Editor zeigt Fallback.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.108",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombination rep/manual: Feld „Pause zw. Serien“ nur ab 2 Serien sichtbar und speicherbar; Hinweis unterscheidet Wechsel zur nächsten Station; API verwirft intra_rep_rest_sec bei nur einer Serie.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.107",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombination Wiederholungsziel: `rep_series_count` in `slot_profiles_v1` (mehrere Serien à Ziel‑Wdh.); Formular‑ und Profil‑Editor‑Felder; Pause als „zwischen Serien“ beschriftet; Coach‑Zusammenfassung angepasst.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.106",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombinationsübung: Stationssteuerung `advance_mode` in `slot_profiles_v1` (zeitlich / Ziel‑Wiederholungen / Coach ohne Arbeitsuhr); Übungsformular + Planungs‑Profil‑Editor; API‑Payload verwirft Arbeit‑Sekunden außer bei Zeitmodus; Coach zeigt verkürzte Planzeile je Station.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.105",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Übungsbearbeitung Kombi: Stationen mit Pool per Modal (nur Einzelübungen), Zeiten pro Station in derselben Karte, Drag&Drop + Pfeile statt Index; API schreibt slot_index aus Reihenfolge; Gesamtdurchläufe bei Zirkel/Sequenz/Parcours/Parallel klar beschriftet.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.104",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombinations‑Ablaufprofil UX: Stationszeilen (slot_profiles_v1); Schnellwahlen Arbeit↔Pause (Zirkel + Intervall); Planungs‑Override ohne JSON; Übungsformular: Reihenfolge Stationen dann Ablaufprofil.",
|
||||
"Arbeitspapier: `.claude/docs/working/COMBINATION_TIMING_PROFILE_PLAN.md`.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.103",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Trainingsplanung: bei Kombinationszeilen optionales `planning_method_profile` (Migration 057); Planungs-Editor mit Ablaufprofil-Details, „wie Katalog“ / „aus Katalog kopieren“; Payload/Coach-PUT übernehmen Snapshot.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.102",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Kombinationsübung beim Anlegen/Bearbeiten: archetypbezogenes Ablaufprofil (geführt) + eingeklappt Roh-JSON (`CombinationMethodProfileEditor`); Schlüsselmanifest `combinationMethodProfileUi.js`. Coach: angelegtes method_profile unter Stationenliste lesbar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.101",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Training-Coach bei Kombinationsübungen: Stationen/Kandidaten mit geladenem Katalog (Kurzbeschreibung, aufklappbar Ablauf/Trainerhinweise); Archetyp-spezifischer Coach-Hilfstext; Archetyp-Labels aus `combinationArchetypes.js`.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.100",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Planungs-API/UI: Kombinationsübungen in Trainingsseinheiten (exercise_kind in Sektions-Responses; PATCH verbietet exercise_variant_id für combination); ExercisePicker ohne simple-only Filter, Badge Kombination.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.99",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"exercises Phase 2 (Kombinationsübungen): Migration 056 (`exercise_kind`, `method_archetype`, `method_profile`; Tabellen Slots/Kandidaten); CRUD über POST/PUT/GET Übung mit `combination_slots`; Liste-Filter `exercise_kind_any`; Varianten-Endpoints verbieten `exercise_kind=combination`.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.98",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"profiles: `training_planning_prefs` JSONB (Migration 055), Patch via PUT Profil — z.B. Darstellung kopierter Trainingsmodule in der Planungs-UI (nutzerspezifisch).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.97",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"Trainingsmodule (Phase 1): Bibliothek `training_modules` + `training_module_items` (Migration 054); REST `/api/training-modules`; Übernahme in Einheiten per `POST /api/training-units/{id}/apply-training-module`; Herkunft `source_training_module_id` auf kopierten Sektions-Items; UI unter /planning/training-modules und Übernahme-Dialog in der Trainingsplanung.",
|
||||
"Umsetzungsplan: `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.96",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"P-01 Admin Rechtstexte: Live-Vorschau je Abschnitt (Markdown) neben dem Editor; modale „Vollständige Vorschau“ aus dem Formular; Augen-Symbol in der Dokumentenliste für die gerenderte Ansicht (API-Laden).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.95",
|
||||
"date": "2026-05-12",
|
||||
"changes": [
|
||||
"P-01 Rechtstexte: Abschnitte in der Ausgabe mit fortlaufender §1, §2, … (nur Darstellung/PDF, nicht in der DB); Fließtext mit Markdown (react-markdown) inkl. PDF-Rendering (fett/kursiv, Listen, Links, Codeblöcke).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.94",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-13: set_legal_hold_from_report wirft 403 fuer plain Admin vor DB-Zugriff (CI-Testkonsistenz).",
|
||||
"Fix P-13: Tests test_list_inbox_requires_platform_admin und test_patch_report_under_review repariert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.93",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-13: Club-Admins können Inhaltsmeldungen zu Vereinsmedien bearbeiten (PATCH, GET-Detail).",
|
||||
"Fix P-13: Club-Admins können Legal Hold auf Vereinsmedien (nicht 'official') aus Meldung heraus setzen.",
|
||||
"Fix P-13: Abgeschlossene Meldungen in der Inbox in kollabierbare Archiv-Sektion verschoben.",
|
||||
"Fix P-13: isClubAdmin + isPlatformAdmin im OrgInboxContext exponiert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.92",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-13: Badge in Medienbibliothek aktualisiert sich sofort nach Einreichen einer Meldung.",
|
||||
"Fix P-13: Inbox zeigt Fehlermeldung statt leerem Bereich wenn Backend-Fehler auftritt.",
|
||||
"Fix P-13: Meldungen lassen sich nach Abschluss wieder öffnen (Wieder-öffnen-Button).",
|
||||
"Fix P-13: Bearbeitungskommentare werden separat im Audit-Log protokolliert.",
|
||||
"Fix P-13: Reviewer-Felder werden beim Wieder-öffnen einer Meldung zurückgesetzt.",
|
||||
"Fix P-13: Workflow-Balken im Meldungs-Detail zeigt aktuellen Bearbeitungsstand.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.91",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-13: Name- und E-Mail-Felder im Melde-Dialog fuer eingeloggte Nutzer nicht mehr bearbeitbar (readOnly).",
|
||||
"Fix P-13: Journaleintraege fuer content_report_filed leserlich (Meldegrund, Prioritaet, Status auf Deutsch).",
|
||||
"Fix P-13: Badge auf Medienkacheln zeigt Anzahl offener Meldungen (nur fuer Admins).",
|
||||
"Fix P-13: Statuswechsel an Meldungen werden im Journal des Mediums protokolliert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.90",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-13: Club-Admins sehen jetzt Inhaltsmeldungen ihrer Vereinsmedien in der Inbox (Backend-Filter + Frontend canSeeContentReports).",
|
||||
"Fix P-13: Journaleintrag (content_report_filed) in media_asset_audit_log beim Einreichen einer Meldung (Migration 053).",
|
||||
"Fix P-13: E-Mail-Benachrichtigung an alle Plattform-Admins bei neuer Meldung (best-effort).",
|
||||
"Fix P-13: Bestätigungs-E-Mail an Melder beim Einreichen (best-effort).",
|
||||
"Fix P-13: Medienname (target_filename/target_exercise_name) korrekt in Inbox-Liste angezeigt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.89",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Feat P-13: MediaPreviewModal — geteilter Medienvorschau-Dialog für alle Kontexte (Bibliothek, Übungsbearbeitung, angehängte Medien); optionale Melden- und Bearbeiten-Buttons im Header.",
|
||||
"Feat P-13: Melde-Button im ExerciseFormPage-Viewer (verlinktes Medium → Vorschau → Melden).",
|
||||
"Refactor: Inline-Vorschau-Blöcke in MediaLibraryPage, ExerciseFormPage und ExerciseAttachmentMediaStrip durch MediaPreviewModal ersetzt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.88",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Feat P-13: Melde-Button in Medienbibliothek (Grid + Liste) — öffnet ReportContentModal; nur aktive Medien ohne Legal Hold.",
|
||||
"Feat P-13: Melde-Link an jedem Medium in ExerciseAttachmentMediaStrip (Lesemodus Übung).",
|
||||
"Feat P-13: ReportContentModal — wiederverwendbares Formular (Grund, Beschreibung, Name, E-Mail, Gutglaubenserklärung); Vorausfüllung für eingeloggte Nutzer.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.87",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Feat P-13: Content-Melde-Backend (DSA/KRIT-03) — Migration 052 content_reports; POST /api/content-reports (optionale Auth, official+aktive Medien ohne Login meldbar); GET /api/me/inbox/content-reports (Plattform-Admin); PATCH /api/content-reports/{id}; POST /api/content-reports/{id}/legal-hold (Superadmin, P-11 Integration).",
|
||||
"Feat P-13: Automatische Priorisierung high fuer minors/illegal_content/youth_protection.",
|
||||
"Feat P-13: Inbox-Integration — zweiter Abschnitt 'Inhaltsmeldungen' in InboxPage.jsx; OrgInboxContext liefert contentReports + contentReportCount.",
|
||||
"Feat P-13: P-11 Legal-Hold via set_legal_hold() aus report heraus (reason_code-Mapping); keine separate Moderations-Queue.",
|
||||
"Tests: 15 Backend-Unit-Tests test_p13_content_reports.py.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.86",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-11: download_exercise_media_file gibt 451 zurück für Legal-Hold-Assets (Datei nicht mehr auslieferbar).",
|
||||
"Fix P-11: enrich_exercise_detail liefert asset_legal_hold_active im Media-Array (Frontend-Komponenten koennen Hold erkennen).",
|
||||
"Fix P-11: ExerciseMediaEmbed + ExerciseMediaThumbTile zeigen 'Medium nicht verfügbar / Gesperrt' statt Datei laden.",
|
||||
"Fix P-11: ExerciseFormPage Vorschau-Modal zeigt Hinweis statt Datei bei Legal-Hold.",
|
||||
"Fix P-11: Media-Bibliothek-Liste (list_media_assets) schliesst Legal-Hold fuer Plattform-Admins aus — nur Superadmin sieht sie.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.85",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-11: Listquery fehlte legal_hold_active/reason_code/reason_note/set_at — Badge und 'Sperre aufheben' im Modal waren nie sichtbar.",
|
||||
"Fix P-11: submitLegalHold rief loadMedia() statt loadItems() auf ('loadMedia is not a function').",
|
||||
"Fix P-11: Journal-Renderpfad verwendete nw.legal_hold_reason_code/note statt nw.reason_code/note (Keys aus dem Audit-Log).",
|
||||
"Fix P-11: Archiv-Picker (ExerciseFormPage, ExerciseInlineFileMediaModal) filtert Legal-Hold-Assets auch fuer Superadmins heraus.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.84",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Feat P-11: Legal-Hold-Sofortsperre — Migration 051 (legal_hold_active + Metadaten in media_assets; audit_log um legal_hold_set/released erweitert).",
|
||||
"Feat P-11: media_legal_hold.py — zentrale Services set_legal_hold, release_legal_hold, assert_not_under_legal_hold.",
|
||||
"Feat P-11: Retention-Job ueberspringt Assets mit legal_hold_active=TRUE (keine automatische Loeschung unter Hold).",
|
||||
"Feat P-11: Neue Admin-Endpoints POST /api/admin/media-assets/{id}/legal-hold, POST …/legal-hold/release, GET …/legal-hold (nur Superadmin).",
|
||||
"Feat P-11: Sichtbarkeitsfilter erweitert — normale Nutzer sehen Legal-Hold-Assets nicht; Superadmin/Plattform-Admin sehen sie.",
|
||||
"Feat P-11: exercises from-asset prueft Legal-Hold (LEGAL_HOLD_ACTIVE 403) vor Verknuepfung.",
|
||||
"Feat P-11: Frontend MediaLibraryPage — Legal-Hold-Badge, Superadmin-Aktionen, Bestaetigungs-Dialog, Journal-Renderpfad fuer legal_hold_set/released.",
|
||||
"Tests: 15 Backend-Unit-Tests test_p11_legal_hold.py.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.83",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix: Journal + Korrektur-Endpoint: club_admin-Pruefung nutzte falsches Schema (role-Spalte nicht in club_members, sondern in club_member_roles via has_club_role); lieferte immer 500.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.82",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Feat P-06: Volljournal fuer Medien (Migration 050) — media_asset_audit_log protokolliert Sichtbarkeits-, Copyright-, Metadaten- und Lifecycle-Aenderungen automatisch.",
|
||||
"Feat P-06: Korrektur-Deklaration (action_type='correction') via POST /api/admin/media-rights/assets/{id}/correction — zugaenglich fuer Superadmin, Uploader, Vereinsadmin.",
|
||||
"Feat P-06: Journal-Endpoint gibt jetzt events[] (Deklarationen + Auditlog chronologisch gemischt) und can_correct zurueck; Zugriff fuer Superadmin + Uploader + Vereinsadmin.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.81",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-06: check_rights_coverage gibt bei rights_status='declared' immer 'ok' zurueck — Erklaerung gilt sichtbarkeitsunabhaengig (Inhalt aendert sich nicht durch Sichtbarkeits-Promotion). 'insufficient'-Pfad entfernt. Tests angepasst.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.80",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-06: Bei Sichtbarkeits-Promotion (private→club, club→official) oeffnet das Frontend bei RIGHTS_SCOPE_INSUFFICIENT / LEGACY_REDECLARATION_REQUIRED automatisch den Einwilligungsdialog (promotion/redeclaration-Modus) statt eines alert()-Fehlers; PATCH wird nach Bestaetigung mit P-06-Feldern wiederholt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.79",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix: profiles.username -> profiles.name in Journal-Endpoint (500er behoben); RightsDeclarationDialog: doppelter Abbrechen-Button entfernt (Header-X statt Text); Playwright P-01: Platzhalter-Pruefung optional (echtes Impressum deployed); Playwright P-06c: Selector-Konflikt durch UI-Fix beseitigt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.78",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"P-06 Superadmin Medienjournal: GET /api/admin/media-rights/assets/{id}/journal liefert vollstaendiges Deklarations-Log pro Medium; Frontend: Journal-Button im Bearbeitungs-Modal (nur Superadmin), scrollbare Timeline aller Einwilligungserklaerungen mit Kontext-Feldern.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.77",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"P-06 Erweiterung: Migration 049 — 4 optionale Freitext-Kontextfelder in media_asset_rights_declarations (person_consent_context, parental_consent_context, music_rights_context, third_party_rights_context); copyright_notice direkt im Upload-Dialog erfassbar; alle drei Dialoge (RightsDeclarationDialog, ExerciseInlineFileMediaModal, ExerciseInlineEmbedModal) und alle Backend-Endpoints aktualisiert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.76",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"Fix P-06: RightsDeclarationDialog in ExerciseInlineFileMediaModal (Upload-Tab) und ExerciseInlineEmbedModal integriert; vor jedem Exercise-Media-Upload oeffnet sich der vollstaendige Einwilligungsdialog statt eines nicht-benutzbaren alert()",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.75",
|
||||
"date": "2026-05-11",
|
||||
"changes": [
|
||||
"P-06 (Upload-Einwilligungsdialog) technisch umgesetzt unter konservativen Erstannahmen (p06-v1-conservative): Migration 048 (media_asset_rights_declarations + rights_status/rights_declared_for_visibility/rights_declared_at in media_assets); zentrales Policy-Modul media_rights.py; Bulk-Upload und PATCH/Bulk-Patch mit P-06-Enforcement; Re-Deklarations-Endpoint (POST /api/media-assets/{id}/rights-declarations); Admin-Legacy-Summary (GET /api/admin/media-rights/legacy-summary+/legacy-assets); exercises.py: P-06 bei upload_exercise_media und from-asset; Frontend: RightsDeclarationDialog + Altbestand-Indikator in Medienbibliothek. KRIT-04 bleibt offen bis juristische Validierung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.74",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Rechtstexte: echtes PDF-Download via jsPDF (pdf.save) statt Browser-Print-Dialog; LegalPage und AdminLegalDocumentsPage",
|
||||
"Rechtstexte Admin: Abschnitts-Reihenfolge per Pfeil-Buttons aendern; neuen Abschnitt an beliebiger Stelle einfuegen",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.73",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Rechtstexte: PDF-Export via Browser-Print (kein neues Paket); Drucker-Button in AdminLegalDocumentsPage (laedt Volldokument) und auf LegalPage (nur bei veroeffentlichtem Inhalt); Dokument enthaelt Versionsnummer und Gueltigkeitsdatum",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.72",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Rechtstexte: Als-Entwurf-kopieren — POST /api/admin/legal-documents/{id}/copy-as-draft; Inhalt und Titel werden uebernommen, Versionsnummer inkrementiert",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.71",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Compliance P-01c: Admin-konfigurierbare Rechtstexte — DB 047 (legal_documents + legal_document_audit); Superadmin CRUD + Publish/Archive-Workflow; LegalPage laedt aus API mit Platzhalter-Fallback; AdminLegalDocumentsPage unter /admin/legal-documents",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.70",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Compliance P-01b: Einstellungen/Rechtliches (/settings/legal) fuer mobile/PWA-Darstellung; Hub mit Links zu Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.69",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Compliance P-01 (KRIT-01) technischer Teil: Rechtstextseiten /impressum, /datenschutz, /nutzungsbedingungen, /medienrichtlinie als oeffentliche Routen angelegt (Platzhalter, kein Auth erforderlich)",
|
||||
"Login-Seite und Desktop-Sidebar enthalten Links zu allen vier Rechtstextseiten",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.68",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Sicherheit P-12 (MITT-05): logout() bereinigt alle sj_coach_*-Schlüssel aus sessionStorage; Präfix-gezielte Löschung, keine fremden Schlüssel betroffen",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.67",
|
||||
"date": "2026-05-10",
|
||||
"changes": [
|
||||
"Sicherheit P-05b: PasswordResetConfirm.new_password min_length=8 (POST /auth/reset-password)",
|
||||
"Sicherheit P-03b: Retention-Default HIDDEN_TO_PURGE 90->30 Tage (gemaess Loeschkonzept 30+30)",
|
||||
"Sicherheit P-04: Positive Promotion-Tests haerten (explizit 200 + Payload); Umlaut in Fehlermeldung",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.66",
|
||||
"date": "2026-05-09",
|
||||
"changes": [
|
||||
"Sicherheit P-03: Papierkorb-Retention-Job (media_retention_job.py) als Docker-Service retention-cron aktiviert (lauft taglich um 03:00 Uhr)",
|
||||
"Sicherheit P-04: Copyright-Pflicht bei Sichtbarkeits-Promotion auf club/official in PATCH und bulk-patch (media_assets)",
|
||||
"Sicherheit P-05: Passwort-Mindestlange PUT /auth/pin von 4 auf 8 Zeichen angehoben",
|
||||
"Sicherheit P-07: Release-Test fur ALLOW_PUBLIC_MEDIA_STATIC in test_security_release.py ergaenzt",
|
||||
"Sicherheit P-23: LoginPage minLength 6 auf 8 angehoben; hartcodierter Versionsstring entfernt",
|
||||
"Sicherheit P-24: CORS allow_methods und allow_headers auf benotigte Werte eingeschrankt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.65",
|
||||
"date": "2026-05-08",
|
||||
|
||||
@@ -81,6 +81,44 @@ services:
|
||||
networks:
|
||||
- shinkan-network
|
||||
|
||||
retention-cron:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: shinkan-retention-cron
|
||||
command: >
|
||||
python -c "
|
||||
import time, subprocess, sys, os, datetime
|
||||
def next_3am():
|
||||
now = datetime.datetime.now()
|
||||
target = now.replace(hour=3, minute=0, second=0, microsecond=0)
|
||||
if target <= now:
|
||||
target += datetime.timedelta(days=1)
|
||||
return (target - now).total_seconds()
|
||||
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
|
||||
while True:
|
||||
time.sleep(next_3am())
|
||||
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
|
||||
"
|
||||
working_dir: /app
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
DB_NAME: shinkan
|
||||
DB_USER: shinkan_user
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
# Loeschkonzept (Audit P-03b): 30 Tage Soft-Trash, dann 30 Tage Hidden, dann Purge (gesamt 60 Tage).
|
||||
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS: "${MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS:-30}"
|
||||
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS: "${MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS:-30}"
|
||||
volumes:
|
||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
||||
depends_on:
|
||||
- postgres
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- shinkan-network
|
||||
|
||||
volumes:
|
||||
shinkan-db-data:
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# Shinkan Jinkendo – Fachliche Nutzerfunktionen (Ist-Stand)
|
||||
|
||||
**Zweck:** Überblick über die **wesentlichen, produktiv nutzbaren Funktionen** aus Nutzer- und Fachperspektive – zur Weitergabe an Design, Product Discovery oder externe Fachplanung.
|
||||
|
||||
**Technischer Detailstand:** App-Version (`APP_VERSION`) und Datenbankschema (`DB_SCHEMA_VERSION`) siehe **`backend/version.py`** — dort ist der autoritative Stand.
|
||||
|
||||
**Vertiefung:** Domänenmodell `.claude/docs/functional/DOMAIN_MODEL.md`, Lieferdetal `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md`, Projektstatus `.claude/docs/PROJECT_STATUS.md`, Entwickler-Handover `docs/HANDOVER.md`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Produktauftrag und Zielgruppe
|
||||
|
||||
**Shinkan Jinkendo** ist eine **Web-Applikation für Trainer, Vereinsadmins und Inhaltsverantwortliche** in der Kampfsport- und Trainingsplanung: zentrale Übungs- und Methodenverwaltung, strukturierte **Trainingsplanung für Gruppen**, wiederverwendbare **Rahmenprogramme**, sowie **Governance** von Inhalten (Sichtbarkeit, Vereinszuordnung, Plattform-Inhalte).
|
||||
|
||||
**Explizit keine persönliche Sportler-App:** Es geht nicht um individuelles Leistungstracking von Endnutzern oder um ein Athleten-Tagebuch; der Fokus liegt auf **vereinlicher/trainersicher Organisation von Wissen und Ablaufplänen**.
|
||||
|
||||
---
|
||||
|
||||
## 2. Rollen (vereinfachte Nutzerbilder)
|
||||
|
||||
Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter Nutzer, aktiver Verein, Plattform- vs. Vereins-Admin).
|
||||
|
||||
| Rollenprofil (fachlich) | Typische Aufgaben in der App |
|
||||
|-------------------------|------------------------------|
|
||||
| **Trainer / Redakteur** | Übungen anlegen und pflegen, medienreich beschreiben, filtern/suchen; Trainingseinheiten für Gruppen planen; Rahmenprogramme nutzen oder mitgestalten (je nach Berechtigung); Medienbibliothek nutzen. |
|
||||
| **Vereinsadmin** | Vereinsdaten, Mitgliedschaften, ggf. vereinsgebundene Inhalte und Medien; kann je nach Implementierung **Inhaltsmeldungen zu Vereinsmedien** bearbeiten und **Legal Hold** für Vereinsmedien auslösen. |
|
||||
| **Plattform-Admin** | Globale Kataloge, Hierarchien, Importe, Nutzerverwaltung (soweit freigeschaltet); **Posteingang** inkl. organisationsbezogener Meldungen; Reifegradmodelle / Matrix-Stack. |
|
||||
| **Superadmin** | Stärkste technische Rolle: u. a. **offizielle Plattform-Inhalte** (`official`), tiefe Medien-Lifecycle-Operationen, ausgewählte Hochrisiko-Aktionen (z. B. bestimmte Legal-Hold-Fälle). |
|
||||
|
||||
**Aktiver Verein:** Nutzer mit Vereinsbezug arbeiten oft im Kontext eines **gewählten aktiven Vereins** (Profil, API-Header); das beeinflusst Sichtbarkeit von Inhalten und Mandantenlogik.
|
||||
|
||||
---
|
||||
|
||||
## 3. Hauptnavigation (Nutzerpfade)
|
||||
|
||||
Über die **Hauptnavigation** (mobil und Desktop) sind u. a. erreichbar:
|
||||
|
||||
- **Übersicht** – Einstieg / Dashboard.
|
||||
- **Posteingang** – für berechtigte Nutzer: **Änderungs- und Organisationsanfragen** sowie **Inhaltsmeldungen** (Workflow, Status, Archiv).
|
||||
- **Übungen** – Katalogarbeit, Suche, Filter, Detail, Bearbeitung; **Progressionsgraphen** zwischen Übungen; **Fähigkeiten** (Skills) als verknüpfte Dimension.
|
||||
- **Planung** – Kalender-/Listenlogik für **Trainingseinheiten** (Sektionen, Übungen, optional **Übungsvarianten**); **Trainingsrahmen (Bibliothek)** mit Zielen und Slots; **Durchführungsansicht** und **Coaching-Modus** pro Einheit (je Route).
|
||||
- **Medien** – zentrale **Medienbibliothek** (Filter, Suche, Tags, Lifecycle, Copyright-Hinweise; rollenabhängige Bearbeitung).
|
||||
- **Vereine** – Organisation: Vereine, Struktur, Gruppen (soweit für den Nutzer freigeschaltet).
|
||||
- **Einstellungen** – Profil, Systeminfos, ggf. Rechtstexte; **Trainer-Kontexte** separat (Route `trainer-contexts`).
|
||||
- **Admin** (nur Admin-Rolle) – Plattformbereich: Nutzer, Hierarchie/Kataloge, Reifegradmodelle, MediaWiki-Import, **Rechtstexte/P-01** u. a.
|
||||
|
||||
Öffentlich bzw. ohne volle App: **Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie**; Login/Registrierung/Verifizierung.
|
||||
|
||||
---
|
||||
|
||||
## 4. Funktionsblöcke im Detail (fachlich)
|
||||
|
||||
### 4.1 Übungen (Kernobjekt)
|
||||
|
||||
- **Anlegen, Bearbeiten, Archivieren/Löschen** je nach Rolle und Sichtbarkeit.
|
||||
- **Mehrdimensionale Einordnung:** Fokusbereiche, Stilrichtungen, Trainingsstile, Zielgruppen, **Fähigkeiten mit Stufen**; Suche und Filter über diese Dimensionen.
|
||||
- **Übungsvarianten:** mehrere Ausprägungen einer Übung (z. B. Aufbau, Schwierigkeit, Material), mit Reihenfolge und optionaler **Voraussetzungsvariante**.
|
||||
- **Progressionsgraph:** gerichtete Beziehungen **von Übung zu Übung** (und Variantenbezug), Pflege in der Übungswelt; unterstützt didaktische „weiter“-Ketten.
|
||||
- **Medien an der Übung:** Upload, Einbettung, Verknüpfung aus dem **Archiv**; Darstellung in Detail- und Bearbeitungsansicht.
|
||||
- **Rich-Text-Felder** (Ablauf, Ziele, Hinweise): **Inline-Verweise auf verknüpfte Medien** über eine einheitliche Platzhalter-/Renderlogik (konsistent mit Archiv-Governance).
|
||||
- **Exercise Blocks** („Bausteine“) und gespeicherte Suchpräferenzen, wo implementiert.
|
||||
- **Kombinationsübungen** („combination“, Migration 056): Sonderform im Übungskatalog mit **Stationen/Slots**, **Trainingsmethode-/Archetyp** (`method_archetype`), optionalem strukturierten **Ablaufprofil** (`method_profile`). In der Planung wie eine Übung ohne Variante einsetzbar; im **Coach** werden Stations-Kandidaten und Archetyp-Hilfstexte angezeigt (Ausbauschritte B/C nach Fachspez § 10.4 dokumentiert unter `.claude/docs/functional/… Kombinationsübungen Spezifikation V2.md` Anhang A).
|
||||
|
||||
### 4.2 Fähigkeiten, Methoden, Kataloge
|
||||
|
||||
- **Globaler Fähigkeitskatalog** mit hierarchischer Struktur (Kategorien, Stufen); Zuordnung zu Übungen.
|
||||
- **Trainingsmethoden-Katalog** (bestehende Domäne).
|
||||
- **Admin/Katalog-Pflege** für Fokusbereiche, Stile, Zielgruppen und Zusammenhänge (Plattform-Admin-Bereich).
|
||||
|
||||
### 4.3 Reifegradmodelle (Fähigkeitsmatrix)
|
||||
|
||||
- **Matrixbasierte Modelle** mit Stufen und Zelltexten; **kontextsensitive Auflösung** (Fokus, optional Stilrichtung, Trainingsart) über Bindings.
|
||||
- **Export/Import** einzelner Modelle und **Komplett-Stack** (Admin-Werkzeuge) für Übertrag zwischen Umgebungen oder Backup.
|
||||
|
||||
### 4.4 Trainingsplanung
|
||||
|
||||
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
|
||||
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden.
|
||||
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
|
||||
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
|
||||
- **Durchführung:** Ansicht zum Abarbeiten einer Einheit; **Coaching-Modus** als separater Erlebnispfad (generischer Zeit-Block pro Platzierung); bei **Kombinationsübungen** zusätzliche **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** siehe Kombination-Fachspez **Anhang A** (implementierter Umfang vs. nächste Stufen).
|
||||
|
||||
### 4.5 Medienbibliothek und Archiv
|
||||
|
||||
- **Zentrale Medienverwaltung:** Suche, Filter (u. a. Lifecycle, Medientyp, Verein für Admins), Tags, Copyright-Felder.
|
||||
- **Lifecycle:** aktive Nutzung, Papierkorb-Stufen, Wiederherstellung; endgültiges Entfernen stark eingeschränkt (Superadmin-Kontext).
|
||||
- **Governance:** Sichtbarkeit (z. B. privat, vereinsbezogen, **official**); **official** ist fachlich „Plattform offiziell“ und an **Superadmin** gebunden.
|
||||
- **Rechtliche Sofortmaßnahme:** **Legal Hold** kann Medien vor automatisiertem Lifecycle schützen (Fälle aus Meldungen oder Admin-Prozessen).
|
||||
|
||||
### 4.6 Organisation und Mitgliedschaft
|
||||
|
||||
- **Vereine (Clubs)** mit Struktur (Sparten/Divisions, Trainingsgruppen) je nach Ausprägung.
|
||||
- **Beitritts- und Mitgliedschaftslogik** (Requests, Rollen) für mandantenfähige Zusammenarbeit.
|
||||
|
||||
### 4.7 Governance von Übungsinhalten
|
||||
|
||||
- **Änderungsanfragen** (Content Change Requests) für vorgeschlagene Änderungen an Inhalten – Einreichung und Bearbeitung über Posteingang/Admin-Prozesse (Detailtiefe siehe Fachdoku).
|
||||
- **Sichtbarkeits- und Statusmodelle** für Übungen (Entwurf, veröffentlicht, archiviert – konkrete Werte siehe Datenmodell).
|
||||
|
||||
### 4.8 Inhaltsmeldungen (P-13, vertrauens- und compliance-orientiert)
|
||||
|
||||
- **Melden** von problematischen Inhalten (auch aus Medien- und Übungskontexten; **official**-Medien teils ohne Login meldbar).
|
||||
- **Posteingang für Admins:** Eingang neuer Meldungen, **Statusworkflow** (z. B. eingereicht, in Prüfung, erledigt/abgelehnt), Notizen, **Wiedereröffnen**; getrennte Darstellung abgeschlossener Fälle (Archiv).
|
||||
- **Priorisierung** bei sensiblen Kategorien (Minderjährige, illegaler Inhalt, Jugendschutz – fachlich automatisch höher gewichtet).
|
||||
- Anbindung an **Legal Hold** und Audit-Spuren im Medien-Journal wo vorgesehen.
|
||||
|
||||
### 4.9 Import und Plattform-Werkzeuge
|
||||
|
||||
- **MediaWiki-basierter Import** von Übungsinhalten mit Tracking und Duplikat-Referenzen (Admin).
|
||||
- **Plattformnutzerverwaltung** und **Rechtstexte** mit editorseitiger und listenbasierter Vorschau (Markdown, strukturierte Ausgabe inkl. PDF-Darstellung – siehe technische Versionsnotizen).
|
||||
|
||||
---
|
||||
|
||||
## 5. Bekannte Lücken und Planungshinweise (kurz)
|
||||
|
||||
Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen** für Product/Design:
|
||||
|
||||
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
|
||||
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
|
||||
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
|
||||
- **Coach / Kombination:** nächste Stufen **Zeitleisten-Splitting** und **Archetyp-Timer** (Fachspez § 10.4 Stufe B/C; Umsetzungsplan Phase 4b–d); **geführtes Erfassen** von `method_profile` im Übungseditor.
|
||||
|
||||
---
|
||||
|
||||
## 6. Änderungshistorie dieser Zusammenfassung
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-12 | Erstfassung für Übergabe an fachliches Design; Abgleich mit Code-Navigation, `version.py`, `HANDOVER.md`, `FEATURES_DELIVERED`, `DOMAIN_MODEL`. |
|
||||
| 2026-05-12 | Kombinationsübungen + Coaching Stufe A; Verweise auf Fachspezifikation (`…Kombinationsuebungen…` V3 Anhang A) und `TRAINING_MODULES_IMPLEMENTATION_PLAN.md`. |
|
||||
+61
-20
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-07
|
||||
**App-Version / DB-Schema:** App **0.8.59**, DB-Schema siehe `backend/version.py` (`DB_SCHEMA_VERSION`)
|
||||
**Stand:** 2026-05-13
|
||||
**App-Version / DB-Schema:** App **0.8.120**, DB-Schema **`20260514062`** (`backend/version.py`: `APP_VERSION`, `DB_SCHEMA_VERSION`)
|
||||
|
||||
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
|
||||
|
||||
@@ -20,6 +20,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
| Thema | Pfad |
|
||||
|--------|------|
|
||||
| **Architektur-Zielbild, Refaktor, Roadmap, Regeln** | **`docs/architecture/README.md`** |
|
||||
| **Performance-Baseline (Phase 0)** | **`docs/architecture/BASELINE_SNAPSHOT.md`**, **`scripts/load/README.md`** |
|
||||
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
@@ -29,9 +31,12 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
|
||||
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
|
||||
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| **Trainingsmodule & Kombinationsübungen (Fachspez, Drift-Schutz)** | `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (§ 10.2.1 Archetyp-IDs, § 10.4 Coaching-Stufen, **Anhang A** Code-Abgleich) |
|
||||
| **Umsetzungsplan** (Module/Kombination/Coach) | `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` |
|
||||
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
|
||||
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
|
||||
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
|
||||
---
|
||||
|
||||
@@ -71,6 +76,12 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
|
||||
### Trainingsmodule, Kombinationsübungen und Coach (Stand **0.8.120**)
|
||||
|
||||
- **Fachspez & Drift-Schutz:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (**§ 10.2.1** IDs, **§ 10.4** Coaching-Stufen, **§ 10.6** Produkt-Backlog, **Anhang A** Abgleich).
|
||||
- **Umsetzungsplan:** `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase **2** / **4** teilweise; Pakete **4a–g** — u. a. **4e** Archetyp-Admin, **4f** Massen-Vorbelegung, **4g** Backend-Validierung).
|
||||
- **Ist kurz:** Trainingsmodule-Bibliothek (Phase **1**) umgesetzt; Kombi-Katalog (**056**), Planungs-Snapshot **`planning_method_profile` (057)** mit **Client-Merge** Katalog+Planung (`comboPlanningMethodProfile.js`); Planung: Modal **„Ablauf bearbeiten…“**, Klammer `CombinationPlanBracket`; Coach **Stufe A** mit lesenden Profil-Labels und konsistenter Slot-Darstellung (`CombinationCoachSlots`, `ExerciseFullContent`). **Offen:** Coach **Stufe B/C** (individuelle Archetyp-Steuerung), **Administrierbarkeit der Archetypen** (derzeit nur Konstanten), **einfache Vorbelegung aller** Zeit-/Anzahlfelder, **serverseitige** Profil↔Archetyp-Restriktionen — siehe Fachspez **§ 10.6**.
|
||||
|
||||
---
|
||||
|
||||
## 4. Stand: Medien-Management (Ist, 2026-05-07)
|
||||
@@ -105,35 +116,65 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
---
|
||||
|
||||
## 5. Geplant: Inline-Medienverlinkung (nicht umgesetzt)
|
||||
## 5. Inline-Medien im Fließtext (Spec Abschnitt 11 — umgesetzt)
|
||||
|
||||
**Ziel:** Mediendarstellung **innerhalb** von Fließtext-Feldern (Ablauf, Ziele, Trainerhinweise), konsistent mit derselben **`exercise_media`‑** bzw. Asset-Governance wie die Medienliste.
|
||||
**Ist:** Platzhalter-Syntax, zentraler Render-Pfad, Modal-Picker, Größenwahl, Drag-and-Drop in den Übungstextfeldern — siehe **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (Abschnitt 11), **`FEATURES_DELIVERED_2026-Q2.md`** Abschnitt 12.3 und **`PROJECT_STATUS.md`**.
|
||||
|
||||
**Norm:** **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — u. a.:
|
||||
|
||||
- Verweis auf **`exercise_media.id`** (oder kanonisch übersetzte Markup-Syntax), **keine** zweite Sichtbarkeitslogik.
|
||||
- **Ein** zentraler Render-/Sanitize-Pfad für Übungstexte; keine verstreuten „roh `dangerouslySetInnerHTML`“-Pfade.
|
||||
- XSS/CSP: nur Allowlist-HTML und kontrollierte Player-Komponenten.
|
||||
|
||||
**Reihenfolge:** Archiv & aktuelle Governance gelten als Basis; Inline ist die **nächste** inhaltliche Ausbaustufe für Medien (siehe **`PROJECT_STATUS.md`** Nächste Schritte).
|
||||
**Weiteres:** UX-Politik, ggf. strategische Vereinheitlichung der Referenzmodellierung (reine Asset-Referenz vs. `exercise_media`) — siehe Nächste Schritte in **`PROJECT_STATUS.md`**.
|
||||
|
||||
---
|
||||
|
||||
## 6. Nächste Session — sinnvolle Arbeitspakete
|
||||
## 6. P-13: Content-Meldeverfahren (vollständig implementiert, 2026-05-11)
|
||||
|
||||
1. **Inline §11:** Syntax festlegen (z. B. `{{exerciseMedia:id}}` → kanonisches HTML), Server normalisieren bei Speichern, einen **`renderExerciseRichText()`**-Pfad im Frontend.
|
||||
2. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
3. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
4. **S3/Adapter:** Speicher-Abstraktion §7 — wenn Produkt es verlangt.
|
||||
5. **Rahmen/UI:** Kalender „aus Rahmen übernehmen“ weiter anbinden (parallel, unabhängig von Medien).
|
||||
**DSA-konformes Meldeverfahren (KRIT-03) — App 0.8.87–0.8.94.**
|
||||
|
||||
**Backend (`backend/routers/content_reports.py`, Migrationen 052–053):**
|
||||
- `POST /api/content-reports` — optionale Auth; `official`-Medien ohne Login meldbar; E-Mail-Bestätigung an Melder + Benachrichtigung aller Plattform-Admins (best-effort).
|
||||
- `GET /api/me/inbox/content-reports` — Plattform-Admin: alle Meldungen; Club-Admin: nur Meldungen zu Medien eigener Vereine.
|
||||
- `GET /api/content-reports/{id}` — Plattform-Admin + zuständiger Club-Admin.
|
||||
- `PATCH /api/content-reports/{id}` — Status-Übergang (submitted → under_review → resolved/rejected); Wiedereröffnen (→ submitted) setzt Prüferfelder zurück; Audit-Log-Einträge bei Status- und Notizänderungen.
|
||||
- `POST /api/content-reports/{id}/legal-hold` — Superadmin (immer) oder Club-Admin (Vereinsmedien, nicht `official`); integriert P-11 `set_legal_hold()`; plain Admin erhält früh 403.
|
||||
- Automatische Priorisierung `high` für `minors`/`illegal_content`/`youth_protection`.
|
||||
- Migration 053: `content_report_filed` Event-Typ in `media_asset_audit_log` CHECK-Constraint.
|
||||
- `open_report_count` in `list_media_assets`-Response für Admin-Nutzer.
|
||||
- 15 Backend-Tests in `backend/tests/test_p13_content_reports.py` (alle grün nach CI-Fix 0.8.94).
|
||||
|
||||
**Frontend:**
|
||||
- `ReportContentModal.jsx` — Melde-Formular; `onSuccess`-Callback; readOnly-Felder für eingeloggte Nutzer.
|
||||
- `MediaPreviewModal.jsx` — geteilter Vorschau-Dialog; optionale Melden- und Bearbeiten-Buttons.
|
||||
- `InboxPage.jsx` — zweiter Abschnitt „Inhaltsmeldungen”; `WorkflowBar` (3-Schritte-Fortschrittsbalken); `ReportDetailModal` mit Workflow, Prüferinfo, Notiz, Wiedereröffnen-Button; Archiv-Trennung (offen vs. abgeschlossen, kollabierbar); Legal-Hold-Button für Superadmin + Club-Admin.
|
||||
- `OrgInboxContext.jsx` — liefert `contentReports`, `contentReportCount`, `canAccessContentReports`, `isClubAdmin`, `isPlatformAdmin`, `isSuperadmin`, `contentReportsError`; Club-Admins haben Zugriff auf Berichte.
|
||||
- `MediaLibraryPage.jsx` — rotes Badge mit `open_report_count` auf Medienkarten; Journal-Eintrag für `content_report_filed`; Badge-Aktualisierung via `onSuccess`.
|
||||
- Melde-Button in **MediaLibraryPage** (Grid + Liste + Viewer), **ExerciseFormPage** (Viewer), **ExerciseAttachmentMediaStrip** (Viewer).
|
||||
|
||||
**Offen (explizit zurückgestellt):**
|
||||
- P-14 Moderations-UI (eigene Seite), P-15 Uploader-Benachrichtigung bei Sperrung, P-16 Beschwerdeverfahren.
|
||||
- Melde-Einstieg im Coaching-Modus (Feedback-Schritt, nicht kritisch).
|
||||
|
||||
---
|
||||
|
||||
## 7. Technische Referenz (kurz)
|
||||
## 7. Nächste Session — sinnvolle Arbeitspakete
|
||||
|
||||
1. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
||||
2. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||
3. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
4. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
5. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||
6. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||
7. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||
8. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||
9. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||
10. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||
11. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||
|
||||
---
|
||||
|
||||
## 8. Technische Referenz (kurz)
|
||||
|
||||
| Bereich | Einstieg |
|
||||
|---------|----------|
|
||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
||||
| Coach-Kombination / Merge-Profil (Frontend) | `TrainingCoachPage.jsx`, `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
|
||||
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
|
||||
| Frontend API | `frontend/src/utils/api.js` |
|
||||
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
|
||||
@@ -141,7 +182,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
---
|
||||
|
||||
## 8. Veraltete Hinweise
|
||||
## 9. Veraltete Hinweise
|
||||
|
||||
`.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Phase 0 – Performance-Baseline (Shinkan Jinkendo)
|
||||
|
||||
**Zweck:** Reproduzierbarer Startpunkt **vor** Phase 2 (Backend-Lesepfade, Summary-API).
|
||||
**Stand:** 2026-05-13 · Backend-App-Version laut `backend/version.py`: **0.8.110**
|
||||
|
||||
Nach grösseren Deployments oder Schema-Änderungen: Bundle-Abschnitt neu erfassen (`npm run build`); API-/k6-Werte bei Bedarf aktualisieren.
|
||||
|
||||
---
|
||||
|
||||
## 1. Frontend-Bundle (`npm run build`)
|
||||
|
||||
Messung: Repo-Root → `cd frontend && npm run build` (Vite Production).
|
||||
**Hinweis:** Dateinamen mit Hash (`index-*.js`) ändern sich pro Build; relevant sind Grössenordnungen und gzip.
|
||||
|
||||
### 1.1 Einstieg & globale Vendor-Chunks (Auszug letzter Lauf CI-lokal)
|
||||
|
||||
| Asset (Muster) | raw kB | gzip kB | Rolle |
|
||||
|----------------|--------|---------|--------|
|
||||
| `index.html` | 1.84 | 0.73 | Einstieg |
|
||||
| `index-*.css` | 127.55 | 21.58 | Globale Styles |
|
||||
| `index-*.js` (App-Shell / Router) | 64.83 | 17.45 | Haupteinstieg nach Code-Splitting |
|
||||
| `vendor-react-*.js` | 142.42 | 45.67 | React + DOM |
|
||||
| `vendor-router-*.js` | 65.94 | 22.51 | react-router |
|
||||
| `vendor-markdown-*.js` | 161.54 | 49.31 | Markdown-Stack (wird mit Routen geladen) |
|
||||
| `vendor-pdf-*.js` | 390.80 | 128.98 | jsPDF (Route-bezogen) |
|
||||
|
||||
### 1.2 Schwerste Route-Chunks (lazy, nach Route)
|
||||
|
||||
| Bereich | typ. Chunk-Grösse (raw / gzip) | Datei-Muster (Beispiel) |
|
||||
|---------|-------------------------------|-------------------------|
|
||||
| Trainingsplanung | 71.81 kB / 18.67 kB | `TrainingPlanningPage-*.js` |
|
||||
| Übung bearbeiten | 91.31 kB / 22.49 kB | `ExerciseFormPage-*.js` |
|
||||
| Medienbibliothek | 59.42 kB / 13.69 kB | `MediaLibraryPage-*.js` |
|
||||
| Dashboard | 19.97 kB / 5.93 kB | `Dashboard-*.js` |
|
||||
|
||||
**Abnahme Phase 0 (Bundle):** Zahlen dokumentiert; Re-Run: `npm run build` und Tabelle abgleichen.
|
||||
|
||||
---
|
||||
|
||||
## 2. API-Latenz (p95) – Top-Routen
|
||||
|
||||
**Messung** erfolgt auf **Zielumgebung** (z. B. dev.shinkan / prod) mit gleicher Topologie wie Nutzer (HTTPS, Proxy). Nicht aus dem leeren Arbeitsverzeichnis ohne laufendes Backend messbar.
|
||||
|
||||
### 2.1 Vorgehen (empfohlen)
|
||||
|
||||
- **Access-Logs** des Reverse-Proxy (Request-Zeit), oder
|
||||
- **APM** / OpenTelemetry, oder
|
||||
- **k6** mit authentifizierten Szenarien (Token aus Testaccount; Header `X-Auth-Token`, ggf. `X-Active-Club-Id`), oder
|
||||
- manuell: wiederholte `curl -w '%{time_total}\n'` mit gleichem Token
|
||||
|
||||
### 2.2 Vorlage (aus Umgebung ausfüllen)
|
||||
|
||||
| Route (Beispiel) | Methode | p95 (ms) | Datum / Umgebung | Bemerkung |
|
||||
|------------------|---------|----------|------------------|-----------|
|
||||
| `/api/profiles/me` | GET | *—* | *nach Messung* | |
|
||||
| `/api/exercises` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
|
||||
| `/api/training-units` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
|
||||
| `/api/media-assets` (Liste) | GET | *—* | *nach Messung* | |
|
||||
| `/health` | GET | *—* | *nach Messung* | k6: siehe `scripts/load/` |
|
||||
|
||||
**Abnahme Phase 0 (API):** Verfahren steht; Tabelle mindestens für **`/health`** nach erstem k6-Lauf befüllbar; übrige Zeilen bei nächstem Monitoring-Export.
|
||||
|
||||
---
|
||||
|
||||
## 3. Lasttestszenario
|
||||
|
||||
### 3.1 E2E-Smoke (fachlicher Pfad)
|
||||
|
||||
- **Befehl:** Repository-Root, `npm run test:e2e` (setzt `PLAYWRIGHT_BASE_URL`, Testuser per Env, siehe `.gitea/workflows/test.yml`).
|
||||
- **Abdeckung:** Login, Dashboard, Navigation u. a. – entspricht grob „Login → Dashboard → weitere Screens“.
|
||||
- **Baseline notieren:** Dauer eines vollen Laufs, Anzahl passed (z. B. 26 Tests), Datum.
|
||||
|
||||
| Messung | Wert | Datum |
|
||||
|---------|------|-------|
|
||||
| Playwright Gesamtlauf (lokal/CI) | *—* | *nach Messung* |
|
||||
| passed / total | 26 / 26 (Ziel) | |
|
||||
|
||||
### 3.2 EXPLAIN (Phase 2 – Lesepfade)
|
||||
|
||||
- **Datei:** **`scripts/load/explain-readpaths.sql`** — repräsentative Statements für `list_exercises` / Stufenfilter / `training_units`; auf der Ziel-DB mit `EXPLAIN (ANALYZE, BUFFERS)` ausführen (Token/Tenant nicht im Skript; wie bei echten API-Queries filtern).
|
||||
|
||||
### 3.3 k6 – parallele /health
|
||||
|
||||
- **Skript:** `scripts/load/k6-health-baseline.js`
|
||||
- **CI:** Läuft **automatisch** im Gitea-Workflow im Job **`k6-health-baseline`** (eigenständig, ohne Playwright; `.gitea/workflows/test.yml`). Parallel dazu **Playwright** im Job **`playwright-tests`**.
|
||||
- **Lokal:** siehe `scripts/load/README.md`
|
||||
- **Baseline notieren:** k6-Ausgabe `http_req_duration` p(95), Checks succeeded.
|
||||
|
||||
| Szenario | p95 / Fehlerquote | Datum / BASE_URL |
|
||||
|----------|-------------------|------------------|
|
||||
| 10 VUs, 30 s `/health` | *—* | *nach Messung* |
|
||||
|
||||
### 3.4 Aus dem Deployment-/CI-Log übernehmen (k6 `k6-health-baseline`)
|
||||
|
||||
Das Skript `scripts/load/k6-health-baseline.js` nutzt **10 VUs**, **30 s**, Ziel **`GET {BASE_URL}/health`** (siehe Workflow-Env für `BASE_URL`).
|
||||
|
||||
**In die Tabelle oben (Abschnitt 3.3) eintragen — aus der k6-Zusammenfassung am Ende des Jobs:**
|
||||
|
||||
| Feld in BASELINE_SNAPSHOT | Wo im k6-Log (typisch) |
|
||||
|---------------------------|-------------------------|
|
||||
| **p95** (Latenz ms) | Zeile **`http_req_duration`** → Wert **`p(95)=…`** (ganze Zahl oder ms mit Einheit wie `12.34ms`) |
|
||||
| **Fehlerquote** | Zeile **`http_req_failed`** → z. B. `0.00%` bzw. `✓ 0%` — oder kurz „0 %“ notieren |
|
||||
| **Checks** (optional) | Zeile **`checks`** → Anteil **`✓`** (soll **100 %** sein, sonst Hinweis) |
|
||||
| **Datum / BASE_URL** | Deploy-Datum + die **öffentliche** Basis-URL des Laufs (wie im Workflow gesetzt, z. B. `https://dev.shinkan.jinkendo.de`) |
|
||||
| **App-Version** (optional) | dieselbe wie im Deploy (`backend/version.py` / Release), damit M2-Vergleich ressortfähig bleibt |
|
||||
|
||||
**Zusätzlich (Abschnitt 2.2):** nur die Zeile **`/health` GET`** mit dem **gleichen** p95 befüllen, wenn ihr dort noch Platzhalter habt — echte API-Routen (`/api/...`) kommen weiter aus Monitoring/k6 mit Auth, nicht aus diesem Job.
|
||||
|
||||
---
|
||||
|
||||
## 4. Nächster Schritt (Roadmap)
|
||||
|
||||
- **Phase 0** ist für den Pipeline-Teil **abgeschlossen**: Bundle dokumentiert; **k6** läuft in CI nach jedem relevanten Deploy (mit Test-Suite); API-p95-Tabellen kann das Team aus Monitoring weiter befüllen (optional, kein Deploy-Blocker).
|
||||
- **Phase 2** (Backend Lesepfade) ist **abgeschlossen** — siehe [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md); nach Deploy **p95 erneut messen** und mit den Werten aus Abschnitt 2 dieser Datei vergleichen (**Meilenstein M2**).
|
||||
|
||||
---
|
||||
|
||||
## Verweise
|
||||
|
||||
- Roadmap: [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md)
|
||||
- k6: [scripts/load/README.md](../../scripts/load/README.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Architektur: Zielbild, Refaktor, Regeln (Shinkan Jinkendo)
|
||||
|
||||
Dieses Bündel ist die **Leitlinie für die große Refaktorierung** nach dem MVP. Es ergänzt die bestehenden Pflichtdokumente (`.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht, Media-Spec) und ist für **Wartbarkeit, Performance und sichere Erweiterung** verbindlich, soweit hier ausdrücklich festgelegt.
|
||||
|
||||
## Inhalt
|
||||
|
||||
| Datei | Zweck |
|
||||
|--------|--------|
|
||||
| [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md) | Zielarchitektur (Frontend, API, Daten), Qualitätsziele, Einbindung neuer Features |
|
||||
| [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md) | Erfasste Architekturschuld, Reihenfolge und Massnahmen zur Behebung |
|
||||
| [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md) | Phasen, Meilensteine, Abnahmekriterien, Aufwandsschwerpunkte |
|
||||
| [`frontend/src/api/client.js`](../../frontend/src/api/client.js) | Phase 4: zentraler HTTP-Client (`request`, `ACTIVE_CLUB_STORAGE_KEY`, `API_URL`, `mergeActiveClubHeader`) |
|
||||
| [`frontend/src/api/exercises.js`](../../frontend/src/api/exercises.js) | Phase 4: Übungen, Medien/Archiv, Progressionsgraphen, KI-Hilfen |
|
||||
| [`frontend/src/api/planning.js`](../../frontend/src/api/planning.js) | Phase 4: Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, KPIs) |
|
||||
| [BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md) | Phase 0: Bundle-, API- und Last-Baseline (Messvorlagen, Vergleich nach Phase 2) |
|
||||
| [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) | **Verbindliche** Shinkan-spezifische Regeln (Ergänzung zu den globalen Rules) |
|
||||
|
||||
## Tests (E2E / Refaktor-Budget)
|
||||
|
||||
- **`tests/dev-smoke-test.spec.js`** – Playwright-Suite (Smoke + Compliance). Enthält u. a. **Test 8:** nach Login und **Reload** des Dashboards werden GET-Aufrufe zu `/api/profiles/me` und `/api/training-units` gezählt (Absicherung Dashboard-Refaktor Phase 1). Ausführung: `npm run test:e2e`; CI: `.gitea/workflows/test.yml` Job **playwright-tests**. **k6**-Baseline: Job **`k6-health-baseline`** (siehe `scripts/load/README.md`).
|
||||
|
||||
## Pflege
|
||||
|
||||
- Bei abgeschlossenen Phasen: Roadmap und Remediation-Dokument aktualisieren; bei Regeländerungen: nur mit **expliziter Projektfreigabe** (gleiches Verfahren wie bei `.claude/rules/ARCHITECTURE.md`).
|
||||
- Querschnitt: **`docs/HANDOVER.md`** soll auf die aktive Roadmap-Phase verweisen.
|
||||
|
||||
## Bezug MVP
|
||||
|
||||
Die aktuelle Codebasis ist funktional MVP-tauglich; strukturell bestehen bekannte Schwerpunkte (grosse Seiten-Monolithen, API-Monolith im Client, redundante Lesepfade, schwere Listenqueries). Dieses Bündel definiert, wie nach **dem** MVP weitergebaut wird, ohne jedes neue Feature erneut mit **architektonischer Schuld** zu überfrachten.
|
||||
@@ -0,0 +1,133 @@
|
||||
# Architekturschuld – Erfassung und Behebungsschritte
|
||||
|
||||
Dieses Dokument listet **bewusst** die aus MVP und Code-Review bekannten strukturellen Themen auf und ordnet **konkrete Massnahmen** zu. Reihenfolge ist an die Roadmap gekoppelt; hier die inhaltliche Detailierung.
|
||||
|
||||
---
|
||||
|
||||
## A. Frontend
|
||||
|
||||
### A1 – „God Pages“ (Training, Übungsformular, Vereine)
|
||||
|
||||
**Schuld:** Sehr grosse Dateien (tausende Zeilen) mit viel State, vielen Effekten und eingebetteten Modals.
|
||||
|
||||
**Risiko:** Hohe Re-Render-Kosten, schwerer zu testen, hoher RAM auf schwachen Geräten, neue Features vergrössern die Datei weiter.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. **Inventar:** pro Page kurze Gliederung (Abschnitte) und Ziel-Komponenten benennen.
|
||||
2. **Extrahieren:** Zuerst isolierbare Blöcke (Listen, Modals, Sidebar, Form-Sektionen) in Unterkomponenten; Props/Oberfläche dokumentieren.
|
||||
3. **Hooks:** wiederkehrende Logik (`useEffect`-Ketten, Filter-State) in `useXxx`-Hooks pro Domäne.
|
||||
4. **Optional `features/training/` o. ä.:** wenn 3+ zusammengehörige Komponenten entstehen.
|
||||
|
||||
**Erfolgskriterium:** Page-Datei unter dem in `VERBINDLICHE_REGELN_SHINKAN.md` genannten Soft-Limit oder dokumentierte Ausnahme.
|
||||
|
||||
---
|
||||
|
||||
### A2 – Monolithischer API-Client (`utils/api.js`)
|
||||
|
||||
**Schuld:** Eine Datei bündelt alle Endpoints; erschwert Tree-Shaking, Navigation und domänenweise Ownership.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. Verzeichnisstruktur festlegen, z. B. `frontend/src/api/` mit `client.js` (Token, `request`), `exercises.js`, `planning.js`, …
|
||||
2. Bestehende `api.js` schrittweise zur **Facade** (`export * from …`) degradieren oder re-exportieren.
|
||||
3. Neue Features **nur** in domänenspezifischen Dateien implementieren.
|
||||
|
||||
**Erfolgskriterium:** Kein Wachstum des Monolithen über bestehende Endpoint-Anzahl hinaus; mittelfristig dominieren kleine Module.
|
||||
|
||||
---
|
||||
|
||||
### A3 – Redundante und „chatty“ Client-Requests
|
||||
|
||||
**Schuld (Beispiele):** Dashboard lädt Profil erneut trotz Auth; mehrere nahezu gleiche `listTrainingUnits`-Aufrufe; doppelte `listExercises` für KPIs.
|
||||
|
||||
**Risiko:** Mehr Last auf API/DB, schlechtere UX auf langsamen Geräten.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. **Profil:** eine kanonische Quelle (Auth-Profil reicht für Anzeige; fehlende Felder gezielt nachladen oder Auth-Check erweitern – fachlich klären).
|
||||
2. **Dashboard:** einen **Summary-Endpoint** spezifizieren und implementieren (siehe Backend B1) oder Client auf einen aggregierten Aufruf reduzieren.
|
||||
3. **Org-Inbox / globale Fetches:** Ladestrategie definieren (on-demand vs. TTL vs. sichtbarkeitsabhängig) und `OrgInboxContext` entsprechend umbauen.
|
||||
|
||||
**Stand Umsetzung:** Gemeinsame Funktion `fetchOrgInboxSnapshot` für Mount und `refreshOrgInbox` (ein Codepfad, gleiche API-Calls). Optionales verzögertes Laden / TTL weiterhin offen.
|
||||
|
||||
**Erfolgskriterium:** Dashboard-Initialisierung ohne redundanten `getCurrentProfile`; ohne drei parallele fast gleiche Trainingslisten (oder dokumentierte Ausnahme).
|
||||
|
||||
---
|
||||
|
||||
### A4 – Schwere Abhängigkeiten
|
||||
|
||||
**Schuld:** PDF/Markdown/Canvas-Pfade ziehen grosse Chunks.
|
||||
|
||||
**Behebungsschritte:** Strikte `import()` an Nutzeraktion; keine statischen Top-Level-Imports schwerer Libs in gemeinsamen Einstiegspfaden.
|
||||
|
||||
**Erfolgskriterium:** Lighthouse / Bundle-Analyse zeigt schwere Libs nur auf betroffenen Routen.
|
||||
|
||||
---
|
||||
|
||||
## B. Backend
|
||||
|
||||
### B1 – Aggregations- und Summary-APIs
|
||||
|
||||
**Schuld:** Bildschirme holen mehrere Listen und aggregieren im Client.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. Endpoint(s) z. B. `GET /api/dashboard/summary` oder domänenspezifisch mit gleicher Sichtbarkeitslogik wie Einzel-Listen.
|
||||
2. Tests oder manuelle Checkliste gegen **Tenant-Leaks** (nur eigene/sehbare Daten).
|
||||
3. Versionierung in `version.py` bei neuem Router-Block oder signifikantem Modul-Update.
|
||||
|
||||
**Erfolgskriterium:** Fertigest Dashboard mit einer serverseitigen Zusammenfassung (oder festgelegte Client-Reduktion mit Messung).
|
||||
|
||||
---
|
||||
|
||||
### B2 – Listenqueries (z. B. Übungsliste)
|
||||
|
||||
**Schuld:** Korrelierte Subqueries pro Zeile können bei Wachstum teuer werden.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. `EXPLAIN (ANALYZE, BUFFERS)` auf Produktions-näher Konfiguration mit realistischem `limit`.
|
||||
2. Indizes für Filter und Sortierung ergänzen.
|
||||
3. Refactoring: JOINs/LATERAL statt N-facher Subquery, wo messbar besser.
|
||||
|
||||
**Erfolgskriterium:** Dokumentierte p95-Zielwerte erreicht oder Trend verbessert (siehe Roadmap).
|
||||
|
||||
---
|
||||
|
||||
### B3 – Pagination
|
||||
|
||||
**Schuld:** Tiefe `OFFSET`-Werte skalieren schlecht.
|
||||
|
||||
**Behebungsschritte:** Keyset-Pagination für grosse Listen in späteren Phasen einführen; API-Vertrag dokumentieren.
|
||||
|
||||
---
|
||||
|
||||
## C. Querschnitt
|
||||
|
||||
### C1 – Messbarkeit
|
||||
|
||||
**Schuld:** Optimierung ohne Baseline.
|
||||
|
||||
**Behebungsschritte:** Einmalig Baseline (API p95, Bundle-Grössen Haupt-Route, ein Lasttest-Szenario) festhalten; wiederholen nach grossen Phasen.
|
||||
|
||||
---
|
||||
|
||||
### C2 – Dokumentation und Audit
|
||||
|
||||
**Schuld:** Wissen nur in Chats.
|
||||
|
||||
**Behebungsschritte:** `HANDOVER.md` und `ACCESS_LAYER_ENDPOINT_AUDIT.md` bei jedem grösseren API-Block aktualisieren; Roadmap-Phase abhaken.
|
||||
|
||||
---
|
||||
|
||||
## Mapping: Schuld → Regel
|
||||
|
||||
| Schuld | Primär-Regel (Shinkan) |
|
||||
|--------|-------------------------|
|
||||
| God Pages | S1, S2 |
|
||||
| API-Monolith | S3 |
|
||||
| Globale Fetches | S4 |
|
||||
| Chatty API | S5 |
|
||||
| Caching-Ideen | S6 |
|
||||
| Grössere Features ohne Messung | S7, S8 |
|
||||
@@ -0,0 +1,156 @@
|
||||
# Umsetzungsplan und Roadmap – Refaktorierung Shinkan Jinkendo
|
||||
|
||||
**Aktueller Stand (laufend):**
|
||||
|
||||
- **Phase 0:** abgeschlossen – siehe **[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)** (Bundle festgehalten, API-/k6-Vorlagen + Skripte unter `scripts/load/`).
|
||||
- **Phase 1 (Teil):** Dashboard: kein zweites `getCurrentProfile`; Trainings-Vorschau über **`GET /api/dashboard/kpis`** (`training_home`); Playwright **Test 8** sichert API-Budget ab.
|
||||
- **Phase 1 (Teil):** Org-Inbox: **ein** gemeinsamer Ladepfad `fetchOrgInboxSnapshot` für Mount-`useEffect` und `refreshOrgInbox` (gleiche Requests, weniger Drift-Risiko; Verhalten unverändert).
|
||||
- **Phase 2:** **abgeschlossen** (2026-05-14) — Indizes 058–062, Keyset `/api/exercises` + `/api/training-units`, **`/api/dashboard/kpis`** inkl. `training_home`, EXPLAIN-Vorlagen **`scripts/load/explain-readpaths.sql`**.
|
||||
- **Offen Phase 1:** Inbox optional **TTL** / nur bei sichtbarem Widget.
|
||||
- **Phase 3 (abgeschlossen 2026-05-14):** Übungsliste modularisiert; Trainingsplanung/Übungsformular: **Page-Dateien unter Soft-Limit** — Implementierung in `TrainingPlanningPageRoot.jsx`, `ExerciseFormPageRoot.jsx`, `ExercisesListPageRoot.jsx`; `pages/*.jsx` nur Re-Export. Playwright **Tests 9–10**.
|
||||
- **Phase 4 (fortlaufend 2026-05-14):** API **Welle 1** `client.js`; **Welle 2** `planning.js`; **Welle 3** `exercises.js`; `utils/api.js` bleibt Facade (`export *`, `api`-Objekt `...exercises`, `...planning`).
|
||||
|
||||
**Ziel:** Nach MVP eine **nachhaltige** Architektur für Wachstum, **Performance** (Server + schwache Clients) und **sichere Feature-Erweiterung**.
|
||||
**Leitdokumente:** [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md), [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md), [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md).
|
||||
|
||||
---
|
||||
|
||||
## Leitplanken (vereinbart)
|
||||
|
||||
- **Kein Breaking** der Zugriffsschicht: neue und geänderte Endpoints folgen `get_tenant_context` / Audit wie bisher.
|
||||
- **Inkrementell:** Jede Phase liefert **nutzbaren** Stand (kein Big-Bang-Stillstand).
|
||||
- **Neue Features** während der Roadmap: **S8 Checkliste** und **S1/S3** strikt; wo möglich gleich im neuen API-Modul-Pfad.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 – Baseline (kurz, Pflicht)
|
||||
|
||||
**Status:** **Erledigt** (2026-05-13). Siehe **`docs/architecture/BASELINE_SNAPSHOT.md`** und **`scripts/load/`**.
|
||||
|
||||
| Task | Output |
|
||||
|------|--------|
|
||||
| API p95 der Top-5-Routen messen (z. B. `profiles/me`, `exercises` list, `training-units` list, `media-assets` list) | Vorlage + Messverfahren in **BASELINE_SNAPSHOT.md**; Werte nach erstem Lauf auf Dev/Prod eintragen |
|
||||
| Ein Lasttestszenario (Login → Dashboard → Übungen → Planung) | Playwright `npm run test:e2e` + k6 **`scripts/load/k6-health-baseline.js`** (README dort) |
|
||||
| Bundle: Grösse Einstieg + schwerste Route | In **BASELINE_SNAPSHOT.md** dokumentiert (Auszug `vite build`) |
|
||||
|
||||
**Abnahme:** Bundle dokumentiert; Mess- und Lastskripte vorhanden; API-Tabelle iterativ befüllbar. **Phase 2** beginnt nach diesem Freeze-Punkt.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 – Quick Wins Netzwerk (hoher ROI, geringes Risiko)
|
||||
|
||||
**Fokus:** Weniger redundante Requests, bessere Mobile-UX, kaum strukturelle Risiken.
|
||||
|
||||
| Task | Bezug Remediation | Status |
|
||||
|------|-------------------|--------|
|
||||
| Dashboard: Doppel-`getCurrentProfile` auflösen; kanonisches Profil klären | A3 | erledigt |
|
||||
| Dashboard: `listTrainingUnits`-Reduktion (ein Call statt zweier identischer) | A3 | erledigt |
|
||||
| Dashboard: `listExercises`-Doppelabruf / Summary-Call | A3, B1 | erledigt (`GET /api/dashboard/kpis`) |
|
||||
| Org-Inbox: Ladestrategie; Umsetzung Teil 1 (gemeinsamer Ladepfad, keine doppelte Logik) | A3 | erledigt |
|
||||
| Org-Inbox: TTL / verzögertes Laden (nur nach Bedarf) | A3 | teils (Erstlade per `requestIdleCallback`, max. 1,5s) |
|
||||
|
||||
**Abnahme:** Kein funktionales Leck; Netzwerk-Tab zeigt messbar weniger parallele gleiche Muster beim ersten Dashboard-Load.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 – Backend Lesepfade (Skalierung „viele Nutzer“)
|
||||
|
||||
**Status:** **Abgeschlossen** (2026-05-14).
|
||||
|
||||
**Voraussetzung:** Phase 0 abgeschlossen (**[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)**). Nach Deploy: p95 der Top-Routen erneut messen und mit Baseline vergleichen ([M2](#meilensteine-empfohlen)).
|
||||
|
||||
**Fokus:** DB und API stabil unter parallelen Lesern.
|
||||
|
||||
| Task | Bezug | Status |
|
||||
|------|-------|--------|
|
||||
| `EXPLAIN` + Index-Tuning für `list_exercises` und nächste schwere Listen | B2 | erledigt (Indizes 058–060, 062; Vorlagen **[explain-readpaths.sql](../../scripts/load/explain-readpaths.sql)**; Messung Team) |
|
||||
| Summary-API finalisieren/erweitern falls in P1 nur Teilbereich | B1 | erledigt (`GET /api/dashboard/kpis` + **`training_home`**) |
|
||||
| Keyset-Pagination für Listen mit Sort-Key | B3 | erledigt (`/api/exercises`, `/api/training-units`) |
|
||||
|
||||
**Lieferung:** Migrationen **058–062**; Keyset-Parameter wie dokumentiert in OpenAPI/Router; Dashboard nutzt **ein** KPI-Request für Kennzahlen und Trainings-Vorschau.
|
||||
|
||||
**Abnahme:** p95 der optimierten Routen nach Messung dokumentiert verbessert ggü. Phase 0 oder Obergrenze notiert (siehe Baseline-Tabelle).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 – Frontend-Struktur (Wartbarkeit + Client-Performance)
|
||||
|
||||
**Fokus:** God-Pages abbauen, Virtualisierung wo nötig.
|
||||
|
||||
| Task | Bezug |
|
||||
|------|--------|
|
||||
| Eine Page komplett zerteilen als Referenz (z. B. `TrainingPlanningPage` **oder** `ExerciseFormPage`) – Rest priorisiert nach Nutzung | A1 |
|
||||
| Virtualisierung für die längste produktive Liste | A1, S2 |
|
||||
| Schwere Imports auf `import()` umziehen (gezielt) | A4 |
|
||||
|
||||
**Teil umgesetzt (2026-05-13):** `ExercisesListPage` — Karten `ExerciseListCard.jsx`; Filter/Massenänderung `ExerciseListFilterModal.jsx` / `ExerciseListBulkModal.jsx`; Tab „Progressionsgraphen“ **lazy**; **Picker** virtualisiert; Gitter `data-testid` + `content-visibility`; Playwright **Tests 9–10**.
|
||||
|
||||
**Abgeschlossen (2026-05-14):** Routen bleiben unter `frontend/src/pages/`; schwere Implementierung in **`components/planning/TrainingPlanningPageRoot.jsx`**, **`components/exercises/ExerciseFormPageRoot.jsx`**, **`components/exercises/ExercisesListPageRoot.jsx`** — **`pages/*` nur Re-Export** (Soft-Limit ~500 Zeilen laut `VERBINDLICHE_REGELN_SHINKAN.md`).
|
||||
|
||||
**Abnahme:** Referenz-Page unter Soft-Limit; Regel S1 für neue Änderungen durchsetzbar.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 – API-Client Modularisierung
|
||||
|
||||
**Status:** **fortlaufend** (2026-05-14) — Welle 1: **`client.js`**; Welle 2: **`planning.js`**; Welle 3: **`exercises.js`**; **`utils/api.js`** bleibt vollständige Facade.
|
||||
|
||||
**Fokus:** Wartbarkeit für viele neue Features.
|
||||
|
||||
| Task | Bezug | Status |
|
||||
|------|-------|--------|
|
||||
| `frontend/src/api/client.js` — zentraler HTTP-Client | A2 | erledigt (Welle 1) |
|
||||
| `frontend/src/api/planning.js` — Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, Dashboard-KPIs) | A2 | erledigt (Welle 2) |
|
||||
| `frontend/src/api/exercises.js` — Übungen, Medien/Archiv, Varianten, Progressionsgraphen, KI | A2 | erledigt (Welle 3) |
|
||||
| Weitere Domänen-Module unter `frontend/src/api/` + Entlastung von `utils/api.js` | A2 | offen |
|
||||
| Neue Endpoints primär in Domänen-Dateien | S3 | offen |
|
||||
|
||||
**Abnahme:** Anteil neuer Module > X% der neuen Zeilen (Team-Ziel); Monolith wächst nicht weiter.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 – Vertiefung DB & Pagination
|
||||
|
||||
**Fokus:** Wachstum Datenbestand.
|
||||
|
||||
| Task | Bezug |
|
||||
|------|--------|
|
||||
| Keyset für weitere Listen | B3 |
|
||||
| Weitere Query-Refactorings nach Monitoring | B2 |
|
||||
|
||||
**Abnahme:** Dokumentierte Paginierungs-API; keine Regression in der Zugriffsschicht.
|
||||
|
||||
---
|
||||
|
||||
## Meilensteine (empfohlen)
|
||||
|
||||
| Meilenstein | Inhalt |
|
||||
|-------------|--------|
|
||||
| **M1** | Phase 0 + 1 abgeschlossen, HANDOVER aktualisiert |
|
||||
| **M2** | Phase 2 abgeschlossen, Lasttest / p95 nachziehen |
|
||||
| **M3** | Phase 3 abgeschlossen: Page-Dateien Soft-Limit (Re-Export); Virtualisierung Übungsliste |
|
||||
| **M4** | Phase 4 migrationsbereit für alle neuen Features |
|
||||
| **M5** | Phase 5 für Top-Listen abgeschlossen |
|
||||
|
||||
---
|
||||
|
||||
## Parallel: neue Features
|
||||
|
||||
- Jedes Feature: [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) **S8**.
|
||||
- Berührung schwerer Pfade: kurzer Performance-Nachweis (S7).
|
||||
|
||||
---
|
||||
|
||||
## Risiken und Mitigation
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Summary-Endpoint falsch gefiltert | Code-Review + Abgleich mit Einzel-Endpoint-Logik; Tests mit mehreren Rollen |
|
||||
| Refaktor bricht PWA/Offline | Smoke-Test nach grossen Frontend-Phasen |
|
||||
| Keyset bricht alte Clients | Versionierte Query-Parameter oder Übergangsfenster |
|
||||
|
||||
---
|
||||
|
||||
## Pflege
|
||||
|
||||
Nach jeder Phase: **README** dieses Bündels prüfen; **Roadmap** Checkboxen/Status; **HANDOVER** nächste Phase nennen.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Verbindliche Architekturregeln – Shinkan (Ergänzung)
|
||||
|
||||
**Status:** verbindlich für die Shinkan-Codebasis, **ergänzend** zu:
|
||||
|
||||
- `.claude/rules/ARCHITECTURE.md`
|
||||
- `.claude/rules/CODING_RULES.md`
|
||||
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
|
||||
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
|
||||
Bei Widerspruch gewinnt die **spezifischere** Regel zur **Zugriffsschicht und Governance** (Sicherheit vor Komfort). Bei Widerspruch zwischen diesem Dokument und allgemeinen Mitai-Template-Resten in `ARCHITECTURE.md` gilt für **Shinkan** dieses Dokument und die Shinkan-Pflichtlektüre in `CLAUDE.md`.
|
||||
|
||||
---
|
||||
|
||||
## S1 – Frontend: Grösse und Zerlegung von Seiten
|
||||
|
||||
1. **Soft-Limit:** Neue oder stark erweiterte Seiten sollen **unter ~500 Zeilen** im Page-File bleiben. Darüber: Auslagern in Komponenten/Hooks/Feature-Module mit klaren Namen.
|
||||
2. **Ausnahmen** nur mit Kurzbegründung im PR und Verweis auf Messung (Bundle/Performance) oder fachliche Unteilbarkeit.
|
||||
3. **Wiederkehrende UI-Blöcke** nicht per Copy-Paste über Seiten hinweg duplizieren; extrahieren in `components/` oder `features/`.
|
||||
|
||||
## S2 – Frontend: Listen und Speicher
|
||||
|
||||
1. Listen, die **typischerweise > 100 sichtbare oder gehaltene Einträge** im DOM ermöglichen, **müssen** virtualisiert werden (oder serverseitig strikt begrenzt + „mehr laden“ mit dokumentiertem UX – nicht beides unbegründet ignorieren).
|
||||
2. **Modals und zweite Raster** gleichzeitig zum Hauptbaum nur laden, wenn geöffnet (lazy mount), wo technisch machbar ohne UX-Bruch.
|
||||
|
||||
## S3 – Frontend: API-Zugriff
|
||||
|
||||
1. **Alle** API-Aufrufe über die zentrale Schicht (`utils/api` bzw. nach Modularisierung dessen Module). **Kein** `fetch('/api/...')` ohne diese Schicht.
|
||||
2. Während der Migration vom API-Monolithen: **neue** Endpoints ausschliesslich im **domänenspezifischen** Modul anlegen; nur bei Bedarf Re-Export über die Facade.
|
||||
|
||||
## S4 – Frontend: Globale Daten und Context
|
||||
|
||||
1. Neue **global** geladene Daten (jede authentifizierte Session) **bedürfen** technischer Begründung (Badge-Kritikalität, Sicherheit). Alternative: **on-demand** beim ersten Bezug oder **TTL-Cache** mit dokumentierter Invalidierung (`shinkan:…`-Events bleiben möglich).
|
||||
2. Context-`value`-Objekte **müssen** stabil gehalten werden (`useMemo` / `useCallback`), wenn nicht-triviale Unterbäume davon abhängen (bereits etabliert für Auth; gleiches Muster für neue Contexts).
|
||||
|
||||
## S5 – Backend: Lesepfad-Design
|
||||
|
||||
1. **Keine** mehrfachen fast identischen Listenaufrufe durch den Client für **denselben** zusammensetzbaren Bildschirm, wenn ein **einzelner** Summary-Endpoint unter gleicher Sichtbarkeitslogik möglich ist. Ausnahme: nachweislich unterschiedliche Cache-Lebensdauer oder unterschiedliche Rechte – dokumentieren.
|
||||
2. Neue Listen-Endpoints: **Paginierung** (`limit`/`offset` oder Keyset nach Roadmap) und Obergrenzen; keine „unbegrenzt alles“-Defaults für grosse Tabellen.
|
||||
3. Schwere SQL-Konstruktionen (viele korrelierte Subqueries pro Zeile) **nur** mit Kommentar **Warum** und Hinweis auf Indexlage oder geplantes Refactoring-Ticket.
|
||||
|
||||
## S6 – Backend: Mandanten und Caching
|
||||
|
||||
1. **Kein** HTTP- oder Anwendungs-Cache für mandantenspezifische oder nutzerspezifische Daten **ohne** expliziten Schlüssel (mindestens: Tenant-Kontext + relevante Parameter) und **Invalidierungsstrategie**.
|
||||
2. Öffentliche oder global geteilte Katalogdaten dürfen mit `ETag` / kurzem Cache optimiert werden – **nach** Abgleich mit Governance.
|
||||
|
||||
## S7 – Performance und Messung (Definition of Done für grössere Features)
|
||||
|
||||
1. Features, die neue Listen schwerer als bestehende Top-10-Queries machen oder **> ~50 KB** zusätzliches Client-JS pro Route erzeugen: **kurz** messen (Lighthouse mobil oder Netzwerk-Timing) und im PR festhalten.
|
||||
2. Regressions in **p95** der betroffenen API nach Deploy: bei Bedarf Rollback- oder Nachsteuerungskriterium mit Team vereinbaren (Zahlen Zielbild/Roadmap).
|
||||
|
||||
## S8 – Feature-Checkliste (DoD)
|
||||
|
||||
Vor Merge einer grösseren Erweiterung:
|
||||
|
||||
- [ ] Zugriffsschicht / Audit aktualisiert (falls zutreffend)
|
||||
- [ ] Kein Verstoss gegen S1–S7 ohne dokumentierte Ausnahme
|
||||
- [ ] Keine neue direkte DB-Nutzung im Frontend
|
||||
- [ ] Medien/Lifecycle (falls Medien betroffen) nach Media-Spec
|
||||
|
||||
---
|
||||
|
||||
**Änderungen** an diesen Regeln nur mit **expliziter Projektfreigabe** (analog zu `ARCHITECTURE.md`).
|
||||
@@ -0,0 +1,78 @@
|
||||
# Architektur-Zielbild – Shinkan Jinkendo
|
||||
|
||||
**Geltungsbereich:** Trainer-/Vereinsplattform, Multi-Tenancy und Governance nach bestehender Zugriffsschicht.
|
||||
**Ziele:** dauerhaft tragfähig, performant bei vielen gleichzeitigen Nutzern, akzeptabel auf **geringer Client-Leistung** (wenig RAM/CPU), **wartbar** und so strukturiert, dass **neue Features** ohne neue Grosseinkaufe an technischer Schuld einbindbar sind.
|
||||
|
||||
---
|
||||
|
||||
## 1. Leitprinzipien
|
||||
|
||||
1. **API-first, Mandanten-sicher** – Fachlogik und Sichtbarkeit serverseitig; das Frontend orchestriert und zeigt. Unverändert gemäss bestehender Regeln (`ACCESS_LAYER`, Governance-Helfer).
|
||||
2. **Schlanke Client-Oberfläche** – JavaScript pro Route begrenzen; schwere Abhängigkeiten nur bei Bedarf laden; Listen dort virtualisieren, wo Grössenordnungen wachsen.
|
||||
3. **Explizite Lesepfade** – Aggregation und Zusammenfassungen dort, wo mehrere fast gleiche Requests heute nötig sind (Dashboard, Badges), **statt** Chatty-Client-Muster.
|
||||
4. **Vorhersehbarkeit für die DB** – Listenqueries ohne unnötige O(n)·Subquery-Kosten pro Zeile; Indizes und Paginierungsstrategie sind Teil des Designs.
|
||||
5. **Feature-Einbindung per Checkliste** – Jedes neue Feature durchläuft die gleiche Architektur- und Performance-Checkliste (siehe Regeldokument), bevor es als „fertig“ gilt.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielbild Frontend
|
||||
|
||||
### 2.1 Struktur
|
||||
|
||||
- **Seiten (`pages/`)** bleiben Routing-Einstiege und Komposition; **keine** Dauerlösung für Logikblöcke > ~400–500 Zeilen in einer Datei – Auslagerung in `components/`, `hooks/`, `features/<name>/`.
|
||||
- **Feature-Ordner (Ziel):** wo sinnvoll `frontend/src/features/<domäne>/` mit klarer Grenze: UI + feature-spezifische Hooks; geteilte Helfer in `utils/` nur wenn domänenübergreifend.
|
||||
- **State:** Server-State über API (keine Business-Duplikation); UI-State lokal oder in bestehenden Contexts nur, wenn mehrere Schichten der Shell betroffen sind.
|
||||
|
||||
### 2.2 Performance und schwache Endgeräte
|
||||
|
||||
- Route-basiertes Code-Splitting bleibt Standard; **zusätzlich** innere `dynamic import()` für schwere Pakete (PDF, grosse Editoren), sobald eine Route sie braucht.
|
||||
- Lange Listen: **Virtualisierung** ab einer projektdefinierten Schwelle (siehe Regeln).
|
||||
- Globale Daten (Posteingang, Badges): **bedarfsgesteuert oder mit klar dokumentiertem Cache/TTL**, nicht pauschal jede Session mit voller Last – konkrete Strategie in Roadmap/Remediation.
|
||||
|
||||
### 2.3 API-Schicht im Client
|
||||
|
||||
- **Ziel:** Aufteilung des heutigen `utils/api.js`-Monolithen in **domänenspezifische Module** (z. B. `api/exercises`, `api/planning`, `api/media`), mit einer dünnen **Barrel- oder Facade-Export** für Kompatibilität während der Migration.
|
||||
- **Konstante:** alle HTTP-Aufrufe mit Token/Mandanten-Headern zentral; kein Rohtransport aus Komponenten.
|
||||
|
||||
---
|
||||
|
||||
## 3. Zielbild Backend / API
|
||||
|
||||
- **Router-Disziplin** unverändert: ein fachliches Modul, ein Router (bestehende Architekturregeln).
|
||||
- **Read-Model / Summary-Endpoints** für Dashboards und wiederkehrende Kacheln: **eine** abgestimmte Antwort pro Bildschirm, wo heute mehrere Listen parallel zusammengerechnet werden – unter strikt gleicher Sichtbarkeitslogik wie die Einzel-Endpoints.
|
||||
- **Listen:** sortierte Indizes passend zu `WHERE` + `ORDER BY`; für grosse Datenmengen langfristig **Keyset-Pagination** statt tiefer Offsets.
|
||||
- **Schwere Queries:** Korrelierte Subqueries pro Zeile nur, wenn messbar unkritisch; sonst JOIN-/Aggregate-Refactoring mit Review.
|
||||
|
||||
---
|
||||
|
||||
## 4. Zielbild Datenhaltung
|
||||
|
||||
- PostgreSQL bleibt System der Wahrheit; Migrationen nummeriert, wie heute.
|
||||
- Kein Mandanten-Cache ohne expliziten Key und Invalidierungskonzept (Regeldokument).
|
||||
|
||||
---
|
||||
|
||||
## 5. Einbindung neuer Features (vereinbartes Muster)
|
||||
|
||||
1. Fachliche Kurzspez (oder Ticket) mit **Sichtbarkeit** und **Nutzungskontext** (Mobile/Desktop, erwartete Listenlängen).
|
||||
2. API-Design: Endpoints, Payload-Grösse, Paginierung; Zugriffsschicht-Check.
|
||||
3. UI-Modul: Route lazy, Komponentengrösse, ggf. Virtualisierung.
|
||||
4. Messung: minimal Lighthouse/Netzwerk oder Server-Timing für den neuen Pfad.
|
||||
5. Audit-Eintrag bei neuen geschützten Endpoints (bestehendes Verfahren).
|
||||
|
||||
---
|
||||
|
||||
## 6. Nicht-Ziele dieses Zielbilds
|
||||
|
||||
- Ersetzen der Zugriffsschicht oder der Medien-Spec.
|
||||
- Microservices oder zweite Schreib-Datenbank ohne ausdrücklichen Projektbeschluss.
|
||||
- „Framework-Wechsel“ (React bleibt, solange nicht separat entschieden).
|
||||
|
||||
---
|
||||
|
||||
## 7. Abnahme „Zielbild erreicht“ (high level)
|
||||
|
||||
- Keine bekannten **God-Pages** oberhalb dokumentierter Schwellen ohne dokumentierte Ausnahme.
|
||||
- API-Client modularisiert oder klar phasierter Migrationsstand mit festem Enddatum.
|
||||
- Dashboard und vergleichbare Homescreens ohne redundante Mehrfach-Listen desselben Objekttyps (oder dokumentierte technische Begründung + Messung).
|
||||
- Datenbank-Lesepfade der Top-5-Listen unter definierter Latenz-Schwelle auf Referenz-Hardware in Lasttests (Werte in Roadmap festzulegen).
|
||||
@@ -0,0 +1,992 @@
|
||||
# Compliance-Audit – Shinkan Jinkendo
|
||||
|
||||
> **Status:** Entwurf — technischer Audit, kein Rechtsanwalt
|
||||
> **Datum:** 2026-05-09
|
||||
> **Auditor:** Claude Code
|
||||
> **App-Version:** 0.8.65
|
||||
> **Rechtlicher Hinweis:** Dieses Dokument ist eine technische Analyse. Es ersetzt keine Rechtsberatung. Alle als „juristisch zu prüfen" markierten Punkte müssen durch einen Rechtsanwalt oder Datenschutzbeauftragten bewertet werden. Kein Code wurde verändert.
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
Die Shinkan Jinkendo App ist technisch solide aufgebaut: robuste Mandantentrennung (TenantContext), mehrstufiges Löschkonzept für Medien, serverseitig erzwungene Zugriffskontrolle. Die Kernarchitektur der Datenschicht ist gut.
|
||||
|
||||
**Kritische Compliance-Lücken:**
|
||||
|
||||
- Keine Rechtstexte (Impressum, Datenschutzerklärung, Nutzungsbedingungen, Medienrichtlinie)
|
||||
- Kein DSA-konformes Meldeverfahren für rechtswidrige Inhalte (UGC-Plattform)
|
||||
- Kein Recht-am-eigenen-Bild/Minderjährigen-Check beim Medienupload
|
||||
- Kein Self-Service-Löschrecht für Nutzer (nur Admin kann Konten löschen)
|
||||
- Auth-Token im localStorage (XSS-Risiko, TDDDG-Dokumentationspflicht)
|
||||
- HSTS-Header fehlt in der Nginx-Konfiguration
|
||||
- Papierkorb-Retention-Job nicht automatisch geplant
|
||||
- Passwort-Mindestlänge inkonsistent (Register: 8, PIN-Änderung: 4 Zeichen)
|
||||
|
||||
Vor öffentlichem Betrieb sind die kritischen Findings (KRIT-01 bis KRIT-07) zu adressieren.
|
||||
|
||||
---
|
||||
|
||||
## 2. Scope
|
||||
|
||||
| Bereich | Geprüft |
|
||||
|---------|---------|
|
||||
| Backend-Router (alle .py) | ✓ |
|
||||
| Datenbankmigrationen (001–046) | ✓ |
|
||||
| Frontend App.jsx, Routing, Auth | ✓ |
|
||||
| API-Authentifizierung und Autorisierung | ✓ |
|
||||
| Mandanten-/Zugriffschicht (TenantContext, club_tenancy) | ✓ |
|
||||
| Medien-Archiv (media_assets, lifecycle) | ✓ |
|
||||
| PWA-Konfiguration (manifest.webmanifest) | ✓ |
|
||||
| Nginx-Konfiguration (nginx.conf) | ✓ |
|
||||
| Docker-Compose (docker-compose.yml) | ✓ |
|
||||
| Vorhandene Tests (backend/tests/*.py) | ✓ |
|
||||
| LocalStorage / SessionStorage Nutzung | ✓ |
|
||||
| Rechtstexte (Impressum, DSGVO, AGB) | ✓ |
|
||||
| CSP / Security-Header | ✓ |
|
||||
| Passwort-Handling, Session-Management | ✓ |
|
||||
|
||||
---
|
||||
|
||||
## 3. Annahmen
|
||||
|
||||
- App ist öffentlich im Internet erreichbar unter `shinkan.jinkendo.de` (HTTPS)
|
||||
- SSL/TLS-Terminierung erfolgt am externen Reverse-Proxy vor dem Nginx-Container
|
||||
- Betreiber ist im EU-Raum ansässig (DSGVO anwendbar)
|
||||
- Minderjährige können sich registrieren (keine Altersverifikation vorhanden)
|
||||
- Die Plattform erlaubt Upload und Anzeige von Bildern und Videos mit Personenabbildungen
|
||||
|
||||
---
|
||||
|
||||
## 4. Nicht geprüfte Bereiche
|
||||
|
||||
- Produktions-Infrastruktur (Synology NAS, Raspberry Pi 5) – nur Konfigurationsdateien
|
||||
- Netzwerkinfrastruktur (Fritz!Box) – außerhalb des Repos
|
||||
- SMTP-Anbieter im Detail (Anbieter unbekannt aus Umgebungsvariablen)
|
||||
- Aktive Penetrationstests
|
||||
- Backup-Prozess und Restore-Test (kein Skript im Repository)
|
||||
|
||||
---
|
||||
|
||||
## 5. Technische Bestandsaufnahme
|
||||
|
||||
### 5.1 Architektur
|
||||
|
||||
| Komponente | Technologie | Sicherheitsrelevanz |
|
||||
|-----------|-------------|---------------------|
|
||||
| Frontend | React 18 + Vite, SPA | Routing, Token-Speicherung |
|
||||
| Backend | FastAPI Python 3.12 | Zugriffskontrolle, Validierung |
|
||||
| Datenbank | PostgreSQL 16 Alpine | Datenhaltung, Mandantentrennung |
|
||||
| Proxy | Nginx (Docker) | CSP, Security-Header, Upload-Limit |
|
||||
| Storage | Lokaler Bind-Mount via Docker | Medienspeicherung |
|
||||
| Auth | Token-basiert (Sessions-Tabelle) | Session-Management |
|
||||
| PWA | Web App Manifest + Icons | Offline-Caching (kein Service Worker!) |
|
||||
| E-Mail | SMTP (konfigurierbar) | Registrierung, Passwort-Reset |
|
||||
| KI | OpenRouter (optional, nicht MVP) | KI-Features |
|
||||
|
||||
### 5.2 Authentifizierung
|
||||
|
||||
- Token: `secrets.token_urlsafe(32)` (kryptografisch sicher)
|
||||
- Hashing: bcrypt mit auto-Upgrade von Legacy SHA256
|
||||
- Session-Ablauf: 30 Tage (konfigurierbar per `session_days`)
|
||||
- Rate-Limiting: Login 30/min, Forgot-Password 3/min, Register 3/hour (slowapi)
|
||||
- No-Enumeration: `/forgot-password` gibt keine Info über E-Mail-Existenz preis
|
||||
|
||||
### 5.3 Rollen (global)
|
||||
|
||||
| Rolle | Rechte |
|
||||
|-------|--------|
|
||||
| `trainer` | Standard-Nutzer; Upload, private Übungen, Planung |
|
||||
| `admin` | Plattform-Admin; alle Vereine, alle Profile einsehbar |
|
||||
| `superadmin` | Vollzugriff; Official-Promotion, physische Löschung, Admin-Konfiguration |
|
||||
|
||||
### 5.4 Vereinsrollen (pro Verein)
|
||||
|
||||
| Rolle | Rechte |
|
||||
|-------|--------|
|
||||
| `club_admin` | Vereinsstruktur, Mitglieder, Vereins-Medien/Übungen |
|
||||
| `trainer` | Training planen, Übungen verwalten |
|
||||
| `content_editor` | Inhalte bearbeiten |
|
||||
| `division_lead` | Spartenleitung |
|
||||
|
||||
### 5.5 PWA / Service Worker
|
||||
|
||||
- **Kein Service Worker** im Repository vorhanden
|
||||
- Keine Workbox- oder sw.js-Datei gefunden
|
||||
- **Bedeutung:** Das Hauptrisiko (private Medien im PWA-Cache) entfällt mangels Service Worker
|
||||
|
||||
### 5.6 Browser-Storage-Nutzung
|
||||
|
||||
| Speicherart | Inhalt | TDDDG-Klassifikation |
|
||||
|-------------|--------|----------------------|
|
||||
| `localStorage['authToken']` | Auth-Session-Token | Technisch notwendig |
|
||||
| `localStorage['shinkan_active_club']` | Aktiver Verein (ID) | Technisch notwendig |
|
||||
| `localStorage['shinkan_active_profile']` | Profil-ID | Technisch notwendig |
|
||||
| `sessionStorage[storageStepKey]` | Trainingsschritt (Coach-Page) | Session-temporär, nicht personenbezogen |
|
||||
| `sessionStorage[storageDeltasKey]` | Trainingsdeltas JSON | Session-temporär |
|
||||
| `sessionStorage[storageDebriefKey]` | Debrief-Status | Session-temporär |
|
||||
| Cookies | **keine** | – |
|
||||
| IndexedDB | **keine** | – |
|
||||
|
||||
---
|
||||
|
||||
## 6. Datenflussanalyse
|
||||
|
||||
### 6.1 Registrierung / Login
|
||||
|
||||
```
|
||||
Nutzer → POST /api/auth/register → Profil (inaktiv) + Verifikations-E-Mail
|
||||
Nutzer → E-Mail-Link → GET /api/auth/verify/{token}
|
||||
→ Profil aktiv, Session-Token in Response
|
||||
→ Frontend: localStorage.setItem('authToken', token)
|
||||
|
||||
Nutzer → POST /api/auth/login → Token in Response
|
||||
→ Frontend: localStorage.setItem('authToken', token)
|
||||
```
|
||||
|
||||
Gespeicherte Daten: Name, E-Mail, bcrypt-Hash, Rolle, Tier, trial_ends_at, email_verified, verification_token (temporär, wird nach Verifikation gelöscht)
|
||||
|
||||
### 6.2 Medienupload
|
||||
|
||||
```
|
||||
Nutzer → POST /api/exercises/{id}/media (multipart) [50 MB Limit]
|
||||
→ MIME-Type-Prüfung (magic bytes)
|
||||
→ SHA256-Hash (Deduplizierung)
|
||||
→ Dateispeicherung: library/{scope}/{kind}/{sha256}{ext}
|
||||
→ DB-Eintrag: media_assets + exercise_media
|
||||
|
||||
Admin → POST /api/media-assets/bulk-upload [1 GB Limit]
|
||||
→ gleicher Pfad; Sichtbarkeit + Verein als Formular-Parameter
|
||||
```
|
||||
|
||||
### 6.3 Medienpromotion
|
||||
|
||||
```
|
||||
Vereins-Admin → PATCH /api/media-assets/{id}
|
||||
→ assert_valid_governance_visibility() → Mitgliedschaftsprüfung
|
||||
→ Bei visibility=club: club_id Pflicht + Mitgliedschaft
|
||||
→ Bei visibility=official: NUR Superadmin
|
||||
→ copyright_notice: KEIN Pflichtfeld (nur im exercises-Router für official)
|
||||
|
||||
PROBLEM: Copyright-Pflicht ist NICHT im media_assets-Router für alle Promotions implementiert
|
||||
```
|
||||
|
||||
### 6.4 Medienlöschung
|
||||
|
||||
```
|
||||
Stufe 1 (Soft-Trash, lifecycle_state='trash_soft'):
|
||||
→ Manuell durch Eigentümer / Vereins-Admin / Superadmin
|
||||
→ Datei bleibt auf Disk; weiterhin sichtbar (je nach Exercise-Implementierung)
|
||||
|
||||
Stufe 2 (Hidden, lifecycle_state='trash_hidden'):
|
||||
→ Nach 30 Tagen (Job) oder manuell
|
||||
→ Nicht mehr in normalen Abfragen sichtbar
|
||||
|
||||
Stufe 3 (Purge):
|
||||
→ Nach weiteren 30 Tagen (Job) oder Superadmin manuell
|
||||
→ Datei physisch gelöscht
|
||||
|
||||
PROBLEM: media_retention_job.py ist NICHT automatisch geplant
|
||||
```
|
||||
|
||||
### 6.5 Rechteprüfung
|
||||
|
||||
```
|
||||
Jeder Request → require_auth() → Token aus X-Auth-Token-Header → Session aus DB
|
||||
Vereinsdaten → get_tenant_context() → TenantContext (profile_id, role, effective_club_id)
|
||||
Listenabfragen → library_content_visibility_sql() → SQL WHERE-Baustein
|
||||
Schreibzugriffe → assert_valid_governance_visibility() → 403 bei Verstoß
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Rollen- und Rechteanalyse
|
||||
|
||||
### 7.1 Mandantentrennung – Stärken
|
||||
|
||||
- `TenantContext` konsequent in allen vereinsrelevanten Routern via `Depends(get_tenant_context)`
|
||||
- `library_content_visibility_sql()` als zentraler Sichtbarkeits-Filter (SQL-Ebene)
|
||||
- `effective_club_id` aus Header nur für Mitglieder, beliebig nur für Plattform-Admins
|
||||
- Integrationstests vorhanden: `test_access_layer_integration.py`
|
||||
|
||||
### 7.2 Klarstellung: Wer kann Vereinsmedien bearbeiten?
|
||||
|
||||
Die Audit-Anforderung „alle Vereinsnutzer können bearbeiten" trifft auf die tatsächliche Implementierung **nicht** zu. In `_item_permissions()` (media_assets.py) ist `edit_metadata` nur für `club_admin`-Rolle oder Plattform-Admin True – normale Mitglieder können Vereinsmedien nicht bearbeiten. **Dies ist ein positiver Befund.**
|
||||
|
||||
### 7.3 Profil-Löschung (DSGVO-Lücke)
|
||||
|
||||
`DELETE /api/profiles/{pid}` – nur Plattform-Admin. Nutzer können ihr eigenes Konto **nicht** selbst löschen. Potenzielle DSGVO-Verletzung (Art. 17).
|
||||
|
||||
---
|
||||
|
||||
## 8. Medienrechteanalyse
|
||||
|
||||
### 8.1 Copyright-Feld
|
||||
|
||||
- Vorhanden: `copyright_notice` (max. 8000 Zeichen) in `media_assets`
|
||||
- Pflichtfeld bei `exercise_media` mit `visibility='official'` (exercises-Router)
|
||||
- **NICHT** Pflichtfeld beim direkten Upload in das Medienarchiv
|
||||
- **NICHT** Pflichtfeld bei Promotion von `private` zu `club`
|
||||
- **NICHT** dokumentiert: Wer hat erklärt? Wann? Welche Lizenzversion?
|
||||
|
||||
### 8.2 Rechteerklärung beim Upload
|
||||
|
||||
- Keine Einwilligungserklärung beim Upload: „Ich bestätige, alle Rechte an dieser Datei zu besitzen"
|
||||
- Kein Upload-Dialog mit Pflicht-Checkbox
|
||||
- Kein Hinweis auf verbotene Inhalte (Rechte Dritter, Persönlichkeitsrechte)
|
||||
|
||||
### 8.3 Recht am eigenen Bild
|
||||
|
||||
- Keine Abfrage, ob erkennbare Personen abgebildet sind
|
||||
- Keine Abfrage, ob Minderjährige enthalten sind
|
||||
- Keine Abfrage nach Einwilligung der abgebildeten Personen
|
||||
- Juristisch zu prüfen: Anforderungen nach §22 KUG
|
||||
|
||||
---
|
||||
|
||||
## 9. Löschkonzeptanalyse
|
||||
|
||||
### 9.1 Stärken
|
||||
|
||||
- Klares 3-Stufen-Lifecycle-Modell (active → trash_soft → trash_hidden → purged)
|
||||
- Superadmin-Direktlöschung als Sofortmaßnahme
|
||||
- SHA256-Deduplizierung verhindert doppelte physische Dateien
|
||||
- Datei-Relokation bei Sichtbarkeitsänderung implementiert
|
||||
|
||||
### 9.2 Lücken
|
||||
|
||||
| Problem | Risiko |
|
||||
|---------|--------|
|
||||
| Papierkorb-Job nicht automatisch geplant | Dateien bleiben physisch nach Ablauf der Fristen |
|
||||
| Keine Löschung aus Backups dokumentiert | DSGVO Art. 17: Backup-Retention oder Löschprozess nötig |
|
||||
| Kein Legal-Hold-Status | Bei Rechtsverletzung dauert es 30 Tage bis zur vollständigen Unsichtbarkeit |
|
||||
| Kein Audit-Log für Löschgründe | Keine Nachvollziehbarkeit für DSA/DSGVO |
|
||||
| Kein Uploader-Benachrichtigungssystem | Bei Sperrung / Löschung kein Feedback an Uploader |
|
||||
|
||||
---
|
||||
|
||||
## 10. PWA- / Storage-Analyse
|
||||
|
||||
### 10.1 Positiv
|
||||
|
||||
- Kein Service Worker → kein PWA-Cache-Risiko für Medien
|
||||
- Keine Cookies → kein Cookie-Banner nötig (für Cookies)
|
||||
- CSP-Header gesetzt: `script-src 'self'` (XSS-Mitigation)
|
||||
|
||||
### 10.2 LocalStorage-Bewertung
|
||||
|
||||
Die localStorage-Nutzung ist technisch notwendig (Auth, Mandantenkontext). Nach TDDDG §25 ist technisch notwendige Speicherung ohne Einwilligung zulässig. Dokumentation in der Datenschutzerklärung ist Pflicht.
|
||||
|
||||
### 10.3 Token-Sicherheit
|
||||
|
||||
- Auth-Token in `localStorage`: vulnerabel bei XSS
|
||||
- CSP `script-src 'self'` reduziert XSS-Risiko erheblich
|
||||
- Kein CSRF-Problem (Token im Header, nicht in Cookie)
|
||||
- `HttpOnly`-Cookie wäre sicherer, erfordert Architekturanpassung
|
||||
|
||||
---
|
||||
|
||||
## 11. Datenschutzanalyse (DSGVO)
|
||||
|
||||
### 11.1 Identifizierte Verarbeitungsvorgänge
|
||||
|
||||
| Vorgang | Rechtsgrundlage (technisch) | VVT-Status |
|
||||
|---------|----------------------------|-----------|
|
||||
| Registrierung (Name, E-Mail, Passwort-Hash) | Vertrag (Art. 6 Abs. 1 lit. b) | ❌ Kein VVT |
|
||||
| Login / Session-Management | Berechtigtes Interesse | ❌ Kein VVT |
|
||||
| E-Mail-Versand | Vertragserfüllung | ❌ Kein VVT, SMTP-Anbieter unbekannt |
|
||||
| Medienupload (Bilder/Videos) | Einwilligung oder Vertragserfüllung | ❌ Keine Einwilligung abgeholt |
|
||||
| Vereinszugehörigkeit | Vertragserfüllung | ❌ Kein VVT |
|
||||
| Training-Logging | Berechtigtes Interesse | ❌ Kein VVT |
|
||||
| Backup (implizit) | Berechtigtes Interesse | ❌ Keine Retention dokumentiert |
|
||||
|
||||
### 11.2 Betroffenenrechte
|
||||
|
||||
| Recht | Status |
|
||||
|-------|--------|
|
||||
| Auskunft (Art. 15) | ❌ Kein Self-Service-Export |
|
||||
| Berichtigung (Art. 16) | ⚠ Nur eigener Name/E-Mail über Einstellungen |
|
||||
| Löschung (Art. 17) | ❌ Kein Self-Service-Löschung |
|
||||
| Einschränkung (Art. 18) | ❌ Nicht implementiert |
|
||||
| Datenübertragbarkeit (Art. 20) | ❌ Kein Export-Endpoint |
|
||||
| Widerspruch (Art. 21) | ❌ Kein Mechanismus |
|
||||
|
||||
### 11.3 Auftragsverarbeiter (identifiziert)
|
||||
|
||||
| Dienst | Anbieter | AV-Vertrag |
|
||||
|--------|----------|-----------|
|
||||
| Hosting | Selbstbetrieb (Raspberry Pi) | Entfällt |
|
||||
| SMTP / E-Mail | Unbekannt (Env-Variable) | ❌ Nicht dokumentiert |
|
||||
| MediaWiki-Import | karatetrainer.net | ❌ Nicht dokumentiert |
|
||||
| OpenRouter (KI) | OpenRouter.ai | ❌ Nicht dokumentiert |
|
||||
|
||||
### 11.4 Minderjährige
|
||||
|
||||
- Keine Altersverifikation bei Registrierung
|
||||
- Keine besondere Schutzmaßnahme
|
||||
- Juristisch zu prüfen: §8 DSGVO
|
||||
|
||||
---
|
||||
|
||||
## 12. DSA-/UGC-Analyse
|
||||
|
||||
### 12.1 Einordnung
|
||||
|
||||
Die App erlaubt Upload von User Generated Content (Bilder, Videos). Inhalte können öffentlich sichtbar sein (`official`-Stufe: plattformweit). Dies ist UGC im Sinne des DSA.
|
||||
|
||||
**Juristisch zu prüfen:** Ab welcher Nutzerzahl und unter welchen Voraussetzungen der DSA für diese Plattform gilt.
|
||||
|
||||
### 12.2 Fehlende Mechanismen
|
||||
|
||||
| DSA-Anforderung | Status |
|
||||
|-----------------|--------|
|
||||
| Meldeverfahren für rechtswidrige Inhalte | ❌ |
|
||||
| „Inhalt melden"-Funktion | ❌ |
|
||||
| Moderations-Backend mit Statuswerten | ❌ |
|
||||
| Benachrichtigung des Uploaders bei Sperrung | ❌ |
|
||||
| Begründung für Moderationsentscheidungen | ❌ |
|
||||
| Beschwerdemechanismus | ❌ |
|
||||
| Eskalation für schwere Inhalte (CSAM, Straftaten) | ❌ |
|
||||
| Audit-Log für Meldungen und Entscheidungen | ❌ |
|
||||
|
||||
### 12.3 Was vorhanden ist (Notfall-Maßnahmen)
|
||||
|
||||
- Superadmin kann Inhalte sofort physisch löschen (`superadmin_hard_delete`)
|
||||
- Lifecycle-System ermöglicht schrittweise Deaktivierung
|
||||
- `official`-Promotion nur durch Superadmin (redaktioneller Prozess)
|
||||
|
||||
---
|
||||
|
||||
## 13. Sicherheitsanalyse
|
||||
|
||||
### 13.1 Positiv bewertete Maßnahmen
|
||||
|
||||
| Maßnahme | Status |
|
||||
|----------|--------|
|
||||
| HTTPS (Produktion via Reverse-Proxy) | ✓ |
|
||||
| bcrypt Passwort-Hashing mit Legacy-SHA256-Upgrade | ✓ |
|
||||
| Rate-Limiting (slowapi) | ✓ |
|
||||
| CSRF-Schutz (Token im Header, nicht Cookie) | ✓ |
|
||||
| SQL-Injection-Schutz (parameterisierte Queries) | ✓ |
|
||||
| CSP-Header (nginx) | ✓ |
|
||||
| X-Content-Type-Options: nosniff (nginx + FastAPI-Middleware) | ✓ |
|
||||
| X-Frame-Options: SAMEORIGIN | ✓ |
|
||||
| Referrer-Policy: strict-origin-when-cross-origin | ✓ |
|
||||
| Permissions-Policy (camera/mic/geo) | ✓ |
|
||||
| OpenAPI in Produktion deaktiviert | ✓ |
|
||||
| DB-Port nur localhost exponiert | ✓ |
|
||||
| MIME-Type-Validierung beim Upload | ✓ |
|
||||
| SHA256-Integritätsprüfung + Deduplizierung | ✓ |
|
||||
| Secrets in .env (nicht im Code) | ✓ |
|
||||
| User-Enumeration verhindert (forgot-password, resend-verification) | ✓ |
|
||||
| Path-Traversal-Schutz in media_storage.py (`path_under_media_root` + `.relative_to()`) | ✓ |
|
||||
| Club-Name-Slugify: nur `[a-z0-9-]` im Dateipfad | ✓ |
|
||||
| CORS: Origins eingeschränkt (ALLOWED_ORIGINS aus Env) | ✓ |
|
||||
|
||||
### 13.2 Sicherheitslücken
|
||||
|
||||
| ID | Titel | Schwere | Datei/Nachweis |
|
||||
|----|-------|---------|----------------|
|
||||
| SEC-01 | Kein HSTS-Header | Hoch | `frontend/nginx.conf` – kein `Strict-Transport-Security` |
|
||||
| SEC-02 | Auth-Token in localStorage | Mittel | `frontend/src/context/AuthContext.jsx:47` |
|
||||
| SEC-03 | `style-src 'unsafe-inline'` in CSP | Niedrig | `frontend/nginx.conf:23` |
|
||||
| SEC-04 | Passwort-Mindestlänge inkonsistent: Backend 3 Stellen, Frontend-Feld minLength=6, Backend-Register-Minimum=8 | Mittel | `backend/routers/auth.py:104` (`< 4`), `frontend/src/pages/LoginPage.jsx:175` (`minLength="6"`) |
|
||||
| SEC-05 | ALLOW_PUBLIC_MEDIA_STATIC umgeht Auth für alle Medien | Hoch | `backend/main.py:222-223` |
|
||||
| SEC-06 | Kein MFA für Superadmins | Mittel | Kein TOTP/OTP implementiert |
|
||||
| SEC-07 | Kein Audit-Log für Admin-Aktionen | Mittel | Keine `admin_audit_log`-Tabelle |
|
||||
| SEC-08 | Password-Reset-Token in sessions-Tabelle (Präfix `reset_`) | Niedrig | `backend/routers/auth.py:143` |
|
||||
| SEC-09 | Kein Backup-Konzept dokumentiert | Mittel | Kein Backup-Skript im Repo |
|
||||
| SEC-10 | Kein Anti-Virus-Scan für Uploads | Niedrig | Kein ClamAV o.ä. |
|
||||
| SEC-11 | Kein genereller HTML-Sanitizer für Rich-Text-Felder | Mittel | `backend/exercise_rich_text.py` – nur Inline-Media-Normalisierung, kein bleach/nh3 |
|
||||
| SEC-12 | `minLength="6"` im Login-Formular, Backend fordert 8 Zeichen | Niedrig | `frontend/src/pages/LoginPage.jsx:175` |
|
||||
| SEC-13 | Hartcodierte Versionsangabe `v0.1.0 • Development` auf Login-Seite (falsch + Info-Leak) | Niedrig | `frontend/src/pages/LoginPage.jsx:242` |
|
||||
| SEC-14 | CORS: `allow_methods=["*"]` und `allow_headers=["*"]` breiter als nötig | Niedrig | `backend/main.py:84-87` |
|
||||
|
||||
### 13.3 Ergänzende Befunde aus Restprüfung
|
||||
|
||||
#### main.py — CORS-Konfiguration
|
||||
|
||||
```python
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=ALLOWED_ORIGINS, # ✓ aus Env, keine Wildcard-Origins
|
||||
allow_credentials=True, # ✓ korrekt (kein * + credentials)
|
||||
allow_methods=["*"], # ⚠ breiter als nötig
|
||||
allow_headers=["*"], # ⚠ breiter als nötig
|
||||
)
|
||||
```
|
||||
|
||||
`allow_credentials=True` in Kombination mit `allow_origins=["*"]` wäre ein kritischer Fehler (FastAPI würde ihn aber abweisen). Durch die explizite Origin-Liste ist das Risiko gering. `allow_methods=["*"]` und `allow_headers=["*"]` könnten auf die tatsächlich benötigten Methoden (GET, POST, PUT, PATCH, DELETE) und Header (X-Auth-Token, X-Active-Club-Id, Content-Type) eingeschränkt werden.
|
||||
|
||||
#### media_storage.py — Path-Traversal-Schutz (positiv)
|
||||
|
||||
`path_under_media_root()` kombiniert zwei unabhängige Prüfungen:
|
||||
1. String-Prüfung: `".." in key.split("/")`
|
||||
2. Filesystem-Prüfung: `p.relative_to(media_root.resolve())`
|
||||
|
||||
Die Dateiendung wird auf 16 Zeichen begrenzt. Club-Namen werden auf `[a-z0-9-]` normalisiert. SHA256 als Dateiname ist manipulationssicher. **Bewertung: Gut implementiert, kein Path-Traversal-Risiko erkennbar.**
|
||||
|
||||
#### exercise_rich_text.py — Fehlender genereller HTML-Sanitizer
|
||||
|
||||
Das Modul normalisiert ausschließlich das Inline-Media-Markup (`{{exerciseMedia:id}}` → `<span>`). Es enthält **keinen** generellen HTML-Sanitizer (kein bleach, lxml-cleaner, nh3 o.ä.).
|
||||
|
||||
Felder in `RICH_HTML_EXERCISE_FIELDS` (`summary`, `goal`, `execution`, `preparation`, `trainer_notes`) können beliebiges HTML enthalten. Risikominderung:
|
||||
- CSP `script-src 'self'` verhindert `<script>`-Ausführung
|
||||
- React's `dangerouslySetInnerHTML` muss im Frontend für XSS genutzt werden — zu prüfen
|
||||
- Betroffene Felder sind nur für eingeloggte Nutzer sichtbar (kein öffentlicher Angriffspfad)
|
||||
|
||||
**Empfehlung:** bleach oder nh3 für Allowlist-basierte HTML-Sanitierung einsetzen.
|
||||
|
||||
#### LoginPage.jsx — Weitere Befunde
|
||||
|
||||
1. **Keine Rechtstexte-Links:** Kein Link auf Impressum oder Datenschutzerklärung (bestätigt KRIT-01)
|
||||
2. **`minLength="6"`:** Browser-seitig 6 Zeichen, Backend erzwingt 8 → UX-Bruch, Nutzer sieht kein Frontend-Feedback
|
||||
3. **Hartcodierter Versionsstring:** `v0.1.0 • Development` ist öffentlich sichtbar, falsch (App ist 0.8.65) und leakt Umgebungsinfo
|
||||
|
||||
### 13.5 Warnung: ALLOW_PUBLIC_MEDIA_STATIC (SEC-05)
|
||||
|
||||
Das Flag `ALLOW_PUBLIC_MEDIA_STATIC=1` würde bei Aktivierung alle Mediendateien ohne Auth unter `/media/` ausliefern und das gesamte Sichtbarkeitskonzept (privat, Verein, offiziell) für alle gespeicherten Mediendateien unterlaufen. Bestätigt in `backend/main.py:222-223`:
|
||||
|
||||
```python
|
||||
if os.getenv("ALLOW_PUBLIC_MEDIA_STATIC", "").strip().lower() in ("1", "true", "yes"):
|
||||
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
|
||||
```
|
||||
|
||||
**Dieses Flag darf in Produktionsumgebungen niemals gesetzt sein.** Muss in der Betriebsdokumentation explizit verboten und per Release-Checkliste überprüft werden.
|
||||
|
||||
---
|
||||
|
||||
## 14. Dokumentationsanalyse
|
||||
|
||||
### 14.1 Vorhandene technische Dokumentation
|
||||
|
||||
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` ✓
|
||||
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` ✓
|
||||
- `backend/version.py` mit CHANGELOG ✓
|
||||
- `backend/scripts/check_access_layer_hints.py` ✓
|
||||
|
||||
### 14.2 Fehlende rechtliche Dokumentation
|
||||
|
||||
| Dokument | Status (Audit 2026-05-09) | Stand 2026-05-10 |
|
||||
|----------|--------------------------|------------------|
|
||||
| Impressum | ❌ Keine Seite, kein Inhalt, keine Route | ⚠️ Route + Platzhalter vorhanden; Inhalt durch Betreiber/Rechtsanwalt ausstehend |
|
||||
| Datenschutzerklärung | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
|
||||
| Nutzungsbedingungen / AGB | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
|
||||
| Medienrichtlinie / Community-Regeln | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
|
||||
| Verzeichnis der Verarbeitungstätigkeiten (VVT) | ❌ | ❌ offen (Betreiber-Aufgabe) |
|
||||
| AV-Verträge mit Auftragsverarbeitern | ❌ | ❌ offen (Betreiber-Aufgabe) |
|
||||
| Backup-Konzept schriftlich | ❌ | ❌ offen (Betreiber-Aufgabe) |
|
||||
|
||||
> **Amendment 2026-05-10:** Routen und Platzhalterseiten implementiert (P-01, 0.8.69); Mobile/PWA via `/settings/legal` (P-01b, 0.8.70); Admin-konfigurierbare Rechtstexte mit DB-Versionierung, Superadmin-UI, PDF-Download, Abschnitts-Editor (P-01c, 0.8.71–0.8.74). KRIT-01 bleibt offen bis zur Veröffentlichung juristisch geprüfter Inhalte.
|
||||
|
||||
### 14.3 Fehlende Frontend-Routen
|
||||
|
||||
In `frontend/src/App.jsx` fehlen (Stand Audit 2026-05-09):
|
||||
- `/impressum`
|
||||
- `/datenschutz`
|
||||
- `/nutzungsbedingungen`
|
||||
- `/medienrichtlinie`
|
||||
|
||||
Alle müssen **vor der Authentifizierung** erreichbar und in der PWA verfügbar sein.
|
||||
|
||||
> **Amendment 2026-05-10 (P-01, Version 0.8.69):** Alle vier Routen sind implementiert und ohne Auth erreichbar. Links in LoginPage-Footer, DesktopSidebar-Footer und `/settings/legal` (P-01b). Migrationsnummer der Datenbank: bis 046 geprüft (Audit-Scope). Migration 047 (legal_documents) wurde außerhalb des Audit-Zeitfensters angelegt — siehe `docs/compliance-implementation.md` §P-01c.
|
||||
|
||||
---
|
||||
|
||||
## 15. Testanalyse
|
||||
|
||||
### 15.1 Vorhandene Tests
|
||||
|
||||
| Test-Datei | Inhalt |
|
||||
|-----------|--------|
|
||||
| `test_access_layer.py` | Sichtbarkeits-SQL-Logik |
|
||||
| `test_access_layer_integration.py` | Cross-Tenant-Isolation mit echter DB |
|
||||
| `test_exercises_delete_policy.py` | DELETE-Logik |
|
||||
| `test_exercise_media_download.py` | Download-Zugriffsschutz |
|
||||
| `test_official_exercise_media_rules.py` | Official-Promotion + Copyright |
|
||||
| `test_media_assets_archive.py` | Deduplizierung, Lifecycle |
|
||||
| `test_club_exercise_media_copyright.py` | Copyright bei Vereinsübungen |
|
||||
| `test_exercise_inline_post.py` | Inline-Medien-Validierung |
|
||||
| `test_exercise_rich_text.py` | HTML-Sanitizer |
|
||||
| `test_security_release.py` | OpenAPI/Health in Produktion |
|
||||
| `test_profiles_read_access.py` | Profil-Zugriffsrechte |
|
||||
|
||||
### 15.2 Testlücken
|
||||
|
||||
| Bereich | Status |
|
||||
|---------|--------|
|
||||
| DSA-Meldeverfahren | ❌ Funktion fehlt |
|
||||
| DSGVO-Betroffenenrechte (Löschung, Export) | ❌ Funktion fehlt |
|
||||
| Minderjährigen-Check beim Upload | ❌ Funktion fehlt |
|
||||
| Einwilligungs-Check beim Upload | ❌ Funktion fehlt |
|
||||
| ALLOW_PUBLIC_MEDIA_STATIC=1 aktiviert | ❌ Nicht getestet |
|
||||
| Admin-Audit-Log | ❌ Funktion fehlt |
|
||||
| Passwort-Mindestlänge bei PIN-Änderung | ❌ Nicht getestet |
|
||||
| Copyright-Pflicht bei Archiv-Promotion | ❌ Nicht getestet |
|
||||
|
||||
---
|
||||
|
||||
## 16. Risiko-Matrix
|
||||
|
||||
### KRITISCH
|
||||
|
||||
| ID | Titel | Beschreibung | Betroffene Dateien | Juristisch prüfen | Aufwand |
|
||||
|----|-------|-------------|-------------------|-------------------|---------|
|
||||
| KRIT-01 | Keine Rechtstexte | Keine Impressum-, Datenschutz-, AGB- oder Medienrichtlinien-Seite. Öffentlich erreichbare App ohne Impressum ist Ordnungswidrigkeit (TMG §5, TDDDG). | `frontend/src/App.jsx` – keine Routen | Ja | 2–5 Tage (Technik) + Rechtsanwalt |
|
||||
| KRIT-02 | Kein Self-Service-Löschrecht | Nutzer können ihr Konto nicht selbst löschen (DSGVO Art. 17). Nur Plattform-Admin kann Konten löschen. | `backend/routers/profiles.py:414` | Ja | 5–8 Tage |
|
||||
| KRIT-03 | Kein DSA-Meldeverfahren | Keine Möglichkeit, rechtswidrige Inhalte zu melden. Kein Moderationssystem für UGC-Plattform. | Kein Router vorhanden | Ja | 10–20 Tage |
|
||||
| KRIT-04 | Kein Recht-am-eigenen-Bild-Check | Keine Abfrage bei Medienupload, ob Personen oder Minderjährige abgebildet sind. | `backend/routers/exercises.py`, `backend/routers/media_assets.py` | Ja | 3–7 Tage |
|
||||
| KRIT-05 | Kein DSGVO-Self-Service (Auskunft, Export) | Keine Datenauskunft, kein Datenexport, keine Berichtigungsmöglichkeit (DSGVO Art. 15, 16, 20). | Kein Endpoint | Ja | 5–10 Tage |
|
||||
| KRIT-06 | Copyright-Pflicht inkonsistent | Copyright ist Pflichtfeld nur im exercises-Router für `official`. Im media_assets-Router (Archiv) kann ohne Copyright zu `club`/`official` promoted werden. | `backend/routers/media_assets.py:766–784` | Ja | 1–2 Tage |
|
||||
| KRIT-07 | Papierkorb-Job nicht geplant | `media_retention_job.py` existiert, aber kein Cron-Job konfiguriert. Medien bleiben physisch nach Ablauf der DSGVO-Fristen auf dem Server. | `backend/media_retention_job.py` | Nein | 1 Tag |
|
||||
|
||||
### HOCH
|
||||
|
||||
| ID | Titel | Beschreibung | Aufwand |
|
||||
|----|-------|-------------|---------|
|
||||
| HOCH-01 | ALLOW_PUBLIC_MEDIA_STATIC | Wenn gesetzt, sind alle Mediendateien ohne Auth abrufbar – untergräbt gesamtes Sichtbarkeitskonzept | Dokumentation + Test |
|
||||
| HOCH-02 | Kein HSTS | Kein `Strict-Transport-Security`-Header in nginx.conf | Dokumentation (Reverse-Proxy) |
|
||||
| HOCH-03 | Auth-Token in localStorage | XSS könnte Token extrahieren; CSP reduziert, eliminiert nicht | Dokumentation (HttpOnly als Langfrist-Plan) |
|
||||
| HOCH-04 | Kein MFA für Superadmins | Superadmin hat unbegrenzten Systemzugriff ohne zweiten Faktor | 5–8 Tage |
|
||||
| HOCH-05 | Kein Admin-Audit-Log | Profil-Löschungen, Lifecycle-Aktionen nicht geloggt | 3–5 Tage |
|
||||
| HOCH-06 | Keine Mindestalter-Abfrage | Keine Schranke gegen Registrierung Minderjähriger | 1–2 Tage |
|
||||
|
||||
### MITTEL
|
||||
|
||||
| ID | Titel | Beschreibung | Aufwand |
|
||||
|----|-------|-------------|---------|
|
||||
| MITT-01 | Passwort-Mindestlänge inkonsistent | Register: 8 Zeichen, `PUT /api/auth/pin`: 4 Zeichen | 30 Min |
|
||||
| MITT-02 | Keine Sofortsperrung bei Rechtsverletzung | Stufe-1-Papierkorb dauert 30 Tage bis zur vollständigen Unsichtbarkeit | 2–3 Tage |
|
||||
| MITT-03 | Kein VVT | Kein Verzeichnis der Verarbeitungstätigkeiten (DSGVO Art. 30) | Betreiber |
|
||||
| MITT-04 | SMTP-Anbieter unbekannt | Kein AV-Vertrag; E-Mail-Dienstleister nicht dokumentiert | Betreiber |
|
||||
| MITT-05 | sessionStorage nicht bei Logout bereinigt | TrainingCoachPage-Fortschritt bleibt nach Logout im sessionStorage | 0,5 Tage |
|
||||
| MITT-06 | Keine Löschung aus Backups | DSGVO-Löschungsanfragen greifen nicht auf Backups | Betreiber (Policy) |
|
||||
| MITT-07 | MediaWiki-Integration ohne AV-Vertrag | Datentransfer zu karatetrainer.net nicht dokumentiert | Betreiber |
|
||||
| MITT-08 | OpenRouter ohne AV-Vertrag | Erst aktivieren wenn AV-Vertrag vorhanden | Betreiber |
|
||||
|
||||
### NIEDRIG
|
||||
|
||||
| ID | Titel | Beschreibung | Aufwand |
|
||||
|----|-------|-------------|---------|
|
||||
| NIED-01 | `style-src 'unsafe-inline'` | Inline-Styles in CSP erlaubt | Nonce/Hash |
|
||||
| NIED-02 | Kein Anti-Virus-Scan | Malware-Dateien hochladbar | ClamAV-Integration |
|
||||
| NIED-03 | Reset-Token in sessions-Tabelle | Token mit `reset_`-Präfix in Auth-Tabelle | Separate Tabelle |
|
||||
| NIED-04 | SHA256-Hash in API-Response | Datei-Fingerprinting möglich | Response-Filterung |
|
||||
| NIED-05 | Kein Passwort-Complexity-Check | Nur Mindestlänge geprüft | zxcvbn o.ä. |
|
||||
| NIED-06 | `minLength="6"` im Login-Formular | Inkonsistent mit Backend (8 Zeichen); Browser lässt 6-7-char-Passwörter zu, Backend lehnt sie dann ab | `frontend/src/pages/LoginPage.jsx:175` |
|
||||
| NIED-07 | Hartcodierter Versionsstring auf Login-Seite | `v0.1.0 • Development` sichtbar ohne Auth; falsche Version (0.8.65) + Umgebungsinfo | `frontend/src/pages/LoginPage.jsx:242` |
|
||||
| NIED-08 | CORS allow_methods/headers=`["*"]` | Breiter als nötig; Origins sind korrekt eingeschränkt, aber Methoden/Header nicht | `backend/main.py:84-87` |
|
||||
| NIED-09 | Kein genereller HTML-Sanitizer für Rich-Text | `exercise_rich_text.py` bereinigt nur Inline-Media-Markup; beliebiges HTML in `summary`, `goal`, `execution` etc. möglich (CSP schützt gegen Script-Execution) | `backend/exercise_rich_text.py` |
|
||||
|
||||
---
|
||||
|
||||
## 17. Umsetzungsplan
|
||||
|
||||
### Empfohlene Reihenfolge
|
||||
|
||||
**Etappe 1 – Pflicht vor öffentlichem Betrieb (Kritische Blocker)**
|
||||
|
||||
| Paket-ID | Titel | Findings | Aufwand |
|
||||
|----------|-------|---------|---------|
|
||||
| P-01 | Rechtstexte (Seiten + Routen, Inhalte durch Rechtsanwalt) | KRIT-01 | 2–5 Tage Technik |
|
||||
| P-02 | Self-Service-Kontolöschung + Datenexport | KRIT-02, KRIT-05 | 5–8 Tage |
|
||||
| P-03 | Papierkorb-Retention-Job aktivieren | KRIT-07 | 1 Tag |
|
||||
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | KRIT-06 | 1 Tag |
|
||||
| P-05 | Passwort-Mindestlänge angleichen | MITT-01 | 30 Min |
|
||||
| P-06 | Upload-Einwilligungsdialog (Personen, Minderjährige, Rechte) | KRIT-04 | 2–4 Tage |
|
||||
|
||||
**Etappe 2 – Sicherheit und Datenschutz (dringend empfohlen)**
|
||||
|
||||
| Paket-ID | Titel | Findings | Aufwand |
|
||||
|----------|-------|---------|---------|
|
||||
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test | HOCH-01, SEC-05 | 0,5 Tage |
|
||||
| P-08 | HSTS und externe Proxy-Sicherheit dokumentieren | HOCH-02, SEC-01 | 0,5 Tage |
|
||||
| P-09 | Admin-Audit-Log | HOCH-05, SEC-07 | 3–5 Tage |
|
||||
| P-10 | Mindestalter-Abfrage | HOCH-06 | 1–2 Tage |
|
||||
| P-11 | Legal-Hold Lifecycle-Status | MITT-02 | 2–3 Tage |
|
||||
| P-12 | sessionStorage bei Logout bereinigen | MITT-05 | 0,5 Tage |
|
||||
| P-22 | HTML-Sanitizer für Rich-Text-Felder (bleach/nh3) | NIED-09, SEC-11 | 1–2 Tage |
|
||||
| P-23 | LoginPage: minLength angleichen + Version entfernen | NIED-06, NIED-07, SEC-12, SEC-13 | 1 Stunde |
|
||||
| P-24 | CORS einschränken (Methoden + Header) | NIED-08, SEC-14 | 1 Stunde |
|
||||
|
||||
**Etappe 3 – DSA-Meldeverfahren (mittelfristig, nach juristischer Klärung)**
|
||||
|
||||
| Paket-ID | Titel | Findings | Aufwand |
|
||||
|----------|-------|---------|---------|
|
||||
| P-13 | Content-Melde-Backend (content_reports-Tabelle + Endpoints) | KRIT-03 | 5–8 Tage |
|
||||
| P-14 | Moderations-UI (Frontend) | KRIT-03 | 3–5 Tage |
|
||||
| P-15 | Uploader-Benachrichtigung bei Sperrung | KRIT-03 | 1–2 Tage |
|
||||
| P-16 | Beschwerdeverfahren | KRIT-03 | 2–4 Tage |
|
||||
|
||||
**Etappe 4 – Langfristige Optimierungen**
|
||||
|
||||
| Paket-ID | Titel | Aufwand |
|
||||
|----------|-------|---------|
|
||||
| P-17 | MFA für Superadmins (TOTP) | 5–8 Tage |
|
||||
| P-18 | HttpOnly-Cookie als Auth-Alternative | 3–5 Tage |
|
||||
| P-19 | Anti-Virus-Scan (ClamAV) | 3–5 Tage |
|
||||
| P-20 | VVT erstellen | Betreiber |
|
||||
| P-21 | AV-Verträge abschließen | Betreiber |
|
||||
|
||||
---
|
||||
|
||||
### P-04 im Detail: Copyright-Pflicht vereinheitlichen
|
||||
|
||||
**Technische Änderung Backend:**
|
||||
In `backend/routers/media_assets.py`, Funktionen `patch_media_asset()` und `bulk_media_patch()`:
|
||||
- Bei Visibility-Wechsel zu `club` oder `official`: `copyright_notice` muss vorhanden und min. 3 Zeichen lang sein
|
||||
- Fehler: HTTP 422 mit klarer Fehlermeldung
|
||||
|
||||
**Test:** Promotion ohne copyright_notice → HTTP 422; mit copyright_notice → OK
|
||||
|
||||
---
|
||||
|
||||
### P-05 im Detail: Passwort-Mindestlänge angleichen
|
||||
|
||||
**Technische Änderung:**
|
||||
- `backend/routers/auth.py:104`: `if len(new_pin) < 8:` statt `< 4`
|
||||
- Fehlermeldung: „Passwort muss mindestens 8 Zeichen lang haben"
|
||||
|
||||
---
|
||||
|
||||
### P-13 im Detail: Content-Melde-Backend
|
||||
|
||||
**Neue DB-Migration (`backend/migrations/047_content_reports.sql`):**
|
||||
```sql
|
||||
CREATE TABLE content_reports (
|
||||
id SERIAL PRIMARY KEY,
|
||||
reporter_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
target_type VARCHAR(20) NOT NULL CHECK (target_type IN ('exercise', 'media_asset')),
|
||||
target_id INTEGER NOT NULL,
|
||||
reason VARCHAR(50) NOT NULL
|
||||
CHECK (reason IN ('illegal_content', 'copyright', 'personal_rights',
|
||||
'minor_protection', 'hate_speech', 'spam', 'other')),
|
||||
description TEXT,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending', 'under_review', 'resolved_removed',
|
||||
'resolved_kept', 'rejected')),
|
||||
moderator_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
moderator_note TEXT,
|
||||
resolved_at TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
```
|
||||
|
||||
**Neue Endpoints:**
|
||||
- `POST /api/reports` – Meldung einreichen (require_auth)
|
||||
- `GET /api/admin/reports` – Moderations-Queue (Admin/Superadmin)
|
||||
- `PATCH /api/admin/reports/{id}` – Status setzen + Notiz
|
||||
|
||||
---
|
||||
|
||||
## 18. Dauerhafter Auditplan
|
||||
|
||||
### 18.1 Audit-Frequenzen
|
||||
|
||||
| Typ | Frequenz |
|
||||
|-----|----------|
|
||||
| Mini-Audit | Bei jedem PR mit Compliance-Relevanz |
|
||||
| Release-Audit | Vor jedem Produktions-Deployment |
|
||||
| Quartalsaudit | Alle 3 Monate |
|
||||
| Jahresaudit | Einmal jährlich (mit Rechtsanwalt/Datenschutzbeauftragtem) |
|
||||
|
||||
### 18.2 Sonderaudit-Auslöser
|
||||
|
||||
- Neue öffentlich sichtbare Features
|
||||
- Neue Upload-Funktionen (Medientypen, Quellen)
|
||||
- Neue Rollen oder Rechteänderungen
|
||||
- Neue externe Dienstleister
|
||||
- Einführung von Analytics oder Tracking
|
||||
- Änderungen am Minderjährigenschutz
|
||||
- Sicherheitsvorfall oder Datenpanne
|
||||
- Datenschutzanfrage eines Nutzers
|
||||
- Meldung rechtswidriger Inhalte
|
||||
- Größere Architekturänderungen
|
||||
- Gesetzesänderungen (DSGVO, DSA, TDDDG)
|
||||
|
||||
### 18.3 Checkliste: Mini-Audit bei Feature-PR
|
||||
|
||||
```
|
||||
[ ] Betrifft der PR personenbezogene Daten? → DSGVO-Check
|
||||
[ ] Betrifft der PR Medienupload oder -anzeige? → Rechte-Check + DSA-Check
|
||||
[ ] Betrifft der PR Rollen oder Sichtbarkeit? → Access-Layer-Check
|
||||
[ ] Betrifft der PR Storage oder Caching? → TDDDG-Check
|
||||
[ ] Betrifft der PR externe Dienste? → AV-Vertrag prüfen
|
||||
[ ] Betrifft der PR Auth oder Session? → Sicherheits-Check
|
||||
[ ] Neuer Endpoint → require_auth / get_tenant_context vorhanden?
|
||||
[ ] Neue Datenspalte → Migration + Lösch-Cascade korrekt?
|
||||
[ ] Neue Frontend-Speicherung → TDDDG-Klassifikation dokumentiert?
|
||||
[ ] ACCESS_LAYER: python backend/scripts/check_access_layer_hints.py
|
||||
```
|
||||
|
||||
### 18.4 Checkliste: Release-Audit
|
||||
|
||||
```
|
||||
[ ] Versions-Bump (backend/version.py + frontend/src/version.js)
|
||||
[ ] ALLOW_PUBLIC_MEDIA_STATIC nicht in Prod-Env gesetzt
|
||||
[ ] OpenAPI/Swagger nicht öffentlich (ENVIRONMENT=production)
|
||||
[ ] HSTS am externen Reverse-Proxy konfiguriert (manuell prüfen)
|
||||
[ ] Papierkorb-Retention-Job läuft (Logs prüfen)
|
||||
[ ] SSL-Zertifikat gültig
|
||||
[ ] DB-Backup der letzten 24h vorhanden
|
||||
[ ] Rechtstexte aktuell (kein Placeholder, kein veraltetes Datum)
|
||||
[ ] pytest -m "not slow" grün
|
||||
[ ] ACCESS_LAYER_INTEGRATION=1 pytest tests/test_access_layer_integration.py grün
|
||||
[ ] test_security_release.py grün
|
||||
[ ] pip-audit (keine kritischen CVEs)
|
||||
[ ] npm audit --audit-level=high (keine kritischen CVEs)
|
||||
```
|
||||
|
||||
### 18.5 Checkliste: Neues Feature
|
||||
|
||||
```
|
||||
[ ] Verarbeitet das Feature personenbezogene Daten? → VVT aktualisieren
|
||||
[ ] Neue DB-Tabellen → Lösch-Cascade und Retention definiert?
|
||||
[ ] Neue API-Endpoints → Access Layer korrekt?
|
||||
[ ] Feature mit UGC? → DSA-Meldeverfahren abgedeckt?
|
||||
[ ] Feature mit Medien? → Lifecycle, Sichtbarkeit, Copyright?
|
||||
[ ] Feature für Minderjährige relevant? → Schutzmaßnahmen?
|
||||
[ ] Neue localStorage/sessionStorage-Nutzung → TDDDG + Datenschutzerklärung?
|
||||
[ ] Neue externe Abhängigkeit → AV-Vertrag?
|
||||
[ ] Keine sensitiven Daten in Fehlerausgaben?
|
||||
[ ] api.js für alle Frontend API-Calls?
|
||||
[ ] Tests geschrieben und grün?
|
||||
```
|
||||
|
||||
### 18.6 Checkliste: Änderung am Medienmodell
|
||||
|
||||
```
|
||||
[ ] Neue Medientypen → MIME-Type-Validierung aktualisiert?
|
||||
[ ] Neue Sichtbarkeitsstufen → library_content_visibility_sql() aktualisiert?
|
||||
[ ] Lifecycle-Änderungen → Papierkorb-Job angepasst?
|
||||
[ ] Copyright-Anforderungen konsistent für alle Promotions-Wege?
|
||||
[ ] ALLOW_PUBLIC_MEDIA_STATIC explizit: In Prod verboten (dokumentiert)?
|
||||
[ ] Neue Download-Endpoints → require_auth_flexible implementiert?
|
||||
[ ] Recht-am-eigenen-Bild-Abfragen aktualisiert?
|
||||
```
|
||||
|
||||
### 18.7 Checkliste: Änderung am Rollenmodell
|
||||
|
||||
```
|
||||
[ ] Neue Rollen → assert_valid_governance_visibility() berücksichtigt?
|
||||
[ ] EXEMPT-Liste in check_access_layer_hints.py aktualisiert?
|
||||
[ ] test_access_layer*.py angepasst?
|
||||
[ ] MFA-Anforderung für neue Admin-Rollen geprüft?
|
||||
[ ] Audit-Log für neue Aktionen?
|
||||
```
|
||||
|
||||
### 18.8 Pflichttests vor Release
|
||||
|
||||
```bash
|
||||
# Zugriffskontrolle
|
||||
pytest backend/tests/test_access_layer.py -v
|
||||
|
||||
# Cross-Tenant-Integration (mit PostgreSQL)
|
||||
ACCESS_LAYER_INTEGRATION=1 pytest backend/tests/test_access_layer_integration.py -v
|
||||
|
||||
# Mediensicherheit
|
||||
pytest backend/tests/test_exercise_media_download.py -v
|
||||
pytest backend/tests/test_official_exercise_media_rules.py -v
|
||||
pytest backend/tests/test_media_assets_archive.py -v
|
||||
pytest backend/tests/test_club_exercise_media_copyright.py -v
|
||||
|
||||
# Sicherheits-Release-Checks
|
||||
pytest backend/tests/test_security_release.py -v
|
||||
|
||||
# Access Layer Script (Strict Mode)
|
||||
ACCESS_LAYER_STRICT=1 python backend/scripts/check_access_layer_hints.py
|
||||
|
||||
# Abhängigkeits-Scan
|
||||
cd backend && pip-audit
|
||||
cd frontend && npm audit --audit-level=high
|
||||
```
|
||||
|
||||
### 18.9 Vorlage: Quartalsaudit-Bericht
|
||||
|
||||
```markdown
|
||||
# Compliance-Quartalsaudit Q[X]/[Jahr]
|
||||
|
||||
Datum: [DATUM] | Auditor: [NAME]
|
||||
|
||||
## 1. Status offener Findings
|
||||
[Tabelle: ID – Titel – Status]
|
||||
|
||||
## 2. Neue Findings dieser Periode
|
||||
[Tabelle: ID – Titel – Schwere – Aufwand]
|
||||
|
||||
## 3. Rechtstexte
|
||||
[ ] Impressum geprüft: [DATUM]
|
||||
[ ] Datenschutzerklärung geprüft: [DATUM]
|
||||
[ ] AGB/Nutzungsbedingungen geprüft: [DATUM]
|
||||
[ ] Medienrichtlinie geprüft: [DATUM]
|
||||
|
||||
## 4. DSGVO-Status
|
||||
[ ] VVT aktuell
|
||||
[ ] AV-Verträge vollständig
|
||||
[ ] Backup-Retention-Policy dokumentiert
|
||||
[ ] Betroffenenrechte-Mechanismen getestet
|
||||
|
||||
## 5. DSA-Status
|
||||
[ ] Meldeverfahren Test-Meldung durchgeführt: [DATUM]
|
||||
[ ] Offene Meldungen: [X] (alle bearbeitet: Ja/Nein)
|
||||
[ ] Eskalationspfad dokumentiert: Ja/Nein
|
||||
|
||||
## 6. Technische Sicherheit
|
||||
[ ] Abhängigkeits-Scan: [DATUM] – Kritische CVEs: [X]
|
||||
[ ] SSL gültig bis: [DATUM]
|
||||
[ ] HSTS konfiguriert: Ja/Nein
|
||||
[ ] Alle Pflichttests grün: Ja/Nein
|
||||
|
||||
## 7. Empfehlungen
|
||||
[Liste]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 19. Entscheidungsvorlage
|
||||
|
||||
### 19.1 Was ist aktuell kritisch?
|
||||
|
||||
1. Keine Rechtstexte – App ist öffentlich ohne Impressum (Ordnungswidrigkeit)
|
||||
2. Kein Löschrecht für Nutzer – DSGVO Art. 17 verletzt
|
||||
3. Kein DSA-Meldeverfahren – bei UGC-Plattform möglicherweise Pflicht
|
||||
4. Copyright-Lücke – Archiv-Upload ohne Copyright-Pflicht bei Promotion
|
||||
5. Kein Recht-am-eigenen-Bild-Check bei Upload
|
||||
|
||||
### 19.2 Was blockiert sicheren öffentlichen Betrieb (technisch)?
|
||||
|
||||
1. KRIT-01: Rechtstexte fehlen vollständig
|
||||
2. KRIT-02: Kein Self-Service-Löschrecht
|
||||
3. KRIT-07: Papierkorb-Job läuft nicht automatisch
|
||||
4. HOCH-01: ALLOW_PUBLIC_MEDIA_STATIC muss in Prod-Doku explizit verboten sein
|
||||
5. HOCH-02: HSTS am externen Reverse-Proxy überprüfen
|
||||
|
||||
### 19.3 Mindest-Paket vor erstem öffentlichem Betrieb
|
||||
|
||||
- P-05 (30 Min): Passwort-Mindestlänge angleichen
|
||||
- P-04 (1 Tag): Copyright-Pflicht vereinheitlichen
|
||||
- P-03 (1 Tag): Papierkorb-Job aktivieren
|
||||
- P-06 (2 Tage): Upload-Einwilligungsdialog
|
||||
- P-01 (2 Tage Technik + Rechtsanwalt): Rechtstexte-Seiten
|
||||
- P-02 (5 Tage): Self-Service-Kontolöschung
|
||||
|
||||
### 19.4 Was kann zurückgestellt werden?
|
||||
|
||||
- P-17 (HttpOnly-Cookie): Größere Architekturänderung, kein unmittelbarer Compliance-Bedarf
|
||||
- P-19 (Anti-Virus-Scan): Hoher Aufwand, Risiko bei lokalem Storage gering
|
||||
- P-13 bis P-16 (DSA-Meldeverfahren): Erst juristisch klären ob und in welchem Umfang erforderlich
|
||||
|
||||
### 19.5 Juristisch zu prüfende Fragen
|
||||
|
||||
| Thema | Frage |
|
||||
|-------|-------|
|
||||
| DSGVO Art. 17 | Wie muss Löschung aus Backups gehandhabt werden? |
|
||||
| DSA | Ab welcher Nutzerzahl gilt der DSA? Welche Pflichten für Kleinplattformen? |
|
||||
| §22 KUG | Welche Einwilligungen für Personenbilder im Vereinskontext? |
|
||||
| §8 DSGVO | Mindestalter für die Registrierung? |
|
||||
| TDDDG §25 | Muss für localStorage eine Einwilligung eingeholt werden? |
|
||||
| Impressum-Pflicht | Vollständige Angaben des Verantwortlichen? |
|
||||
| AV-Verträge | Welche Dienstleister benötigen einen AVV? |
|
||||
| MediaWiki | Lizenzanforderungen für Übungsinhalte aus karatetrainer.net? |
|
||||
|
||||
### 19.6 Organisatorische Aufgaben für den Betreiber
|
||||
|
||||
1. Rechtsanwalt beauftragen (Rechtstexte)
|
||||
2. VVT erstellen (DSGVO Art. 30)
|
||||
3. AV-Verträge abschließen (SMTP-Anbieter, ggf. MediaWiki)
|
||||
4. Backup-Prozess dokumentieren und Restore-Tests durchführen
|
||||
5. Moderationsprozess definieren
|
||||
6. Notfallkontakt für Datenpannen benennen
|
||||
7. HSTS am externen Reverse-Proxy sicherstellen
|
||||
8. Papierkorb-Job-Monitoring einrichten
|
||||
|
||||
### 19.7 Verbleibende Risiken nach technischer Umsetzung
|
||||
|
||||
- HSTS liegt außerhalb des Repos (Betreiber-Verantwortung)
|
||||
- Backup-Löschung bei DSGVO-Anfragen erfordert manuelle Prozesse
|
||||
- Minderjährige können Altersangabe fälschen (kein verlässlicher Online-Altersnachweis)
|
||||
- Rechtswidrige Inhalte können zwischen Upload und Moderationsentscheidung sichtbar sein
|
||||
- SMTP-Anbieter kann E-Mail-Inhalte verarbeiten
|
||||
|
||||
### 19.8 Freigabe-Formulierungen
|
||||
|
||||
Verwende diese exakten Formulierungen zur Freigabe einzelner Pakete:
|
||||
|
||||
| Paket | Freigabe-Formulierung |
|
||||
|-------|----------------------|
|
||||
| P-05 | „Freigabe zur Umsetzung P-05: Passwort-Mindestlänge angleichen" |
|
||||
| P-04 | „Freigabe zur Umsetzung P-04: Copyright-Pflicht vereinheitlichen" |
|
||||
| P-03 | „Freigabe zur Umsetzung P-03: Papierkorb-Retention-Job aktivieren" |
|
||||
| P-06 | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
|
||||
| P-01 | „Freigabe zur Umsetzung P-01: Rechtstexte-Seiten technisch anlegen" |
|
||||
| P-02 | „Freigabe zur Umsetzung P-02: Self-Service-Kontolöschung und Datenexport" |
|
||||
| P-09 | „Freigabe zur Umsetzung P-09: Admin-Audit-Log" |
|
||||
| P-13 | „Freigabe zur Umsetzung P-13: Content-Melde-Backend" |
|
||||
| Etappe 1 komplett | „Freigabe zur Umsetzung Etappe 1" |
|
||||
| Etappe 1+2 | „Freigabe zur Umsetzung Etappen 1 und 2" |
|
||||
|
||||
---
|
||||
|
||||
**Audit abgeschlossen. Keine Codeänderungen vorgenommen. Umsetzung erst nach ausdrücklicher Freigabe.**
|
||||
|
||||
---
|
||||
|
||||
## 20. Regel zur Paket-ID-Stabilität
|
||||
|
||||
> Ergänzt: 2026-05-10 — Kanonisches Referenzdokument: `docs/compliance-package-register.md`
|
||||
|
||||
### 20.1 Grundsatz
|
||||
|
||||
Paket-IDs (P-01 bis P-24 und alle künftigen) werden nach ihrer ersten Vergabe in diesem Dokument **nie wieder umnummeriert, gelöscht oder wiederverwendet.** Die in §17 (Umsetzungsplan) vergebenen IDs sind dauerhaft stabil.
|
||||
|
||||
### 20.2 Regeln im Einzelnen
|
||||
|
||||
| Regel | Beschreibung |
|
||||
|-------|-------------|
|
||||
| **ID-Stabilität** | Eine einmal vergebene Paket-ID bleibt für immer mit dem ursprünglichen fachlichen Inhalt verknüpft. |
|
||||
| **Titel-Präzisierung erlaubt** | Der Titel eines Pakets darf präzisiert werden, wenn die fachliche Substanz unverändert bleibt. Die ID ändert sich dabei nicht. |
|
||||
| **Neue Pakete** | Künftige Arbeitspakete erhalten aufsteigende neue IDs (P-25, P-26 …). Keine Wiedervergabe von IDs abgeschlossener oder gelöschter Pakete. |
|
||||
| **Nacharbeiten mit Suffix** | Nacharbeiten, Korrekturen oder Teilprobleme eines bestehenden Pakets werden mit alphabetischen Suffixen dokumentiert (P-03b, P-05b, …), nicht als eigenständige Hauptpakete. |
|
||||
| **Freigabe-Formulierung** | Freigaben müssen immer die Paket-ID **und** den kanonischen Titel aus diesem Dokument oder aus `docs/compliance-package-register.md` nennen, um Verwechslungen auszuschließen. |
|
||||
| **Kanonisches Register** | `docs/compliance-package-register.md` ist die verbindliche Quelle für alle Umsetzungsberichte, Re-Audit-Dokumente und Freigaben. Bei Widerspruch zwischen Dokumenten gilt dieses Audit als ursprüngliche Quelle; das Register als aktuell gepflegte Wahrheit. |
|
||||
|
||||
### 20.3 Umgang mit Drift in nachgelagerten Dokumenten
|
||||
|
||||
Falls ein nachgelagertes Dokument (Umsetzungsbericht, Re-Audit, Mini-Fix) eine abweichende Beschreibung für eine bekannte ID verwendet, gilt:
|
||||
|
||||
1. Die abweichende Beschreibung ist ein **Dokumentationsfehler**, kein neues Paket.
|
||||
2. Das betroffene Dokument ist auf die kanonische ID und den kanonischen Titel zu korrigieren.
|
||||
3. Der Drift und die Korrektur sind im Konsistenzbericht des Paketregisters zu vermerken.
|
||||
4. Kein fachlicher Inhalt darf bei der Korrektur verloren gehen — er wird ggf. dem richtigen Paket-Eintrag zugeordnet.
|
||||
|
||||
### 20.4 Freigabe-Vorlagen (aktualisiert)
|
||||
|
||||
Verwende diese exakten Formulierungen zur Freigabe einzelner Pakete:
|
||||
|
||||
| Paket | Freigabe-Formulierung |
|
||||
|-------|----------------------|
|
||||
| P-01 | „Freigabe zur Umsetzung P-01: Rechtstexte" |
|
||||
| P-02 | „Freigabe zur Umsetzung P-02: Self-Service-Kontolöschung und Datenexport" |
|
||||
| P-03 | „Freigabe zur Umsetzung P-03: Papierkorb-Retention-Job aktivieren" |
|
||||
| P-04 | „Freigabe zur Umsetzung P-04: Copyright-Pflicht für Archiv-Promotion vereinheitlichen" |
|
||||
| P-05 | „Freigabe zur Umsetzung P-05: Passwort-Mindestlänge angleichen" |
|
||||
| P-06 | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
|
||||
| P-07 | „Freigabe zur Umsetzung P-07: ALLOW_PUBLIC_MEDIA_STATIC dokumentieren und testen" |
|
||||
| P-08 | „Freigabe zur Umsetzung P-08: HSTS und externe Proxy-Sicherheit dokumentieren" |
|
||||
| P-09 | „Freigabe zur Umsetzung P-09: Admin-Audit-Log" |
|
||||
| P-10 | „Freigabe zur Umsetzung P-10: Mindestalter-Abfrage" |
|
||||
| P-11 | „Freigabe zur Umsetzung P-11: Legal-Hold Lifecycle-Status" |
|
||||
| P-12 | „Freigabe zur Umsetzung P-12: sessionStorage bei Logout bereinigen" |
|
||||
| P-13 | „Freigabe zur Umsetzung P-13: Content-Melde-Backend" |
|
||||
| P-17 | „Freigabe zur Umsetzung P-17: MFA für Superadmins" |
|
||||
| P-18 | „Freigabe zur Umsetzung P-18: HttpOnly-Cookie als Auth-Alternative" |
|
||||
| P-22 | „Freigabe zur Umsetzung P-22: HTML-Sanitizer für Rich-Text-Felder" |
|
||||
| Etappe 1 komplett | „Freigabe zur Umsetzung Etappe 1" |
|
||||
| Etappe 1+2 | „Freigabe zur Umsetzung Etappen 1 und 2" |
|
||||
|
||||
> Die ursprüngliche Freigabe-Tabelle in §19.8 bleibt erhalten und zeigt den Stand des Initial-Audits. §20.4 ist die aktuellere, vollständigere Version.
|
||||
|
||||
---
|
||||
|
||||
*Dokument erstellt: 2026-05-09 | Auditor: Claude Code | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
|
||||
@@ -0,0 +1,662 @@
|
||||
# Compliance-Implementierung – Umsetzungsbericht
|
||||
|
||||
**Erstellt:** 2026-05-09
|
||||
**Zuletzt aktualisiert:** 2026-05-11
|
||||
**Audit-Basis:** `docs/compliance-audit.md`
|
||||
**App-Version nach Umsetzung:** 0.8.94
|
||||
|
||||
---
|
||||
|
||||
## Freigegebene Pakete und Umsetzungsstatus
|
||||
|
||||
### P-01 – Rechtstexte ⚠️ (technischer Teil umgesetzt; juristische Inhalte offen)
|
||||
|
||||
**Status:** Technisch teilweise umgesetzt (2026-05-10, Version 0.8.69)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `frontend/src/pages/LegalPage.jsx` (neu) — Platzhalter-Komponente für alle vier Seiten
|
||||
- `frontend/src/App.jsx` — 4 neue öffentliche Routen
|
||||
- `frontend/src/pages/LoginPage.jsx` — Rechtstext-Links im Card-Footer
|
||||
- `frontend/src/components/DesktopSidebar.jsx` — Rechtstext-Links im Sidebar-Footer
|
||||
|
||||
**Technische Änderung:**
|
||||
Vier öffentliche Routen angelegt, kein Auth erforderlich, kein Redirect für nicht eingeloggte Nutzer:
|
||||
- `/impressum` → `<LegalPage type="impressum" />`
|
||||
- `/datenschutz` → `<LegalPage type="datenschutz" />`
|
||||
- `/nutzungsbedingungen` → `<LegalPage type="nutzungsbedingungen" />`
|
||||
- `/medienrichtlinie` → `<LegalPage type="medienrichtlinie" />`
|
||||
|
||||
Jede Seite enthält:
|
||||
- Deutlich sichtbaren Platzhalterhinweis: „MUSTER / PLATZHALTER – Inhalt wird vor Produktivbetrieb juristisch geprüft und durch den Betreiber ergänzt."
|
||||
- Strukturierte Pflichtfelder je Rechtstext (Betreiber, Rechtsgrundlagen, Betroffenenrechte etc.)
|
||||
- Querlinks zu den anderen drei Rechtstextseiten
|
||||
|
||||
Links zu allen vier Seiten sind in der Login-/Registrierungsseite (Card-Footer) und im Desktop-Sidebar-Footer sichtbar ohne Anmeldung erreichbar.
|
||||
|
||||
**Nicht umgesetzt (außerhalb Freigabe):**
|
||||
Juristische Texte, inhaltliche Überprüfung, Admin-konfigurierbare Inhalte, Einwilligungs-Checkboxen.
|
||||
|
||||
**KRIT-01 Blocking-Status:**
|
||||
Der Blocker KRIT-01 bleibt **offen** bis juristisch geprüfte Texte durch den Betreiber eingepflegt sind. Die technische Voraussetzung (Routen und Seitenstruktur) ist erfüllt.
|
||||
|
||||
**Tests:** 5 Playwright-Tests, alle grün:
|
||||
- Impressum ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
|
||||
- Datenschutz ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
|
||||
- Nutzungsbedingungen ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
|
||||
- Medienrichtlinie ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
|
||||
- Login-Seite enthält alle vier Rechtstext-Links
|
||||
|
||||
---
|
||||
|
||||
### P-01b – Mobile/PWA-Erreichbarkeit der Rechtstexte ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10, Version 0.8.70) — Nacharbeit zu P-01
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `frontend/src/pages/SettingsLegalPage.jsx` (neu) — Hub-Seite `/settings/legal`
|
||||
- `frontend/src/App.jsx` — Route `/settings/legal` im ProtectedLayout
|
||||
- `frontend/src/pages/AccountSettingsPage.jsx` — Link zu `/settings/legal`
|
||||
|
||||
**Technische Änderung:**
|
||||
Neue Seite `/settings/legal` im eingeloggten Einstellungsbereich: Hub-Seite mit Links zu allen vier Rechtstextseiten, erreichbar über Einstellungen → Rechtliches. Entspricht dem bestehenden Pattern von `/settings/system`. Auf der AccountSettingsPage ist ein Link „Rechtliches" unterhalb der System-Info-Verlinkung ergänzt.
|
||||
|
||||
**Tests:** 3 Playwright-Tests, alle grün (17/17 Gesamt):
|
||||
- Einstellungen enthält Link zu `/settings/legal`
|
||||
- `/settings/legal` enthält Überschrift + alle vier Rechtstext-Links
|
||||
- Jeder Link aus `/settings/legal` führt zur korrekten öffentlichen Route
|
||||
|
||||
---
|
||||
|
||||
### P-01c – Admin-konfigurierbare Rechtstexte ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10, Version 0.8.71) — Nacharbeit zu P-01
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/047_legal_documents.sql` (neu) — Tabellen `legal_documents` + `legal_document_audit`
|
||||
- `backend/routers/legal_documents.py` (neu) — Öffentliche + Superadmin-Endpoints
|
||||
- `backend/main.py` — Router-Registrierung
|
||||
- `frontend/src/pages/LegalPage.jsx` — API-Fetch mit Fallback auf statischen Platzhalter
|
||||
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` (neu) — Superadmin-UI
|
||||
- `frontend/src/App.jsx` — Route `/admin/legal-documents`
|
||||
- `frontend/src/components/AdminPageNav.jsx` — Link „Rechtstexte" im Admin-Nav
|
||||
- `frontend/src/utils/api.js` — 8 neue API-Funktionen
|
||||
|
||||
**Technische Änderung:**
|
||||
|
||||
**Datenbank (Migration 047):**
|
||||
Tabelle `legal_documents`: versionierte Rechtstexte mit Workflow `draft → published → archived`. Felder: `document_type` (impressum | privacy_policy | terms_of_use | media_policy), `version` (INT, auto-inkrementiert), `title`, `content_sections` (JSONB: `[{heading, content}]`), `status`, `change_note`, Timestamps, FK auf Ersteller + Publisher. Partial-Unique-Index: nur ein `published`-Datensatz pro `document_type` gleichzeitig. Tabelle `legal_document_audit`: unveränderlicher Änderungslog je Dokument.
|
||||
|
||||
**Backend-Endpoints:**
|
||||
|
||||
| Endpoint | Auth | Beschreibung |
|
||||
|----------|------|--------------|
|
||||
| `GET /api/legal-documents/{type}/published` | Kein | Liefert veröffentlichtes Dokument oder `null` |
|
||||
| `GET /api/admin/legal-documents` | Superadmin | Alle Versionen aller Typen |
|
||||
| `POST /api/admin/legal-documents` | Superadmin | Neuen Entwurf anlegen |
|
||||
| `GET /api/admin/legal-documents/{id}` | Superadmin | Einzeldokument mit `content_sections` |
|
||||
| `PUT /api/admin/legal-documents/{id}` | Superadmin | Entwurf bearbeiten (nur `status=draft`) |
|
||||
| `POST /api/admin/legal-documents/{id}/publish` | Superadmin | Veröffentlichen; bisherige Version → `archived` |
|
||||
| `POST /api/admin/legal-documents/{id}/archive` | Superadmin | Archivieren |
|
||||
| `GET /api/admin/legal-documents/{id}/audit` | Superadmin | Änderungslog |
|
||||
|
||||
**Frontend:**
|
||||
`LegalPage.jsx` ruft beim Laden `GET /api/legal-documents/{type}/published` ab. Gibt die API `null` zurück (kein veröffentlichtes Dokument vorhanden), zeigt die Seite weiterhin den bisherigen Platzhalter mit MUSTER-Banner. Ist ein Dokument veröffentlicht, wird dessen Inhalt ohne Platzhalter-Banner angezeigt. `AdminLegalDocumentsPage.jsx` unter `/admin/legal-documents` (nur Superadmin) ermöglicht Erstellen, Bearbeiten, Veröffentlichen und Archivieren von Entwürfen mit Tabs pro Dokumententyp und Änderungslog.
|
||||
|
||||
**Kein neues npm-Paket notwendig** — JSONB-Struktur mit `{heading, content}` statt Markdown; keine XSS-Gefahr.
|
||||
|
||||
**Tests:** 3 Playwright-Tests:
|
||||
- Rechtstextseiten laden ohne Fehler (API-fetch mit Fallback)
|
||||
- `/admin/legal-documents` erreichbar für Superadmin mit korrekter Überschrift
|
||||
- Admin-Nav enthält Link zu Rechtstexten
|
||||
|
||||
---
|
||||
|
||||
### P-01c Erweiterung — Als-Entwurf-kopieren ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10, Version 0.8.72) — Ergänzung zu P-01c
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/routers/legal_documents.py` — Neuer Endpoint `POST /api/admin/legal-documents/{id}/copy-as-draft`
|
||||
- `frontend/src/utils/api.js` — `copyLegalDocumentAsDraft(id)`
|
||||
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` — „Als Entwurf kopieren"-Button in der Dokumentliste
|
||||
|
||||
**Technische Änderung:**
|
||||
Neuer Superadmin-Endpoint kopiert `title` und `content_sections` eines bestehenden Dokuments in einen neuen Entwurf. Die Versionsnummer wird dabei automatisch inkrementiert (letztes Dokument dieses Typs + 1). Status ist immer `draft`. Ermöglicht inkrementelle Überarbeitung ohne vollständige Neueingabe.
|
||||
|
||||
**Motivation:** Bei jeder fälligen Textanpassung mussten alle Abschnitte neu erfasst werden. Die Kopierfunktion ermöglicht, den letzten Stand zu übernehmen und nur die geänderten Abschnitte zu bearbeiten.
|
||||
|
||||
---
|
||||
|
||||
### P-01c Erweiterung — Echter PDF-Download + Abschnitts-Sortierung ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10, Version 0.8.74) — Ergänzung zu P-01c
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` — `generateLegalPdf()` via jsPDF, `SectionEditor` mit Sortierung
|
||||
- `frontend/src/pages/LegalPage.jsx` — `generateLegalPdf()` via jsPDF, Button „PDF herunterladen"
|
||||
- `frontend/package.json` — neues npm-Paket `jspdf`
|
||||
|
||||
**Technische Änderung — PDF:**
|
||||
Ersetzt die bisherige `window.open()` + `window.print()`-Lösung (Browser-Druckdialog) durch `jsPDF`. Die Funktion `generateLegalPdf(doc)` erzeugt ein A4-PDF client-seitig mit:
|
||||
- Titel (bold, 20 pt), Metazeile (Version + Gültigkeitsdatum), Trennlinie
|
||||
- Abschnitte mit Heading (bold, 11 pt) und Fließtext (10 pt, `splitTextToSize` für automatischen Zeilenumbruch)
|
||||
- Automatischer Seitenumbruch bei `y > 277 mm`
|
||||
- Footer auf jeder Seite: „Shinkan Jinkendo | Exportiert am DD.MM.YYYY Seite X von Y"
|
||||
- Direkter Dateidownload via `pdf.save('{document_type}_v{version}.pdf')`
|
||||
|
||||
Gilt sowohl für die Admin-Seite (Download aus der Dokumentliste, ruft `getLegalDocument(id)` für Volldokument ab) als auch für `LegalPage.jsx` (öffentlich, nur bei veröffentlichten Dokumenten).
|
||||
|
||||
**Technische Änderung — Abschnitts-Sortierung und Einfügen:**
|
||||
`SectionEditor` in `AdminLegalDocumentsPage.jsx` erhält:
|
||||
- ▲/▼-Buttons pro Abschnitt (deaktiviert an den Rändern) — Reihenfolge per Array-Swap
|
||||
- `InsertButton` zwischen jedem Abschnitt (inkl. vor dem ersten) — fügt leeren Abschnitt an beliebiger Stelle per `splice` ein
|
||||
- Kein Drag-and-Drop-Framework — reine React-State-Manipulation
|
||||
|
||||
---
|
||||
|
||||
### P-03 – Papierkorb-Retention-Job aktivieren ✅
|
||||
|
||||
**Status:** Umgesetzt
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `docker-compose.yml` – neuer Service `retention-cron`
|
||||
|
||||
**Technische Änderung:**
|
||||
Neuer Docker-Service `retention-cron` nutzt dasselbe Backend-Image und führt `scripts/media_retention_job.py` täglich um 03:00 Uhr aus. Der Service startet beim ersten Hochfahren sofort und schläft bis zum nächsten 3 AM (Python-basierter Loop ohne externe Cron-Abhängigkeit). Zugriff auf DB und Media-Volume identisch zur Backend-Konfiguration.
|
||||
|
||||
**Tests:** Keine automatisierten Tests möglich (Runtime-Verhalten); operativ über Container-Logs (`docker logs shinkan-retention-cron`) überprüfbar.
|
||||
|
||||
---
|
||||
|
||||
### P-03b – Retention-Zeiten mit Löschkonzept abgleichen ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/media_lifecycle.py:24` – Default `HIDDEN_TO_PURGE_DAYS`
|
||||
- `docker-compose.yml` – explizite Env-Variable im `retention-cron`-Service
|
||||
|
||||
**Befund des Re-Audits:**
|
||||
Das fachliche Löschkonzept (Audit §6.4) sieht 30 + 30 Tage vor:
|
||||
- Stufe 1 → Stufe 2 (Soft → Hidden): 30 Tage ✓ (war bereits korrekt)
|
||||
- Stufe 2 → Purge (Hidden → gelöscht): **weitere 30 Tage** → Code-Default war 90 Tage ❌
|
||||
|
||||
**Technische Änderung:**
|
||||
```python
|
||||
# media_lifecycle.py Zeile 24 (vorher "90", jetzt "30"):
|
||||
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "30")))
|
||||
```
|
||||
|
||||
`docker-compose.yml` enthält jetzt explizit `MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS: "${...:-30}"` mit Kommentar, der das 30+30-Konzept dokumentiert. Der Wert kann per Env-Variable in einzelnen Deployments überschrieben werden.
|
||||
|
||||
---
|
||||
|
||||
### P-04 – Copyright-Pflicht bei Archiv-Promotion vereinheitlichen ✅
|
||||
|
||||
**Status:** Umgesetzt; Tests nachgehärtet (2026-05-10)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/routers/media_assets.py` – `patch_media_asset()` und `bulk_media_patch()`
|
||||
- `backend/tests/test_media_assets_copyright_promotion.py`
|
||||
|
||||
**Technische Änderung:**
|
||||
Beide Endpoints prüfen, ob `copyright_notice` vorhanden ist, wenn `visibility` auf `club` oder `official` gewechselt wird. Priorität: Wert aus dem Request-Body > bestehender Wert in der DB. Ist beides leer, wird HTTP 400 zurückgegeben.
|
||||
|
||||
Fehlermeldung: `"Für Vereins- oder offizielle Medien ist eine Urheberrechtsangabe (copyright_notice) Pflicht."` (Umlaut korrekt, 2026-05-10 korrigiert)
|
||||
|
||||
**Tests:** 7 Tests, alle grün:
|
||||
- Promotion zu `club` ohne Copyright → **400** (exakt)
|
||||
- Promotion zu `official` ohne Copyright → **400** (exakt)
|
||||
- Promotion zu `club` mit Copyright im Body → **200** + Payload-Prüfung (gehärtet)
|
||||
- Promotion zu `club`, Copyright bereits auf Asset → **200** + Payload-Prüfung (gehärtet)
|
||||
- Kein Visibility-Wechsel → keine Copyright-Prüfung → **200** (exakt)
|
||||
- Bulk: ohne Copyright → in `failed`, `updated_count == 0` (exakt)
|
||||
- Bulk: mit Copyright → in `updated`, `updated_count == 1` (exakt)
|
||||
|
||||
---
|
||||
|
||||
### P-05 – Passwort-Mindestlänge angleichen ⚠️ (Teil 1 von 2 – Re-Audit-Auflage offen)
|
||||
|
||||
**Status:** Teilweise umgesetzt
|
||||
|
||||
**Betroffene Dateien (initialer Fix 2026-05-09):**
|
||||
- `backend/routers/auth.py:101` – `PUT /api/auth/pin`: `< 4` → `< 8`
|
||||
- `frontend/src/pages/LoginPage.jsx:175` – `minLength="6"` → `minLength="8"`
|
||||
- `frontend/src/pages/AccountSettingsPage.jsx:403` – `minLength={4}` → `minLength={8}`
|
||||
|
||||
**Verbleibende Lücke identifiziert im Re-Audit 2026-05-09:** `POST /api/auth/reset-password` hatte kein Mindestlängen-Limit → siehe P-05b.
|
||||
|
||||
---
|
||||
|
||||
### P-05b – reset-password Mindestlänge 8 Zeichen ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/models.py:29` – `PasswordResetConfirm.new_password`
|
||||
- `backend/tests/test_auth_password_reset_minlength.py` – 7 neue Tests
|
||||
|
||||
**Technische Änderung:**
|
||||
```python
|
||||
# models.py (vorher):
|
||||
class PasswordResetConfirm(BaseModel):
|
||||
token: str
|
||||
new_password: str
|
||||
|
||||
# models.py (nachher):
|
||||
class PasswordResetConfirm(BaseModel):
|
||||
token: str
|
||||
new_password: str = Field(min_length=8, max_length=128)
|
||||
```
|
||||
|
||||
FastAPI lehnt Requests mit `new_password < 8 Zeichen` nun mit HTTP **422** (Pydantic Validation Error) ab, bevor der Endpoint-Handler ausgeführt wird. Kein DB-Zugriff erfolgt für unvalide Requests.
|
||||
|
||||
**Tests:** 7 Tests, alle grün:
|
||||
- Leer-String → 422
|
||||
- 1-Zeichen-Passwort → 422
|
||||
- 7-Zeichen-Passwort (`"1234567"`) → 422
|
||||
- Exakt 8 Zeichen (`"12345678"`) → **200** ✓
|
||||
- Langes Passwort → **200** ✓
|
||||
- Fehlendes `new_password`-Feld → 422
|
||||
- Gültiges Passwort, ungültiger Token → 400
|
||||
|
||||
**P-05 vollständig geschlossen?** Ja — alle passwortverarbeitenden Backend-Endpoints erzwingen jetzt Mindestlänge 8:
|
||||
|
||||
| Endpoint | Mindestlänge | Mechanismus |
|
||||
|---|---|---|
|
||||
| `POST /api/auth/register` | 8 | `if len(password) < 8` im Handler |
|
||||
| `PUT /api/auth/pin` | 8 | `if len(new_pin) < 8` im Handler |
|
||||
| `POST /api/auth/reset-password` | 8 | Pydantic `Field(min_length=8)` |
|
||||
| Management-Reset (profiles.py) | 8 | Pydantic `Field(min_length=8)` |
|
||||
| Frontend LoginPage | 8 | `minLength="8"` |
|
||||
| Frontend AccountSettingsPage | 8 | `minLength={8}` |
|
||||
|
||||
---
|
||||
|
||||
### P-07 – ALLOW_PUBLIC_MEDIA_STATIC Release-Test ✅
|
||||
|
||||
**Status:** Umgesetzt
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/tests/test_security_release.py` – 2 neue Tests
|
||||
|
||||
**Tests:** Beide grün.
|
||||
|
||||
---
|
||||
|
||||
### P-11 – Legal-Hold Lifecycle-Status ✅
|
||||
|
||||
**Status:** Vollständig umgesetzt (2026-05-11, Version 0.8.84 + Nachfixe 0.8.85–0.8.86)
|
||||
|
||||
#### P-11 Kernumsetzung (Version 0.8.84)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/051_legal_hold.sql` – neue Spalten `legal_hold_active`, `legal_hold_reason_code`, `legal_hold_reason_note`, `legal_hold_set_by_profile_id`, `legal_hold_set_at`, `legal_hold_released_by_profile_id`, `legal_hold_released_at`, `legal_hold_release_note` in `media_assets`; Audit-Log-CHECK um `legal_hold_set`/`legal_hold_released` erweitert
|
||||
- `backend/media_legal_hold.py` – Neu: zentrale Services `set_legal_hold`, `release_legal_hold`, `assert_not_under_legal_hold`, `is_media_available_for_normal_use`, `assert_superadmin_for_legal_hold`
|
||||
- `backend/media_lifecycle.py` – `run_retention_pass()` filtert `AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)` in beiden Retention-Queries
|
||||
- `backend/routers/media_assets.py` – `admin_legal_hold_router` mit drei Endpoints; `_list_active_visibility_clause()` berücksichtigt `include_legal_hold`-Parameter; `download_media_asset_file()` prüft Legal-Hold für Nicht-Superadmins
|
||||
- `backend/routers/exercises.py` – `attach_exercise_media_from_asset()` ruft `assert_not_under_legal_hold()` vor Verknüpfung auf
|
||||
- `backend/main.py` – `app.include_router(media_assets.admin_legal_hold_router)`
|
||||
- `frontend/src/utils/api.js` – `setMediaAssetLegalHold`, `releaseMediaAssetLegalHold`, `listMediaAssetsWithLegalHold`
|
||||
- `frontend/src/pages/MediaLibraryPage.jsx` – Legal-Hold-Badge auf Kacheln; Superadmin-Aktionen „Sofort sperren"/„Sperre aufheben" im Edit-Modal; Bestätigungs-Dialog mit Pflichtfeldern; Journal-Renderpfad für `legal_hold_set`/`legal_hold_released`
|
||||
- `frontend/src/app.css` – CSS-Klassen für Legal-Hold-Badge, -Dialog, -Button
|
||||
|
||||
**Neue API-Endpoints (Superadmin):**
|
||||
- `POST /api/admin/media-assets/{asset_id}/legal-hold` — Sofortsperre setzen (reason_code + reason_note Pflicht)
|
||||
- `POST /api/admin/media-assets/{asset_id}/legal-hold/release` — Sofortsperre aufheben (release_note Pflicht)
|
||||
- `GET /api/admin/media-assets/legal-hold` — Liste aller aktuell gesperrten Assets
|
||||
|
||||
**Tests:** 15 Backend-Unit-Tests in `backend/tests/test_p11_legal_hold.py` — alle grün.
|
||||
|
||||
#### P-11 Nachfixe – UI-Bugs und Sichtbarkeitskorrektur (Version 0.8.85–0.8.86)
|
||||
|
||||
Nach Erstimplementierung wurden beim Testen weitere Mängel festgestellt und behoben:
|
||||
|
||||
**Version 0.8.85 – UI-Bugfixes:**
|
||||
- Fix: `submitLegalHold` rief `loadMedia()` statt `loadItems()` auf → "loadMedia is not a function" beim Sperren
|
||||
- Fix: Listabfrage in `list_media_assets` enthielt `legal_hold_active`, `reason_code`, `reason_note`, `set_at` nicht → Badge und „Sperre aufheben"-Button im Modal waren nie sichtbar
|
||||
- Fix: Journal-Renderpfad verwendete Keys `nw.legal_hold_reason_code/note` statt `nw.reason_code/note` (Audit-Log-Format) → Begründung und Kommentar nicht angezeigt
|
||||
- Fix: Archiv-Picker (ExerciseFormPage, ExerciseInlineFileMediaModal) filterte Legal-Hold-Assets bereits client-seitig heraus
|
||||
|
||||
**Version 0.8.86 – Vollständige Absicherung der Auslieferung:**
|
||||
|
||||
Betroffene Dateien:
|
||||
- `backend/routers/exercises.py` – `download_exercise_media_file()` gibt HTTP 451 zurück wenn `asset_legal_hold_active=TRUE` (Datei wird nicht ausgeliefert); `enrich_exercise_detail()` SELECT erweitert um `ma.legal_hold_active AS asset_legal_hold_active`
|
||||
- `backend/routers/media_assets.py` – `list_media_assets` übergibt `include_legal_hold=is_sup` statt `include_legal_hold=(is_plat or is_sup)` — Legal-Hold-Assets nur noch für Superadmin sichtbar, nicht für alle Plattform-Admins
|
||||
- `frontend/src/components/ExerciseMediaEmbed.jsx` – Zeigt „Medium nicht verfügbar (gesperrt)" statt Datei wenn `asset_legal_hold_active`
|
||||
- `frontend/src/components/ExerciseMediaThumbTile.jsx` – Zeigt rot-markierte „Gesperrt"-Kachel statt Dateivorschau; kein Preview-Trigger
|
||||
- `frontend/src/pages/ExerciseFormPage.jsx` – Vorschau-Modal zeigt Hinweis statt Datei wenn `asset_legal_hold_active`
|
||||
|
||||
#### Sicherheitsarchitektur (vollständig)
|
||||
|
||||
- Legal-Hold ist orthogonal zum normalen Papierkorb-Lifecycle (P-03) — kein 30-Tage-Warten
|
||||
- `rights_status='blocked'` wird als Schnell-Spiegel gesetzt und bei Aufhebung basierend auf vorhandenen Deklarationen wiederhergestellt (`declared` wenn Deklaration vorhanden, sonst `legacy_unreviewed`)
|
||||
- Nur Superadmin darf setzen/aufheben; nur Superadmin sieht Legal-Hold-Assets in der Medienliste; normale Nutzer sehen gesperrte Assets nicht
|
||||
- Retention-Job überspringt Legal-Hold-Assets (verhindert versehentliche Löschung unter laufender Sperrmaßnahme)
|
||||
- `assert_not_under_legal_hold()` blockiert das Verknüpfen von Legal-Hold-Assets mit Übungen
|
||||
- Dateiauslieferung (`download_exercise_media_file`) gibt HTTP 451 zurück — keine Umgehung via direkten File-Endpoint
|
||||
- Frontend-Komponenten zeigen Placeholder statt Datei, auch wenn das Asset bereits in einer Übung verknüpft ist
|
||||
|
||||
---
|
||||
|
||||
### P-12 – sessionStorage bei Logout bereinigen ✅
|
||||
|
||||
**Status:** Umgesetzt (2026-05-10, Version 0.8.68)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `frontend/src/context/AuthContext.jsx` – `logout()`
|
||||
- `tests/dev-smoke-test.spec.js` – neuer Playwright-Test
|
||||
|
||||
**Befund (war offen):**
|
||||
`logout()` löschte nur `localStorage`-Einträge. `TrainingCoachPage` schrieb sessionStorage-Schlüssel mit Präfix `sj_coach_` (`sj_coach_step_{unitId}`, `sj_coach_deltas_{unitId}`, `sj_coach_debrief_{unitId}`), die nach Logout im Tab erhalten blieben. Bei Nutzerwechsel im selben Tab (geteilter Rechner) konnte der neue Nutzer Trainingsfortschritt des Vorgängers sehen.
|
||||
|
||||
**Technische Änderung:**
|
||||
Gezielte Präfix-Löschung aller `sj_coach_*`-Schlüssel beim Logout (kein `sessionStorage.clear()`). Fremde sessionStorage-Schlüssel (Browser-Extensions o. ä.) bleiben erhalten.
|
||||
|
||||
```javascript
|
||||
// AuthContext.jsx logout() — Ergänzung:
|
||||
for (const key of Object.keys(sessionStorage)) {
|
||||
if (key.startsWith('sj_coach_')) {
|
||||
sessionStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Begründung gezielte statt vollständiger Löschung:**
|
||||
Alle Shinkan-spezifischen sessionStorage-Schlüssel sind eindeutig über den Präfix `sj_coach_` identifizierbar (definiert in `TrainingCoachPage.jsx` Zeilen 15–25). Ein `sessionStorage.clear()` würde auch Schlüssel fremder Quellen im selben Tab löschen; die Präfix-Löschung ist spezifischer und sicherer.
|
||||
|
||||
**Tests:** Playwright E2E-Test `tests/dev-smoke-test.spec.js` (Test „P-12: sessionStorage wird bei Logout bereinigt"):
|
||||
- Setzt drei `sj_coach_*`-Schlüssel und einen fremden Schlüssel
|
||||
- Klickt „Abmelden"
|
||||
- Prüft: `sj_coach_*` → null (entfernt), fremder Schlüssel → erhalten, `authToken` → null (localStorage weiterhin korrekt bereinigt)
|
||||
|
||||
**Hinweis Tests:** Das Projekt verfügt über kein Frontend-Unit-Test-Framework (kein Vitest/Jest in package.json). Der Test ist als Playwright E2E-Test implementiert, der einen laufenden Dev-Server voraussetzt. Automatisierte Ausführung der Playwright-Tests erfordert `npx playwright test` mit gesetzter `PLAYWRIGHT_BASE_URL`.
|
||||
|
||||
---
|
||||
|
||||
### P-23 – LoginPage: minLength + Versionsstring ✅
|
||||
|
||||
**Status:** Umgesetzt
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `frontend/src/pages/LoginPage.jsx`
|
||||
|
||||
**Technische Änderung:**
|
||||
- `minLength="6"` → `minLength="8"`
|
||||
- Hardcodierter Versionsstring `v0.1.0 • Development` entfernt
|
||||
|
||||
---
|
||||
|
||||
### P-24 – CORS allow_methods und allow_headers einschränken ✅
|
||||
|
||||
**Status:** Umgesetzt
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/main.py:85-86`
|
||||
|
||||
**Technische Änderung:**
|
||||
```python
|
||||
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
||||
allow_headers=["Content-Type", "X-Auth-Token", "X-Active-Club-Id"],
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Test-Zusammenfassung (Stand 0.8.94)
|
||||
|
||||
```
|
||||
tests/test_auth_password_reset_minlength.py 7 passed (neu, P-05b)
|
||||
tests/test_media_assets_copyright_promotion.py 7 passed (gehärtet, P-04)
|
||||
tests/test_media_rights_declaration.py 25 passed (neu, P-06a–P-06d)
|
||||
tests/test_security_release.py 9 passed (inkl. 2 P-07-Tests)
|
||||
tests/test_p11_legal_hold.py 15 passed (neu, P-11)
|
||||
tests/test_p13_content_reports.py 15 passed (neu, P-13; CI-Fix 0.8.94)
|
||||
Weitere bestehende Tests: 81 passed, 6 skipped
|
||||
Gesamt (Backend): 159 passed, 6 skipped, 1 failed
|
||||
|
||||
Fehlgeschlagener Test: test_list_media_assets_invalid_lifecycle_400
|
||||
→ Pre-existing: benötigt laufenden PostgreSQL-Container (Hostname "postgres")
|
||||
→ Bestand bereits vor allen Compliance-Änderungen (verifiziert per git stash)
|
||||
|
||||
Playwright E2E (dev-smoke-test.spec.js): 22+ passed (inkl. P-06-Tests)
|
||||
→ P-01: 4× Route ohne Auth + Platzhalterhinweis + Reload, 1× Login-Links
|
||||
→ P-01b: 3× /settings/legal (Link in Einstellungen, Überschrift, Rechtstext-Links)
|
||||
→ P-01c: 3× Admin-Rechtstexte (Seitenladung, Route /admin/legal-documents, Admin-Nav)
|
||||
→ P-12: sessionStorage-Bereinigung (grün)
|
||||
→ P-06: 5× RightsDeclarationDialog (Anzeige, Pflichtfeld-Validierung, Upload-Flow,
|
||||
Promotions-Dialog, Legacy-Altbestand-Indikator)
|
||||
|
||||
Anmerkung jsPDF (0.8.74):
|
||||
→ PDF-Download via pdf.save() ist ein Browser-Download, kein Server-Request.
|
||||
→ Kein Backend-Test möglich; funktional im Browser verifizierbar.
|
||||
→ Playwright-E2E-Test erfordert laufenden Dev-Server (npx playwright test).
|
||||
|
||||
Anmerkung P-06+ Journal/Korrektur (0.8.82–0.8.83):
|
||||
→ Journal-Endpoint und Korrektur-Endpoint durch manuellen API-Test (curl) auf Dev-System verifiziert.
|
||||
→ Bugfix club_admin-Prüfung (has_club_role) verifiziert: 500 → 200 nach Fix.
|
||||
→ Keine dedizierte Playwright-Testsuite für Journal-Modal und Korrektur-Formular (UI-Verifikation ausstehend).
|
||||
|
||||
Anmerkung P-11 Frontend-Absicherung (0.8.85–0.8.86):
|
||||
→ UI-Fixes (loadItems, Badge-Sichtbarkeit, Journal-Keys) manuell auf Dev-System verifiziert.
|
||||
→ 15 Backend-Unit-Tests decken Services und Retention-Schutz ab.
|
||||
→ Keine Playwright-Tests für Legal-Hold-Aktionen im Modal — manuelle UI-Verifikation.
|
||||
|
||||
Anmerkung P-13 Erweiterungen (0.8.88–0.8.94):
|
||||
→ E-Mail-Benachrichtigungen, Audit-Log, Club-Admin-Rechte, Workflow manuell auf Dev-System verifiziert.
|
||||
→ CI-Fix (0.8.94): 3 pytest-Tests angepasst (frühzeitige 403, vollständige Mock-Zeile, DB-Mock für COUNT).
|
||||
→ Alle 15 pytest-Tests grün nach CI-Fix.
|
||||
→ Keine Playwright-Tests für InboxPage Meldungs-Workflow — manuelle UI-Verifikation.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### P-06 – Upload-Einwilligungsdialog ⚠️ (technisch vollständig umgesetzt inkl. P-06+; juristische Validierung offen)
|
||||
|
||||
**Status:** Technisch vollständig umgesetzt (inkl. P-06+ Volljournal + Korrektur, Version 0.8.83) — KRIT-04 bleibt offen.
|
||||
|
||||
**Deklarationsversion:** `p06-v1-conservative`
|
||||
|
||||
---
|
||||
|
||||
#### P-06a–P-06d — Kernumsetzung (Version 0.8.75)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/048_media_rights_declarations.sql` (neu) — Append-only Deklarations-Log + 3 Schnellfelder in `media_assets` (`rights_status`, `rights_declared_for_visibility`, `rights_declared_at`)
|
||||
- `backend/migrations/049_media_rights_consent_context.sql` (neu) — Kontext-Freitextfelder in `media_asset_rights_declarations` (`person_consent_context`, `parental_consent_context`, `music_rights_context`, `third_party_rights_context`)
|
||||
- `backend/media_rights.py` (neu) — Zentrales Policy-Modul: `validate_rights_declaration`, `check_rights_coverage`, `assert_rights_for_promotion`, `assert_rights_for_exercise_link`, `write_rights_declaration`, `update_rights_quick_fields`
|
||||
- `backend/routers/media_assets.py` — P-06-Enforcement in Bulk-Upload, PATCH, Bulk-PATCH; 3 neue Endpoints
|
||||
- `backend/routers/exercises.py` — P-06 bei `upload_exercise_media` (neue Assets) und `attach_exercise_media_from_asset`
|
||||
- `frontend/src/components/RightsDeclarationDialog.jsx` (neu) — Einwilligungsdialog (9 Pflichtfelder + Kontext-Freitexte)
|
||||
- `frontend/src/pages/MediaLibraryPage.jsx` — Dialog-Integration vor Bulk-Upload; Altbestand-Indikator
|
||||
- `frontend/src/pages/ExerciseInlineFileMediaModal.jsx` + `ExerciseInlineEmbedModal.jsx` — RightsDeclarationDialog vor Upload
|
||||
- `frontend/src/utils/api.js` — `bulkUploadMediaAssets` erweitert um P-06-Felder
|
||||
- `backend/tests/test_media_rights_declaration.py` (neu) — 25 Unit/HTTP-Tests
|
||||
|
||||
**Neue Endpoints (P-06b):**
|
||||
|
||||
| Endpoint | Beschreibung |
|
||||
|----------|-------------|
|
||||
| `POST /api/media-assets/{id}/rights-declarations` | Explizite Re-/Nachdeklaration |
|
||||
| `GET /api/admin/media-rights/legacy-summary` | Zusammenfassung Altbestand nach Sichtbarkeit (Plattform-Admin) |
|
||||
| `GET /api/admin/media-rights/legacy-assets` | Paginierte Liste Altbestand club/official (Plattform-Admin) |
|
||||
|
||||
**Abweichung von Spec §3 (konservative Erstannahme):**
|
||||
Person-Fragen sind auch bei Sichtbarkeit `private` Pflicht (§10.1 in `docs/p06-upload-rights-spec.md`).
|
||||
|
||||
**Altbestand (Legacy):**
|
||||
Alle vor Migration 048 hochgeladenen Medien erhalten `rights_status = 'legacy_unreviewed'`.
|
||||
Promotion blockiert bis Nachdeklaration. In Bibliotheks-UI als „Altbestand ⚠" markiert.
|
||||
|
||||
---
|
||||
|
||||
#### P-06+ — Volljournal + Korrektur (Version 0.8.82–0.8.83)
|
||||
|
||||
**Motivation:** Vollständige Nachvollziehbarkeit aller Medien-Ereignisse, nicht nur der Deklarationen. Plus: Möglichkeit, fehlerhafte Deklarationen mit Begründung nachträglich zu korrigieren (append-only — neueste gilt).
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/050_media_audit_log.sql` (neu) — Neue Tabelle `media_asset_audit_log` + `correction_note TEXT` in Deklarations-Tabelle + erweiterter CHECK (action_type += 'correction')
|
||||
- `backend/media_rights.py` — Neue Funktionen: `write_audit_log_entry()`, `write_rights_correction_declaration()`
|
||||
- `backend/routers/media_assets.py` — Neues Pydantic-Model `RightsCorrectionBody`; PATCH-Endpoint schreibt Audit-Log-Einträge; Lifecycle-Aktionen schreiben `lifecycle_change`-Einträge; 2 neue Endpoints; Import `has_club_role` ergänzt
|
||||
- `frontend/src/pages/MediaLibraryPage.jsx` — Journal-Modal komplett überarbeitet: unified `events[]`-Ansicht; Korrektur-Formular inline; Helper-Funktionen `actionTypeLabel`, `eventTypeLabel`, `visLabel`
|
||||
- `frontend/src/utils/api.js` — Neue Funktion `addMediaAssetDeclarationCorrection(assetId, body)`
|
||||
- `frontend/src/app.css` — CSS für Audit-Einträge (`--audit`), Korrektur-Einträge (`--correction`), Korrektur-Formular
|
||||
|
||||
**Neue Endpoints (P-06+):**
|
||||
|
||||
| Endpoint | Auth | Beschreibung |
|
||||
|----------|------|-------------|
|
||||
| `GET /api/admin/media-rights/assets/{id}/journal` | Superadmin / Uploader / Vereins-Admin | Volljournal: `events[]` aus Deklarationen + Audit chronologisch gemischt. Gibt `can_correct` zurück. |
|
||||
| `POST /api/admin/media-rights/assets/{id}/correction` | Superadmin / Uploader / Vereins-Admin | Korrektur-Deklaration (append-only, neueste gilt). Felder = P-06-Dialog + `correction_note`. |
|
||||
|
||||
**Automatische Audit-Log-Einträge:**
|
||||
|
||||
| event_type | Auslöser |
|
||||
|-----------|----------|
|
||||
| `visibility_change` | PATCH wenn `visibility` oder `club_id` sich ändert |
|
||||
| `copyright_change` | PATCH wenn `copyright_notice` sich ändert |
|
||||
| `metadata_change` | PATCH wenn `original_filename` etc. sich ändert |
|
||||
| `lifecycle_change` | Lifecycle-Aktionen: trash_soft, trash_hidden, recover, reactivate (nicht bei Hard-Delete/Purge) |
|
||||
|
||||
**Bugfixes in P-06+:**
|
||||
|
||||
| Bug | Fix |
|
||||
|-----|-----|
|
||||
| Journal + Korrektur gaben 500 (falsches Schema club_admin) | `has_club_role(cur, profile_id, club_id, "club_admin")` statt `AND role = 'admin'` in `club_members` |
|
||||
| Frontend-Build-Fehler: doppelte `lcLabel`-Deklaration | Duplikat in Zeile 264 von `MediaLibraryPage.jsx` entfernt |
|
||||
|
||||
**KRIT-04 Status:**
|
||||
Offen. Juristische Validierung der Feldtexte (§10.3 p06-v1-conservative, T1–T10), KUG/DSGVO-Anforderungen (§7.1–§7.12 der Spec) und Korrekturfähigkeit (Spec §11.9) steht aus.
|
||||
Referenz: `docs/p06-upload-rights-spec.md` §10.5, §11.9.
|
||||
|
||||
---
|
||||
|
||||
### P-13 – Content-Melde-Backend ✅
|
||||
|
||||
**Status:** Vollständig umgesetzt (2026-05-11, Version 0.8.87–0.8.94)
|
||||
**Finding:** KRIT-03
|
||||
|
||||
**Architekturentscheidung:** Anstelle einer separaten Moderations-Queue wurde die bestehende Admin-Inbox (`InboxPage.jsx`) um einen zweiten Abschnitt erweitert. Keine generische `inbox_items`-Tabelle, keine separate `/api/admin/reports`-Queue.
|
||||
|
||||
#### P-13 Kernumsetzung (Version 0.8.87)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/052_content_reports.sql` (neu) — Tabelle `content_reports` mit Status-Workflow, Priorisierung, 3 Indizes
|
||||
- `backend/routers/content_reports.py` (neu) — alle Endpoints, Reason-Code-Mapping, Priorisierung
|
||||
- `backend/tests/test_p13_content_reports.py` (neu) — 15 Unit-Tests
|
||||
- `backend/main.py` — Router-Registrierung
|
||||
- `frontend/src/utils/api.js` — 5 neue API-Funktionen (submitContentReport, getInboxContentReports, getContentReport, patchContentReport, setLegalHoldFromReport)
|
||||
- `frontend/src/context/OrgInboxContext.jsx` — contentReports-State, contentReportCount, canAccessContentReports, isSuperadmin
|
||||
- `frontend/src/pages/InboxPage.jsx` — zweiter Abschnitt „Inhaltsmeldungen", ReportDetailModal
|
||||
- `frontend/src/components/ReportContentModal.jsx` (neu) — Meldungsformular
|
||||
- `frontend/src/components/MediaPreviewModal.jsx` (neu) — geteilter Vorschau-Dialog
|
||||
|
||||
**API-Endpoints (Kernumsetzung):**
|
||||
|
||||
| Endpoint | Auth | Beschreibung |
|
||||
|----------|------|--------------|
|
||||
| `POST /api/content-reports` | Optional | Meldung einreichen (official-Medien ohne Login; eingeloggt: alle sichtbaren Medien) |
|
||||
| `GET /api/me/inbox/content-reports` | Plattform-Admin | Liste aller Meldungen, JOIN auf Zieltabellen |
|
||||
| `GET /api/content-reports/{id}` | Plattform-Admin | Einzel-Detail |
|
||||
| `PATCH /api/content-reports/{id}` | Plattform-Admin | Status/Notiz/Zuweisung; resolution_note Pflicht für Abschluss-Status |
|
||||
| `POST /api/content-reports/{id}/legal-hold` | Superadmin | Legal Hold via P-11 `set_legal_hold()`; setzt Status auf `resolved_legal_hold` |
|
||||
|
||||
**Reason-Code-Mapping (P-13 → P-11):**
|
||||
|
||||
| Meldegrund | Legal-Hold reason_code |
|
||||
|------------|------------------------|
|
||||
| copyright | copyright_complaint |
|
||||
| image_rights | rights_dispute |
|
||||
| privacy | privacy_complaint |
|
||||
| minors | youth_protection |
|
||||
| illegal_content | illegal_content |
|
||||
| youth_protection | youth_protection |
|
||||
| offensive_content | illegal_content |
|
||||
| other | other |
|
||||
|
||||
---
|
||||
|
||||
#### P-13 Erweiterungen — Audit-Log, E-Mail, Workflow, Club-Admin (Version 0.8.88–0.8.94)
|
||||
|
||||
**Betroffene Dateien:**
|
||||
- `backend/migrations/053_content_report_audit_event.sql` (neu) — `content_report_filed` Event-Typ dem `media_asset_audit_log` CHECK-Constraint hinzugefügt (alle 7 gültigen Event-Typen)
|
||||
- `backend/routers/content_reports.py` — stark erweitert: E-Mail-Benachrichtigungen, Audit-Log, deutsche Labels, Club-Admin-Berechtigungen, Workflow-Verbesserungen, frühzeitige 403-Prüfung
|
||||
- `backend/routers/media_assets.py` — `open_report_count` Batch-Query für Admin-Nutzer in `list_media_assets`
|
||||
- `frontend/src/pages/InboxPage.jsx` — vollständig überarbeitetes `ReportDetailModal` mit Workflow-Bar, Archiv-Trennung
|
||||
- `frontend/src/pages/MediaLibraryPage.jsx` — Badge auf Medienkarten, Journal-Eintrag für `content_report_filed`
|
||||
- `frontend/src/components/ReportContentModal.jsx` — `onSuccess` Callback, readOnly-Felder für eingeloggte Nutzer
|
||||
- `frontend/src/context/OrgInboxContext.jsx` — `contentReportsError`, `isClubAdmin`, `isPlatformAdmin` exponiert
|
||||
|
||||
**Backend-Erweiterungen:**
|
||||
|
||||
- **E-Mail-Benachrichtigungen** (best-effort, nach Commit): Bestätigung an Melder + Benachrichtigung aller Plattform-Admins nach Eingang einer Meldung; `original_filename` oder `exercises.title` als Medienbezeichnung im E-Mail-Betreff
|
||||
- **Audit-Log-Integration**: Bei `target_type='media_asset'` Eintrag `content_report_filed` in `media_asset_audit_log`; bei Statuswechseln und reinen Notizänderungen via PATCH ebenfalls; deutsche Labels via `REASON_LABELS_DE` / `STATUS_LABELS_DE`
|
||||
- **Club-Admin-Berechtigungen**: `GET /me/inbox/content-reports` liefert Club-Admins nur Meldungen zu Medien ihrer Vereine (COUNT-Check, 403 wenn keine Club-Admin-Rolle); `GET /content-reports/{id}` und `PATCH` via `_assert_can_manage_report()` auch für Club-Admins (nur eigene Vereinsmedien); `POST /content-reports/{id}/legal-hold` für Club-Admins auf nicht-offizielle Vereinsmedien via `_assert_can_set_legal_hold_from_report()`; Superadmin-Prüfung frühzeitig vor DB-Zugriff (plain Admin → sofort 403)
|
||||
- **Workflow-Verbesserungen in PATCH**: Wiedereröffnen einer Meldung (`status='submitted'`) setzt `reviewed_by_profile_id` und `reviewed_at` auf NULL zurück
|
||||
- **`open_report_count`** in `list_media_assets`: Für Admin-Nutzer wird je Medium die Anzahl offener Meldungen (`submitted`/`under_review`) als Batch-Query zurückgegeben
|
||||
|
||||
**Frontend-Erweiterungen:**
|
||||
|
||||
- **`WorkflowBar`** in InboxPage: 3-Schritte-Fortschrittsbalken (Eingegangen → In Bearbeitung → Abgeschlossen) mit visueller Hervorhebung des aktuellen Schritts
|
||||
- **`ReportDetailModal`** überarbeitet: zeigt WorkflowBar, Prüferinformationen (`reviewed_by_name`, `reviewed_at`), `resolution_note` (readOnly bei abgeschlossenen Meldungen), eigener „Kommentar speichern"-Button, „Meldung wieder öffnen"-Button für abgeschlossene Meldungen
|
||||
- **Archiv-Trennung**: Offene Meldungen (`submitted`/`under_review`) im Hauptbereich; abgeschlossene/abgewiesene Meldungen in einer kollabierbaren Archiv-Sektion (Standard: zugeklappt)
|
||||
- **Legal-Hold-Button** in ReportDetailModal: sichtbar für Superadmin sowie Club-Admins (bei nicht-offiziellen Medien)
|
||||
- **Badge auf Medienkarten** in MediaLibraryPage: rotes Badge mit `open_report_count` (nur sichtbar wenn > 0); wird nach erfolgreicher Meldung via `onSuccess`-Callback sofort aktualisiert
|
||||
- **Journal-Eintrag** in MediaLibraryPage: `content_report_filed`-Ereignisse mit Meldungs-ID, Grund, Priorität, Status, Begründung
|
||||
- **`OrgInboxContext`**: `contentReportsError` (Fehlerstring oder null), `isClubAdmin` und `isPlatformAdmin` exponiert; `contentReportCount` zählt nur offene Meldungen (submitted/under_review)
|
||||
- **`ReportContentModal`**: `onSuccess`-Callback nach erfolgreichem Submit; Name und E-Mail readOnly für eingeloggte Nutzer (grauer Hintergrund)
|
||||
- **Melde-Einstieg**: `MediaPreviewModal` (geteilt) + Melden-Button in MediaLibraryPage, ExerciseFormPage und ExerciseAttachmentMediaStrip
|
||||
|
||||
**CI-Fix (Version 0.8.94):**
|
||||
3 pytest-Tests in `test_p13_content_reports.py` repariert: frühzeitige 403-Prüfung in `set_legal_hold_from_report` für plain Admin (vor DB-Zugriff); Test 10 mit korrektem DB-Mock für COUNT-Query; Test 12 mit vollständiger Mock-Zeile (`target_type`, `target_id`, `resolution_note`). Alle 15 Tests grün.
|
||||
|
||||
**Nicht in P-13-Scope:** P-14 (Moderations-UI als eigene Seite), P-15 (Uploader-Benachrichtigung per E-Mail bei Sperrung), P-16 (Beschwerdeverfahren).
|
||||
|
||||
---
|
||||
|
||||
## Nicht umgesetzte Pakete
|
||||
|
||||
> Paket-IDs und -Titel gemäß kanonischem Register `docs/compliance-package-register.md`.
|
||||
> Abweichende Beschreibungen in der Ursprungsversion dieses Abschnitts wurden am 2026-05-10 korrigiert (P-06, P-08, P-09, P-10, P-11, P-18 — Details im Konsistenzbericht des Registers).
|
||||
|
||||
| Paket | Kanonischer Titel | Status | Begründung |
|
||||
|-------|------------------|--------|------------|
|
||||
| P-01 | Rechtstexte | offen | Scope ausgeschlossen (juristischer Inhalt) |
|
||||
| P-02 | Self-Service-Kontolöschung + Datenexport | offen | Scope ausgeschlossen |
|
||||
| P-06 | Upload-Einwilligungsdialog (Recht am eigenen Bild) | **teilweise umgesetzt** | Technisch umgesetzt (2026-05-11, v0.8.75) unter vorläufigen Erstannahmen `p06-v1-conservative` — siehe §P-06 unten. KRIT-04 bleibt offen bis juristische Validierung. |
|
||||
| P-08 | HSTS / externe Proxy-Sicherheit dokumentieren | offen | Scope ausgeschlossen (außerhalb Repo — Reverse-Proxy) |
|
||||
| P-09 | Admin-Audit-Log | offen | Scope ausgeschlossen |
|
||||
| P-10 | Mindestalter-Abfrage | offen | Scope ausgeschlossen |
|
||||
| P-11 | Legal-Hold Lifecycle-Status | ✅ umgesetzt | Version 0.8.84–0.8.86 — siehe §P-11 oben |
|
||||
| P-12 | sessionStorage bei Logout bereinigen | ✅ umgesetzt | Version 0.8.68 — siehe §P-12 oben |
|
||||
| P-13 | Content-Melde-Backend | ✅ umgesetzt | Version 0.8.87 — siehe §P-13 unten |
|
||||
| P-14 | Moderations-UI | offen | Scope ausgeschlossen |
|
||||
| P-15 | Uploader-Benachrichtigung bei Sperrung | offen | Scope ausgeschlossen |
|
||||
| P-16 | Beschwerdeverfahren | offen | Scope ausgeschlossen |
|
||||
| P-17 | MFA für Superadmins (TOTP) | offen | Scope ausgeschlossen |
|
||||
| P-18 | HttpOnly-Cookie als Auth-Alternative | offen | Scope ausgeschlossen |
|
||||
| P-19 | Anti-Virus-Scan (ClamAV) | offen | Scope ausgeschlossen |
|
||||
| P-20 | VVT erstellen | offen | Scope ausgeschlossen (Betreiber-Aufgabe) |
|
||||
| P-21 | AV-Verträge abschließen | offen | Scope ausgeschlossen (Betreiber-Aufgabe) |
|
||||
| P-22 | HTML-Sanitizer für Rich-Text-Felder | offen | Scope ausgeschlossen |
|
||||
|
||||
---
|
||||
|
||||
## Re-Audit-Empfehlung
|
||||
|
||||
Operativ prüfen (Stand 0.8.94):
|
||||
|
||||
1. **P-03/P-03b**: `docker logs shinkan-retention-cron` — Job läuft täglich 03:00 Uhr; Retention-Zeiten: 30 → 30 Tage
|
||||
2. **P-04**: Manuell: PATCH privates Medium auf `official` ohne `copyright_notice` → muss 400 liefern
|
||||
3. **P-05b**: Manuell: Reset-Link mit 7-Zeichen-Passwort → muss mit Fehler abgewiesen werden
|
||||
4. **P-24**: Browser DevTools Preflight → `Access-Control-Allow-Headers: content-type, x-auth-token, x-active-club-id`
|
||||
5. **P-06**: Manuell: Upload ohne `rights_holder_confirmed` → muss 400 liefern; Journal-Endpoint für vorhandene Assets → muss 200 + `events[]` liefern; Korrektur-Endpoint → muss neue Deklaration mit `action_type='correction'` schreiben
|
||||
6. **P-06 Audit-Log**: PATCH Sichtbarkeit eines Assets → `media_asset_audit_log` muss Eintrag `visibility_change` enthalten
|
||||
7. **P-11**: Superadmin → Medium sperren → in Übung öffnen → Kachel zeigt „Gesperrt"; direkter Dateiaufruf `/exercises/{id}/media/{mid}/file` → muss HTTP 451 liefern; Plattform-Admin (kein Superadmin) → gesperrtes Medium darf in Medienliste nicht erscheinen
|
||||
8. **P-13 Grundfunktion**: Anonym → `POST /api/content-reports` für official-Medium ohne Auth → muss 200 liefern; `good_faith_confirmed=false` → muss 400 liefern; Plattform-Admin → `GET /api/me/inbox/content-reports` → Liste; Superadmin → `POST /api/content-reports/{id}/legal-hold` → setzt Legal Hold + Report-Status `resolved_legal_hold`
|
||||
9. **P-13 E-Mail**: Meldung einreichen → Melder erhält Bestätigungs-E-Mail; Plattform-Admins erhalten Benachrichtigungs-E-Mail (sofern SMTP konfiguriert)
|
||||
10. **P-13 Club-Admin**: Club-Admin → `GET /api/me/inbox/content-reports` → liefert nur Meldungen zu Medien des eigenen Vereins; Club-Admin → `PATCH /api/content-reports/{id}` für Meldung zu eigenem Vereinsmedium → muss 200 liefern
|
||||
11. **P-13 Audit-Log**: Meldung einreichen für media_asset → `media_asset_audit_log` muss Eintrag `content_report_filed` enthalten; Statuswechsel via PATCH → muss weiteren Audit-Eintrag enthalten
|
||||
12. **P-13 Badge**: Medium mit offener Meldung in Medienbibliothek → rotes Badge mit Zähler sichtbar
|
||||
13. **P-13 Workflow**: Abgeschlossene Meldungen in InboxPage im Archiv (kollabierbar); Wiedereröffnen einer Meldung → `reviewed_by_profile_id` und `reviewed_at` werden zurückgesetzt
|
||||
|
||||
Nächster vollständiger Re-Audit empfohlen nach juristischer Klärung P-06/KRIT-04 (Textfreigabe T1–T10) und nach Einpflegen der Rechtstexte P-01 durch Betreiber.
|
||||
@@ -0,0 +1,435 @@
|
||||
# Compliance-Paketregister – Shinkan Jinkendo
|
||||
|
||||
**Typ:** Kanonisches Referenzdokument
|
||||
**Erstellt:** 2026-05-10
|
||||
**Basisdokument:** `docs/compliance-audit.md` (Initial-Audit 2026-05-09, App-Version 0.8.65)
|
||||
**Letzte Aktualisierung:** 2026-05-11 (App-Version 0.8.94)
|
||||
|
||||
---
|
||||
|
||||
> **Verbindliche Regel:** Paket-IDs werden nach ihrer ersten Vergabe in `docs/compliance-audit.md` nie wieder umnummeriert oder wiederverwendet. Dieses Dokument ist der kanonische Verweis für alle Freigaben, Umsetzungsberichte und Audits. Abweichende Nummerierungen in nachgelagerten Dokumenten sind Fehler und müssen auf die kanonische ID korrigiert werden. Nacharbeiten zu einem Paket erhalten Suffixe (z. B. P-03b, P-05b), keine neue Hauptnummer.
|
||||
|
||||
---
|
||||
|
||||
## Status-Legende
|
||||
|
||||
| Symbol | Bedeutung |
|
||||
|--------|-----------|
|
||||
| ✅ implemented | Vollständig umgesetzt und getestet |
|
||||
| ⚠️ partially implemented | Teilweise umgesetzt; Nacharbeit dokumentiert |
|
||||
| ❌ open | Nicht umgesetzt, offen |
|
||||
| 🔒 scope excluded | Bewusst außerhalb des technischen Umsetzungsscopes |
|
||||
|
||||
---
|
||||
|
||||
## Etappe 1 – Pflicht vor öffentlichem Betrieb
|
||||
|
||||
### P-01 – Rechtstexte
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Rechtstexte (Impressum, Datenschutzerklärung, AGB, Medienrichtlinie) |
|
||||
| **Findings** | KRIT-01 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ⚠️ partially implemented |
|
||||
| **Letzter Stand** | Technischer Teil vollständig umgesetzt (2026-05-10, Version 0.8.74, inkl. P-01b + P-01c + Erweiterungen): Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`, `/medienrichtlinie` öffentlich erreichbar ohne Auth. Platzhalterseiten mit strukturierten Pflichtfeldern und sichtbarem Muster-Hinweis. Links in LoginPage, DesktopSidebar und `/settings/legal` (Mobile/PWA, P-01b, 0.8.70). Admin-konfigurierbare Rechtstexte mit Versionierung + Publish/Archive-Workflow (DB 047, Superadmin-UI `/admin/legal-documents`, P-01c, 0.8.71). Als-Entwurf-kopieren: `POST /api/admin/legal-documents/{id}/copy-as-draft` (0.8.72). Echter PDF-Download via jsPDF (direkter Dateidownload, A4, Seitenumbruch, Footer), Abschnitte sortieren (▲/▼) und an beliebiger Stelle einfügen (0.8.74). **Juristisch geprüfte Inhalte fehlen noch — Betreiber + Rechtsanwalt erforderlich. KRIT-01 bleibt offen bis zur Veröffentlichung echter Texte.** |
|
||||
| **Verweise** | `docs/compliance-audit.md` §14.2, §17, §19.1; `docs/compliance-implementation.md` §P-01, §P-01b, §P-01c; `frontend/src/pages/LegalPage.jsx`; `frontend/src/pages/SettingsLegalPage.jsx`; `frontend/src/pages/AdminLegalDocumentsPage.jsx`; `backend/routers/legal_documents.py`; `backend/migrations/047_legal_documents.sql` |
|
||||
| **Hinweise** | P-01b (Mobile-Erreichbarkeit, 0.8.70) und P-01c (Admin-konfigurierbar, 0.8.71) als Suffix-Pakete ergänzt und vollständig umgesetzt. Erweiterungen: copy-as-draft (0.8.72), jsPDF + Abschnitts-Sortierung/-Einfügen (0.8.74). Keine Nummerierungsabweichung. |
|
||||
|
||||
---
|
||||
|
||||
### P-02 – Self-Service-Kontolöschung + Datenexport
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Self-Service-Kontolöschung und Datenexport (DSGVO Art. 17, 15, 20) |
|
||||
| **Findings** | KRIT-02, KRIT-05 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. `DELETE /api/profiles/{pid}` nur für Plattform-Admin. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §7.3, §11.2, §17 |
|
||||
| **Hinweise** | In `docs/compliance-implementation.md` als „Self-Service-Löschworkflow" bezeichnet — inhaltlich korrekt, Titel leicht abgekürzt. |
|
||||
|
||||
---
|
||||
|
||||
### P-03 – Papierkorb-Retention-Job aktivieren
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Papierkorb-Retention-Job aktivieren (automatische tägliche Ausführung) |
|
||||
| **Findings** | KRIT-07 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt in Version 0.8.66. Neuer Docker-Service `retention-cron` in `docker-compose.yml`. Python-basierter Loop, täglich 03:00 Uhr. |
|
||||
| **Nacharbeit** | P-03b (Retention-Zeiten mit Löschkonzept abgleichen) — siehe unten |
|
||||
| **Verweise** | `docs/compliance-audit.md` §9.2, §17; `docs/compliance-implementation.md` §P-03 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
#### P-03b – Nacharbeit: Retention-Zeiten mit Löschkonzept abgleichen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Typ** | Nacharbeit zu P-03 (kein eigenes Hauptpaket) |
|
||||
| **Status** | ✅ implemented (2026-05-10, Version 0.8.67) |
|
||||
| **Befund** | Default `HIDDEN_TO_PURGE_DAYS` war 90 Tage; fachliches Löschkonzept sieht 30+30 vor. |
|
||||
| **Änderung** | `backend/media_lifecycle.py`: Default `"90"` → `"30"`; `docker-compose.yml`: Env-Variable dokumentiert. |
|
||||
| **Verweise** | `docs/compliance-implementation.md` §P-03b |
|
||||
|
||||
---
|
||||
|
||||
### P-04 – Copyright-Pflicht für Archiv-Promotion vereinheitlichen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Copyright-Pflicht bei Archiv-Promotion vereinheitlichen |
|
||||
| **Findings** | KRIT-06 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `patch_media_asset()` und `bulk_media_patch()` erzwingen `copyright_notice` bei Promotion auf `club`/`official`. 7 Tests, alle grün. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §6.3, §8.1, §17; `docs/compliance-implementation.md` §P-04; `backend/tests/test_media_assets_copyright_promotion.py` |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-05 – Passwort-Mindestlänge angleichen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Passwort-Mindestlänge angleichen (alle Endpoints: mindestens 8 Zeichen) |
|
||||
| **Findings** | MITT-01, SEC-04, SEC-12, NIED-06 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ✅ implemented (vollständig, inkl. P-05b) |
|
||||
| **Letzter Stand** | Version 0.8.66: `PUT /api/auth/pin`, `LoginPage.jsx`, `AccountSettingsPage.jsx`. Version 0.8.67: `POST /api/auth/reset-password` via P-05b. Alle 6 Punkte geschlossen. |
|
||||
| **Nacharbeit** | P-05b (`reset-password` Mindestlänge) — siehe unten |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-04, SEC-12), §16 (MITT-01); `docs/compliance-implementation.md` §P-05, §P-05b |
|
||||
| **Hinweise** | P-05 gilt als vollständig geschlossen nach Abschluss von P-05b (2026-05-10). |
|
||||
|
||||
#### P-05b – Nacharbeit: reset-password Mindestlänge
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Typ** | Nacharbeit zu P-05 (kein eigenes Hauptpaket) |
|
||||
| **Status** | ✅ implemented (2026-05-10, Version 0.8.67) |
|
||||
| **Befund** | `POST /api/auth/reset-password` hatte kein Mindestlängen-Limit im Backend. |
|
||||
| **Änderung** | `backend/models.py`: `PasswordResetConfirm.new_password = Field(min_length=8, max_length=128)`. 7 neue Tests. |
|
||||
| **Verweise** | `docs/compliance-implementation.md` §P-05b; `backend/tests/test_auth_password_reset_minlength.py` |
|
||||
|
||||
---
|
||||
|
||||
### P-06 – Upload-Einwilligungsdialog
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Upload-Einwilligungsdialog (Recht am eigenen Bild, Personen, Minderjährige) |
|
||||
| **Findings** | KRIT-04 |
|
||||
| **Etappe** | 1 |
|
||||
| **Status** | ⚠️ teilweise umgesetzt (KRIT-04 offen) |
|
||||
| **Letzter Stand** | **Vollständig technisch umgesetzt inkl. P-06+ (2026-05-11, v0.8.83)** unter vorläufigen Erstannahmen `p06-v1-conservative`. **Kernumsetzung (v0.8.75):** Migration 048 (`media_asset_rights_declarations` + 3 Schnellfelder in `media_assets`); Migration 049 (Kontext-Felder); `backend/media_rights.py`; Enforcement in Bulk-Upload, PATCH, Bulk-PATCH, exercises.py; `RightsDeclarationDialog.jsx`; Altbestand-Indikator; 3 neue Admin-Endpoints. **P-06+ Volljournal + Korrektur (v0.8.82–0.8.83):** Migration 050 (`media_asset_audit_log` + `correction_note` in Deklarations-Tabelle); automatische Audit-Log-Einträge bei Sichtbarkeits-, Copyright-, Metadaten- und Lifecycle-Änderungen; neuer Journal-Endpoint `GET /api/admin/media-rights/assets/{id}/journal` (chronologisch gemischte events[] aus Deklarationen + Audit); neuer Korrektur-Endpoint `POST /api/admin/media-rights/assets/{id}/correction`; Zugriff für Superadmin + Uploader + Vereins-Admin; Korrektur-Formular im Journal-Modal. Juristische Klärungspunkte (§22 KUG, §8 DSGVO, Widerrufsrecht etc.) offen — KRIT-04 bleibt. Details: `docs/p06-upload-rights-spec.md` §10, §11; `docs/compliance-implementation.md` §P-06. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §8.2, §8.3, §11.4, §17; `docs/p06-upload-rights-spec.md`; `docs/compliance-implementation.md` §P-06; `backend/media_rights.py`; `backend/migrations/048_media_rights_declarations.sql`; `backend/migrations/050_media_audit_log.sql` |
|
||||
| **Hinweise** | **Drift-Hinweis (2026-05-10):** In `docs/compliance-implementation.md` (vor Korrektur) wurde P-06 fälschlich als „HSTS-Header" beschrieben. Korrigiert. **P-06+ (2026-05-11, v0.8.82–0.8.83):** Volljournal + Korrektur als notwendige Erweiterung nach Ersterstellung implementiert. Bugfix: Club-Admin-Prüfung im Journal/Korrektur-Endpoint nutzte falsches Schema (`role`-Spalte auf `club_members` existiert nicht) — korrigiert auf `has_club_role()`. |
|
||||
|
||||
---
|
||||
|
||||
## Etappe 2 – Sicherheit und Datenschutz
|
||||
|
||||
### P-07 – ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren und Release-Test einrichten |
|
||||
| **Findings** | HOCH-01, SEC-05 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt in Version 0.8.66. 2 Tests in `test_security_release.py`: Flag deaktiviert per Default; Flag aktiviert mounted `/media`. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.5, §17; `docs/compliance-implementation.md` §P-07; `backend/tests/test_security_release.py` |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-08 – HSTS / externe Proxy-Sicherheit dokumentieren
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | HSTS und externe Proxy-Sicherheit dokumentieren |
|
||||
| **Findings** | HOCH-02, SEC-01 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. HSTS liegt außerhalb des Repo-Scopes (Reverse-Proxy/Fritz!Box). Betreiber-Verantwortung. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-01), §19.7 |
|
||||
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) fehlte P-08 vollständig in der „Nicht umgesetzte Pakete"-Tabelle. Der Inhalt „HSTS-Header" war fälschlich P-06 zugeordnet. Korrigiert in `docs/compliance-implementation.md`. |
|
||||
|
||||
---
|
||||
|
||||
### P-09 – Admin-Audit-Log
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Admin-Audit-Log (Protokollierung von Admin-Aktionen) |
|
||||
| **Findings** | HOCH-05, SEC-07 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Keine `admin_audit_log`-Tabelle vorhanden. Profil-Löschungen und Lifecycle-Aktionen nicht protokolliert. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-07), §16 (HOCH-05), §17 |
|
||||
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde P-09 fälschlich als „Kein Einwilligungsdialog Recht am eigenes Bild" beschrieben. Der korrekte Titel ist „Admin-Audit-Log". Der Einwilligungsdialog gehört zu P-06. Korrigiert in `docs/compliance-implementation.md`. |
|
||||
|
||||
---
|
||||
|
||||
### P-10 – Mindestalter-Abfrage
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Mindestalter-Abfrage bei Registrierung |
|
||||
| **Findings** | HOCH-06 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Keine Altersverifikation bei Registrierung. Juristisch zu prüfen (§8 DSGVO). |
|
||||
| **Verweise** | `docs/compliance-audit.md` §11.4, §16 (HOCH-06), §17 |
|
||||
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde P-10 fälschlich als „DSA-Meldeverfahren" beschrieben. Der korrekte Titel ist „Mindestalter-Abfrage". Das DSA-Meldeverfahren gehört zu P-13–P-16. Korrigiert in `docs/compliance-implementation.md`. |
|
||||
|
||||
---
|
||||
|
||||
### P-11 – Legal-Hold Lifecycle-Status
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Legal-Hold Lifecycle-Status (Sofortsperrung bei Rechtsverletzung) |
|
||||
| **Findings** | MITT-02 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Vollständig umgesetzt in Version 0.8.84 (2026-05-11), mit Nachfixen in 0.8.85–0.8.86. **Kernumsetzung (0.8.84):** Migration 051 (`legal_hold_active` + Metadatenfelder in `media_assets`; Audit-Log-Ereignistypen `legal_hold_set`/`legal_hold_released`); zentrales Service-Modul `media_legal_hold.py`; Retention-Job überspringt Legal-Hold-Assets; 3 Superadmin-API-Endpoints; Frontend-Badge + Bestätigungs-Dialog + Journal-Renderpfad; 15 Backend-Unit-Tests. **Nachfixe (0.8.85):** UI-Bugs behoben (loadItems, Badge-Sichtbarkeit, Journal-Keys). **Nachfixe (0.8.86):** `download_exercise_media_file` gibt HTTP 451 für Legal-Hold-Assets zurück; `enrich_exercise_detail` liefert `asset_legal_hold_active` mit; `ExerciseMediaEmbed` + `ExerciseMediaThumbTile` + `ExerciseFormPage` zeigen Placeholder statt Datei; Medienliste (`list_media_assets`) nur noch für Superadmin mit Legal-Hold-Einträgen (nicht mehr alle Plattform-Admins). |
|
||||
| **Verweise** | `docs/compliance-audit.md` §9.2, §16 (MITT-02), §17; `docs/compliance-implementation.md` §P-11; `backend/media_legal_hold.py`; `backend/routers/media_assets.py` (admin_legal_hold_router); `backend/routers/exercises.py` (download_exercise_media_file, enrich_exercise_detail); `backend/migrations/051_legal_hold.sql`; `backend/tests/test_p11_legal_hold.py`; `frontend/src/components/ExerciseMediaEmbed.jsx`; `frontend/src/components/ExerciseMediaThumbTile.jsx` |
|
||||
| **Hinweise** | Orthogonal zum normalen Papierkorb-Lifecycle (P-03). `rights_status='blocked'` wird als Schnell-Spiegel gesetzt und bei Aufhebung basierend auf vorhandenen Deklarationen wiederhergestellt. Dateiauslieferung über den exercise-Media-Endpoint gibt HTTP 451 zurück — keine Umgehung über direkten Download. Scope abgegrenzt: P-13 (Meldeverfahren), P-14 (DSA-Transparenz), P-15 (DSA-Moderationslog), P-16 (DSA-Beschwerdeweg) bleiben eigene Pakete. |
|
||||
|
||||
---
|
||||
|
||||
### P-12 – sessionStorage bei Logout bereinigen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | sessionStorage bei Logout bereinigen |
|
||||
| **Findings** | MITT-05 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt 2026-05-10, Version 0.8.68. `logout()` in `AuthContext.jsx` löscht jetzt alle `sj_coach_*`-Schlüssel via Präfix-Iteration. Gezielte Löschung (kein `sessionStorage.clear()`), fremde Schlüssel bleiben erhalten. Playwright-Test ergänzt in `tests/dev-smoke-test.spec.js`. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §5.6, §16 (MITT-05), §17; `docs/compliance-implementation.md` §P-12; `frontend/src/context/AuthContext.jsx`; `tests/dev-smoke-test.spec.js` |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-22 – HTML-Sanitizer für Rich-Text-Felder
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | HTML-Sanitizer für Rich-Text-Felder (bleach/nh3 Allowlist) |
|
||||
| **Findings** | NIED-09, SEC-11 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. `exercise_rich_text.py` normalisiert nur Inline-Media-Markup. Beliebiges HTML in `summary`, `goal`, `execution`, `preparation`, `trainer_notes` möglich. CSP schützt gegen Script-Execution. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.3 (SEC-11), §13.2 (NIED-09), §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-23 – LoginPage: minLength angleichen + Versionsstring entfernen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | LoginPage: minLength angleichen und hartcodierten Versionsstring entfernen |
|
||||
| **Findings** | NIED-06, NIED-07, SEC-12, SEC-13 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `minLength="6"` → `"8"`; Versionsstring `v0.1.0 • Development` entfernt. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-12, SEC-13, NIED-06, NIED-07), §17; `docs/compliance-implementation.md` §P-23 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-24 – CORS einschränken
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | CORS allow_methods und allow_headers auf tatsächlich benötigte Werte einschränken |
|
||||
| **Findings** | NIED-08, SEC-14 |
|
||||
| **Etappe** | 2 |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `allow_methods=["GET","POST","PUT","PATCH","DELETE","OPTIONS"]`; `allow_headers=["Content-Type","X-Auth-Token","X-Active-Club-Id"]`. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.3, §17; `docs/compliance-implementation.md` §P-24 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
## Etappe 3 – DSA-Meldeverfahren
|
||||
|
||||
### P-13 – Content-Melde-Backend
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Content-Melde-Backend (content_reports-Tabelle + Endpoints) |
|
||||
| **Findings** | KRIT-03 |
|
||||
| **Etappe** | 3 → B (vorgezogen; → `docs/compliance-roadmap.md` §4) |
|
||||
| **Status** | ✅ implemented |
|
||||
| **Letzter Stand** | Vollständig umgesetzt in Version 0.8.87 (Kernumsetzung) + 0.8.88–0.8.94 (Erweiterungen + CI-Fix). **Kernumsetzung (0.8.87):** Migration 052 (`content_reports`-Tabelle, Indizes); `POST /api/content-reports` (optionale Auth, official-Medien ohne Login, good_faith_confirmed-Pflicht, auto-Priorisierung); `GET /api/me/inbox/content-reports` (Plattform-Admin, JOIN auf Zieltabellen); `GET /api/content-reports/{id}`; `PATCH /api/content-reports/{id}` (Status/Notiz/Zuweisung, resolution_note Pflicht für Abschluss-Status); `POST /api/content-reports/{id}/legal-hold` (Superadmin, P-11 set_legal_hold(), reason_code-Mapping, setzt Status auf resolved_legal_hold). Inbox-Integration in `InboxPage.jsx`; `ReportContentModal.jsx` + `MediaPreviewModal.jsx` (geteilt). 15 Backend-Unit-Tests. **Erweiterungen (0.8.88–0.8.94):** Migration 053 (content_report_filed Event-Typ im Audit-Log CHECK-Constraint); E-Mail-Benachrichtigungen nach Meldungseingang (Bestätigung an Melder + alle Plattform-Admins, best-effort); Audit-Log-Einträge bei Meldungseingang, Statuswechsel, reinen Notizänderungen; deutsche Labels (REASON_LABELS_DE, STATUS_LABELS_DE); Club-Admin-Berechtigung (sieht und bearbeitet Meldungen zu Medien eigener Vereine; Legal Hold auf nicht-offizielle Vereinsmedien); frühzeitige 403 für plain Admin in set_legal_hold_from_report (vor DB-Zugriff); Wiedereröffnen einer Meldung (status=submitted setzt reviewed_by/at zurück); WorkflowBar (3-Schritte-Fortschrittsbalken) in InboxPage; Archiv-Trennung (offene vs. abgeschlossene Meldungen, kollabierbar); open_report_count-Badge auf Medienkarten (MediaLibraryPage); Journal-Eintrag content_report_filed in MediaLibraryPage; isClubAdmin/isPlatformAdmin/contentReportsError in OrgInboxContext; onSuccess-Callback in ReportContentModal. **CI-Fix (0.8.94):** 3 pytest-Tests repariert; alle 15 Tests grün. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §12, §17; `backend/migrations/052_content_reports.sql`; `backend/migrations/053_content_report_audit_event.sql`; `backend/routers/content_reports.py`; `backend/routers/media_assets.py`; `backend/tests/test_p13_content_reports.py`; `frontend/src/pages/InboxPage.jsx`; `frontend/src/context/OrgInboxContext.jsx`; `frontend/src/pages/MediaLibraryPage.jsx`; `frontend/src/components/ReportContentModal.jsx`; `frontend/src/components/MediaPreviewModal.jsx`; `frontend/src/utils/api.js` |
|
||||
| **Hinweise** | Architekturentscheidung: Die bestehende Admin-Inbox (`InboxPage.jsx`) wurde um einen zweiten Abschnitt erweitert statt einer separaten Moderations-Queue. Club-Admin-Rechte sind bewusst auf Vereinsmedien (nicht official) beschränkt. P-14 (Moderations-UI), P-15 (Uploader-Benachrichtigung bei Sperrung — SMTP vorhanden), P-16 (Beschwerdeverfahren) folgen in Etappe D. |
|
||||
|
||||
---
|
||||
|
||||
### P-14 – Moderations-UI
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Moderations-UI (Frontend für Moderation-Queue) |
|
||||
| **Findings** | KRIT-03 |
|
||||
| **Etappe** | 3 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Abhängig von P-13. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §12, §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-15 – Uploader-Benachrichtigung bei Sperrung
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Uploader-Benachrichtigung bei Sperrung oder Löschung |
|
||||
| **Findings** | KRIT-03 |
|
||||
| **Etappe** | 3 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Kein Benachrichtigungssystem vorhanden. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §9.2, §12, §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-16 – Beschwerdeverfahren
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Beschwerdeverfahren (Nutzer-Rechtsbehelfsweg gegen Moderationsentscheidungen) |
|
||||
| **Findings** | KRIT-03 |
|
||||
| **Etappe** | 3 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Abhängig von P-13–P-15. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §12, §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
## Etappe 4 – Langfristige Optimierungen
|
||||
|
||||
### P-17 – MFA für Superadmins (TOTP)
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | MFA für Superadmins (TOTP-Zweifaktorauthentifizierung) |
|
||||
| **Findings** | HOCH-04, SEC-06 |
|
||||
| **Etappe** | 4 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Kein TOTP/OTP implementiert. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-06), §16 (HOCH-04), §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-18 – HttpOnly-Cookie als Auth-Alternative
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | HttpOnly-Cookie als Auth-Alternative (XSS-Schutz für Auth-Token) |
|
||||
| **Findings** | HOCH-03, SEC-02 |
|
||||
| **Etappe** | 4 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Auth-Token liegt weiterhin in `localStorage`. Größere Architekturänderung erforderlich. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §10.3, §13.2 (SEC-02), §17 |
|
||||
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde der Inhalt „HttpOnly-Cookie-Migration" fälschlich P-11 zugeordnet. Der korrekte Titel gehört zu P-18. Korrigiert in `docs/compliance-implementation.md`. |
|
||||
|
||||
---
|
||||
|
||||
### P-19 – Anti-Virus-Scan (ClamAV)
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Anti-Virus-Scan für Uploads (ClamAV oder vergleichbar) |
|
||||
| **Findings** | NIED-02, SEC-10 |
|
||||
| **Etappe** | 4 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Hoher Aufwand, Risiko bei lokalem Storage gering. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-10), §16 (NIED-02), §17 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-20 – VVT erstellen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | Verzeichnis der Verarbeitungstätigkeiten (VVT) erstellen (DSGVO Art. 30) |
|
||||
| **Findings** | MITT-03 |
|
||||
| **Etappe** | 4 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Betreiber-Aufgabe. Identifizierte Verarbeitungsvorgänge in `docs/compliance-audit.md` §11.1. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §11.1, §17, §19.6 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
### P-21 – AV-Verträge abschließen
|
||||
|
||||
| Feld | Inhalt |
|
||||
|------|--------|
|
||||
| **Kanonischer Titel** | AV-Verträge mit Auftragsverarbeitern abschließen (SMTP, MediaWiki, OpenRouter) |
|
||||
| **Findings** | MITT-04, MITT-07, MITT-08 |
|
||||
| **Etappe** | 4 |
|
||||
| **Status** | ❌ open |
|
||||
| **Letzter Stand** | Nicht umgesetzt. Betreiber-Aufgabe. Drei identifizierte Auftragsverarbeiter ohne Vertrag. |
|
||||
| **Verweise** | `docs/compliance-audit.md` §11.3, §17, §19.6 |
|
||||
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
|
||||
|
||||
---
|
||||
|
||||
## Übersichtstabelle aller Pakete
|
||||
|
||||
| ID | Kanonischer Titel | Etappe | Findings | Status |
|
||||
|----|------------------|--------|----------|--------|
|
||||
| P-01 | Rechtstexte | 1 | KRIT-01 | ⚠️ partially implemented |
|
||||
| P-02 | Self-Service-Kontolöschung + Datenexport | 1 | KRIT-02, KRIT-05 | ❌ open |
|
||||
| P-03 | Papierkorb-Retention-Job aktivieren | 1 | KRIT-07 | ✅ implemented |
|
||||
| P-03b | _Nacharbeit:_ Retention-Zeiten mit Löschkonzept abgleichen | — | — | ✅ implemented |
|
||||
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | 1 | KRIT-06 | ✅ implemented |
|
||||
| P-05 | Passwort-Mindestlänge angleichen | 1 | MITT-01, SEC-04, SEC-12, NIED-06 | ✅ implemented |
|
||||
| P-05b | _Nacharbeit:_ reset-password Mindestlänge | — | — | ✅ implemented |
|
||||
| P-06 | Upload-Einwilligungsdialog | 1 | KRIT-04 | ⚠️ teilweise (KRIT-04 offen) |
|
||||
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test | 2 | HOCH-01, SEC-05 | ✅ implemented |
|
||||
| P-08 | HSTS / externe Proxy-Sicherheit dokumentieren | 2 | HOCH-02, SEC-01 | ❌ open |
|
||||
| P-09 | Admin-Audit-Log | 2 | HOCH-05, SEC-07 | ❌ open |
|
||||
| P-10 | Mindestalter-Abfrage | 2 | HOCH-06 | ❌ open |
|
||||
| P-11 | Legal-Hold Lifecycle-Status | 2 | MITT-02 | ✅ implemented |
|
||||
| P-12 | sessionStorage bei Logout bereinigen | 2 | MITT-05 | ✅ implemented |
|
||||
| P-13 | Content-Melde-Backend | 3→B | KRIT-03 | ✅ implemented |
|
||||
| P-14 | Moderations-UI | 3 | KRIT-03 | ❌ open |
|
||||
| P-15 | Uploader-Benachrichtigung bei Sperrung | 3 | KRIT-03 | ❌ open |
|
||||
| P-16 | Beschwerdeverfahren | 3 | KRIT-03 | ❌ open |
|
||||
| P-17 | MFA für Superadmins (TOTP) | 4 | HOCH-04, SEC-06 | ❌ open |
|
||||
| P-18 | HttpOnly-Cookie als Auth-Alternative | 4 | HOCH-03, SEC-02 | ❌ open |
|
||||
| P-19 | Anti-Virus-Scan (ClamAV) | 4 | NIED-02, SEC-10 | ❌ open |
|
||||
| P-20 | VVT erstellen | 4 | MITT-03 | ❌ open |
|
||||
| P-21 | AV-Verträge abschließen | 4 | MITT-04, MITT-07, MITT-08 | ❌ open |
|
||||
| P-22 | HTML-Sanitizer für Rich-Text-Felder | 2 | NIED-09, SEC-11 | ❌ open |
|
||||
| P-23 | LoginPage: minLength angleichen + Versionsstring entfernen | 2 | NIED-06, NIED-07, SEC-12, SEC-13 | ✅ implemented |
|
||||
| P-24 | CORS einschränken (Methoden + Header) | 2 | NIED-08, SEC-14 | ✅ implemented |
|
||||
|
||||
---
|
||||
|
||||
## Fortschritt
|
||||
|
||||
**Implementiert (vollständig):** P-03, P-03b, P-04, P-05, P-05b, P-07, P-11, P-12, P-13, P-23, P-24 — 11 Pakete (inkl. 2 Nacharbeiten)
|
||||
**Teilweise implementiert:** P-01 (technischer Teil vollständig inkl. P-01b, P-01c, copy-as-draft, jsPDF; juristische Inhalte offen) — 1 Paket
|
||||
**Teilweise umgesetzt (KRIT offen):** P-06 (Upload-Einwilligungsdialog inkl. P-06+ Volljournal + Korrektur — KRIT-04 bis juristische Validierung ausstehend)
|
||||
**Offen:** P-02, P-08, P-09, P-10, P-14, P-15, P-16, P-17, P-18, P-19, P-20, P-21, P-22 — 13 Pakete
|
||||
**App-Version bei letzter Aktualisierung:** 0.8.94
|
||||
**Letztes Umsetzungsdatum:** 2026-05-11
|
||||
|
||||
---
|
||||
|
||||
*Erstellt: 2026-05-10 | Quelle: `docs/compliance-audit.md` (Initial-Audit 2026-05-09) | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
|
||||
@@ -0,0 +1,364 @@
|
||||
# Compliance-Roadmap – Shinkan Jinkendo
|
||||
|
||||
**Typ:** Lebendes Steuerungsdokument
|
||||
**Erstellt:** 2026-05-10
|
||||
**App-Version:** 0.8.94
|
||||
**Zuletzt aktualisiert:** 2026-05-11
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck und Geltung
|
||||
|
||||
Dieses Dokument steuert die aktuelle Priorisierung, Release-Readiness und nächste Freigabeschritte für das Compliance-Programm. Es ersetzt **keines** der folgenden Dokumente, sondern ergänzt sie:
|
||||
|
||||
| Dokument | Rolle |
|
||||
|----------|-------|
|
||||
| `docs/compliance-audit.md` | Historischer Initialbefund (unveränderlich als Quelle) |
|
||||
| `docs/compliance-package-register.md` | Kanonische Quelle für Paket-IDs und aktuellen Paketstatus |
|
||||
| `docs/compliance-implementation.md` | Chronologischer Umsetzungsnachweis |
|
||||
| **`docs/compliance-roadmap.md`** | **Aktuelle Prioritäten, Release-Gates, nächste Freigaben** |
|
||||
|
||||
**Bindungsregeln:**
|
||||
- Paket-IDs → immer aus dem Paketregister
|
||||
- Historische Findings und Severity-Einstufungen → immer aus dem Initial-Audit
|
||||
- Aktuelle Reihenfolge und Freigabeempfehlungen → **dieses Dokument**
|
||||
|
||||
Diese Roadmap ist nach jedem Re-Audit zu aktualisieren. Abweichungen von der bisherigen Priorität werden mit Datum und Begründung dokumentiert (→ §4, §10).
|
||||
|
||||
---
|
||||
|
||||
## 2. Aktueller Stand (2026-05-11)
|
||||
|
||||
### App-Version: 0.8.94
|
||||
|
||||
### Teilweise umgesetzte Pakete
|
||||
|
||||
| ID | Titel | Version | Offen |
|
||||
|----|-------|---------|-------|
|
||||
| P-01 | Rechtstexte | 0.8.74 | Juristische Inhalte — Betreiber + Rechtsanwalt |
|
||||
| P-06 | Upload-Einwilligungsdialog + P-06+ Volljournal + Korrektur | 0.8.83 | KRIT-04: Juristische Validierung (§22 KUG, §8 DSGVO, Widerrufsrecht, Texte p06-v1-conservative) |
|
||||
|
||||
### Vollständig geschlossene Pakete
|
||||
|
||||
| ID | Titel | Version |
|
||||
|----|-------|---------|
|
||||
| P-03 | Papierkorb-Retention-Job aktivieren | 0.8.66 |
|
||||
| P-03b | _Nacharbeit:_ Retention-Zeiten 30+30 Tage | 0.8.67 |
|
||||
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | 0.8.66 |
|
||||
| P-05 | Passwort-Mindestlänge angleichen (alle Endpoints) | 0.8.66–0.8.67 |
|
||||
| P-05b | _Nacharbeit:_ reset-password Mindestlänge | 0.8.67 |
|
||||
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Release-Test | 0.8.66 |
|
||||
| P-12 | sessionStorage bei Logout bereinigen | 0.8.68 |
|
||||
| P-23 | LoginPage: minLength angleichen + Versionsstring entfernen | 0.8.66 |
|
||||
| P-24 | CORS einschränken (Methoden + Header) | 0.8.66 |
|
||||
| P-01b | _Nacharbeit:_ Mobile/PWA-Erreichbarkeit Rechtstexte via `/settings/legal` | 0.8.70 |
|
||||
| P-01c | _Nacharbeit:_ Admin-konfigurierbare Rechtstexte (DB 047, Superadmin-UI, API) | 0.8.71 |
|
||||
| P-01c+ | _Erweiterung:_ Als-Entwurf-kopieren (`copy-as-draft`) | 0.8.72 |
|
||||
| P-01c++ | _Erweiterung:_ Echter PDF-Download (jsPDF) + Abschnitts-Sortierung/-Einfügen | 0.8.74 |
|
||||
| P-13 | Content-Melde-Backend + Erweiterungen (Audit-Log, E-Mail, Club-Admin, Workflow) | 0.8.87–0.8.94 |
|
||||
|
||||
**Vollständig abgeschlossen:** 10 Hauptpakete + 4 Nacharbeiten + 2 Erweiterungen = 16 Umsetzungseinheiten (P-13 inkl. umfangreicher Nachfixe 0.8.88–0.8.94)
|
||||
**Teilweise umgesetzt (technisch):** P-01, P-06
|
||||
|
||||
### Offene Pakete (13)
|
||||
|
||||
P-02, P-08, P-09, P-10, P-14, P-15, P-16, P-17, P-18, P-19, P-20, P-21, P-22
|
||||
|
||||
### Gesamtstatus
|
||||
|
||||
> **⛔ Nicht öffentlich freigabefähig**
|
||||
|
||||
**Begründung:** Die App kann im aktuellen Zustand nicht für allgemeine öffentliche Registrierung beworben oder aktiv vermarktet werden. Folgende zwingende Voraussetzungen fehlen noch:
|
||||
|
||||
1. **P-01:** Kein Impressum, keine Datenschutzerklärung, keine AGB. Eine öffentlich erreichbare App ohne Impressum ist eine Ordnungswidrigkeit nach § 5 DDG.
|
||||
2. **P-06:** Keine Einwilligungserklärung beim Medienupload. Personenbilder können ohne jede Rechteabklärung hochgeladen werden.
|
||||
3. **P-02:** Nutzer können ihr Konto nicht selbst löschen (DSGVO Art. 17). Der Prozess ist noch nicht einmal fachlich spezifiziert.
|
||||
4. ~~**P-13:** Keine Möglichkeit, rechtswidrige Inhalte zu melden.~~ ✅ **Implementiert (v0.8.87).** Content-Melde-Backend umgesetzt: POST `/api/content-reports`, Admin-Inbox-Integration, P-11 Legal-Hold-Anbindung.
|
||||
5. ~~**P-11:** Kein Legal-Hold-Status.~~ ✅ **Implementiert (v0.8.84).**
|
||||
|
||||
**Was geöffnet bleiben kann (mit Dokumentation):** Vereinsinterne Nutzung durch bekannte Trainer-Gruppen ist mit dem aktuellen Stand vertretbar, solange keine öffentliche Vermarktung stattfindet und kein `official`-Content aktiviert wird.
|
||||
|
||||
---
|
||||
|
||||
## 3. Aktuelle Blocker vor öffentlichem Betrieb
|
||||
|
||||
Die folgenden Pakete sind vor der Freigabe für allgemeine öffentliche Registrierung zwingend zu adressieren. Die Reihenfolge entspricht der in §5 definierten Umsetzungsreihenfolge.
|
||||
|
||||
### Blocker 1 — P-01: Rechtstexte
|
||||
|
||||
**Finding:** KRIT-01 (Ordnungswidrigkeit, § 5 DDG)
|
||||
**Technischer Stand:** ⚠️ Vollständige technische Infrastruktur vorhanden (Version 0.8.74):
|
||||
- Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`, `/medienrichtlinie` öffentlich ohne Auth erreichbar (P-01, 0.8.69)
|
||||
- Mobile/PWA-Erreichbarkeit via `/settings/legal` (P-01b, 0.8.70)
|
||||
- Admin-konfigurierbare Rechtstexte: DB-Versionierung, Publish/Archive-Workflow, Superadmin-UI `/admin/legal-documents` (P-01c, 0.8.71)
|
||||
- Als-Entwurf-kopieren: Bestehendes Dokument als Basis für neue Version übernehmen (0.8.72)
|
||||
- Echter PDF-Download via jsPDF (direkter Dateidownload, kein Druckdialog), Abschnitte sortieren (▲/▼) und an beliebiger Stelle einfügen (0.8.74)
|
||||
|
||||
**Warum noch offen:** Impressum, Datenschutzerklärung und AGB ohne juristisch geprüfte Inhalte genügen der gesetzlichen Pflicht nicht. Die Superadmin-UI bietet alle Werkzeuge zum Einpflegen, Versionieren und Veröffentlichen von Texten — sobald Inhalte vorliegen, verschwindet der Platzhalter-Banner automatisch.
|
||||
**Nächster Schritt:** Rechtsanwalt beauftragen → Inhalte über `/admin/legal-documents` einpflegen → Veröffentlichen → Platzhaltermarkierung verschwindet automatisch.
|
||||
|
||||
### Blocker 2 — P-06: Upload-Einwilligungsdialog
|
||||
|
||||
**Finding:** KRIT-04 (§22 KUG, §8 DSGVO)
|
||||
**Warum zwingend:** Jeder hochgeladene Bildinhalt mit erkennbaren Personen ist ohne dokumentierte Einwilligung rechtlich problematisch. Das Risiko besteht nicht erst bei öffentlichen Inhalten — es beginnt beim Upload.
|
||||
**Technischer Stand:** ⚠️ Vollständig technisch umgesetzt (v0.8.83):
|
||||
- **P-06a–P-06d (v0.8.75):** Deklarations-Log, Backend-Enforcement, `RightsDeclarationDialog.jsx`, 3 neue Admin-Endpoints, Altbestand-Indikator, 25 Backend-Tests
|
||||
- **P-06+ Volljournal + Korrektur (v0.8.83):** Vollständiger Audit-Log (`media_asset_audit_log`) für alle Asset-Änderungen; Journal-Endpoint (`events[]` chronologisch); Korrektur-Endpoint für nachträgliche Deklarations-Korrekturen; Zugriff Superadmin + Uploader + Vereins-Admin
|
||||
|
||||
**Warum noch KRIT-04 offen:** Juristische Validierung der Einwilligungsformulierungen (§7.7), KUG-Anforderungen im Vereinskontext (§7.2), Minderjährigenschutz (§7.4) und Altbestand-Behandlung (§7.8) steht aus. Texte sind Arbeitsfassungen (`p06-v1-conservative`) ohne anwaltliche Freigabe.
|
||||
**Nächster Schritt:** Rechtsanwalt für juristische Prüfung der Feldtexte (T1–T10 in `docs/p06-upload-rights-spec.md` §10.3) und der offenen KUG/DSGVO-Fragen beauftragen. Nach Klärung: Textfreigabe eintragen → KRIT-04 kann geschlossen werden.
|
||||
|
||||
### ~~Blocker 3 — P-11: Legal-Hold Lifecycle-Status~~ ✅ Implementiert (v0.8.84–0.8.86)
|
||||
|
||||
**Finding:** MITT-02
|
||||
**Abgeschlossen:** 2026-05-11. Migration 051, `media_legal_hold.py`, Retention-Schutz, Superadmin-API + Frontend (0.8.84); UI-Bugfixes (0.8.85); vollständige Auslieferungssperre (`download_exercise_media_file` HTTP 451), Frontend-Placeholder in allen Übungskomponenten, Medienliste nur noch für Superadmin mit Legal-Hold-Einträgen (0.8.86). Details: `docs/compliance-package-register.md` §P-11.
|
||||
|
||||
### ~~Blocker 3 (neu) — P-13: Content-Melde-Backend (Minimalversion)~~ ✅ Implementiert (v0.8.87)
|
||||
|
||||
**Finding:** KRIT-03
|
||||
**Abgeschlossen:** 2026-05-11. Migration 052 (`content_reports`); `POST /api/content-reports` (optionale Auth, official-Medien ohne Login meldbar); `GET /api/me/inbox/content-reports` (Plattform-Admin); `PATCH /api/content-reports/{id}`; `POST /api/content-reports/{id}/legal-hold` (Superadmin, P-11-Integration, reason_code-Mapping). Inbox-Erweiterung `InboxPage.jsx` mit zweitem Abschnitt „Inhaltsmeldungen". Keine separate Moderations-Queue — bestehende Admin-Inbox erweitert. 15 Backend-Unit-Tests. Details: `docs/compliance-package-register.md` §P-13.
|
||||
|
||||
### Blocker 5 — P-02: DSGVO-Self-Service (fachliche Spezifikation zuerst)
|
||||
|
||||
**Finding:** KRIT-02, KRIT-05
|
||||
**Warum zuerst spezifizieren, dann umsetzen:** P-02 berührt Kontolöschung, Medienarchiv, Vereinsinhalte, Backups und Fristen. Eine voreilige Implementierung riskiert unvollständige oder juristisch falsche Umsetzung. → Erst spezifizieren (→ §5 Etappe C), dann freigeben.
|
||||
**Juristisch zu klären:** Anonymisierung vs. Löschung bei Vereinsinhalten; Backup-Retention-Policy.
|
||||
|
||||
### Blocker 6 — P-08: HSTS-Betriebsnachweis (Betreiber-Aufgabe)
|
||||
|
||||
**Finding:** HOCH-02, SEC-01
|
||||
**Status:** Außerhalb des Repo-Scopes. HSTS muss am externen Reverse-Proxy (Fritz!Box → Synology → Nginx) konfiguriert sein.
|
||||
**Anforderung:** Vor öffentlichem Betrieb: manueller Nachweis (z. B. `curl -I https://shinkan.jinkendo.de` zeigt `Strict-Transport-Security`-Header).
|
||||
**Nicht im Code zu lösen** — aber als Release-Gate dokumentiert (→ §7).
|
||||
|
||||
---
|
||||
|
||||
## 4. Abweichungen gegenüber der ursprünglichen Audit-Reihenfolge
|
||||
|
||||
### P-13 wird vorgezogen (Etappe 3 → Etappe B)
|
||||
|
||||
Das Initial-Audit (`docs/compliance-audit.md` §17) ordnete P-13–P-16 (DSA-Meldeverfahren) in Etappe 3 ein, nach den Sicherheits- und Datenschutzpaketen von Etappe 2. Die Begründung war: juristische Klärung des DSA-Anwendungsbereichs zuerst.
|
||||
|
||||
**Aktuelle Einschätzung (2026-05-10):** Diese Reihenfolge bleibt für den vollen DSA-Stack (P-14–P-16) richtig. Für den Kern von P-13 — die technische Möglichkeit, eine Inhaltsmeldung abzugeben und zu bearbeiten — ist eine Vorziehung geboten, weil:
|
||||
|
||||
- Die App erlaubt bereits jetzt Upload und Anzeige von Nutzerinhalten mit `official`-Sichtbarkeit
|
||||
- Das Risiko ungemeldeter Rechtsverletzungen ist kein langfristiges, sondern ein unmittelbares
|
||||
- Die juristische DSA-Bewertung (ab welcher Nutzerzahl, welche Pflichten) bleibt offen — sie entscheidet über den Umfang, nicht über das Ob einer Grundfähigkeit
|
||||
- Eine minimale Melde-Queue kostet weniger als P-14–P-16 zusammen und schafft handlungsfähige Grundstruktur
|
||||
|
||||
**Keine ID-Änderung:** P-13 bleibt P-13. Die Neuprioritisierung ist eine Planungsentscheidung, keine inhaltliche Änderung des Pakets.
|
||||
|
||||
### P-22 (HTML-Sanitizer) bleibt in Etappe D
|
||||
|
||||
Das Initial-Audit platzierte P-22 in Etappe 2. Die aktuelle Einschätzung: CSP `script-src 'self'` reduziert das XSS-Risiko für eingeloggte Nutzer erheblich. Das Risiko ist real, aber kein harter Blocker vor öffentlichem Betrieb im Vergleich zu P-01, P-06, P-11, P-13. P-22 bleibt auf der Roadmap, wird aber nicht als Release-Gate behandelt.
|
||||
|
||||
---
|
||||
|
||||
## 5. Aktuell empfohlene Umsetzungsreihenfolge
|
||||
|
||||
### ✅ Etappe A – Abgeschlossen (2026-05-10, Version 0.8.68)
|
||||
|
||||
| Paket | Titel | Aufwand | Status |
|
||||
|-------|-------|---------|--------|
|
||||
| P-12 | sessionStorage bei Logout bereinigen | ~15 min | ✅ umgesetzt |
|
||||
|
||||
**Abschluss:** P-12 wurde am 2026-05-10 in Version 0.8.68 umgesetzt. `logout()` in `AuthContext.jsx` löscht alle `sj_coach_*`-Schlüssel via Präfix-Iteration. Playwright-Test verifiziert. MITT-05 geschlossen.
|
||||
|
||||
---
|
||||
|
||||
### Etappe B – Technische Grundlagen für öffentlichen Betrieb
|
||||
|
||||
Reihenfolge innerhalb der Etappe ist flexibel; P-01 und P-06 haben keine gegenseitige Abhängigkeit.
|
||||
|
||||
| Paket | Titel | Aufwand | Abhängigkeit | Freigabe-Formulierung |
|
||||
|-------|-------|---------|-------------|----------------------|
|
||||
| P-01 | Rechtstexte technisch anlegen (Platzhalter-Seiten, Routen) | 2–4 h Technik | Inhalt durch Rechtsanwalt separat | „Freigabe zur Umsetzung P-01: Rechtstexte" |
|
||||
| P-06 | Upload-Einwilligungsdialog | 2–4 Tage | — | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
|
||||
| ~~P-11~~ | ~~Legal-Hold Lifecycle-Status~~ | — | ✅ implementiert (v0.8.84) | — |
|
||||
| ~~P-13~~ | ~~Content-Melde-Backend (Minimalversion)~~ | — | ✅ implementiert (v0.8.87) | — |
|
||||
|
||||
**Hinweis P-01:** Die technische Anlage (leere Seiten, Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`) ist von der juristischen Ausarbeitung des Inhalts zu trennen. Beide Teilschritte können unabhängig voneinander freigegeben und durchgeführt werden.
|
||||
|
||||
**Hinweis P-13:** ✅ Vollständig implementiert (v0.8.87–0.8.94). Kernumsetzung: `POST /api/content-reports`, `GET /api/me/inbox/content-reports`, `PATCH /api/content-reports/{id}`, `POST /api/content-reports/{id}/legal-hold`. Erweiterungen: Audit-Log (Migration 053), E-Mail-Benachrichtigungen, Club-Admin-Rechte (Vereinsmedien), Workflow-Bar + Archiv-Trennung, Badge auf Medienkarten, CI-Fix (15 Tests grün). Keine separate Moderations-Queue — bestehende Admin-Inbox erweitert. P-14 (Moderations-UI), P-15 (Uploader-Benachrichtigung), P-16 (Beschwerdeverfahren) folgen in Etappe D.
|
||||
|
||||
---
|
||||
|
||||
### Etappe C – DSGVO-Self-Service sauber spezifizieren (vor Umsetzungsfreigabe)
|
||||
|
||||
P-02 erhält eine eigene Spezifikationsphase, bevor eine Umsetzungsfreigabe erteilt wird. Zu klärende Punkte:
|
||||
|
||||
| Frage | Entscheidungsträger |
|
||||
|-------|---------------------|
|
||||
| Löschung vs. Anonymisierung bei Vereinsinhalten | Betreiber + Rechtsanwalt |
|
||||
| Verhalten bei Medien, die anderen Vereinen zugeordnet sind | Betreiber + Technik |
|
||||
| Umgang mit Backups (Retention vs. Löschung auf Antrag) | Betreiber + Rechtsanwalt |
|
||||
| Fristen: Bearbeitungszeit für Löschanträge | Rechtsanwalt |
|
||||
| Audit-Log für Löschanträge (wer, wann, was) | Technik |
|
||||
| Datenexport-Format und Umfang | Technik + Betreiber |
|
||||
|
||||
Erst wenn diese Fragen beantwortet und als Spec dokumentiert sind, wird P-02 in Etappe C freigegeben.
|
||||
|
||||
---
|
||||
|
||||
### Etappe D – Ausbau und langfristige Optimierungen
|
||||
|
||||
| Paket | Titel | Aufwand | Priorität |
|
||||
|-------|-------|---------|-----------|
|
||||
| P-09 | Admin-Audit-Log | 3–5 Tage | Hoch |
|
||||
| P-10 | Mindestalter-Abfrage | 1–2 Tage | Mittel |
|
||||
| P-14 | Moderations-UI (Frontend) | 3–5 Tage | Mittel (nach P-13) |
|
||||
| P-15 | Uploader-Benachrichtigung bei Sperrung | 1–2 Tage | Mittel (nach P-13) |
|
||||
| P-16 | Beschwerdeverfahren | 2–4 Tage | Niedrig (nach P-15) |
|
||||
| P-08 | HSTS-Dokumentation / Betriebsnachweis | Betreiber | Hoch (Release-Gate) |
|
||||
| P-22 | HTML-Sanitizer für Rich-Text-Felder | 1–2 Tage | Mittel |
|
||||
| P-20 | VVT erstellen | Betreiber | Hoch |
|
||||
| P-21 | AV-Verträge abschließen | Betreiber | Hoch |
|
||||
| P-02 | Self-Service-Kontolöschung + Datenexport | 5–8 Tage | Hoch (nach Spezifikation Etappe C) |
|
||||
| P-17 | MFA für Superadmins (TOTP) | 5–8 Tage | Mittel |
|
||||
| P-18 | HttpOnly-Cookie als Auth-Alternative | 3–5 Tage | Niedrig |
|
||||
| P-19 | Anti-Virus-Scan (ClamAV) | 3–5 Tage | Niedrig |
|
||||
|
||||
---
|
||||
|
||||
## 6. Nächste empfohlene Freigabe
|
||||
|
||||
**P-01 + P-01b + P-01c technisch vollständig umgesetzt (Version 0.8.74).** Rechtstexte über Login, Desktop-Sidebar und Einstellungen → Rechtliches (Mobile/PWA) erreichbar. Superadmin kann über `/admin/legal-documents` versionierte Rechtstexte anlegen, bearbeiten (inkl. Abschnitts-Sortierung und Einfügen an beliebiger Stelle), als Entwurf kopieren, veröffentlichen und als PDF herunterladen — sobald Inhalte eingepflegt sind, verschwindet der Platzhalter-Banner automatisch. Juristische Inhalte bleiben offen (Betreiber + Rechtsanwalt).
|
||||
|
||||
Die nächste technische Freigabe sollte **Etappe B** umfassen — beginnend mit P-06:
|
||||
|
||||
**P-06 Spezifikation vorhanden** (`docs/p06-upload-rights-spec.md`, 2026-05-10). Die Umsetzung setzt die Entscheidung über 12 juristische Klärungspunkte voraus (§22 KUG im Vereinskontext, §8 DSGVO Minderjährigenschutz, Widerrufsrecht, Speicherfristen für Einwilligungen). Erst nach dieser Klärung:
|
||||
|
||||
> „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog"
|
||||
|
||||
oder als Paket (nach Klärung P-06):
|
||||
|
||||
> „Freigabe zur Umsetzung Etappe B: P-06, P-11, P-13"
|
||||
|
||||
**Parallel dazu Betreiber-Aufgabe:**
|
||||
Rechtsanwalt für die Ausarbeitung der Inhalte von P-01 beauftragen — Inhalte über `/admin/legal-documents` einpflegen und veröffentlichen. Dies ist eine Betreiber-Aufgabe, keine weitere technische Freigabe.
|
||||
|
||||
**Nach P-01 vollständig (Inhalte eingepflegt):** Gate 1 rückt näher — verbleibende Blocker: P-06, P-02 (Spez.), P-11, P-13, P-08 (Betreiber).
|
||||
|
||||
---
|
||||
|
||||
## 7. Release-Gates
|
||||
|
||||
### Gate 1 — Öffentliche allgemeine Registrierung freischalten
|
||||
|
||||
Folgende Bedingungen müssen **alle** erfüllt sein:
|
||||
|
||||
| Bedingung | Paket | Typ |
|
||||
|-----------|-------|-----|
|
||||
| Impressum und Datenschutzerklärung mit juristisch geprüftem Inhalt | P-01 | ⚠️ Routen vorhanden — Inhalte durch Rechtsanwalt erforderlich |
|
||||
| Upload-Einwilligungsdialog aktiv | P-06 | Code |
|
||||
| DSGVO-Löschprozess spezifiziert (Spec akzeptiert, auch wenn nicht vollständig implementiert) | P-02 | Spezifikation |
|
||||
| Legal-Hold-Status vorhanden | P-11 | ✅ Bereits erfüllt (Version 0.8.84–0.8.86) |
|
||||
| Content-Melde-Backend (Minimalversion) aktiv | P-13 | Code |
|
||||
| HSTS am externen Reverse-Proxy nachgewiesen | P-08 | Betreiber |
|
||||
| Papierkorb-Retention-Job läuft (Monitoring aktiv) | P-03 | Bereits erfüllt |
|
||||
| `ALLOW_PUBLIC_MEDIA_STATIC` nicht in Prod-Env gesetzt | P-07 | Bereits erfüllt |
|
||||
| sessionStorage bei Logout bereinigt | P-12 | ✅ Bereits erfüllt (Version 0.8.68) |
|
||||
|
||||
**Darf bei Gate 1 offen bleiben (mit Dokumentation):**
|
||||
- P-02 vollständige Implementierung (Spezifikation genügt als Zwischenstand, wenn aktiver Prozess für Löschanfragen per E-Mail dokumentiert ist)
|
||||
- P-09 Admin-Audit-Log
|
||||
- P-10 Mindestalter-Abfrage
|
||||
- P-14–P-16 Moderationsausbau
|
||||
- P-17 MFA, P-18 HttpOnly-Cookie, P-19 Anti-Virus-Scan
|
||||
- P-20 VVT (in Erstellung), P-21 AV-Verträge (in Klärung)
|
||||
|
||||
---
|
||||
|
||||
### Gate 2 — Aktivierung öffentlicher Official-Medien (`visibility = official`)
|
||||
|
||||
Bevor Inhalte mit `official`-Sichtbarkeit (plattformweit sichtbar, ohne Login) aktiv eingesetzt werden:
|
||||
|
||||
| Bedingung | Paket | Typ |
|
||||
|-----------|-------|-----|
|
||||
| Gate 1 vollständig erfüllt | — | Voraussetzung |
|
||||
| Upload-Einwilligungsdialog für Personenbilder aktiv | P-06 | Code |
|
||||
| Legal-Hold-Status aktiv (Sofortsperrung möglich) | P-11 | ✅ Bereits erfüllt (Version 0.8.84–0.8.86) |
|
||||
| Content-Melde-Backend aktiv | P-13 | Code |
|
||||
| Copyright-Pflicht bei Promotion aktiv und getestet | P-04 | Bereits erfüllt |
|
||||
| Moderationsprozess organisatorisch dokumentiert (wer, wie schnell, Eskalationspfad) | — | Betreiber |
|
||||
|
||||
---
|
||||
|
||||
### Gate 3 — Aktivierung öffentlicher Inhalte im Vereinsbereich (`visibility = club`)
|
||||
|
||||
Bedingungen für Vereinsinhalte sind weniger streng als für `official`, da der Personenkreis begrenzt ist:
|
||||
|
||||
| Bedingung | Status |
|
||||
|-----------|--------|
|
||||
| Copyright-Pflicht bei Promotion aktiv | ✅ bereits erfüllt (P-04) |
|
||||
| Papierkorb-Retention-Job aktiv | ✅ bereits erfüllt (P-03) |
|
||||
| Upload-Einwilligungsdialog vorhanden | muss mit P-06 kommen |
|
||||
| Mitgliedschaftsbasierte Zugriffskontrolle funktioniert | ✅ (TenantContext, library_content_visibility_sql) |
|
||||
|
||||
---
|
||||
|
||||
## 8. Juristisch zu prüfende Punkte
|
||||
|
||||
Alle folgenden Punkte erfordern Einschätzung durch einen Rechtsanwalt oder Datenschutzbeauftragten. Keine der nachfolgenden Einschätzungen ist rechtlich verbindlich.
|
||||
|
||||
| Thema | Frage | Priorität |
|
||||
|-------|-------|-----------|
|
||||
| **Rechtstexte** | Vollständige Angaben Impressum, Datenschutzerklärung, AGB, Medienrichtlinie. Inhalte können nicht technisch generiert werden. | Sofort |
|
||||
| **DSA-Anwendungsbereich** | Ab welcher Nutzerzahl und unter welchen Voraussetzungen gilt der DSA für diese Plattform? Welche Pflichten für sehr kleine Plattformen? | Vor öffentlichem Betrieb |
|
||||
| **Einwilligungsmodell Personenbilder** | §22 KUG: Welche Einwilligungen sind für Bilder erkennbarer Personen im Vereinskontext erforderlich? Reicht eine pauschale Upload-Erklärung? | Vor öffentlichem Betrieb |
|
||||
| **Minderjährigenschutz** | §8 DSGVO: Ab welchem Alter ist keine elterliche Einwilligung nötig? Wie ist mit Bildern Minderjähriger umzugehen? | Vor öffentlichem Betrieb |
|
||||
| **DSGVO-Löschprozess** | Anonymisierung vs. Löschung bei Vereinsinhalten; Umgang mit Backups; Fristen für Löschanträge (Art. 17) | Vor Implementierung P-02 |
|
||||
| **Datenübertragbarkeit** | Welcher Exportumfang ist für Art. 20 DSGVO ausreichend? Welches Format? | Vor Implementierung P-02 |
|
||||
| **AV-Verträge** | Welche Dienstleister benötigen einen AVV (SMTP-Anbieter, MediaWiki, OpenRouter)? | Vor öffentlichem Betrieb |
|
||||
| **Backup-Retention** | Wie muss die Backup-Retention-Policy aussehen, damit DSGVO-Löschanfragen auch Backups erfassen? | Vor öffentlichem Betrieb |
|
||||
| **MediaWiki-Lizenz** | Welche Lizenzanforderungen gelten für Übungsinhalte von karatetrainer.net? | Klärenswert |
|
||||
|
||||
---
|
||||
|
||||
## 9. Betreiber-Aufgaben
|
||||
|
||||
Diese Punkte liegen außerhalb des Code-Scopes und erfordern organisatorische Maßnahmen durch den Betreiber:
|
||||
|
||||
| Aufgabe | Bezug | Dringlichkeit |
|
||||
|---------|-------|--------------|
|
||||
| Rechtsanwalt beauftragen (Rechtstexte, DSA, KUG) | P-01, P-06 | Sofort |
|
||||
| VVT erstellen (DSGVO Art. 30) | P-20 | Vor öffentlichem Betrieb |
|
||||
| AV-Verträge klären (SMTP, MediaWiki, OpenRouter) | P-21 | Vor öffentlichem Betrieb |
|
||||
| HSTS am Reverse-Proxy (Fritz!Box/Synology) konfigurieren und nachweisen | P-08 | Vor öffentlichem Betrieb |
|
||||
| Backup-Konzept dokumentieren und Restore-Test durchführen | — | Dringend empfohlen |
|
||||
| Moderationsprozess organisatorisch festlegen: Wer moderiert? Wie schnell? Eskalationspfad? | P-13–P-16 | Vor Aktivierung öffentlicher Inhalte |
|
||||
| Notfallkontakt für Datenpannen benennen (DSGVO Art. 33) | — | Vor öffentlichem Betrieb |
|
||||
| Papierkorb-Retention-Job überwachen (`docker logs shinkan-retention-cron`) | P-03 | Laufend |
|
||||
|
||||
---
|
||||
|
||||
## 10. Aktualisierungsregel
|
||||
|
||||
| Anlass | Maßnahme |
|
||||
|--------|----------|
|
||||
| Nach jedem Re-Audit | §2 (Aktueller Stand) und §5 (Reihenfolge) aktualisieren |
|
||||
| Nach jeder Freigabe | Paketregister (`docs/compliance-package-register.md`) aktualisieren; §2 dieser Roadmap anpassen |
|
||||
| Prioritätsänderung gegenüber bisheriger Roadmap | Datum und Begründung in §4 dokumentieren |
|
||||
| Neue Paket-IDs | Immer im Initial-Audit + Paketregister vergeben; nie nur in dieser Roadmap |
|
||||
| Paketstatus | Nie direkt in dieser Roadmap pflegen — immer aus Paketregister übernehmen |
|
||||
|
||||
**Diese Roadmap enthält keine eigenständigen Statusangaben.** §2 wird durch Abfrage des Paketregisters befüllt und bei Aktualisierungen synchronisiert.
|
||||
|
||||
---
|
||||
|
||||
## Anhang: Schnellreferenz Freigabe-Formulierungen
|
||||
|
||||
| Freigabe | Formulierung | Status |
|
||||
|----------|-------------|--------|
|
||||
| ~~P-12 allein~~ | ~~„Freigabe zur Umsetzung P-12: sessionStorage bei Logout bereinigen"~~ | ✅ historisch abgeschlossen (Version 0.8.68) |
|
||||
| ~~P-01 technisch~~ | ~~„Freigabe zur Umsetzung P-01: Rechtstexte technisch anlegen"~~ | ✅ historisch abgeschlossen (Version 0.8.69) |
|
||||
| ~~P-01b~~ | ~~„Freigabe zur Umsetzung P-01b: Mobile/PWA-Zugriff auf Rechtliches"~~ | ✅ historisch abgeschlossen (Version 0.8.70) |
|
||||
| ~~P-01c~~ | ~~„Freigabe zur Umsetzung P-01c: Admin-konfigurierbare Rechtstexte"~~ | ✅ historisch abgeschlossen (Version 0.8.71); Erweiterungen copy-as-draft (0.8.72) + jsPDF/Sortierung (0.8.74) |
|
||||
| **P-06** | **„Freigabe zur Umsetzung P-06 auf Basis konservativer Erstannahmen"** | ✅ erteilt + vollständig umgesetzt (2026-05-11, v0.8.75–0.8.83) — technisch umgesetzt unter `p06-v1-conservative` inkl. P-06+ Volljournal + Korrektur; KRIT-04 bleibt bis juristische Validierung |
|
||||
| **P-11** | **„Freigabe zur Umsetzung P-11: Legal-Hold Lifecycle-Status"** | ✅ vollständig umgesetzt (2026-05-11, v0.8.84–0.8.86) — Migration 051, Retention-Schutz, Superadmin-API + Frontend (0.8.84); UI-Bugfixes (0.8.85); Auslieferungssperre + Frontend-Placeholder + Superadmin-only Medienliste (0.8.86); 15 Backend-Tests |
|
||||
| ~~P-13~~ | ~~„Freigabe zur Umsetzung P-13: Content-Melde-Backend"~~ | ✅ vollständig umgesetzt (2026-05-11, v0.8.87–0.8.94) — Kernumsetzung + Audit-Log, E-Mail-Benachrichtigungen, Club-Admin-Rechte, Workflow-Management, Badge, CI-Fix; 15 Backend-Tests |
|
||||
| P-02 Spezifikation | „Freigabe zur Spezifikation P-02: DSGVO-Self-Service-Prozess" | offen |
|
||||
|
||||
---
|
||||
|
||||
*Erstellt: 2026-05-10 | Quellen: `docs/compliance-audit.md`, `docs/compliance-package-register.md`, `docs/compliance-implementation.md` | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
|
||||
@@ -0,0 +1,984 @@
|
||||
# P-06 – Fachlich-technische Spezifikation: Upload-Einwilligungsdialog
|
||||
|
||||
**Paket-ID:** P-06 (kanonisch, unveränderlich)
|
||||
**Kanonischer Titel:** Upload-Einwilligungsdialog (Recht am eigenen Bild, Personen, Minderjährige)
|
||||
**Dokument-Typ:** Spezifikation + Umsetzungsnachweis
|
||||
**Erstellt:** 2026-05-10
|
||||
**App-Version bei Erstellung:** 0.8.74
|
||||
**Letzte Aktualisierung:** 2026-05-11 (App-Version 0.8.86, P-11 vollständig inkl. Auslieferungssperre + Frontend-Placeholder)
|
||||
**Status P-06:** ⚠️ technisch umgesetzt (P-06a–P-06d, P-06+) | KRIT-04 offen bis juristische Validierung
|
||||
**Rechtlicher Hinweis:** Alle als „juristisch zu prüfen" markierten Einschätzungen sind keine Rechtsberatung. Keine konkrete Textfassung von Erklärungen in diesem Dokument — Formulierungen obliegen dem Rechtsanwalt.
|
||||
|
||||
---
|
||||
|
||||
## 1. Kontext und Ziel
|
||||
|
||||
### 1.1 Ausgangslage (Initial-Audit-Befund)
|
||||
|
||||
Das Initial-Audit (`docs/compliance-audit.md`, §8.2–8.3) identifiziert folgende Lücken:
|
||||
|
||||
- Keine verbindliche Rechteerklärung beim Medienupload
|
||||
- Keine Abfrage, ob erkennbare Personen enthalten sind
|
||||
- Keine Abfrage, ob Minderjährige abgebildet sind
|
||||
- Keine Abfrage, ob erforderliche Einwilligungen abgebildeter Personen vorliegen
|
||||
- Keine Dokumentation, wer wann welche Erklärung abgegeben hat
|
||||
|
||||
### 1.2 Regulatorische Prüfanker (technische Modellierung)
|
||||
|
||||
| Norm | Relevanz für Datenmodell | Juristisch zu prüfen |
|
||||
|------|--------------------------|----------------------|
|
||||
| § 22 KUG | Bildnisse erkennbarer Personen erfordern Einwilligung vor Verbreitung/Zurschaustellung | Gilt auch für vereinsinterne Sichtbarkeit? |
|
||||
| Art. 8 DSGVO | Bei Minderjährigen ggf. Einwilligung Erziehungsberechtigter | Ab welchem Alter? Welche Mechanismen? |
|
||||
| § 19a UrhG | Öffentliche Zugänglichmachung = eigener Nutzungstatbestand | Ab wann gilt `official` als „öffentlich zugänglich"? |
|
||||
| DSGVO Art. 5(1)(e) | Datenminimierung — welche Nachweisdaten dürfen gespeichert werden? | Was ist verhältnismäßig? |
|
||||
|
||||
### 1.3 Ziel dieser Spezifikation
|
||||
|
||||
P-06 soll sicherstellen, dass:
|
||||
|
||||
1. Jeder Medien-Upload mit einer strukturierten, gespeicherten Rechteerklärung verknüpft ist
|
||||
2. Die Erklärung nach Sichtbarkeitsstufe gestuft wird (private minimal, official vollständig)
|
||||
3. Bestehende Prüfungen aus P-04 (copyright_notice) komplementär erhalten bleiben
|
||||
4. Juristische Textanpassungen ohne Codeänderungen möglich sind (Versionierung)
|
||||
5. Altmedien ohne rückwirkenden Zwang behandelt werden können
|
||||
6. Backend-Erzwingung (keine reine Frontend-Kosmetik) besteht
|
||||
|
||||
---
|
||||
|
||||
## 2. IST-Analyse
|
||||
|
||||
### 2.1 Upload-Pfade (vollständige Bestandsaufnahme)
|
||||
|
||||
| # | Endpoint | Datei | Upload-Typ | Sichtbarkeit wählbar | Copyright bei Upload |
|
||||
|---|----------|-------|-----------|---------------------|----------------------|
|
||||
| U1 | `POST /api/exercises/{id}/media` | `routers/exercises.py:2518` | Einzeldatei oder Embed-URL | Folgt Übungssichtbarkeit (implizit) | Nicht abgefragt |
|
||||
| U2 | `POST /api/media-assets/bulk-upload` | `routers/media_assets.py:787` | 1–n Dateien | `visibility` + `club_id` als Form-Parameter | Optional (`copyright_notice` fehlt im POST-Body, nur via PATCH nachträglich) |
|
||||
|
||||
**Kein weiterer Upload-Endpoint vorhanden** (geprüft über Codebase-Suche nach `UploadFile`).
|
||||
|
||||
**Weitere indirekte Upload-Pfade:**
|
||||
- `POST /api/exercises/{id}/media/from-asset` (`exercises.py`) — verknüpft ein bestehendes Archiv-Asset mit einer Übung; kein Upload, kein neues Medium
|
||||
- Embed-URL (`embed_url`, `embed_platform`) — keine Datei, keine Rechteerklärung für Dateiinhalte; externe Plattform verantwortlich
|
||||
|
||||
### 2.2 Promotionspfade (Sichtbarkeitsänderung)
|
||||
|
||||
| # | Endpoint | Datei | Mögliche Promotion |
|
||||
|---|----------|-------|--------------------|
|
||||
| PR1 | `PATCH /api/media-assets/{id}` | `routers/media_assets.py:1223` | private→club, private→official, club→official, auch Rückstufung |
|
||||
| PR2 | `POST /api/media-assets/bulk-patch` | `routers/media_assets.py:1094` | Massenpromotion, gleiche Richtungen |
|
||||
| PR3 | Implizit bei `PUT /api/exercises/{id}` | `routers/exercises.py` | Übungssichtbarkeit→club/official löst `apply_official_exercise_media_rules()` oder `apply_club_exercise_media_copyright_rules()` aus |
|
||||
|
||||
**Rückstufungen** (official→club, club→private) werden nicht gesperrt — juristisch zu prüfen, ob Rückstufung Rechte-Konsequenzen hat.
|
||||
|
||||
### 2.3 Datenmodell `media_assets` (Migration 045 + 046)
|
||||
|
||||
```
|
||||
media_assets
|
||||
├── id SERIAL PK
|
||||
├── mime_type VARCHAR(100)
|
||||
├── byte_size INT
|
||||
├── sha256 CHAR(64) NOT NULL
|
||||
├── original_filename VARCHAR(300)
|
||||
├── visibility VARCHAR(32) NOT NULL DEFAULT 'private' ← Sichtbarkeitsstufe
|
||||
├── club_id INT REFERENCES clubs(id) ← Vereinszuordnung
|
||||
├── uploaded_by_profile_id INT REFERENCES profiles(id) ← Uploader
|
||||
├── copyright_notice TEXT ← Urheberrechtshinweis (P-04)
|
||||
├── storage_backend VARCHAR(32)
|
||||
├── storage_key TEXT NOT NULL UNIQUE
|
||||
├── lifecycle_state VARCHAR(32) DEFAULT 'active'
|
||||
├── trash_soft_at, trash_hidden_at, purge_after_at TIMESTAMP
|
||||
├── created_at, updated_at TIMESTAMP
|
||||
└── tags TEXT[] DEFAULT '{}'
|
||||
```
|
||||
|
||||
**Fehlende P-06-Felder:** Keine Einwilligungsfelder vorhanden. Keine Personenabbildungsmarkierung. Keine Deklarations-Versionierung.
|
||||
|
||||
### 2.4 Rollen und Berechtigungen (Zusammenfassung `_item_permissions()`)
|
||||
|
||||
| Aktion | private | club | official |
|
||||
|--------|---------|------|----------|
|
||||
| Upload (neu) | Jeder authentifizierte Nutzer | Vereinsmitglied + club_id | Nur Superadmin |
|
||||
| `edit_metadata` | Superadmin, Plattform-Admin, Uploader | Superadmin, Plattform-Admin, Club-Admin | Nur Superadmin |
|
||||
| Promotion zu club | Eigener Upload: Uploader; Club-Asset: Club-Admin | — | — |
|
||||
| Promotion zu official | Nur Superadmin | Nur Superadmin | — |
|
||||
| Lifecycle (trash) | Uploader, Plattform-Admin, Superadmin | Club-Admin, Plattform-Admin, Superadmin | Nur Superadmin |
|
||||
|
||||
### 2.5 Bestehende Frontend-Dialoge
|
||||
|
||||
| Stelle | Datei | Aktuelles Verhalten |
|
||||
|--------|-------|---------------------|
|
||||
| Übungsformular Medienupload | `ExerciseFormPage.jsx` | Datei-Picker, kein Einwilligungsdialog |
|
||||
| Archiv Bulk-Upload | `MediaLibraryPage.jsx` | Datei-Picker + optional `copyright_notice` im Editmodal, kein Pflichtdialog |
|
||||
| Übung → official (API-Error) | `ExerciseFormPage.jsx:624` | `window.prompt()` für copyright_notice nach 422-Fehler — reaktiv, kein proaktiver Dialog |
|
||||
| Archiv PATCH Sichtbarkeit | `MediaLibraryPage.jsx` | Backend wirft 400 wenn copyright fehlt; Frontend-Feedback unklar |
|
||||
|
||||
**Ergebnis:** Kein proaktiver strukturierter Einwilligungsdialog vorhanden. Alle Copyright-Abfragen sind reaktiv (nach API-Fehler) oder optional.
|
||||
|
||||
### 2.6 Bestehende Copyright-Prüfungen P-04 (Referenz)
|
||||
|
||||
P-04 erzwingt `copyright_notice` bei Promotion zu `club` oder `official`:
|
||||
- `patch_media_asset()`: HTTP 400 wenn `copyright_notice` leer bei Ziel club/official
|
||||
- `bulk_media_patch()`: Asset in `failed`-Liste wenn copyright fehlt
|
||||
- `apply_official_exercise_media_rules()`: HTTP 422 `OFFICIAL_MEDIA_CONFIRM_REQUIRED` wenn Assets kein copyright
|
||||
- Mindestlänge: 3 Zeichen (`_MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN = 3`)
|
||||
|
||||
**Verhältnis zu P-06:** P-04 (copyright_notice) = Attribution für Dritte (wer besitzt das Recht). P-06 = Selbsterklärung des Uploaders (habe ich das Recht, dieses Medium hochzuladen). Ergänzend, nicht konkurrierend.
|
||||
|
||||
### 2.7 IST-Lücken (P-06-spezifisch)
|
||||
|
||||
| Lücke | Schwere |
|
||||
|-------|---------|
|
||||
| Kein Pflichtfeld „Ich bin Rechteinhaber" beim Upload | Kritisch (Grundlage aller Uploads) |
|
||||
| Keine Abfrage „erkennbare Personen enthalten?" | Hoch (§ 22 KUG-Risiko bei club/official) |
|
||||
| Keine Abfrage „Minderjährige enthalten?" | Hoch (Art. 8 DSGVO, besonderer Schutz) |
|
||||
| Keine Speicherung von Einwilligungszeitpunkt und -version | Hoch (Nachweisbarkeit) |
|
||||
| Keine Erzwingung im Backend (nur Frontend-Checkbox wäre zu wenig) | Kritisch |
|
||||
| Kein Einwilligungslog (wer hat wann welche Version bestätigt?) | Hoch |
|
||||
| copyright_notice beim Erstupload nicht abgefragt | Mittel (P-04 fragt erst bei Promotion) |
|
||||
|
||||
### 2.8 Altbestandsrisiken
|
||||
|
||||
- Alle bestehenden `media_assets`-Zeilen haben keine Einwilligungsmetadaten
|
||||
- Unbekannt, ob bei bestehenden Medien erkennbare Personen/Minderjährige abgebildet sind
|
||||
- Medien mit `visibility=club` oder `visibility=official` existieren ohne dokumentierte Einwilligung
|
||||
- Superadmin kann bestehende official-Medien weiter sehen/nutzen ohne Nachdeklaration
|
||||
- Bei Neuzuweisung zu einer anderen Übung werden bestehende Medien ohne Prüfung verknüpft
|
||||
|
||||
---
|
||||
|
||||
## 3. Entscheidungsmatrix
|
||||
|
||||
Anforderungen nach **Sichtbarkeitsstufe** (Zeilen) × **Aktion** (Spalten). „Pflicht" = Backend-Sperre wenn fehlend. „Optional" = abfragen aber nicht erzwingen.
|
||||
|
||||
| Aktion → | Erstupload | Promotion club | Promotion official | Metadaten-Edit | Reuse in neuer Übung |
|
||||
|-----------|-----------|---------------|-------------------|---------------|---------------------|
|
||||
| **private** | `rights_holder`: Pflicht; Personen-Fragen: optional | — | — | Keine P-06-Pflicht | Keine P-06-Pflicht |
|
||||
| **club** | `rights_holder`: Pflicht; `contains_persons`: Pflicht; `person_consent`: Pflicht wenn Personen | `contains_persons` + `person_consent`: Pflicht; `contains_minors`: Pflicht | — | Keine P-06-Pflicht | Keine P-06-Pflicht |
|
||||
| **official** | Alles Pflicht | Alles Pflicht | Alle Felder Pflicht + copyright_notice (P-04) | Keine P-06-Pflicht | Keine P-06-Pflicht |
|
||||
|
||||
**B: Medieninhalt — Konsequenzen:**
|
||||
|
||||
| Inhalt | private | club | official |
|
||||
|--------|---------|------|----------|
|
||||
| Keine erkennbaren Personen | `person_consent` entfällt | `person_consent` entfällt | `person_consent` entfällt |
|
||||
| Erkennbare Erwachsene | Optional zu deklarieren | Einwilligung Pflicht (juristisch zu prüfen) | Einwilligung Pflicht |
|
||||
| Erkennbare Minderjährige | Optional zu deklarieren | Einwilligung Erziehungsberechtigter Pflicht (juristisch zu prüfen) | Einwilligung Pflicht |
|
||||
| Unklar / nicht beantwortet | Zulässig bei private | Blockiert bei club/official | Blockiert |
|
||||
|
||||
**C: Rechteinhalt — Konsequenzen:**
|
||||
|
||||
| Inhalt | Konsequenz |
|
||||
|--------|-----------|
|
||||
| Nutzer ist selbst Urheber | `rights_holder_confirmed = true` genügt |
|
||||
| Nutzer hat Nutzungsrechte | `rights_holder_confirmed = true` genügt; copyright_notice sollte Rechteinhaber nennen |
|
||||
| Drittmaterial enthalten | `rights_holder_confirmed = true` nur wenn Lizenz vorhanden; copyright_notice Pflicht bei club/official |
|
||||
| Musik enthalten | `contains_music = true`; `music_rights_confirmed` Pflicht (juristisch zu prüfen) |
|
||||
| Logos/Marken/sonstige Fremdinhalte | Fällt unter `rights_holder_confirmed`; juristisch zu prüfen |
|
||||
|
||||
**D: Aktion — Blockierungslogik:**
|
||||
|
||||
| Aktion | Fehlendes Pflichtfeld | Verhalten Backend |
|
||||
|--------|----------------------|-------------------|
|
||||
| Upload | rights_holder_confirmed fehlt | HTTP 400 `RIGHTS_DECLARATION_REQUIRED` |
|
||||
| Promotion club | contains_persons / person_consent fehlt | HTTP 400 `CONSENT_REQUIRED_FOR_CLUB` |
|
||||
| Promotion official | Beliebiges Pflichtfeld fehlt | HTTP 400 `CONSENT_REQUIRED_FOR_OFFICIAL` |
|
||||
| Promotion mit Altmedium (legacy) | rights_status = legacy_unreviewed | HTTP 400 `LEGACY_REDECLARATION_REQUIRED` |
|
||||
|
||||
---
|
||||
|
||||
## 4. Empfohlenes Zielmodell
|
||||
|
||||
### 4.1 Neue Tabelle: `media_asset_rights_declarations`
|
||||
|
||||
Append-only Audit-Log. Jede Erklärung (Upload, Promotion, Nachdeklaration) erzeugt einen neuen Eintrag. Bestehende Einträge werden nie geändert.
|
||||
|
||||
```sql
|
||||
CREATE TABLE media_asset_rights_declarations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||
declared_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
declared_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
|
||||
-- Kontext
|
||||
action_type VARCHAR(50) NOT NULL
|
||||
CHECK (action_type IN (
|
||||
'upload', -- Erstupload
|
||||
'promote_club', -- Promotion zu club
|
||||
'promote_official', -- Promotion zu official
|
||||
're_declaration', -- Nachdeklaration (auf Aufforderung)
|
||||
'legacy_re_declaration' -- Altmedium: erste Deklaration nachgereicht
|
||||
)),
|
||||
target_visibility VARCHAR(32) NOT NULL, -- Sichtbarkeit für die erklärt wird
|
||||
declaration_version VARCHAR(20) NOT NULL DEFAULT 'p06-v1.0', -- Textversion der Erklärung
|
||||
|
||||
-- Pflichtfeld (alle Sichtbarkeiten)
|
||||
rights_holder_confirmed BOOLEAN NOT NULL,
|
||||
|
||||
-- Personenrechte (Pflicht ab club)
|
||||
contains_identifiable_persons BOOLEAN,
|
||||
person_consent_confirmed BOOLEAN, -- Pflicht wenn contains_identifiable_persons = true
|
||||
contains_minors BOOLEAN,
|
||||
parental_consent_confirmed BOOLEAN, -- Pflicht wenn contains_minors = true (juristisch zu prüfen)
|
||||
|
||||
-- Drittmaterial (optional MVP, Pflicht später)
|
||||
contains_music BOOLEAN,
|
||||
music_rights_confirmed BOOLEAN,
|
||||
third_party_content_confirmed BOOLEAN,
|
||||
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_mar_declarations_asset ON media_asset_rights_declarations (media_asset_id);
|
||||
CREATE INDEX idx_mar_declarations_profile ON media_asset_rights_declarations (declared_by_profile_id);
|
||||
```
|
||||
|
||||
### 4.2 Neue Felder in `media_assets`
|
||||
|
||||
Drei neue Schnellzugriffs-Felder (kein Ersatz für den Log, nur für performante Abfragen):
|
||||
|
||||
```sql
|
||||
ALTER TABLE media_assets
|
||||
ADD COLUMN rights_status VARCHAR(32)
|
||||
NOT NULL DEFAULT 'legacy_unreviewed'
|
||||
CHECK (rights_status IN ('pending', 'declared', 'legacy_unreviewed', 'blocked')),
|
||||
ADD COLUMN rights_declared_for_visibility VARCHAR(32), -- Höchste Stufe, für die erklärt wurde
|
||||
ADD COLUMN rights_declared_at TIMESTAMP WITH TIME ZONE; -- Zeitpunkt der aktuellsten Erklärung
|
||||
```
|
||||
|
||||
**Status-Semantik:**
|
||||
|
||||
| rights_status | Bedeutung |
|
||||
|---------------|-----------|
|
||||
| `legacy_unreviewed` | Bestehendes Medium ohne P-06-Daten — Altbestand |
|
||||
| `pending` | Neues Medium, Upload noch ohne Deklaration (Zwischenzustand, darf nie persistent sein) |
|
||||
| `declared` | Gültige Deklaration vorhanden für `rights_declared_for_visibility` |
|
||||
| `blocked` | Deklaration widerrufen oder durch Admin gesperrt (→ P-11/P-13 Schnittstelle) |
|
||||
|
||||
**Visibility-Hierarchie für Prüfung:**
|
||||
```
|
||||
private (1) < club (2) < official (3)
|
||||
```
|
||||
|
||||
Promotion ist erlaubt wenn: `rights_declared_for_visibility` ≥ Ziel-Visibility. Sonst ist neue Deklaration erforderlich.
|
||||
|
||||
### 4.3 Feld-Bewertung: MVP vs. später
|
||||
|
||||
| Feld | MVP-Pflicht | Sinnvoll später | Unnötig / zu früh | Juristisch abhängig |
|
||||
|------|-------------|-----------------|-------------------|---------------------|
|
||||
| `rights_holder_confirmed` | ✅ | — | — | Nein |
|
||||
| `contains_identifiable_persons` | ✅ ab club | — | — | Nein |
|
||||
| `person_consent_confirmed` | ✅ wenn Personen + ≥ club | — | — | Teilweise |
|
||||
| `contains_minors` | ✅ ab official | ✅ auch club | — | Ja (Schwelle) |
|
||||
| `parental_consent_confirmed` | — | ✅ | — | Ja (juristisch zu klären) |
|
||||
| `contains_music` | — | ✅ | — | Ja |
|
||||
| `music_rights_confirmed` | — | ✅ | — | Ja |
|
||||
| `third_party_content_confirmed` | — | ✅ | — | Teilweise |
|
||||
| `declaration_version` | ✅ | — | — | Nein |
|
||||
| `action_type` | ✅ | — | — | Nein |
|
||||
| `rights_status` in media_assets | ✅ | — | — | Nein |
|
||||
| `rights_declared_for_visibility` | ✅ | — | — | Nein |
|
||||
| Separates Upload von Einwilligungsdokumenten | — | — | Zu früh | Ja |
|
||||
| `may_be_embedded_in_exercises` | — | — | Unnötig (exercise_media-Tabelle reicht) | — |
|
||||
| `declaration_scope_*` als einzelne Booleans | — | — | Unnötig (visibility-String reicht) | — |
|
||||
|
||||
### 4.4 Designentscheidungen (mit Begründung)
|
||||
|
||||
**Entscheidung 1: Gestufte Erklärungen je Sichtbarkeitsstufe**
|
||||
|
||||
Nicht eine universale Erklärung für alle Stufen, sondern Promotion auf höhere Stufe erfordert neue Erklärung.
|
||||
|
||||
*Begründung:* Rechtliche Anforderungen steigen mit Sichtbarkeit. Private Medien: nur Eigentümer sieht sie. Official-Medien: plattformweit sichtbar (ggf. öffentlich). Stufenmodell ist rechtsanschlussfähig — spätere juristische Textanpassungen pro Stufe ohne Systemwechsel möglich.
|
||||
|
||||
**Entscheidung 2: Minimalset beim Erstupload**
|
||||
|
||||
Pflicht beim privaten Upload: nur `rights_holder_confirmed`. Personen-Fragen: optional beim Upload, Pflicht erst bei Promotion zu club/official.
|
||||
|
||||
*Begründung:* Die meisten Uploads bleiben privat und werden nie promoted. Volle Fragebogenbelastung beim Upload würde Nutzung hemmen ohne rechtlichen Mehrwert. Personen-Fragen werden erzwungen sobald der Upload für andere sichtbar wird.
|
||||
|
||||
**Entscheidung 3: Keine globale Nutzer-Einwilligung (pro Upload)**
|
||||
|
||||
Erklärung wird pro Upload abgegeben, nicht einmalig pro Nutzer.
|
||||
|
||||
*Begründung:* Jedes Medium ist inhaltlich unterschiedlich. Eine pauschale Einwilligung beim Registrieren oder einmalig je Nutzer deckt nicht ab, ob bei diesem konkreten Video Minderjährige abgebildet sind.
|
||||
|
||||
**Entscheidung 4: Append-only Audit-Log**
|
||||
|
||||
Einmal abgegebene Erklärungen werden nie geändert oder gelöscht. Neue Erklärung = neuer Eintrag.
|
||||
|
||||
*Begründung:* Nachweisbarkeit. Bei späterem Streit muss belegbar sein, was wann erklärt wurde.
|
||||
|
||||
**Entscheidung 5: Versionierung via `declaration_version`-String**
|
||||
|
||||
Wenn Rechtsanwalt Erklärungstexte ändert, wird die neue Version als "p06-v1.1" deklariert. Keine Datenbank-FK auf eine Textversion-Tabelle (zu komplex für MVP).
|
||||
|
||||
*Begründung:* Einfach nachvollziehbar. Ob bei Versionswechsel alle Altdeklarationen erneuert werden müssen, ist juristisch zu entscheiden — technisch ermöglicht das System beides.
|
||||
|
||||
**Entscheidung 6: copyright_notice bleibt separat (P-04 unberührt)**
|
||||
|
||||
P-06 führt keine copyright_notice-Redundanz ein. copyright_notice (P-04) = Attribution. rights_holder_confirmed (P-06) = Berechtigung. Beide sind Pflicht bei official.
|
||||
|
||||
---
|
||||
|
||||
## 5. Ziel-Flows
|
||||
|
||||
### Flow 1: Erstupload eines privaten Mediums (Übung oder Archiv)
|
||||
|
||||
**Frontend:**
|
||||
1. Nutzer öffnet Upload-Dialog (Exercise oder Archiv)
|
||||
2. Dateiauswahl
|
||||
3. **P-06-Dialog erscheint vor Upload-Button-Aktivierung:**
|
||||
- ☑ „Ich bin der Rechteinhaber oder besitze die erforderlichen Nutzungsrechte an diesem Medium." [Pflicht]
|
||||
- ☐ „Das Medium enthält erkennbare Personen." [optional]
|
||||
- → wenn ja: ☑ „Alle abgebildeten Personen haben der Nutzung zugestimmt." [optional bei private, Pflicht bei Promotion]
|
||||
- ☐ „Das Medium enthält Minderjährige." [optional]
|
||||
4. Upload-Button aktiv erst wenn Pflicht-Checkbox gesetzt
|
||||
|
||||
**Backend:**
|
||||
- Empfängt neue Felder: `rights_holder_confirmed`, optional `contains_identifiable_persons`, `person_consent_confirmed`, `contains_minors`
|
||||
- Prüft: `rights_holder_confirmed == true` — sonst HTTP 400 `RIGHTS_DECLARATION_REQUIRED`
|
||||
- INSERT in `media_assets` mit `rights_status = 'declared'`, `rights_declared_for_visibility = 'private'`, `rights_declared_at = NOW()`
|
||||
- INSERT in `media_asset_rights_declarations` mit `action_type = 'upload'`, `declaration_version = 'p06-v1.0'`, alle Felder
|
||||
|
||||
**Fehlermeldungen:**
|
||||
- `RIGHTS_DECLARATION_REQUIRED`: "Bitte bestätige, dass du die erforderlichen Rechte an diesem Medium besitzt."
|
||||
|
||||
**Tests:**
|
||||
- Upload ohne `rights_holder_confirmed` → 400
|
||||
- Upload mit `rights_holder_confirmed=true` → 201, `rights_status='declared'` in DB
|
||||
- Declaration-Log-Eintrag vorhanden mit korrektem `action_type='upload'`
|
||||
|
||||
**Offene juristische Fragen:** Reicht Selbsterklärung oder muss der Betreiber den Upload ansonsten ablehnen? (→ §7.1)
|
||||
|
||||
---
|
||||
|
||||
### Flow 2: Erstupload direkt als club-Medium (Archiv-Bulk-Upload)
|
||||
|
||||
**Frontend:**
|
||||
- Nutzer wählt `visibility = club` im Bulk-Upload-Dialog
|
||||
- P-06-Dialog erweitert (zusätzlich zur privaten Pflicht-Checkbox):
|
||||
- ☑ „Das Medium enthält erkennbare Personen." [Antwort Pflicht bei club]
|
||||
- → wenn ja: ☑ „Alle abgebildeten Personen haben der vereinsinternen Nutzung zugestimmt." [Pflicht]
|
||||
- ☑ „Das Medium enthält Minderjährige." [Antwort Pflicht]
|
||||
- → wenn ja: ☑ „Einwilligung der Erziehungsberechtigten liegt vor." [Pflicht, juristisch zu prüfen]
|
||||
|
||||
**Backend:**
|
||||
- Prüft alle Pflichtfelder für club: `rights_holder_confirmed`, `contains_identifiable_persons` (must be answered), `person_consent_confirmed` (wenn contains_persons=true)
|
||||
- `rights_declared_for_visibility = 'club'`
|
||||
- Eintrag in `media_asset_rights_declarations` mit `action_type = 'upload'`, `target_visibility = 'club'`
|
||||
|
||||
---
|
||||
|
||||
### Flow 3: Bulk-Upload durch Admin (Plattform-Admin / Superadmin)
|
||||
|
||||
**Besonderheit:** Admin lädt oft viele Dateien auf einmal. Dialog-Design muss batch-fähig sein.
|
||||
|
||||
**Empfehlung:** Eine Einwilligungserklärung für den gesamten Batch (nicht je Datei). Alle Dateien des Batches erhalten den gleichen Declarations-Record, jedoch referenziert je `media_asset_id`.
|
||||
|
||||
**Frontend:**
|
||||
- Vor Upload: Batch-Deklaration (gilt für alle Dateien des Batches)
|
||||
- Alternativ: Je Datei separate Deklaration (aufwändiger aber präziser) — juristisch zu prüfen welche Variante ausreichend ist
|
||||
|
||||
**Backend:**
|
||||
- `action_type = 'upload'` für alle Dateien des Batches
|
||||
- Wenn Batch-Deklaration: eine Deklarations-Transaktion, n Einträge in Log (je asset_id)
|
||||
|
||||
**Offene juristische Fragen:** Genügt eine Sammelbestätigung für Batches? (→ §7.6)
|
||||
|
||||
---
|
||||
|
||||
### Flow 4: Promotion private → club
|
||||
|
||||
**Frontend:**
|
||||
1. Nutzer ändert Sichtbarkeit eines Mediums zu `club` (im Archiv oder via Übungssichtbarkeit)
|
||||
2. Frontend erkennt Sichtbarkeitserhöhung
|
||||
3. **P-06-Promotions-Dialog:**
|
||||
- ☑ „Das Medium enthält erkennbare Personen." [Pflicht — Antwort erforderlich]
|
||||
- → wenn ja: ☑ „Alle abgebildeten Personen haben der vereinsinternen Nutzung zugestimmt." [Pflicht]
|
||||
- ☑ „Das Medium enthält Minderjährige." [Pflicht — Antwort erforderlich]
|
||||
- → wenn ja: ☑ „Einwilligung der Erziehungsberechtigten liegt vor." [Pflicht, juristisch zu prüfen]
|
||||
4. Bestehende copyright_notice-Abfrage (P-04) bleibt erhalten — läuft parallel oder im gleichen Dialog
|
||||
|
||||
**Backend:**
|
||||
- PATCH `/api/media-assets/{id}` empfängt: `visibility='club'`, P-06-Felder, `copyright_notice`
|
||||
- Prüft: rights_status='declared' AND rights_declared_for_visibility ≥ 'club' — wenn ja, keine neue Deklaration nötig (z. B. bereits als club hochgeladen)
|
||||
- Wenn nicht: neue Pflichtfelder prüfen, INSERT in Declarations-Log mit `action_type='promote_club'`
|
||||
- Bestehende P-04-Prüfung: copyright_notice weiterhin Pflicht
|
||||
- `rights_declared_for_visibility` in media_assets auf 'club' setzen
|
||||
|
||||
**Backend-Fehler:**
|
||||
- `CONSENT_REQUIRED_FOR_CLUB`: Personenfragen nicht beantwortet
|
||||
- `LEGACY_REDECLARATION_REQUIRED`: Altmedium, muss Nachdeklaration abgeben
|
||||
- `RIGHTS_DECLARATION_REQUIRED` (P-04): copyright_notice fehlt (bestehend)
|
||||
|
||||
---
|
||||
|
||||
### Flow 5: Promotion private/club → official
|
||||
|
||||
**Frontend:**
|
||||
1. Nur Superadmin kann zu official promoten
|
||||
2. Dialog zeigt vollständige Erklärung:
|
||||
- Alle Felder aus Flow 4 (Pflicht)
|
||||
- ☑ zusätzlich: „Das Medium enthält Musik oder sonstige Fremdinhalte." [Pflicht — Antwort erforderlich]
|
||||
- → wenn ja: ☑ „Ich besitze die erforderlichen Lizenzen für die öffentliche Nutzung." [Pflicht]
|
||||
3. copyright_notice (P-04) weiterhin Pflicht (bestehende Logik)
|
||||
|
||||
**Backend:**
|
||||
- Prüft alle Felder + copyright_notice
|
||||
- `action_type = 'promote_official'`, `target_visibility = 'official'`
|
||||
- `rights_declared_for_visibility = 'official'`
|
||||
|
||||
**Offene juristische Fragen:** Reicht Selbstdeklaration oder muss Superadmin bei official höhere Sorgfalt nachweisen? (→ §7.3)
|
||||
|
||||
---
|
||||
|
||||
### Flow 6: Nachbearbeitung von Metadaten (ohne Sichtbarkeitsänderung)
|
||||
|
||||
**Szenario:** Nutzer ändert nur `copyright_notice`, `original_filename`, `tags` — keine Sichtbarkeitsänderung.
|
||||
|
||||
**P-06-Anforderung:** Keine neue Deklaration erforderlich (Metadaten-Edit ist kein Promotions-Schritt).
|
||||
|
||||
**Ausnahme:** Wenn `rights_status = 'blocked'` (durch P-11/P-13 gesetzt) → Metadaten-Edit erlaubt, aber Sichtbarkeitsänderungen bleiben gesperrt.
|
||||
|
||||
---
|
||||
|
||||
### Flow 7: Verwendung bestehender Medien in neuer Übung (`from-asset`)
|
||||
|
||||
**Szenario:** Trainer verknüpft ein bereits im Archiv liegendes Medium mit einer neuen Übung über `POST /api/exercises/{id}/media/from-asset`.
|
||||
|
||||
**P-06-Anforderung:** Keine neue Deklaration erforderlich. Die Deklaration gilt für das Medium selbst, nicht für die Verknüpfung. Voraussetzung: `rights_status` des Assets ist 'declared' für die Sichtbarkeit der Übung.
|
||||
|
||||
**Backend-Prüfung (neu):**
|
||||
- Asset-Sichtbarkeit ≥ Übungs-Sichtbarkeit? Bestehende Prüfung.
|
||||
- `rights_declared_for_visibility` ≥ Übungs-Sichtbarkeit? → Neue Prüfung durch P-06
|
||||
- Wenn nicht: HTTP 400 `RIGHTS_DECLARATION_REQUIRED_FOR_TARGET_VISIBILITY`
|
||||
|
||||
---
|
||||
|
||||
### Flow 8: Behandlung von Altmedien ohne P-06-Metadaten
|
||||
|
||||
**Strategie: Soft-Block bei Promotion, kein Rückwirkungs-Zwang für private Altmedien**
|
||||
|
||||
| Situation | Verhalten |
|
||||
|-----------|-----------|
|
||||
| Altmedium private → weiterhin privat | Unverändert zugänglich; keine Zwangs-Nachdeklaration |
|
||||
| Altmedium privat → Anzeige in Übung (private) | Unverändert; keine neue Deklaration |
|
||||
| Altmedium privat → Promotion zu club | Blocked: `LEGACY_REDECLARATION_REQUIRED`; Nutzer muss Nachdeklaration abgeben |
|
||||
| Altmedium club → Promotion zu official | Blocked; Superadmin muss Nachdeklaration abgeben |
|
||||
| Altmedium mit `rights_status = 'legacy_unreviewed'` | Einsehbar, nicht promotable |
|
||||
|
||||
**Nachdeklarations-Flow:**
|
||||
1. Nutzer versucht Promotion eines Altmediums
|
||||
2. Backend gibt HTTP 400 `LEGACY_REDECLARATION_REQUIRED` zurück
|
||||
3. Frontend zeigt Hinweis und Deklarations-Dialog (analog zu neuem Upload-Dialog)
|
||||
4. Nutzer füllt Deklaration aus
|
||||
5. PATCH mit `legacy_re_declaration=true` + alle Pflichtfelder + `visibility`
|
||||
6. Backend: INSERT in Declarations-Log mit `action_type='legacy_re_declaration'`, aktualisiert `rights_status`, `rights_declared_for_visibility`
|
||||
|
||||
**Migrationsstrategie für bestehende Daten:**
|
||||
- Alle bestehenden `media_assets`-Zeilen bleiben mit `rights_status = 'legacy_unreviewed'` (Default in Migration)
|
||||
- Keine rückwirkende Sperrung
|
||||
- Bestehende club/official-Medien: `rights_status = 'legacy_unreviewed'` — die historische Sichtbarkeit bleibt erhalten, spätere Änderungen erfordern aber Nachdeklaration
|
||||
|
||||
**Juristisch zu prüfen:** Muss der Betreiber aktiv alle Altmedien auf club/official sperren bis zur Nachdeklaration? (→ §7.8)
|
||||
|
||||
---
|
||||
|
||||
### Flow 9: Widerruf / nachträglich fehlende Rechte erkannt
|
||||
|
||||
**Szenario:** Abgebildete Person widerruft Einwilligung oder Uploader erkennt, dass er keine Rechte hatte.
|
||||
|
||||
**P-06 implementiert keinen Widerrufsmechanismus direkt.** Anschluss an spätere Pakete:
|
||||
|
||||
- **P-11 (Legal-Hold):** Superadmin kann `rights_status = 'blocked'` setzen → Medium sofort aus allen öffentlichen Abfragen entfernt
|
||||
- **P-13 (Content-Melde-Backend):** Dritte können Rechtsverletzung melden → Moderationsqueue → Superadmin entscheidet über Sperrung
|
||||
|
||||
**P-06-Schnittstelle:** Das Feld `rights_status = 'blocked'` in `media_assets` ist die technische Brücke zu P-11 und P-13.
|
||||
|
||||
**Empfehlung:** Declaration-Log-Tabelle hat `ON DELETE CASCADE` auf `media_assets.id` — wenn ein Medium purged wird, werden auch alle Deklarationseinträge entfernt. Juristisch zu prüfen, ob Deklarationslog nach Löschung aufbewahrt werden muss (Rechenschaftspflicht Art. 5 Abs. 2 DSGVO).
|
||||
|
||||
---
|
||||
|
||||
### Flow 10: Zusammenspiel mit P-11 (vollständig implementiert) und P-13
|
||||
|
||||
**P-11 Status: ✅ Vollständig implementiert (v0.8.84–0.8.86)**
|
||||
|
||||
| P-06-Element | P-11-Umsetzung | P-13-Anschluss |
|
||||
|-------------|---------------|---------------|
|
||||
| `rights_status = 'blocked'` | P-11 setzt diesen Status als Spiegel bei `legal_hold_active=TRUE`; bei Freigabe auf `declared`/`legacy_unreviewed` zurückgesetzt | P-13-Moderator triggert `set_legal_hold()` |
|
||||
| Declaration-Log | Zeigt, welche Version bei Sperrung galt; wird bei `release_legal_hold` zur Wiederherstellung von `rights_status` genutzt | Kontext für Moderationsentscheidung |
|
||||
| `contains_identifiable_persons` | Relevant für Löschbegründung (KUG), `reason_code=consent_withdrawn` | Relevanzmerkmal für Meldekategorie |
|
||||
| `contains_minors` | Höchste Priorität: `reason_code=youth_protection` | CSAM-Eskalationspfad in P-13 |
|
||||
|
||||
**Implementiertes Schnittstellenmodell P-06 ↔ P-11 (komplett):**
|
||||
|
||||
_Datenhaltung und Audit (v0.8.84):_
|
||||
- `media_legal_hold.py`: `set_legal_hold()` schreibt `rights_status='blocked'` als Spiegel
|
||||
- `media_legal_hold.py`: `release_legal_hold()` stellt `rights_status` anhand vorhandener Deklarationen wieder her (`declared` wenn `COUNT(rights_holder_confirmed=TRUE)>0`, sonst `legacy_unreviewed`)
|
||||
- Audit-Log `media_asset_audit_log` protokolliert `legal_hold_set`/`legal_hold_released` als eigene Ereignistypen (orthogonal zu `copyright_change`, `visibility_change` etc.)
|
||||
|
||||
_Sichtbarkeit und Auslieferungssperre (v0.8.85–0.8.86):_
|
||||
- `list_media_assets`: `include_legal_hold=is_sup` — nur Superadmin sieht gesperrte Assets in der Medienliste; Plattform-Admins ohne Superadmin-Rolle sehen sie nicht mehr
|
||||
- `download_exercise_media_file` (v0.8.86): gibt HTTP **451 Unavailable For Legal Reasons** zurück wenn `asset_legal_hold_active=TRUE` — keine Dateiauslieferung, auch wenn das Asset bereits mit einer Übung verknüpft ist
|
||||
- `enrich_exercise_detail` (v0.8.86): liefert `asset_legal_hold_active` im Media-Array mit — Frontend-Komponenten erhalten den Hold-Status ohne zusätzlichen API-Call
|
||||
- `ExerciseMediaEmbed.jsx` + `ExerciseMediaThumbTile.jsx` + `ExerciseFormPage.jsx` (v0.8.86): zeigen „Medium nicht verfügbar / Gesperrt"-Placeholder statt Datei, wenn `asset_legal_hold_active=true`
|
||||
|
||||
**P-13-Vorbereitung:** `set_legal_hold()` in `media_legal_hold.py` ist eine generische Funktion — P-13 ruft sie mit `reason_code` aus der Moderationsqueue auf, ohne eigene Sperr-Logik implementieren zu müssen. Die Auslieferungssperre (HTTP 451) greift dann automatisch für alle bereits verknüpften Medien.
|
||||
|
||||
---
|
||||
|
||||
## 6. Legacy- und Migrationskonzept
|
||||
|
||||
### 6.1 Fragen und Antworten
|
||||
|
||||
| Frage | Empfehlung | Juristisch zu prüfen |
|
||||
|-------|-----------|----------------------|
|
||||
| Dürfen Altmedien sichtbar bleiben? | Ja — keine rückwirkende Sperrung | Ja — insb. club/official ohne Einwilligung |
|
||||
| Dürfen Altmedien in neuen Übungen verwendet werden? | Ja, wenn Sichtbarkeit kompatibel | Ja — falls keine Rechte vorhanden |
|
||||
| Dürfen Altmedien zu club promoted werden? | Nein — Nachdeklaration erforderlich | Ja — ob Selbstdeklaration genügt |
|
||||
| Dürfen Altmedien zu official promoted werden? | Nein — vollständige Nachdeklaration | Ja — höhere Anforderungen |
|
||||
| Muss bei erster Bearbeitung Nachdeklaration erzwungen werden? | Nein (nur bei Promotion) | Ja — Betreiber-Ermessen |
|
||||
|
||||
### 6.2 Migration-Schritte
|
||||
|
||||
1. **Migration (P-06a):** Neue Spalten in `media_assets` mit `DEFAULT 'legacy_unreviewed'` → alle bestehenden Zeilen erhalten automatisch Status `legacy_unreviewed`
|
||||
2. **Neue Uploads nach P-06:** Code setzt `rights_status = 'declared'` nach erfolgreicher Deklaration
|
||||
3. **Altmedien-Promotion:** Backend blockiert mit `LEGACY_REDECLARATION_REQUIRED`; Nutzer muss Nachdeklaration abgeben
|
||||
4. **Keine automatische Batch-Re-Deklaration** durch Betreiber (wäre fachlich falsch — Betreiber kann nicht für Uploader erklären)
|
||||
|
||||
### 6.3 Empfohlene Übergangsstrategie (Minimales Risiko)
|
||||
|
||||
```
|
||||
private Altmedien: weiter sichtbar und nutzbar | Promotion blockiert
|
||||
club Altmedien: weiter sichtbar | Sichtbarkeitsänderung blockiert
|
||||
official Altmedien: weiter sichtbar | Sichtbarkeitsänderung blockiert
|
||||
```
|
||||
|
||||
*Begründung:* Vollständige Sperrung aller Altmedien würde Betrieb lahmlegen. Die Blockierung bei Promotion schützt vor Eskalation ohne existierende Nutzung zu zerstören. Juristisch bleibt das Risiko bei bereits exponierten Medien — das ist ein organisatorisches Problem, kein technisches.
|
||||
|
||||
---
|
||||
|
||||
## 7. Juristische Klärungsliste
|
||||
|
||||
Alle folgenden Punkte müssen durch einen Rechtsanwalt oder Datenschutzbeauftragten bewertet werden. Keine der folgenden Einschätzungen ist rechtlich bindend.
|
||||
|
||||
| # | Frage | Technische Relevanz | Dringlichkeit |
|
||||
|---|-------|---------------------|---------------|
|
||||
| 7.1 | Welche Erklärung ist für **private** Medien (nur Uploader sieht sie) erforderlich? Reicht `rights_holder_confirmed` oder ist auch ohne Sichtbarkeit Dritter eine Personeneinwilligung nötig? | Ob Personen-Fragen bei private Pflicht werden | Vor MVP |
|
||||
| 7.2 | Welche Erklärung ist für **club**-interne Sichtbarkeit (Vereinsmitglieder) erforderlich? Gilt § 22 KUG für vereinsintern? Reicht Selbsterklärung des Uploaders? | Pflichtfelder bei Promotion zu club | Vor MVP |
|
||||
| 7.3 | Welche Erklärung ist für **official** (plattformweit, ggf. öffentlich) erforderlich? Reicht Selbsterklärung oder muss Einwilligung nachgewiesen werden? | Pflichtfelder bei Promotion zu official | Vor MVP |
|
||||
| 7.4 | Wie ist mit erkennbaren **Minderjährigen** zu verfahren? Ab welchem Alter benötigen Minderjährige elterliche Einwilligung? Welche Einwilligungsform ist rechtssicher? | `contains_minors` + `parental_consent_confirmed` — Pflicht ab welcher Stufe? | Vor MVP |
|
||||
| 7.5 | Reicht eine **Selbsterklärung** des Uploaders oder müssen Einwilligungs-Dokumente (Scan, Upload) archiviert werden? | Dateiupload für Einwilligungs-Scan nötig? (MVP oder später?) | Vor MVP |
|
||||
| 7.6 | Ist eine **Batch-Deklaration** (eine Erklärung für mehrere Dateien des Uploads) rechtlich ausreichend? | Flow 3: Bulk-Upload-Design | Vor MVP |
|
||||
| 7.7 | Muss die **Textfassung** der Erklärungen (Checkbox-Labels) durch Rechtsanwalt freigegeben werden? Welche konkreten Formulierungen sind erforderlich? | `declaration_version` Textbasis | Vor MVP |
|
||||
| 7.8 | Wie sind **Altmedien** zu behandeln, die bereits mit club/official-Sichtbarkeit in der DB stehen? Muss der Betreiber diese sperren bis zur Nachdeklaration? | Migrationsstrategie §6.3 | Zeitnah |
|
||||
| 7.9 | Wie ist bei **Widerruf** einer Einwilligung vorzugehen? Welche Fristen gelten? Muss das Medium sofort gelöscht oder nur gesperrt werden? | rights_status='blocked', Schnittstelle P-11 | Vor P-11 |
|
||||
| 7.10 | Welche **Nachweisdaten** dürfen/sollen gespeichert werden (Datensparsamkeit vs. Rechenschaftspflicht)? Wie lange muss der Declaration-Log aufbewahrt werden? | Retention-Policy für `media_asset_rights_declarations` | Vor MVP |
|
||||
| 7.11 | Welche Anforderungen gelten für **Trainingsvideos mit mehreren Personen**? Muss jede Person einzeln einwilligen oder reicht eine kollektive Erklärung? | `person_consent_confirmed` als Boolean vs. Mehrfach-Einwilligung | Vor MVP |
|
||||
| 7.12 | Welche Anforderungen gelten für **Musik, Logos, Marken, Grafiken** von Dritten im Video/Bild? Ab wann ist eine separate Lizenz nötig? Reicht `music_rights_confirmed` als Selbsterklärung? | `contains_music`, `music_rights_confirmed` — MVP oder Pflicht? | Mittel |
|
||||
|
||||
---
|
||||
|
||||
## 8. Umsetzungsplan (für spätere Codephase — keine Umsetzungsfreigabe)
|
||||
|
||||
### P-06a – Datenmodell / Migration
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| **Ziel** | Neue Tabelle `media_asset_rights_declarations` anlegen; drei neue Spalten in `media_assets` |
|
||||
| **Betroffene Dateien** | `backend/migrations/048_media_rights_declarations.sql` (neu) |
|
||||
| **Migrationsbedarf** | Neue Migration; `DEFAULT 'legacy_unreviewed'` automatisch für bestehende Zeilen |
|
||||
| **Abhängigkeiten** | Keine (neue Tabelle) |
|
||||
| **Testbedarf** | Migration idempotent; bestehende `media_assets`-Zeilen haben `rights_status='legacy_unreviewed'` nach Migration; neue Zeilen haben `rights_status='declared'` nach P-06b |
|
||||
| **Akzeptanzkriterien** | Tabelle angelegt, alle Spalten korrekt typisiert, Indizes vorhanden, ALTER-Migration ohne Downtime anwendbar |
|
||||
| **Risiko** | Niedrig (neue Tabelle + ALTER mit DEFAULT ohne Table-Lock in PostgreSQL 16) |
|
||||
| **Rollback** | DROP TABLE media_asset_rights_declarations; ALTER TABLE media_assets DROP COLUMN rights_status, rights_declared_for_visibility, rights_declared_at |
|
||||
|
||||
---
|
||||
|
||||
### P-06b – Backend-Erzwingung
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| **Ziel** | Backend blockiert Upload und Promotion wenn Pflichtfelder fehlen; schreibt Declarations-Log |
|
||||
| **Betroffene Dateien** | `backend/routers/media_assets.py` (bulk-upload + patch + bulk-patch), `backend/routers/exercises.py` (upload_exercise_media, from-asset), neues Modul `backend/media_rights.py` (Hilfslogik) |
|
||||
| **Neue Pydantic-Models** | `RightsDeclaration` (Pflichtfelder + optionale Felder); Integration in `MediaAssetPatch` + Upload-Endpoints |
|
||||
| **Neue Fehlercodes** | `RIGHTS_DECLARATION_REQUIRED`, `CONSENT_REQUIRED_FOR_CLUB`, `CONSENT_REQUIRED_FOR_OFFICIAL`, `LEGACY_REDECLARATION_REQUIRED`, `RIGHTS_DECLARATION_REQUIRED_FOR_TARGET_VISIBILITY` |
|
||||
| **Abhängigkeiten** | P-06a (Migration) muss abgeschlossen sein |
|
||||
| **Testbedarf** | Unit-Tests für jeden neuen Fehlercode; Integrationstests Upload → Deklarationslog; Promotion ohne/mit Deklaration; Legacy-Block |
|
||||
| **Akzeptanzkriterien** | Upload ohne `rights_holder_confirmed` → 400; promotion ohne Personen-Deklaration → 400; gültige Deklaration → Eintrag in DB vorhanden; bestehender P-04-Test weiterhin grün |
|
||||
| **Risiko** | Mittel (Breaking Change für alle Upload-Clients); Feature-Flag zum schrittweisen Rollout empfohlen |
|
||||
| **Rollback** | Feature-Flag deaktivieren; kein DB-Rollback nötig |
|
||||
|
||||
---
|
||||
|
||||
### P-06c – Frontend-Dialoge
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| **Ziel** | Einwilligungsdialog in allen Upload-Pfaden; Promotions-Dialog bei Sichtbarkeitsänderung |
|
||||
| **Betroffene Dateien** | `frontend/src/components/RightsDeclarationDialog.jsx` (neu, wiederverwendbar), `frontend/src/pages/ExerciseFormPage.jsx`, `frontend/src/pages/MediaLibraryPage.jsx`, `frontend/src/utils/api.js` |
|
||||
| **Dialog-Typen** | Upload-Dialog (privat/club/official je nach Kontext), Promotions-Dialog (erkennt Sichtbarkeitserhöhung), Nachdeklarations-Dialog (für Legacy) |
|
||||
| **Abhängigkeiten** | P-06b (Backend-Codes müssen definiert sein); juristische Textfreigabe für Checkbox-Labels |
|
||||
| **Testbedarf** | Playwright E2E: Dialog erscheint; Upload ohne Checkbox → deaktivierter Button; Dialog mit allem ausgefüllt → erfolgreicher Upload; Backend-Fehler → korrekte Fehlermeldung |
|
||||
| **Akzeptanzkriterien** | Dialog erscheint bei allen Upload-Pfaden; Checkbox-State korrekt; Labels entsprechen juristisch geprüften Formulierungen; Promotions-Dialog erkennt Sichtbarkeitserhöhung |
|
||||
| **Risiko** | Mittel (UX-Änderung an häufig genutzten Pfaden) |
|
||||
| **Rollback** | Feature-Flag; Dialoge können ohne Backend-Änderung deaktiviert werden |
|
||||
|
||||
---
|
||||
|
||||
### P-06d – Tests / Dokumentation
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| **Ziel** | Vollständige Testabdeckung für P-06 + Doku-Update |
|
||||
| **Betroffene Dateien** | `backend/tests/test_media_rights_declaration.py` (neu), `tests/dev-smoke-test.spec.js` (neue P-06-Tests), `docs/compliance-implementation.md`, `docs/compliance-package-register.md`, Access-Layer-Audit aktualisieren |
|
||||
| **Backend-Tests** | Upload-Flows, Promotions-Flows, Legacy-Block, Declaration-Log, alle Fehlercodes |
|
||||
| **Playwright-Tests** | Dialog erscheint, Checkbox-Validierung, vollständiger Upload-Flow, Promotions-Dialog |
|
||||
| **Abhängigkeiten** | P-06a, P-06b, P-06c abgeschlossen |
|
||||
| **Akzeptanzkriterien** | Alle neuen Tests grün; bestehende Tests unverändert grün; ACCESS_LAYER_STRICT=1 grün |
|
||||
| **Risiko** | Niedrig |
|
||||
|
||||
---
|
||||
|
||||
### P-06e – Legacy-Nacharbeit (optional, nach juristischer Klärung)
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| **Ziel** | Massenprüfung und ggf. Sperrung bestehender club/official-Medien ohne Deklaration, falls juristisch notwendig |
|
||||
| **Betroffene Dateien** | `backend/scripts/media_rights_audit.py` (neu), evtl. Admin-UI |
|
||||
| **Inhalt** | Script listet alle `visibility IN ('club', 'official')` mit `rights_status='legacy_unreviewed'`; Superadmin kann Massenmarkierung oder individuelle Überprüfung anstoßen |
|
||||
| **Abhängigkeiten** | P-06a–d; juristische Klärung §7.8 |
|
||||
| **Akzeptanzkriterien** | Script läuft ohne Fehler; erzeugt CSV-Report mit betroffenen Assets |
|
||||
| **Risiko** | Mittel (wenn Sperrung aktiv: Betriebsunterbrechung für Vereinsmedien) |
|
||||
| **Hinweis** | Erst nach juristischer Entscheidung über Altbestand-Behandlung umsetzen |
|
||||
|
||||
---
|
||||
|
||||
## 9. Abschlussbewertung
|
||||
|
||||
### 9.1 Neue / geänderte Dokumente
|
||||
|
||||
| Dokument | Änderung |
|
||||
|----------|---------|
|
||||
| `docs/p06-upload-rights-spec.md` | Neu erstellt (dieses Dokument) |
|
||||
| `docs/compliance-roadmap.md` | P-06: Spezifikation erstellt vermerkt; nächste Freigabe angepasst |
|
||||
| `docs/compliance-implementation.md` | Kurzer P-06-Eintrag: Spezifikation erstellt, keine Umsetzung |
|
||||
| `docs/compliance-package-register.md` | P-06 Letzter Stand: Spezifikation vorhanden |
|
||||
|
||||
### 9.2 Empfohlene P-06-Zielarchitektur (Kurzfassung)
|
||||
|
||||
- **Append-only Log-Tabelle** `media_asset_rights_declarations` (Wer, Wann, Was, Welche Version)
|
||||
- **Drei Status-Felder** in `media_assets`: `rights_status` / `rights_declared_for_visibility` / `rights_declared_at`
|
||||
- **Gestufte Erklärungen**: Upload = Minimalset; Promotion club = Personen-Pflicht; Promotion official = vollständig
|
||||
- **Backend-Erzwingung** über neue Fehlercodes; keine reine Frontend-Checkbox
|
||||
- **Versionierung** über `declaration_version`-String; kein FK auf Texttabelle
|
||||
- **Legacy**: `rights_status = 'legacy_unreviewed'`; Promotion blockiert; Nachdeklarations-Flow
|
||||
|
||||
### 9.3 Kritische Designentscheidungen
|
||||
|
||||
| Entscheidung | Begründung |
|
||||
|-------------|-----------|
|
||||
| Gestufte Erklärungen je Sichtbarkeitsstufe | Rechtsrisiko steigt mit Sichtbarkeit; Rechtsanschlussfähigkeit |
|
||||
| Minimalset beim Erstupload | Nutzbarkeit vs. Compliance; Pflicht-Erweiterung bei Promotion |
|
||||
| Append-only Log (nie löschen/ändern) | Nachweisbarkeit; Audit-Integrität |
|
||||
| rights_status = 'legacy_unreviewed' per Default | Keine rückwirkende Sperrung; kontrollierbarer Übergang |
|
||||
| Kein Einwilligungs-Datei-Upload (MVP) | Aufwand vs. Mehrwert; spätere Nachrüstung möglich |
|
||||
| `rights_status = 'blocked'` als P-11-Schnittstelle | Zukunftssicherheit; P-11/P-13 können sofort anschließen |
|
||||
|
||||
### 9.4 Offene juristische Fragen (Priorisiert)
|
||||
|
||||
| Priorität | Frage | Paket-Impact |
|
||||
|-----------|-------|-------------|
|
||||
| Vor MVP | §7.7 Textfassung der Erklärungen | P-06c (Dialog-Labels) |
|
||||
| Vor MVP | §7.1 Private: Reicht rights_holder allein? | Pflichtfeld-Definition |
|
||||
| Vor MVP | §7.2 Club: § 22 KUG vereinsintern? | contains_persons bei club Pflicht? |
|
||||
| Vor MVP | §7.4 Minderjährige: Schwelle und Form | parental_consent MVP oder später |
|
||||
| Vor MVP | §7.5 Selbsterklärung oder Dokumenten-Upload? | Scope P-06c |
|
||||
| Zeitnah | §7.8 Altmedien club/official: Sperrpflicht? | P-06e Scope |
|
||||
| ~~Vor P-11~~ ✅ | §7.9 Widerruf: Fristen und Mechanismus | P-11 implementiert: `set_legal_hold()` als Sperrmechanismus; juristische Frist-Frage bleibt offen |
|
||||
| Mittel | §7.10 Aufbewahrung Declaration-Log | Retention-Policy |
|
||||
|
||||
### 9.5 Empfohlene spätere Umsetzungsschritte
|
||||
|
||||
1. Rechtsanwalt beauftragt für §7.7 (Texte) und §7.1–7.3 (Anforderungen je Stufe)
|
||||
2. Nach Klärung §7.7: Freigabe P-06a + P-06b parallel (kein Frontend-Merge nötig)
|
||||
3. Nach §7.7 Textfreigabe: Freigabe P-06c (Frontend-Dialoge)
|
||||
4. P-06d: Tests + Doku beim gleichen Merge wie P-06b/P-06c
|
||||
5. Nach §7.8-Klärung: ggf. P-06e (Legacy-Massenprüfung)
|
||||
|
||||
### 9.6 Implementierungsbereitschaft
|
||||
|
||||
| Kriterium | Einschätzung |
|
||||
|-----------|-------------|
|
||||
| P-06 implementierungsreif | Teilweise — Datenmodell und Backend-Logik spezifizierbar; Dialog-Labels nicht ohne juristische Textfreigabe |
|
||||
| Juristische Vorabklärung erforderlich | Ja — §7.7 (Textfassung) blockiert P-06c; §7.1–7.3 bestimmen Pflichtfelder |
|
||||
| P-06a (Migration) vorab umsetzbar | Ja — unabhängig von juristischen Texten |
|
||||
| P-06b (Backend) vorab umsetzbar | Ja — mit Platzhalter-Fehlercodes, Texte nachrüstbar |
|
||||
| P-06c (Frontend-Dialog) vorab umsetzbar | Nein — Dialog-Labels müssen juristisch freigegeben sein |
|
||||
|
||||
### 9.7 Scope-Drift-Prüfung (Stand nach vollständiger Umsetzung)
|
||||
|
||||
| Prüfung | Ergebnis |
|
||||
|---------|---------|
|
||||
| Codeänderungen vorgenommen? | Ja — P-06a–P-06d vollständig; P-06+ nachgezogen |
|
||||
| Neue Migrationen erstellt? | Ja — Migration 048 (Deklarations-Log + Schnellfelder) + Migration 049 (Kontext-Felder) + Migration 050 (Audit-Log + correction_note) |
|
||||
| Neue Endpoints erstellt? | Ja — 5 neue Endpoints (re-declaration, legacy-summary, legacy-assets, journal, correction) |
|
||||
| Paket-ID geändert? | Nein |
|
||||
| Andere Paket-IDs berührt? | Nein (P-11, P-13 nur als Referenz) |
|
||||
| P-06 bleibt nach dieser Arbeit offen? | Ja — technisch umgesetzt; KRIT-04 (juristische Validierung) bleibt offen |
|
||||
|
||||
---
|
||||
|
||||
**P-06 technisch umgesetzt (2026-05-11, v0.8.83). KRIT-04 bleibt bis juristische Validierung (§22 KUG, §8 DSGVO, Textfreigabe).**
|
||||
|
||||
---
|
||||
|
||||
## 10. Vorläufige Implementierungsannahmen (2026-05-11)
|
||||
|
||||
> **Wichtiger Hinweis:** Die folgenden Annahmen gelten als vorläufige Erstfassung. Sie wurden bewusst konservativ gewählt. Die juristische Validierung (insb. §7.1–§7.7 dieser Spec) steht weiterhin aus. Texte, Pflichtfelder und Stufenlogik können nach juristischer Prüfung gelockert oder präzisiert werden. P-06 gilt nach dieser technischen Umsetzung als **technisch umgesetzt unter vorläufigen Annahmen** — nicht als rechtlich endgültig abgeschlossen. KRIT-04 bleibt bis zur anwaltlichen Prüfung als rechtlicher Blocker offen.
|
||||
|
||||
### 10.1 Abweichung gegenüber ursprünglicher Matrix (§3)
|
||||
|
||||
Die Entscheidungsmatrix in §3 sah vor:
|
||||
- **private Upload:** Personenfragen optional
|
||||
- **club/official Upload:** Personenfragen Pflicht
|
||||
|
||||
**Geändert für conservative Erstannahme:**
|
||||
- Personenfragen sind bei **allen** Uploads (auch `private`) Pflicht zu beantworten
|
||||
- Begründung: lieber zunächst strenger und nach juristischer Klärung gezielt lockern; ein bereits gesammeltes „Nein, keine erkennbaren Personen" ist besser als gar kein Datenpunkt
|
||||
- Diese Verschärfung ist als `declaration_version = 'p06-v1-conservative'` dokumentiert
|
||||
- Spätere Lockerung auf `'p06-v1.1'` o. ä. möglich ohne Datenverlust
|
||||
|
||||
### 10.2 Verbindliche Erstannahmen
|
||||
|
||||
| Annahme | Technisch umgesetzt als |
|
||||
|---------|------------------------|
|
||||
| Jeder Upload (auch `private`) erfordert Rechteerklärung | `rights_holder_confirmed = true` Pflicht bei allen Uploads |
|
||||
| Personenfragen bei allen Uploads Pflicht | `contains_identifiable_persons` muss beantwortet sein |
|
||||
| Personeneinwilligung Pflicht wenn Personen vorhanden | `person_consent_confirmed = true` wenn `contains_identifiable_persons = true` |
|
||||
| Minderjährigenfrage bei allen Uploads Pflicht | `contains_minors` muss beantwortet sein |
|
||||
| Elterneinwilligung Pflicht wenn Minderjährige vorhanden | `parental_consent_confirmed = true` wenn `contains_minors = true` |
|
||||
| Musikfrage Pflicht | `contains_music` muss beantwortet sein |
|
||||
| Musikrechte Pflicht wenn Musik vorhanden | `music_rights_confirmed = true` wenn `contains_music = true` |
|
||||
| Fremdmaterial-Frage Pflicht | `contains_third_party_content` muss beantwortet sein |
|
||||
| Fremdmaterialrechte Pflicht wenn Fremdmaterial vorhanden | `third_party_rights_confirmed = true` wenn `contains_third_party_content = true` |
|
||||
| Erklärung gilt für konkrete Zielsichtbarkeit | `target_visibility` = `private` / `club` / `official` |
|
||||
| Promotion zu höherer Sichtbarkeit erfordert neue Erklärung | Backend blockiert ohne passende neue Declaration |
|
||||
| Altmedien bleiben sichtbar | `rights_status = 'legacy_unreviewed'` per Migration-Default |
|
||||
| Altmedien-Promotion blockiert | HTTP 400 `LEGACY_REDECLARATION_REQUIRED` |
|
||||
| Selbsterklärung genügt (MVP) | Kein Dokumenten-Upload erforderlich |
|
||||
| Deklarationsversion | `declaration_version = 'p06-v1-conservative'` |
|
||||
|
||||
### 10.3 Vorläufige Dialogtexte (Arbeitsfassung — juristisch nicht geprüft)
|
||||
|
||||
Die folgenden Texte sind Arbeitsfassungen und explizit als vorläufig zu behandeln. Sie werden in der UI mit einem entsprechenden Hinweis angezeigt. Alle Labels sind in der Frontend-Komponente zentral definiert und ohne Code-Änderung austauschbar.
|
||||
|
||||
| # | Label | Text (Vorläufig) |
|
||||
|---|-------|-----------------|
|
||||
| T1 | Rechteinhaber-Bestätigung | „Ich bestätige, dass ich berechtigt bin, dieses Medium hochzuladen und in der gewählten Sichtbarkeitsstufe zu verwenden, und dass ich über die dafür erforderlichen Rechte verfüge." |
|
||||
| T2 | Personen-Frage | „Sind auf diesem Medium Personen eindeutig erkennbar?" |
|
||||
| T3 | Personen-Einwilligung | „Ich bestätige, dass mir für alle erkennbaren Personen die für diese Nutzung erforderlichen Einwilligungen vorliegen." |
|
||||
| T4 | Minderjährigen-Frage | „Sind auf diesem Medium Minderjährige eindeutig erkennbar?" |
|
||||
| T5 | Minderjährigen-Einwilligung | „Ich bestätige, dass mir die für diese Nutzung erforderlichen Einwilligungen der Sorgeberechtigten vorliegen." |
|
||||
| T6 | Musik-Frage | „Enthält das Medium Musik?" |
|
||||
| T7 | Musik-Rechte | „Ich bestätige, dass ich für die enthaltene Musik die für diese Nutzung erforderlichen Rechte habe." |
|
||||
| T8 | Fremdmaterial-Frage | „Enthält das Medium Logos, Grafiken oder sonstige fremde geschützte Inhalte?" |
|
||||
| T9 | Fremdmaterial-Rechte | „Ich bestätige, dass ich für alle enthaltenen fremden Inhalte die für diese Nutzung erforderlichen Rechte habe." |
|
||||
| T10 | Hinweis | „Diese Erklärung wird protokolliert. Die konkrete rechtliche Ausgestaltung wird noch abschließend geprüft." |
|
||||
|
||||
### 10.4 Tatsächlich implementierte Endpunkte und Felder
|
||||
|
||||
**Migration 048:** `backend/migrations/048_media_rights_declarations.sql`
|
||||
- Neue Tabelle: `media_asset_rights_declarations` (append-only, alle Felder aus §4.1)
|
||||
- Neues Feld `rights_status` in `media_assets` (DEFAULT `'legacy_unreviewed'`)
|
||||
- Neues Feld `rights_declared_for_visibility` in `media_assets`
|
||||
- Neues Feld `rights_declared_at` in `media_assets`
|
||||
|
||||
**Neues Backend-Modul:** `backend/media_rights.py`
|
||||
- `VISIBILITY_LEVELS`: Hierarchie private(1) < club(2) < official(3)
|
||||
- `validate_rights_declaration()`: Prüft vollständige Deklaration je Sichtbarkeit
|
||||
- `check_rights_coverage()`: Prüft ob vorhandene Erklärung Zielsichtbarkeit abdeckt
|
||||
- `write_rights_declaration()`: Schreibt append-only Declaration-Log
|
||||
- `update_rights_quick_fields()`: Aktualisiert Schnellfelder in `media_assets`
|
||||
|
||||
**Angepasste Endpunkte:**
|
||||
| Endpunkt | Änderung |
|
||||
|----------|---------|
|
||||
| `POST /api/media-assets/bulk-upload` | P-06-Pflichtfelder als Form-Parameter; Declaration-Log bei Erfolg |
|
||||
| `PATCH /api/media-assets/{id}` | Rechte-Prüfung bei Promotion; Declaration-Log wenn neue Erklärung |
|
||||
| `POST /api/media-assets/bulk-patch` | Rechte-Prüfung bei Promotion per Asset |
|
||||
| `POST /api/exercises/{id}/media` | P-06-Pflichtfelder; Declaration-Log bei Datei-Upload |
|
||||
| `POST /api/exercises/{id}/media/from-asset` | `rights_status`-Prüfung des Assets gegen Übungssichtbarkeit |
|
||||
|
||||
**Neue Endpunkte (P-06b):**
|
||||
| Endpunkt | Beschreibung |
|
||||
|----------|-------------|
|
||||
| `POST /api/media-assets/{id}/rights-declarations` | Re-/Nachdeklaration für vorhandene Medien |
|
||||
| `GET /api/admin/media-rights/legacy-summary` | Auswertung `legacy_unreviewed` nach Sichtbarkeit |
|
||||
| `GET /api/admin/media-rights/legacy-assets` | Liste `legacy_unreviewed` club/official-Medien |
|
||||
|
||||
**Frontend-Komponente:**
|
||||
- `frontend/src/components/RightsDeclarationDialog.jsx` — wiederverwendbarer Dialog
|
||||
- Integration in `MediaLibraryPage.jsx` (Bulk-Upload) und `ExerciseFormPage.jsx` (Upload)
|
||||
|
||||
**Migration 049 (Kontext-Felder — ergänzend zu 048):**
|
||||
- `person_consent_context TEXT`, `parental_consent_context TEXT`, `music_rights_context TEXT`, `third_party_rights_context TEXT` — Freitextfelder für Einwilligungskontext (z. B. Einwilligungsreferenz, Datum, Beschreibung)
|
||||
|
||||
### 10.5 Juristische Restoffenheit
|
||||
|
||||
Folgende Punkte aus §7 sind technisch mit konservativer Annahme implementiert, aber rechtlich noch zu validieren:
|
||||
|
||||
| §7-Punkt | Konservative Annahme | Juristisch offen |
|
||||
|----------|---------------------|-----------------|
|
||||
| §7.1 private: Reicht rights_holder allein? | Nein — alle Fragen Pflicht | Ja |
|
||||
| §7.2 club: KUG vereinsintern? | Ja — volle Erklärung Pflicht | Ja |
|
||||
| §7.4 Minderjährige: Schwelle, Form? | Pflichtfeld ab Upload | Ja |
|
||||
| §7.5 Selbsterklärung genügt? | Ja (MVP) | Ja |
|
||||
| §7.6 Batch-Deklaration genügend? | Ja — eine Erklärung gilt für alle Batch-Dateien | Ja |
|
||||
| §7.7 Textfassung der Erklärungen | Vorläufige Arbeitsfassung (T1–T10) | Ja — anwaltliche Freigabe nötig |
|
||||
| §7.10 Aufbewahrung Declaration-Log | `ON DELETE SET NULL` für declared_by; CASCADE auf media_asset_id | Ja |
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 11. P-06+ Erweiterungen: Volljournal + Korrektur (2026-05-11, v0.8.82–0.8.83)
|
||||
|
||||
> Diese Erweiterungen gehen über die ursprüngliche P-06-Spezifikation (§8) hinaus und wurden in der Implementierungsphase ergänzt, da das Volljournal und die Korrekturfähigkeit als notwendige Bestandteile eines nachweisfähigen Einwilligungs-Systems erkannt wurden.
|
||||
|
||||
### 11.1 Motivation
|
||||
|
||||
Die ursprüngliche P-06-Spezifikation sah einen append-only Deklarations-Log vor (§4.1, Entscheidung 4). Nicht explizit geplant war:
|
||||
- Protokollierung von Nicht-Deklarations-Änderungen (Sichtbarkeit, Copyright, Lifecycle)
|
||||
- Eine einheitliche chronologische Ansicht aller Ereignisse zu einem Asset
|
||||
- Die Möglichkeit, abgegebene Deklarationen mit Begründung nachträglich zu korrigieren (bei Irrtum oder Widerruf)
|
||||
|
||||
### 11.2 Migration 050: Vollständiger Audit-Log
|
||||
|
||||
**Datei:** `backend/migrations/050_media_audit_log.sql`
|
||||
|
||||
**Neue Tabelle `media_asset_audit_log`:**
|
||||
|
||||
```sql
|
||||
CREATE TABLE media_asset_audit_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||
acting_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
event_type VARCHAR(50) NOT NULL
|
||||
CHECK (event_type IN (
|
||||
'visibility_change',
|
||||
'copyright_change',
|
||||
'metadata_change',
|
||||
'lifecycle_change'
|
||||
)),
|
||||
old_values JSONB,
|
||||
new_values JSONB
|
||||
);
|
||||
```
|
||||
|
||||
Append-only. Wird nie geändert oder gelöscht (außer ON DELETE CASCADE des Assets).
|
||||
|
||||
**Neue Spalte `correction_note`** in `media_asset_rights_declarations`:
|
||||
```sql
|
||||
ALTER TABLE media_asset_rights_declarations
|
||||
ADD COLUMN IF NOT EXISTS correction_note TEXT;
|
||||
```
|
||||
|
||||
**Erweiterter CHECK** in `media_asset_rights_declarations`:
|
||||
- `action_type` nimmt jetzt auch `'correction'` an (zusätzlich zu upload, promote_club, promote_official, re_declaration, legacy_re_declaration)
|
||||
|
||||
### 11.3 Neue Backend-Funktionen (`backend/media_rights.py`)
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
|----------|-------------|
|
||||
| `write_audit_log_entry(cur, asset_id, acting_profile_id, event_type, old_values, new_values)` | Schreibt einen Eintrag in `media_asset_audit_log` (JSONB-serialisiert) |
|
||||
| `write_rights_correction_declaration(cur, asset_id, profile_id, target_visibility, decl, correction_note)` | Schreibt action_type='correction' in `media_asset_rights_declarations` |
|
||||
|
||||
### 11.4 Neue Endpoints (`backend/routers/media_assets.py`)
|
||||
|
||||
| Endpoint | Auth | Beschreibung |
|
||||
|----------|------|-------------|
|
||||
| `GET /api/admin/media-rights/assets/{id}/journal` | Superadmin / Uploader / Vereins-Admin | Vollständiges Medien-Journal: Deklarationen + Audit-Ereignisse chronologisch gemischt (`events[]` mit `kind='declaration'` oder `kind='audit'`). Gibt auch `can_correct` zurück. |
|
||||
| `POST /api/admin/media-rights/assets/{id}/correction` | Superadmin / Uploader / Vereins-Admin | Korrektur-Deklaration einreichen (append-only, neueste gilt). Felder identisch mit P-06-Dialog + `correction_note`. |
|
||||
|
||||
**Journal-Response-Format:**
|
||||
```json
|
||||
{
|
||||
"asset": { "id": 57, "original_filename": "...", "visibility": "club", ... },
|
||||
"events": [
|
||||
{
|
||||
"kind": "declaration",
|
||||
"id": 12,
|
||||
"at": "2026-05-11T10:00:00Z",
|
||||
"action_type": "upload",
|
||||
"target_visibility": "private",
|
||||
"rights_holder_confirmed": true,
|
||||
"contains_identifiable_persons": false,
|
||||
"correction_note": null,
|
||||
"declared_by_name": "Lars",
|
||||
"declared_by_email": "stommer@gmail.com"
|
||||
},
|
||||
{
|
||||
"kind": "audit",
|
||||
"id": 3,
|
||||
"at": "2026-05-11T11:00:00Z",
|
||||
"event_type": "visibility_change",
|
||||
"old_values": {"visibility": "private", "club_id": null},
|
||||
"new_values": {"visibility": "club", "club_id": 2},
|
||||
"acting_name": "Lars"
|
||||
}
|
||||
],
|
||||
"can_correct": true
|
||||
}
|
||||
```
|
||||
|
||||
### 11.5 Automatische Audit-Log-Einträge
|
||||
|
||||
| Aktion | event_type | Auslöser |
|
||||
|--------|-----------|----------|
|
||||
| Sichtbarkeitsänderung via PATCH | `visibility_change` | `PATCH /api/media-assets/{id}` wenn `visibility` oder `club_id` sich ändert |
|
||||
| Copyright-Änderung via PATCH | `copyright_change` | `PATCH /api/media-assets/{id}` wenn `copyright_notice` sich ändert |
|
||||
| Metadaten-Änderung (Dateiname etc.) | `metadata_change` | `PATCH /api/media-assets/{id}` wenn `original_filename` etc. sich ändert |
|
||||
| Lifecycle-Übergang | `lifecycle_change` | `_apply_lifecycle_action`: trash_soft, trash_hidden, recover, reactivate (nicht bei Hard-Delete oder Purge) |
|
||||
|
||||
### 11.6 Frontend-Erweiterungen (`MediaLibraryPage.jsx`)
|
||||
|
||||
- **Unified Journal Modal:** Journal-Ansicht zeigt `events[]` chronologisch. Deklarationseinträge und Audit-Einträge visuell unterschieden (`--audit` CSS-Modifier).
|
||||
- **Korrektur-Formular:** Inline-Formular im Journal-Modal. Erscheint wenn `can_correct = true` und Nutzer „Korrektur erfassen" klickt. Enthält alle P-06-Felder + `correction_note` Freitextfeld.
|
||||
- **Neue `api.js`-Funktion:** `addMediaAssetDeclarationCorrection(assetId, body)` — POST auf Korrektur-Endpoint.
|
||||
|
||||
### 11.7 Zugriffsmodell
|
||||
|
||||
Journal und Korrektur sind **nicht** auf Superadmin beschränkt — bewusste Entscheidung:
|
||||
|
||||
| Rolle | Zugang Journal | Zugang Korrektur |
|
||||
|-------|---------------|-----------------|
|
||||
| Superadmin | ✅ | ✅ |
|
||||
| Uploader (ursprünglicher Upload) | ✅ | ✅ |
|
||||
| Vereins-Admin (bei club-Medien) | ✅ | ✅ |
|
||||
| Andere | ❌ 403 | ❌ 403 |
|
||||
|
||||
Club-Admin-Prüfung erfolgt über `has_club_role(cur, profile_id, club_id, "club_admin")` (Tabelle `club_member_roles`), nicht über direktes `role`-Feld in `club_members`.
|
||||
|
||||
### 11.8 Bugfixes (2026-05-11)
|
||||
|
||||
| Bug | Ursache | Fix |
|
||||
|-----|---------|-----|
|
||||
| Journal und Korrektur gaben 500 zurück | Club-Admin-Prüfung nutzte `AND role = 'admin'` auf `club_members` — diese Spalte existiert dort nicht; Rollen liegen in `club_member_roles` | Ersetzt durch `has_club_role(cur, profile_id, club_id, "club_admin")` |
|
||||
| Frontend-Build-Fehler nach Duplikat `lcLabel` | Funktion `lcLabel` wurde doppelt deklariert (bei Zeile 98 und 264) | Duplikat bei Zeile 264 entfernt |
|
||||
|
||||
### 11.9 Juristische Erweiterungsfragen
|
||||
|
||||
Die Korrekturfähigkeit von Deklarationen wirft zusätzliche juristische Fragen auf:
|
||||
|
||||
| Frage | Technisches Verhalten | Juristisch zu prüfen |
|
||||
|-------|----------------------|---------------------|
|
||||
| Wie lange ist eine Korrektur zulässig? | Kein zeitliches Limit implementiert | Fristenregelung? |
|
||||
| Wer darf eine Korrektur einreichen? | Superadmin, Uploader, Vereins-Admin | Nur Uploader? |
|
||||
| Gilt die neueste Korrektur immer als maßgeblich? | Ja — `rights_declared_for_visibility` wird aktualisiert | Ja, solange append-only |
|
||||
| Muss eine Korrektur begründet werden? | `correction_note` optional, nicht Pflicht | Pflichtfeld? |
|
||||
|
||||
---
|
||||
|
||||
*Erstellt: 2026-05-10 | Implementierungsannahmen hinzugefügt: 2026-05-11 | P-06+ Volljournal + Korrektur: 2026-05-11 (v0.8.82–0.8.83) | Autor: Claude Code | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
|
||||
@@ -8,10 +8,15 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.13.24",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^0.344.0",
|
||||
"marked": "^18.0.3",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.22.0"
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^6.22.0",
|
||||
"remark-breaks": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
|
||||
+161
-113
@@ -1,51 +1,77 @@
|
||||
import React from 'react'
|
||||
import React, { Suspense, lazy } from 'react'
|
||||
import {
|
||||
BrowserRouter as Router,
|
||||
Routes,
|
||||
Route,
|
||||
RouterProvider,
|
||||
createBrowserRouter,
|
||||
Navigate,
|
||||
NavLink,
|
||||
useLocation,
|
||||
Outlet,
|
||||
} from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||
import { ToastProvider } from './context/ToastContext'
|
||||
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
||||
import DesktopSidebar from './components/DesktopSidebar'
|
||||
import { getMainNavItems } from './config/appNav'
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import VerifyPage from './pages/VerifyPage'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import AccountSettingsPage from './pages/AccountSettingsPage'
|
||||
import SettingsSystemInfoPage from './pages/SettingsSystemInfoPage'
|
||||
import ExercisesListPage from './pages/ExercisesListPage'
|
||||
import ExerciseDetailPage from './pages/ExerciseDetailPage'
|
||||
import ExerciseFormPage from './pages/ExerciseFormPage'
|
||||
import ClubsPage from './pages/ClubsPage'
|
||||
import InboxPage from './pages/InboxPage'
|
||||
import SkillsPage from './pages/SkillsPage'
|
||||
import TrainingPlanningPage from './pages/TrainingPlanningPage'
|
||||
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
|
||||
import TrainingFrameworkProgramEditPage from './pages/TrainingFrameworkProgramEditPage'
|
||||
import TrainingUnitRunPage from './pages/TrainingUnitRunPage'
|
||||
import TrainingCoachPage from './pages/TrainingCoachPage'
|
||||
import AdminCatalogsPage from './pages/AdminCatalogsPage'
|
||||
import AdminHierarchyPage from './pages/AdminHierarchyPage'
|
||||
import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
|
||||
import TrainerContextsPage from './pages/TrainerContextsPage'
|
||||
import MediaWikiImportPage from './pages/MediaWikiImportPage'
|
||||
import AdminUsersPage from './pages/AdminUsersPage'
|
||||
import AdminHomeRedirect from './components/AdminHomeRedirect'
|
||||
import PlatformAdminRoute from './components/PlatformAdminRoute'
|
||||
import MediaLibraryPage from './pages/MediaLibraryPage'
|
||||
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
||||
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
|
||||
import './app.css'
|
||||
|
||||
const LoginPage = lazy(() => import('./pages/LoginPage'))
|
||||
const VerifyPage = lazy(() => import('./pages/VerifyPage'))
|
||||
const Dashboard = lazy(() => import('./pages/Dashboard'))
|
||||
const AccountSettingsPage = lazy(() => import('./pages/AccountSettingsPage'))
|
||||
const SettingsSystemInfoPage = lazy(() => import('./pages/SettingsSystemInfoPage'))
|
||||
const ExercisesListPage = lazy(() => import('./pages/ExercisesListPage'))
|
||||
const ExerciseDetailPage = lazy(() => import('./pages/ExerciseDetailPage'))
|
||||
const ExerciseFormPage = lazy(() => import('./pages/ExerciseFormPage'))
|
||||
const ClubsPage = lazy(() => import('./pages/ClubsPage'))
|
||||
const InboxPage = lazy(() => import('./pages/InboxPage'))
|
||||
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
|
||||
const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
|
||||
const TrainingFrameworkProgramsListPage = lazy(() =>
|
||||
import('./pages/TrainingFrameworkProgramsListPage'),
|
||||
)
|
||||
const TrainingFrameworkProgramEditPage = lazy(() =>
|
||||
import('./pages/TrainingFrameworkProgramEditPage'),
|
||||
)
|
||||
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
|
||||
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
|
||||
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
|
||||
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
|
||||
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
|
||||
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
|
||||
const AdminMaturityModelsPage = lazy(() => import('./pages/AdminMaturityModelsPage'))
|
||||
const TrainerContextsPage = lazy(() => import('./pages/TrainerContextsPage'))
|
||||
const MediaWikiImportPage = lazy(() => import('./pages/MediaWikiImportPage'))
|
||||
const AdminUsersPage = lazy(() => import('./pages/AdminUsersPage'))
|
||||
const MediaLibraryPage = lazy(() => import('./pages/MediaLibraryPage'))
|
||||
const LegalPage = lazy(() => import('./pages/LegalPage'))
|
||||
const AdminLegalDocumentsPage = lazy(() => import('./pages/AdminLegalDocumentsPage'))
|
||||
const SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
|
||||
|
||||
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||
function computeShowAdminNav(currentUser) {
|
||||
return currentUser?.role === 'superadmin'
|
||||
}
|
||||
|
||||
function AppRouteFallback() {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg)',
|
||||
}}
|
||||
>
|
||||
<div className="spinner"></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Bottom Navigation (Mobile)
|
||||
function Nav({ showAdminNav }) {
|
||||
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||
@@ -157,96 +183,118 @@ function PublicRoute({ children }) {
|
||||
return !isAuthenticated ? children : <Navigate to="/" replace />
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/verify" element={<VerifyPage />} />
|
||||
|
||||
<Route
|
||||
path="/login"
|
||||
element={
|
||||
<PublicRoute>
|
||||
<LoginPage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route element={<ProtectedLayout />}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="profile" element={<Navigate to="/settings" replace />} />
|
||||
<Route path="settings" element={<AccountSettingsPage />} />
|
||||
<Route path="settings/system" element={<SettingsSystemInfoPage />} />
|
||||
<Route path="media" element={<MediaLibraryPage />} />
|
||||
<Route path="exercises">
|
||||
<Route index element={<ExercisesListPage />} />
|
||||
<Route path="new" element={<ExerciseFormPage />} />
|
||||
<Route path=":id/edit" element={<ExerciseFormPage />} />
|
||||
<Route path=":id" element={<ExerciseDetailPage />} />
|
||||
</Route>
|
||||
<Route path="clubs" element={<ClubsPage />} />
|
||||
<Route path="inbox" element={<InboxPage />} />
|
||||
<Route path="skills" element={<SkillsPage />} />
|
||||
<Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
|
||||
<Route path="planning/framework-programs/:id" element={<TrainingFrameworkProgramEditPage />} />
|
||||
<Route path="planning/framework-programs" element={<TrainingFrameworkProgramsListPage />} />
|
||||
<Route path="planning/run/:unitId/coach" element={<TrainingCoachPage />} />
|
||||
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
|
||||
<Route path="planning" element={<TrainingPlanningPage />} />
|
||||
<Route path="admin" element={<AdminHomeRedirect />} />
|
||||
<Route
|
||||
path="admin/users"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminUsersPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/hierarchy"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminHierarchyPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/maturity-models"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminMaturityModelsPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/catalogs"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminCatalogsPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/mediawiki-import"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<MediaWikiImportPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="trainer-contexts" element={<TrainerContextsPage />} />
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
/**
|
||||
* Data Router — erforderlich für `useBlocker` (ungespeicherte Änderungen).
|
||||
* Klassisches `BrowserRouter` stellt keinen DataRouterContext bereit; ohne Migration
|
||||
* werfen Seiten mit `useUnsavedChangesBlocker` beim Rendern eine Invariante.
|
||||
*/
|
||||
const appRouter = createBrowserRouter([
|
||||
{ path: '/verify', element: <VerifyPage /> },
|
||||
{
|
||||
path: '/login',
|
||||
element: (
|
||||
<PublicRoute>
|
||||
<LoginPage />
|
||||
</PublicRoute>
|
||||
),
|
||||
},
|
||||
{ path: '/impressum', element: <LegalPage type="impressum" /> },
|
||||
{ path: '/datenschutz', element: <LegalPage type="datenschutz" /> },
|
||||
{ path: '/nutzungsbedingungen', element: <LegalPage type="nutzungsbedingungen" /> },
|
||||
{ path: '/medienrichtlinie', element: <LegalPage type="medienrichtlinie" /> },
|
||||
{
|
||||
element: <ProtectedLayout />,
|
||||
children: [
|
||||
{ index: true, element: <Dashboard /> },
|
||||
{ path: 'profile', element: <Navigate to="/settings" replace /> },
|
||||
{ path: 'settings', element: <AccountSettingsPage /> },
|
||||
{ path: 'settings/system', element: <SettingsSystemInfoPage /> },
|
||||
{ path: 'settings/legal', element: <SettingsLegalPage /> },
|
||||
{ path: 'media', element: <MediaLibraryPage /> },
|
||||
{
|
||||
path: 'exercises',
|
||||
children: [
|
||||
{ index: true, element: <ExercisesListPage /> },
|
||||
{ path: 'new', element: <ExerciseFormPage /> },
|
||||
{ path: ':id/edit', element: <ExerciseFormPage /> },
|
||||
{ path: ':id', element: <ExerciseDetailPage /> },
|
||||
],
|
||||
},
|
||||
{ path: 'clubs', element: <ClubsPage /> },
|
||||
{ path: 'inbox', element: <InboxPage /> },
|
||||
{ path: 'skills', element: <SkillsPage /> },
|
||||
{ path: 'planning/framework-programs/new', element: <TrainingFrameworkProgramEditPage /> },
|
||||
{ path: 'planning/framework-programs/:id', element: <TrainingFrameworkProgramEditPage /> },
|
||||
{ path: 'planning/framework-programs', element: <TrainingFrameworkProgramsListPage /> },
|
||||
{ path: 'planning/training-modules/new', element: <TrainingModuleEditPage /> },
|
||||
{ path: 'planning/training-modules/:id', element: <TrainingModuleEditPage /> },
|
||||
{ path: 'planning/training-modules', element: <TrainingModulesListPage /> },
|
||||
{ path: 'planning/run/:unitId/coach', element: <TrainingCoachPage /> },
|
||||
{ path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
|
||||
{ path: 'planning', element: <TrainingPlanningPage /> },
|
||||
{ path: 'admin', element: <AdminHomeRedirect /> },
|
||||
{
|
||||
path: 'admin/users',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminUsersPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/hierarchy',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminHierarchyPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/maturity-models',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminMaturityModelsPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/catalogs',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminCatalogsPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/mediawiki-import',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<MediaWikiImportPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/legal-documents',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminLegalDocumentsPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{ path: 'trainer-contexts', element: <TrainerContextsPage /> },
|
||||
],
|
||||
},
|
||||
{ path: '*', element: <Navigate to="/" replace /> },
|
||||
])
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Router>
|
||||
<AppRoutes />
|
||||
</Router>
|
||||
<ToastProvider>
|
||||
<Suspense fallback={<AppRouteFallback />}>
|
||||
<RouterProvider router={appRouter} />
|
||||
</Suspense>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* HTTP-Client: Token, Mandanten-Header, Fehler-Mapping.
|
||||
* Alle API-Aufrufe laufen über request() — siehe utils/api.js (Facade) und Domänenmodule (planning.js, exercises.js).
|
||||
*/
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
/** LocalStorage + Request-Header für Mandanten-Kontext */
|
||||
export const ACTIVE_CLUB_STORAGE_KEY = 'shinkan_active_club_id'
|
||||
|
||||
export function mergeActiveClubHeader(headers = {}) {
|
||||
const cid = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
if (cid && /^\d+$/.test(String(cid).trim())) {
|
||||
return { ...headers, 'X-Active-Club-Id': String(cid).trim() }
|
||||
}
|
||||
return { ...headers }
|
||||
}
|
||||
|
||||
/**
|
||||
* Generischer API-Aufruf inkl. X-Auth-Token und X-Active-Club-Id.
|
||||
*/
|
||||
export async function request(endpoint, options = {}) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
|
||||
const headers = mergeActiveClubHeader({
|
||||
...options.headers,
|
||||
})
|
||||
if (method !== 'GET' && method !== 'HEAD') {
|
||||
if (!headers['Content-Type'] && !headers['content-type']) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['X-Auth-Token'] = token
|
||||
}
|
||||
|
||||
const url = `${API_URL}${endpoint}`
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const d = parsed.detail
|
||||
throw new Error(typeof d === 'string' ? d : JSON.stringify(d))
|
||||
}
|
||||
if (response.status === 502) {
|
||||
throw new Error(
|
||||
'HTTP 502 (Bad Gateway): Der Reverse-Proxy hat die API nicht korrekt erreicht. Ist `shinkan-api` aktiv (`docker compose ps`, `docker logs shinkan-api`)? Bei Host-Routing nur einen Weg verwenden — alles auf Port 3003 (Nginx nach `backend:8000`) oder sauber `/api` → Backend-Port.'
|
||||
)
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError && (e.message === 'Failed to fetch' || e.message.includes('fetch'))) {
|
||||
const hint =
|
||||
API_URL && API_URL.length > 0
|
||||
? `Verbindung zum API unter ${API_URL} fehlgeschlagen. Läuft das Backend (z. B. Port 8098) und ist CORS erlaubt?`
|
||||
: 'Kein VITE_API_URL gesetzt: Anfragen gehen an die Frontend-URL und schlagen oft fehl. Setze in .env z. B. VITE_API_URL=http://localhost:8098 und starte Vite neu.'
|
||||
throw new Error(`${hint} [Technisch: ${e.message}; URL war ${endpoint}]`)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
/**
|
||||
* Übungen: Liste/CRUD, Medien & Archiv-Anbindung, Progressionsgraphen, KI-Hilfen.
|
||||
*/
|
||||
|
||||
import { stripHtmlToText } from '../utils/htmlUtils'
|
||||
import { normalizeAdvanceMode, parseComboRepSeriesCountUi } from '../utils/combinationMethodProfileUi'
|
||||
import { request, API_URL, ACTIVE_CLUB_STORAGE_KEY } from './client.js'
|
||||
|
||||
/** Wie `mergeActiveClubHeader` in client.js — lokal, damit Raw-`fetch`-Pfade nicht von einem Namensimport abhängen. */
|
||||
function withActiveClubHeaders(headers = {}) {
|
||||
const cid = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
if (cid && /^\d+$/.test(String(cid).trim())) {
|
||||
return { ...headers, 'X-Active-Club-Id': String(cid).trim() }
|
||||
}
|
||||
return { ...headers }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Exercises
|
||||
// ============================================================================
|
||||
|
||||
export async function listExercises(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
Object.entries(filters).forEach(([k, v]) => {
|
||||
if (v === undefined || v === null) return
|
||||
if (typeof v === 'boolean') {
|
||||
q.set(k, v ? 'true' : 'false')
|
||||
return
|
||||
}
|
||||
if (Array.isArray(v)) {
|
||||
if (v.length === 0) return
|
||||
v.forEach((item) => {
|
||||
if (item !== '' && item !== undefined && item !== null && String(item).trim() !== '') {
|
||||
q.append(k, String(item))
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
if (String(v).trim() !== '') q.set(k, String(v))
|
||||
})
|
||||
const query = q.toString()
|
||||
return request(`/api/exercises${query ? '?' + query : ''}`)
|
||||
}
|
||||
|
||||
/** Formular → API-Body (M:N gemäß EXERCISES_API_SPEC + training_types) */
|
||||
export function buildExerciseApiPayload(formData, extras = {}) {
|
||||
const num = (v) => (v === '' || v == null ? null : Number(v))
|
||||
|
||||
const goalHtml = formData.goal || ''
|
||||
const execHtml = formData.execution || ''
|
||||
const goalText = stripHtmlToText(goalHtml)
|
||||
const execText = stripHtmlToText(execHtml)
|
||||
|
||||
if (!goalText && !execText) {
|
||||
throw new Error('Ziel oder Durchführung ausfüllen (mindestens eines, auch mit Formatierung).')
|
||||
}
|
||||
|
||||
const mapFocus = (formData.focus_areas_multi || [])
|
||||
.filter((x) => x && x.focus_area_id)
|
||||
.map((x) => ({ focus_area_id: Number(x.focus_area_id), is_primary: !!x.is_primary }))
|
||||
const mapStyles = (formData.training_styles_multi || [])
|
||||
.filter((x) => x && x.training_style_id)
|
||||
.map((x) => ({ training_style_id: Number(x.training_style_id), is_primary: !!x.is_primary }))
|
||||
const mapTTypes = (formData.training_types_multi || [])
|
||||
.filter((x) => x && x.training_type_id)
|
||||
.map((x) => ({ training_type_id: Number(x.training_type_id), is_primary: !!x.is_primary }))
|
||||
const mapTg = (formData.target_groups_multi || [])
|
||||
.filter((x) => x && x.target_group_id)
|
||||
.map((x) => ({ target_group_id: Number(x.target_group_id), is_primary: !!x.is_primary }))
|
||||
|
||||
const visibilityNorm = String(formData.visibility || 'private').trim().toLowerCase()
|
||||
|
||||
const payload = {
|
||||
title: (formData.title || '').trim(),
|
||||
summary: formData.summary || null,
|
||||
goal: goalHtml.trim() ? goalHtml : null,
|
||||
execution: execHtml.trim() ? execHtml : null,
|
||||
preparation: formData.preparation || null,
|
||||
trainer_notes: formData.trainer_notes || null,
|
||||
duration_min: num(formData.duration_min),
|
||||
duration_max: num(formData.duration_max),
|
||||
group_size_min: num(formData.group_size_min),
|
||||
group_size_max: num(formData.group_size_max),
|
||||
equipment: Array.isArray(formData.equipment) ? formData.equipment : [],
|
||||
focus_areas_multi: mapFocus,
|
||||
training_styles_multi: mapStyles,
|
||||
training_types_multi: mapTTypes,
|
||||
target_groups_multi: mapTg,
|
||||
age_groups: [],
|
||||
skills: (formData.skills || []).map((s) => ({
|
||||
skill_id: s.skill_id,
|
||||
is_primary: !!s.is_primary,
|
||||
intensity: s.intensity || null,
|
||||
required_level: s.required_level || null,
|
||||
target_level: s.target_level || null,
|
||||
})),
|
||||
visibility: visibilityNorm,
|
||||
status: formData.status || 'draft',
|
||||
club_id: visibilityNorm === 'club' ? num(formData.club_id) : null,
|
||||
exercise_kind:
|
||||
String(formData.exercise_kind || 'simple').toLowerCase() === 'combination'
|
||||
? 'combination'
|
||||
: 'simple',
|
||||
...extras,
|
||||
}
|
||||
|
||||
const isCombo = payload.exercise_kind === 'combination'
|
||||
|
||||
if (isCombo) {
|
||||
let mpObj = {}
|
||||
const mpRaw = typeof formData.method_profile_json === 'string' ? formData.method_profile_json.trim() : ''
|
||||
if (mpRaw) {
|
||||
try {
|
||||
const parsed = JSON.parse(mpRaw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('Ablaufprofil muss ein JSON-Objekt sein.')
|
||||
}
|
||||
mpObj = parsed
|
||||
} catch (e) {
|
||||
if (e instanceof SyntaxError) {
|
||||
throw new Error('Ablaufprofil (JSON): Syntax ungültig.')
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const slotRows = Array.isArray(formData.combination_slots) ? formData.combination_slots : []
|
||||
const combination_slots = []
|
||||
|
||||
function parseTimingField(raw) {
|
||||
if (raw === '' || raw == null || raw === undefined) return undefined
|
||||
const n = parseInt(String(raw), 10)
|
||||
return Number.isFinite(n) ? n : undefined
|
||||
}
|
||||
|
||||
for (let i = 0; i < slotRows.length; i += 1) {
|
||||
const row = slotRows[i] || {}
|
||||
let ids = Array.isArray(row.candidate_exercise_ids)
|
||||
? row.candidate_exercise_ids.map((x) => Number(x)).filter((n) => Number.isFinite(n))
|
||||
: []
|
||||
|
||||
/** Legacy: noch idsText Unterstützung für Import von älteren FormStand */
|
||||
if ((!ids || ids.length === 0) && typeof row.idsText === 'string' && row.idsText.trim()) {
|
||||
ids = row.idsText
|
||||
.split(/[\s,;]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((s) => parseInt(s, 10))
|
||||
.filter((n) => Number.isFinite(n))
|
||||
}
|
||||
|
||||
combination_slots.push({
|
||||
slot_index: i,
|
||||
title: (typeof row.title === 'string' && row.title.trim()) || null,
|
||||
candidate_exercise_ids: ids,
|
||||
})
|
||||
}
|
||||
|
||||
const slot_profiles_v1_next = []
|
||||
for (let i = 0; i < slotRows.length; i += 1) {
|
||||
const row = slotRows[i] || {}
|
||||
const o = { slot_index: i }
|
||||
const advanceMode = normalizeAdvanceMode(row.advance_mode)
|
||||
if (advanceMode !== 'timed') o.advance_mode = advanceMode
|
||||
const load = parseTimingField(row.load_sec)
|
||||
const crs = parseTimingField(row.consecutive_reps)
|
||||
const rsc = parseTimingField(row.rep_series_count)
|
||||
const intra = parseTimingField(row.intra_rep_rest_sec)
|
||||
const tran = parseTimingField(row.transition_after_sec)
|
||||
const serienUi = parseComboRepSeriesCountUi(row.rep_series_count)
|
||||
const allowInterSeriesPause =
|
||||
advanceMode === 'timed' ||
|
||||
((advanceMode === 'rep' || advanceMode === 'manual') && serienUi >= 2)
|
||||
|
||||
if (advanceMode === 'timed' && load !== undefined && load >= 0) o.load_sec = Math.round(load)
|
||||
if (crs !== undefined && crs >= 1) o.consecutive_reps = Math.round(crs)
|
||||
if (
|
||||
rsc !== undefined &&
|
||||
rsc >= 1 &&
|
||||
(advanceMode === 'rep' || advanceMode === 'manual')
|
||||
) {
|
||||
o.rep_series_count = Math.round(rsc)
|
||||
}
|
||||
if (intra !== undefined && intra >= 0 && allowInterSeriesPause) o.intra_rep_rest_sec = Math.round(intra)
|
||||
if (tran !== undefined && tran >= 0) o.transition_after_sec = Math.round(tran)
|
||||
if (Object.keys(o).length > 1) slot_profiles_v1_next.push(o)
|
||||
}
|
||||
|
||||
payload.method_archetype = (formData.method_archetype || '').trim() || null
|
||||
if (slot_profiles_v1_next.length > 0) mpObj.slot_profiles_v1 = slot_profiles_v1_next
|
||||
else delete mpObj.slot_profiles_v1
|
||||
payload.method_profile = mpObj
|
||||
payload.combination_slots = combination_slots
|
||||
} else {
|
||||
payload.method_archetype = null
|
||||
payload.method_profile = {}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
export async function uploadExerciseMedia(exerciseId, formData) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({})
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const response = await fetch(`${API_URL}/api/exercises/${exerciseId}/media`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const d = parsed?.detail
|
||||
if (
|
||||
response.status === 409 &&
|
||||
d &&
|
||||
typeof d === 'object' &&
|
||||
!Array.isArray(d) &&
|
||||
typeof d.code === 'string'
|
||||
) {
|
||||
const e = new Error(
|
||||
typeof d.message === 'string' ? d.message : 'Upload konnte nicht verarbeitet werden',
|
||||
)
|
||||
e.code = d.code
|
||||
e.status = 409
|
||||
e.payload = d
|
||||
throw e
|
||||
}
|
||||
if (response.status === 413) {
|
||||
const nginx = (text || '').toLowerCase().includes('nginx')
|
||||
throw new Error(
|
||||
nginx
|
||||
? 'Die Anfrage ist zu groß (413). Häufig: nginx „client_max_body_size“ — z. B. große/r mehrere Videos oder Bulk-Upload. Dateien kleiner aufteilen oder Server-Limit erhöhen (Frontend-Image Neu bauen).'
|
||||
: 'Die Anfrage ist zu groß (413). Dateigröße oder Server-Limit prüfen.',
|
||||
)
|
||||
}
|
||||
const msg =
|
||||
typeof d === 'string'
|
||||
? d
|
||||
: d != null && typeof d === 'object' && typeof d.message === 'string'
|
||||
? d.message
|
||||
: d != null
|
||||
? JSON.stringify(d)
|
||||
: text && text.length < 400 && !/^\s*</.test(text)
|
||||
? `HTTP ${response.status}: ${text.trim()}`
|
||||
: `HTTP ${response.status}`
|
||||
throw new Error(msg)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export async function updateExerciseMedia(exerciseId, mediaId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/media/${mediaId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseMedia(exerciseId, mediaId) {
|
||||
return request(`/api/exercises/${exerciseId}/media/${mediaId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function reorderExerciseMedia(exerciseId, mediaIds) {
|
||||
return request(`/api/exercises/${exerciseId}/media/reorder`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ media_ids: mediaIds }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Papierkorb / Recovery — `action`: trash_soft | trash_hidden | recover | purge | reactivate */
|
||||
export async function postMediaAssetLifecycle(assetId, action, extra = {}) {
|
||||
return request(`/api/media-assets/${assetId}/lifecycle`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ action, ...extra }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Archiv: aktive media_assets sichtbar für den Nutzer (Bibliotheksrechte). */
|
||||
export async function listMediaAssets(params = {}) {
|
||||
const sp = new URLSearchParams()
|
||||
if (params.q) sp.set('q', params.q)
|
||||
if (params.limit != null) sp.set('limit', String(params.limit))
|
||||
if (params.offset != null) sp.set('offset', String(params.offset))
|
||||
if (params.lifecycle) sp.set('lifecycle', String(params.lifecycle))
|
||||
if (params.media_kind) sp.set('media_kind', String(params.media_kind))
|
||||
if (params.club_id != null && params.club_id !== '') sp.set('club_id', String(params.club_id))
|
||||
if (params.uploaded_by != null && params.uploaded_by !== '') sp.set('uploaded_by', String(params.uploaded_by))
|
||||
if (params.include_filter_meta) sp.set('include_filter_meta', 'true')
|
||||
const qs = sp.toString()
|
||||
return request(`/api/media-assets${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function patchMediaAsset(assetId, data) {
|
||||
return request(`/api/media-assets/${assetId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function bulkMediaLifecycle(data) {
|
||||
return request('/api/media-assets/bulk-lifecycle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function bulkPatchMediaAssets(data) {
|
||||
return request('/api/media-assets/bulk-patch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Mehrere Dateien ins Medienarchiv (`POST /api/media-assets/bulk-upload`).
|
||||
* @param {File[]} files
|
||||
* @param {{ visibility?: string, club_id?: number }} [options]
|
||||
*/
|
||||
export async function bulkUploadMediaAssets(files, options = {}) {
|
||||
const visibility = options.visibility || 'private'
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({})
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const formData = new FormData()
|
||||
formData.append('visibility', String(visibility))
|
||||
if (options.club_id != null && options.club_id !== '') {
|
||||
formData.append('club_id', String(options.club_id))
|
||||
}
|
||||
// Copyright + P-06: Rechte-Erklaerung + Kontextfelder
|
||||
if (options.copyright_notice != null && String(options.copyright_notice).trim())
|
||||
formData.append('copyright_notice', String(options.copyright_notice).trim())
|
||||
const p06Fields = [
|
||||
'rights_holder_confirmed',
|
||||
'contains_identifiable_persons',
|
||||
'person_consent_confirmed',
|
||||
'person_consent_context',
|
||||
'contains_minors',
|
||||
'parental_consent_confirmed',
|
||||
'parental_consent_context',
|
||||
'contains_music',
|
||||
'music_rights_confirmed',
|
||||
'music_rights_context',
|
||||
'contains_third_party_content',
|
||||
'third_party_rights_confirmed',
|
||||
'third_party_rights_context',
|
||||
]
|
||||
for (const f of p06Fields) {
|
||||
if (options[f] != null && options[f] !== '') formData.append(f, String(options[f]))
|
||||
}
|
||||
const arr = Array.isArray(files) ? files : [files]
|
||||
for (const f of arr) {
|
||||
if (f) formData.append('files', f)
|
||||
}
|
||||
const url = `${API_URL}/api/media-assets/bulk-upload`
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const d = parsed.detail
|
||||
throw new Error(typeof d === 'string' ? d : JSON.stringify(d))
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** Übung: bestehendes Archiv-Medium verknüpfen (`POST /api/exercises/{id}/media/from-asset`). */
|
||||
export async function getMediaAssetJournal(assetId) {
|
||||
return request(`/api/admin/media-rights/assets/${assetId}/journal`)
|
||||
}
|
||||
|
||||
export async function addMediaAssetDeclarationCorrection(assetId, body) {
|
||||
return request(`/api/admin/media-rights/assets/${assetId}/correction`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function attachExerciseMediaFromAsset(exerciseId, body) {
|
||||
return request(`/api/exercises/${exerciseId}/media/from-asset`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
// P-11: Legal-Hold-Endpunkte
|
||||
export async function setMediaAssetLegalHold(assetId, reasonCode, reasonNote) {
|
||||
return request(`/api/admin/media-assets/${assetId}/legal-hold`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason_code: reasonCode, reason_note: reasonNote }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function releaseMediaAssetLegalHold(assetId, releaseNote) {
|
||||
return request(`/api/admin/media-assets/${assetId}/legal-hold/release`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ release_note: releaseNote }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listMediaAssetsWithLegalHold(limit = 100, offset = 0) {
|
||||
return request(`/api/admin/media-assets/legal-hold?limit=${limit}&offset=${offset}`)
|
||||
}
|
||||
|
||||
export async function getExercise(id) {
|
||||
return request(`/api/exercises/${id}`)
|
||||
}
|
||||
|
||||
export async function createExercise(data) {
|
||||
return request('/api/exercises', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExercise(id, data) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({ 'Content-Type': 'application/json' })
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const url = `${API_URL}/api/exercises/${id}`
|
||||
const response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const d = parsed?.detail
|
||||
if (
|
||||
response.status === 422 &&
|
||||
d &&
|
||||
typeof d === 'object' &&
|
||||
!Array.isArray(d) &&
|
||||
typeof d.code === 'string'
|
||||
) {
|
||||
const e = new Error(typeof d.message === 'string' ? d.message : 'Validierung fehlgeschlagen')
|
||||
e.status = 422
|
||||
e.code = d.code
|
||||
e.payload = d
|
||||
throw e
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const msg = typeof parsed.detail === 'string' ? parsed.detail : JSON.stringify(parsed.detail)
|
||||
throw new Error(msg)
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** Massenänderung Übungen: Sichtbarkeit, Status, Katalog-Zuordnungen (`PATCH /api/exercises/bulk-metadata`). */
|
||||
export async function bulkPatchExercisesMetadata(data) {
|
||||
return request('/api/exercises/bulk-metadata', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExercise(id) {
|
||||
return request(`/api/exercises/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function createExerciseVariant(exerciseId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/variants`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseVariant(exerciseId, variantId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/${variantId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseVariant(exerciseId, variantId) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/${variantId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function reorderExerciseVariants(exerciseId, variantIds) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/reorder`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ variant_ids: variantIds }),
|
||||
})
|
||||
}
|
||||
|
||||
// Progressionsgraphen (Übung → Übung), Migration 032/033
|
||||
export async function listExerciseProgressionGraphs() {
|
||||
return request('/api/exercise-progression-graphs')
|
||||
}
|
||||
|
||||
export async function getExerciseProgressionGraph(id, { includeEdges = false } = {}) {
|
||||
const q = includeEdges ? '?include_edges=true' : ''
|
||||
return request(`/api/exercise-progression-graphs/${id}${q}`)
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionGraph(data) {
|
||||
return request('/api/exercise-progression-graphs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseProgressionGraph(id, data) {
|
||||
return request(`/api/exercise-progression-graphs/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionGraph(id) {
|
||||
return request(`/api/exercise-progression-graphs/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function listExerciseProgressionEdges(graphId, query = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (query.from_exercise_id != null) q.set('from_exercise_id', String(query.from_exercise_id))
|
||||
if (query.to_exercise_id != null) q.set('to_exercise_id', String(query.to_exercise_id))
|
||||
const qs = q.toString()
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionEdge(graphId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseProgressionEdge(graphId, edgeId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/${edgeId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionEdge(graphId, edgeId) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/${edgeId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionSequence(graphId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/sequence`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionEdgesBatch(graphId, edgeIds) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/delete-batch`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ edge_ids: edgeIds }),
|
||||
})
|
||||
}
|
||||
|
||||
/** KI-Ausbaustufe (EXERCISES_API_SPEC): benötigt Backend + z. B. OPENROUTER_API_KEY. */
|
||||
export async function suggestExerciseAi(payload) {
|
||||
return request('/api/exercises/ai/suggest', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function regenerateExerciseAi(exerciseId, payload) {
|
||||
return request(`/api/exercises/${exerciseId}/ai/regenerate`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Trainingsplanung: Einheiten, Vorlagen, Module, Rahmenprogramme, Dashboard-KPIs.
|
||||
* Facade: weiterhin `utils/api.js` (default + Named Exports).
|
||||
*/
|
||||
import { request } from './client.js'
|
||||
|
||||
/** Query-Parameter wie GET /api/training-units. */
|
||||
export async function listTrainingUnits(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (filters.group_id != null && filters.group_id !== '') {
|
||||
q.set('group_id', String(filters.group_id))
|
||||
}
|
||||
if (filters.club_id != null && filters.club_id !== '') {
|
||||
q.set('club_id', String(filters.club_id))
|
||||
}
|
||||
if (filters.start_date) q.set('start_date', filters.start_date)
|
||||
if (filters.end_date) q.set('end_date', filters.end_date)
|
||||
if (filters.status) q.set('status', filters.status)
|
||||
if (filters.debrief_pending === true) q.set('debrief_pending', 'true')
|
||||
if (filters.assigned_to_me === true) q.set('assigned_to_me', 'true')
|
||||
if (filters.sort) q.set('sort', String(filters.sort))
|
||||
if (filters.limit != null && filters.limit !== '') q.set('limit', String(filters.limit))
|
||||
if (filters.cursor_planned_date) q.set('cursor_planned_date', String(filters.cursor_planned_date))
|
||||
if (filters.cursor_planned_time != null && filters.cursor_planned_time !== '') {
|
||||
q.set('cursor_planned_time', String(filters.cursor_planned_time))
|
||||
}
|
||||
if (filters.cursor_id != null && filters.cursor_id !== '') q.set('cursor_id', String(filters.cursor_id))
|
||||
const qs = q.toString()
|
||||
return request(`/api/training-units${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
/** Dashboard Kurzüberblick: Entwürfe / meine Übungen / YTD abgeschlossene Einheiten (ein Roundtrip). */
|
||||
export async function getDashboardKpis() {
|
||||
return request('/api/dashboard/kpis')
|
||||
}
|
||||
|
||||
/** Dashboard: Übungen in geplanten Einheiten, die für den Verein noch auf Sichtbarkeit „Verein“ gehören. */
|
||||
export async function getTrainingExerciseClubVisibilityQueue(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (filters.start_date) q.set('start_date', String(filters.start_date))
|
||||
if (filters.end_date) q.set('end_date', String(filters.end_date))
|
||||
if (filters.assigned_to_me === false) q.set('assigned_to_me', 'false')
|
||||
if (filters.limit_units != null && filters.limit_units !== '') {
|
||||
q.set('limit_units', String(filters.limit_units))
|
||||
}
|
||||
const qs = q.toString()
|
||||
return request(`/api/training-units/exercises-club-visibility-queue${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function getTrainingUnit(id) {
|
||||
return request(`/api/training-units/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingUnit(data) {
|
||||
return request('/api/training-units', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingUnit(id, data) {
|
||||
return request(`/api/training-units/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingUnit(id) {
|
||||
return request(`/api/training-units/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function quickCreateTrainingUnit(data) {
|
||||
return request('/api/training-units/quick-create', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/** Rahmen-Slot → geplante Einheit (tiefe Kopie, origin_framework_slot_id). */
|
||||
export async function createTrainingUnitFromFrameworkSlot(data) {
|
||||
return request('/api/training-units/from-framework-slot', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listTrainingPlanTemplates() {
|
||||
return request('/api/training-plan-templates')
|
||||
}
|
||||
|
||||
export async function getTrainingPlanTemplate(id) {
|
||||
return request(`/api/training-plan-templates/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingPlanTemplate(data) {
|
||||
return request('/api/training-plan-templates', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingPlanTemplate(id, data) {
|
||||
return request(`/api/training-plan-templates/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingPlanTemplate(id) {
|
||||
return request(`/api/training-plan-templates/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function listTrainingModules() {
|
||||
return request('/api/training-modules')
|
||||
}
|
||||
|
||||
export async function getTrainingModule(id) {
|
||||
return request(`/api/training-modules/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingModule(data) {
|
||||
return request('/api/training-modules', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingModule(id, data) {
|
||||
return request(`/api/training-modules/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingModule(id) {
|
||||
return request(`/api/training-modules/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
/** Kopiert Modul-Inhalte ans Ende eines Abschnitts (section_order_index 0-basiert). */
|
||||
export async function applyTrainingModuleToTrainingUnit(unitId, data) {
|
||||
return request(`/api/training-units/${unitId}/apply-training-module`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listTrainingFrameworkPrograms() {
|
||||
return request('/api/training-framework-programs')
|
||||
}
|
||||
|
||||
export async function getTrainingFrameworkProgram(id) {
|
||||
return request(`/api/training-framework-programs/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingFrameworkProgram(data) {
|
||||
return request('/api/training-framework-programs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingFrameworkProgram(id, data) {
|
||||
return request(`/api/training-framework-programs/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingFrameworkProgram(id) {
|
||||
return request(`/api/training-framework-programs/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
@@ -11,6 +11,7 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
|
||||
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
|
||||
{ to: '/admin/legal-documents', label: 'Rechtstexte', icon: Scale },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
/**
|
||||
* Kombinationsübung im Coach: Archetyp-Hinweis + Katalog-Inhalt je Slot/Kandidat.
|
||||
*/
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import {
|
||||
archetypeCoachHint,
|
||||
combinationArchetypeLabel,
|
||||
sortCombinationSlotsForDisplay,
|
||||
} from '../constants/combinationArchetypes'
|
||||
import {
|
||||
describeGlobalComboProfile,
|
||||
effectiveStationTimingSummary,
|
||||
METHOD_PROFILE_GUI_FIELDS,
|
||||
readSlotProfilesV1,
|
||||
} from '../utils/combinationMethodProfileUi'
|
||||
|
||||
function formatInlineProfileValue(val) {
|
||||
if (val === null || val === undefined) return '—'
|
||||
if (typeof val === 'boolean') return val ? 'ja' : 'nein'
|
||||
if (typeof val === 'number' && Number.isFinite(val)) return String(val)
|
||||
if (typeof val === 'string') return val.trim() === '' ? '—' : val
|
||||
try {
|
||||
return JSON.stringify(val)
|
||||
} catch {
|
||||
return String(val)
|
||||
}
|
||||
}
|
||||
|
||||
export default function CombinationCoachSlots({
|
||||
combinationSlots,
|
||||
methodArchetype,
|
||||
methodProfile,
|
||||
compactPlanningView = false,
|
||||
omitGlobalKeyValueBlock = false,
|
||||
/** Wenn gesetzt: Kandidaten als Button → Peek (kein Router-Wechsel, PWA-sicher) */
|
||||
onOpenCandidatePeek,
|
||||
}) {
|
||||
const slots = useMemo(() => sortCombinationSlotsForDisplay(combinationSlots), [combinationSlots])
|
||||
|
||||
const candidateIds = useMemo(() => {
|
||||
const set = new Set()
|
||||
for (const s of slots) {
|
||||
if (Array.isArray(s.candidates) && s.candidates.length) {
|
||||
for (const c of s.candidates) {
|
||||
const raw = c.exercise_id
|
||||
if (raw == null) continue
|
||||
const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10)
|
||||
if (Number.isFinite(n)) set.add(n)
|
||||
}
|
||||
} else {
|
||||
for (const id of s.candidate_exercise_ids || []) {
|
||||
const n = typeof id === 'number' ? id : parseInt(String(id), 10)
|
||||
if (Number.isFinite(n)) set.add(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...set]
|
||||
}, [slots])
|
||||
|
||||
const [byId, setById] = useState({})
|
||||
const [errById, setErrById] = useState({})
|
||||
const [loadingIds, setLoadingIds] = useState(false)
|
||||
|
||||
const sig = candidateIds.slice().sort((a, b) => a - b).join(',')
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setById({})
|
||||
setErrById({})
|
||||
|
||||
if (candidateIds.length === 0) {
|
||||
setLoadingIds(false)
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}
|
||||
|
||||
setLoadingIds(true)
|
||||
Promise.all(
|
||||
candidateIds.map((id) =>
|
||||
api.getExercise(id).then(
|
||||
(ex) => ({ id, ok: true, ex }),
|
||||
(e) => ({
|
||||
id,
|
||||
ok: false,
|
||||
err: e?.message || String(e),
|
||||
}),
|
||||
),
|
||||
),
|
||||
).then((results) => {
|
||||
if (cancelled) return
|
||||
const map = {}
|
||||
const emap = {}
|
||||
for (const r of results) {
|
||||
if (r.ok) map[r.id] = r.ex
|
||||
else emap[r.id] = r.err
|
||||
}
|
||||
setById(map)
|
||||
setErrById(emap)
|
||||
setLoadingIds(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [sig])
|
||||
|
||||
const archeKey = methodArchetype != null ? String(methodArchetype).trim() : ''
|
||||
const archDisplay = archeKey ? combinationArchetypeLabel(archeKey) : null
|
||||
|
||||
const slotTimingByIx = useMemo(() => {
|
||||
if (!methodProfile || typeof methodProfile !== 'object' || Array.isArray(methodProfile)) return new Map()
|
||||
const rows = readSlotProfilesV1(methodProfile)
|
||||
const m = new Map()
|
||||
for (const r of rows) {
|
||||
m.set(Number(r.slot_index), r)
|
||||
}
|
||||
return m
|
||||
}, [methodProfile])
|
||||
|
||||
const globalComboRows = useMemo(
|
||||
() => describeGlobalComboProfile(archeKey, methodProfile || {}),
|
||||
[archeKey, methodProfile],
|
||||
)
|
||||
|
||||
const profileExtraEntries = useMemo(() => {
|
||||
if (!methodProfile || typeof methodProfile !== 'object' || Array.isArray(methodProfile)) return []
|
||||
const known = new Set(['slot_profiles_v1'])
|
||||
for (const f of METHOD_PROFILE_GUI_FIELDS[archeKey] || []) {
|
||||
known.add(f.key)
|
||||
}
|
||||
const out = []
|
||||
for (const [k, val] of Object.entries(methodProfile)) {
|
||||
if (known.has(k)) continue
|
||||
if (val === null || val === undefined || val === '') continue
|
||||
out.push([k, val])
|
||||
}
|
||||
return out.sort((a, b) => String(a[0]).localeCompare(String(b[0]), 'de'))
|
||||
}, [methodProfile, archeKey])
|
||||
|
||||
return (
|
||||
<section
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '14px',
|
||||
padding: '12px 14px',
|
||||
borderLeft: '3px solid var(--accent-dark)',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<h3
|
||||
style={{
|
||||
fontSize: '0.72rem',
|
||||
textTransform: 'uppercase',
|
||||
color: 'var(--text3)',
|
||||
margin: '0 0 6px',
|
||||
letterSpacing: '0.04em',
|
||||
}}
|
||||
>
|
||||
{compactPlanningView ? 'Stationen & Einzelübungen (Katalog)' : 'Kombination · Stationen & Einzelübungen'}
|
||||
</h3>
|
||||
{archDisplay ? (
|
||||
<p style={{ margin: '0 0 6px', fontSize: '0.95rem', fontWeight: 700 }}>{archDisplay}</p>
|
||||
) : null}
|
||||
{compactPlanningView ? null : (
|
||||
<p style={{ margin: '0 0 14px', fontSize: '0.88rem', color: 'var(--text2)', lineHeight: 1.48 }}>
|
||||
{archetypeCoachHint(archeKey)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{methodProfile && typeof methodProfile === 'object' && !Array.isArray(methodProfile) && Object.keys(methodProfile).length && !omitGlobalKeyValueBlock ? (
|
||||
<div
|
||||
style={{
|
||||
margin: '0 0 14px',
|
||||
padding: '8px 10px',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface)',
|
||||
border: '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--text3)', textTransform: 'uppercase', marginBottom: '6px' }}>
|
||||
Globale Eckdaten (wie im Editor)
|
||||
</div>
|
||||
{globalComboRows.length === 0 && profileExtraEntries.length === 0 ? (
|
||||
<p style={{ margin: 0, fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.42 }}>
|
||||
Keine globalen Zahlenfelder gesetzt — Zeiten und Steuerung siehe je Station unter „Plan:“ (oder nur im Freitext der Kombination).
|
||||
</p>
|
||||
) : (
|
||||
<dl style={{ margin: 0, fontSize: '0.82rem', lineHeight: 1.45 }}>
|
||||
{globalComboRows.map((row) => (
|
||||
<div
|
||||
key={row.key}
|
||||
style={{
|
||||
marginBottom: '6px',
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(88px,1fr) minmax(0,1.4fr)',
|
||||
gap: '6px 10px',
|
||||
}}
|
||||
>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>{row.detailLabel}</dt>
|
||||
<dd style={{ margin: 0, color: 'var(--text1)', fontWeight: 600 }}>{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
{profileExtraEntries.map(([k, val]) => (
|
||||
<div
|
||||
key={k}
|
||||
style={{
|
||||
marginBottom: '4px',
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(88px,1fr) minmax(0,1.4fr)',
|
||||
gap: '6px 10px',
|
||||
}}
|
||||
>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)', wordBreak: 'break-all' }}>{k}</dt>
|
||||
<dd style={{ margin: 0, color: 'var(--text1)' }}>{formatInlineProfileValue(val)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!slots.length ? (
|
||||
<p style={{ margin: 0, color: 'var(--text3)', fontSize: '0.88rem' }}>Keine Stationen hinterlegt.</p>
|
||||
) : (
|
||||
<ol style={{ margin: 0, paddingLeft: '1.1rem', display: 'flex', flexDirection: 'column', gap: '14px' }}>
|
||||
{slots.map((slot, si) => {
|
||||
const candIdsRaw = slot.candidate_exercise_ids || []
|
||||
const candIds = candIdsRaw
|
||||
.map((id) => (typeof id === 'number' ? id : parseInt(String(id), 10)))
|
||||
.filter((n) => Number.isFinite(n))
|
||||
|
||||
const slotTitle =
|
||||
(slot.title && String(slot.title).trim()) ||
|
||||
(candIds.length <= 1 && slot.candidates?.[0]?.title) ||
|
||||
`Station ${si + 1}`
|
||||
|
||||
const ix = slot.slot_index != null ? Number(slot.slot_index) : si
|
||||
const timingSummary = effectiveStationTimingSummary(archeKey, methodProfile || {}, slotTimingByIx.get(ix))
|
||||
|
||||
return (
|
||||
<li key={`${slot.slot_index ?? si}-${slotTitle}`} style={{ lineHeight: 1.45 }}>
|
||||
<div style={{ fontWeight: 700, fontSize: '0.92rem', marginBottom: timingSummary ? '4px' : candIds.length > 1 ? '6px' : '8px' }}>
|
||||
{slotTitle}
|
||||
</div>
|
||||
{timingSummary ? (
|
||||
<p style={{ margin: '0 0 8px', fontSize: '0.78rem', color: 'var(--text2)', lineHeight: 1.42 }}>
|
||||
Plan: <span style={{ color: 'var(--text1)', fontWeight: 600 }}>{timingSummary}</span>
|
||||
</p>
|
||||
) : null}
|
||||
{candIds.length === 0 ? (
|
||||
<p style={{ margin: 0, color: 'var(--text3)', fontSize: '0.86rem' }}>Keine Übung zugeordnet.</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px', paddingLeft: 0 }}>
|
||||
{candIds.map((cid, ci) => {
|
||||
const ex = byId[cid]
|
||||
const err = errById[cid]
|
||||
const candTitleFallback =
|
||||
slot.candidates?.find((c) => Number(c.exercise_id) === cid)?.title ||
|
||||
slot.candidates?.[ci]?.title
|
||||
|
||||
const isAlt = candIds.length > 1
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${cid}-${ci}`}
|
||||
style={{
|
||||
padding: '10px 11px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
{isAlt ? (
|
||||
<div style={{ fontSize: '0.72rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '4px' }}>
|
||||
{candIds.length > 2 ? `Alternative ${ci + 1}` : ci === 0 ? 'Alternative A' : 'Alternative B'}
|
||||
</div>
|
||||
) : null}
|
||||
{!ex && loadingIds ? (
|
||||
<div style={{ display: 'flex', gap: '8px', alignItems: 'center', fontSize: '0.86rem', color: 'var(--text2)' }}>
|
||||
<span className="spinner" style={{ transform: 'scale(0.7)' }} />
|
||||
Übung #{cid} laden…
|
||||
</div>
|
||||
) : err ? (
|
||||
<p style={{ margin: 0, color: 'var(--danger)', fontSize: '0.88rem' }}>
|
||||
Übung #{cid}: {err}
|
||||
</p>
|
||||
) : ex ? (
|
||||
compactPlanningView ? (
|
||||
<>
|
||||
<p style={{ margin: '0 0 4px', fontSize: '0.96rem', fontWeight: 700 }}>{ex.title}</p>
|
||||
<p style={{ margin: 0 }}>
|
||||
{typeof onOpenCandidatePeek === 'function' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="combo-coach-cand-link"
|
||||
onClick={() => onOpenCandidatePeek(cid)}
|
||||
>
|
||||
Details anzeigen
|
||||
</button>
|
||||
) : (
|
||||
<Link to={`/exercises/${cid}`} style={{ fontSize: '0.82rem', color: 'var(--accent)' }}>
|
||||
Im Katalog öffnen
|
||||
</Link>
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p style={{ margin: '0 0 6px', fontSize: '0.96rem', fontWeight: 700 }}>{ex.title}</p>
|
||||
{ex.summary ? (
|
||||
<div style={{ marginBottom: ex.execution ? '8px' : 0 }}>
|
||||
<ExerciseRichTextBlock html={ex.summary} exerciseId={ex.id} media={ex.media} />
|
||||
</div>
|
||||
) : (
|
||||
<p style={{ margin: '0 0 6px', fontSize: '0.86rem', color: 'var(--text3)' }}>
|
||||
Keine Kurzbeschreibung im Katalog.
|
||||
</p>
|
||||
)}
|
||||
{ex.execution ? (
|
||||
<details style={{ marginTop: '4px' }}>
|
||||
<summary style={{ cursor: 'pointer', fontSize: '0.82rem', color: 'var(--accent-dark)', fontWeight: 600 }}>
|
||||
Ablauf (Detail)
|
||||
</summary>
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<ExerciseRichTextBlock html={ex.execution} exerciseId={ex.id} media={ex.media} />
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
{ex.trainer_notes ? (
|
||||
<details style={{ marginTop: '6px' }}>
|
||||
<summary style={{ cursor: 'pointer', fontSize: '0.82rem', color: 'var(--accent-dark)', fontWeight: 600 }}>
|
||||
Hinweise Trainer
|
||||
</summary>
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<ExerciseRichTextBlock html={ex.trainer_notes} exerciseId={ex.id} media={ex.media} />
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
<p style={{ marginTop: '8px', marginBottom: 0 }}>
|
||||
{typeof onOpenCandidatePeek === 'function' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="combo-coach-cand-link"
|
||||
onClick={() => onOpenCandidatePeek(cid)}
|
||||
>
|
||||
Volle Übungsansicht
|
||||
</button>
|
||||
) : (
|
||||
<Link to={`/exercises/${cid}`} style={{ fontSize: '0.84rem', color: 'var(--accent)' }}>
|
||||
Volle Übungsseite
|
||||
</Link>
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<p style={{ margin: 0, fontSize: '0.86rem', color: 'var(--text2)' }}>
|
||||
{candTitleFallback || `Übung #${cid}`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { archetypeCoachHint, combinationArchetypeLabel, sortCombinationSlotsForDisplay } from '../constants/combinationArchetypes'
|
||||
import {
|
||||
METHOD_PROFILE_GUI_FIELDS,
|
||||
parseProfileJson,
|
||||
setFullProfileRawJson,
|
||||
updateProfileGuided,
|
||||
patchMethodProfile,
|
||||
readSlotProfilesV1,
|
||||
patchSlotTimingField,
|
||||
patchSlotAdvanceMode,
|
||||
normalizeAdvanceMode,
|
||||
parseComboRepSeriesCountUi,
|
||||
applyCircuitRotateQuickRatio,
|
||||
applyIntervalDomainQuickRatio,
|
||||
} from '../utils/combinationMethodProfileUi'
|
||||
|
||||
function clampInt(n, min, max) {
|
||||
if (!Number.isFinite(n)) return null
|
||||
let x = n
|
||||
if (typeof min === 'number' && x < min) x = min
|
||||
if (typeof max === 'number' && x > max) x = max
|
||||
return Math.round(x)
|
||||
}
|
||||
|
||||
/** Archetypen mit klar bezifferbarer Stationslogik · alle mit Slot-Liste sinnvoll */
|
||||
const ARCHETYPES_WITH_SLOT_TIMING = new Set([
|
||||
'circuit_rotate_time',
|
||||
'sequence_linear',
|
||||
'station_parcour',
|
||||
'time_domain_interval',
|
||||
'circuit_all_parallel',
|
||||
'pair_superset',
|
||||
'free_method_block',
|
||||
])
|
||||
|
||||
/**
|
||||
* Kombination: geführtes method_profile (+ optional Stationszeilen, ohne JSON für Trainer).
|
||||
*
|
||||
* @param {boolean} [props.plannerMode] — z. B. Planungs‑Override: keine Roh‑JSON‑Sektion.
|
||||
* @param {boolean} [props.allowExpertJson] — wenn true und nicht plannerMode: Roh‑JSON (Support).
|
||||
* @param {{ slot_index?: number|string, title?: string }[]} [props.comboSlotsOutline] — für Slot‑Felder aus der Übung
|
||||
*/
|
||||
export default function CombinationMethodProfileEditor({
|
||||
methodArchetype,
|
||||
methodProfileJson,
|
||||
onChangeMethodProfileJson,
|
||||
plannerMode = false,
|
||||
allowExpertJson = false,
|
||||
comboSlotsOutline = null,
|
||||
omitPerSlotTiming = false,
|
||||
}) {
|
||||
const arch = typeof methodArchetype === 'string' ? methodArchetype.trim() : ''
|
||||
const fieldsGui = METHOD_PROFILE_GUI_FIELDS[arch]
|
||||
const fields = Array.isArray(fieldsGui) ? fieldsGui : null
|
||||
const parseState = useMemo(() => parseProfileJson(methodProfileJson || '{}'), [methodProfileJson])
|
||||
const [rawOpenError, setRawOpenError] = useState(null)
|
||||
const [rawDraft, setRawDraft] = useState(null)
|
||||
const [presetHint, setPresetHint] = useState(null)
|
||||
|
||||
const profileObj = parseState.ok ? parseState.obj : {}
|
||||
|
||||
const outlineSorted = useMemo(() => {
|
||||
if (!comboSlotsOutline || !Array.isArray(comboSlotsOutline) || comboSlotsOutline.length === 0) return []
|
||||
return sortCombinationSlotsForDisplay(comboSlotsOutline)
|
||||
}, [comboSlotsOutline])
|
||||
|
||||
const showSlotTiming =
|
||||
!omitPerSlotTiming && ARCHETYPES_WITH_SLOT_TIMING.has(arch) && outlineSorted.length > 0
|
||||
|
||||
const slotRowsModel = useMemo(() => readSlotProfilesV1(profileObj), [profileObj])
|
||||
|
||||
const lookupSlotTiming = (slotIndex) =>
|
||||
slotRowsModel.find((r) => Number(r.slot_index) === Number(slotIndex)) || {}
|
||||
|
||||
const applyGuided = (key, value, kind) => {
|
||||
if (kind === 'bool') {
|
||||
const res = updateProfileGuided(arch, methodProfileJson || '{}', key, value, 'bool')
|
||||
if (!res.ok) return
|
||||
onChangeMethodProfileJson(res.json)
|
||||
setPresetHint(null)
|
||||
return
|
||||
}
|
||||
if (value === '' || value === undefined || value === null) {
|
||||
const res = updateProfileGuided(arch, methodProfileJson || '{}', key, '', 'int')
|
||||
if (!res.ok) return
|
||||
onChangeMethodProfileJson(res.json)
|
||||
setPresetHint(null)
|
||||
return
|
||||
}
|
||||
const num = typeof value === 'number' ? value : parseInt(String(value), 10)
|
||||
if (!Number.isFinite(num)) return
|
||||
const def = METHOD_PROFILE_GUI_FIELDS[arch]?.find((f) => f.key === key && f.kind === 'int')
|
||||
const c = clampInt(num, def?.min, def?.max)
|
||||
if (c == null) return
|
||||
const res = updateProfileGuided(arch, methodProfileJson || '{}', key, c, 'int')
|
||||
if (!res.ok) return
|
||||
onChangeMethodProfileJson(res.json)
|
||||
setPresetHint(null)
|
||||
}
|
||||
|
||||
const onSlotField = (slotIx, field, rawStr) => {
|
||||
const patched = patchMethodProfile(methodProfileJson || '{}', (d) =>
|
||||
patchSlotTimingField(d, slotIx, field, rawStr)
|
||||
)
|
||||
if (!patched.ok) return
|
||||
onChangeMethodProfileJson(patched.json)
|
||||
setPresetHint(null)
|
||||
}
|
||||
|
||||
const onSlotAdvanceChange = (slotIx, rawMode) => {
|
||||
const patched = patchMethodProfile(methodProfileJson || '{}', (d) =>
|
||||
patchSlotAdvanceMode(d, slotIx, rawMode)
|
||||
)
|
||||
if (!patched.ok) return
|
||||
onChangeMethodProfileJson(patched.json)
|
||||
setPresetHint(null)
|
||||
}
|
||||
|
||||
const onSlotRepSeriesCount = (slotIx, rawStr) => {
|
||||
const trimmed = String(rawStr ?? '').trim()
|
||||
const effective = trimmed === '' ? '1' : trimmed
|
||||
const pn = parseInt(effective, 10)
|
||||
const clearIntra = !Number.isFinite(pn) || pn < 2
|
||||
const patched = patchMethodProfile(methodProfileJson || '{}', (d) => {
|
||||
patchSlotTimingField(d, slotIx, 'rep_series_count', effective)
|
||||
if (clearIntra) patchSlotTimingField(d, slotIx, 'intra_rep_rest_sec', '')
|
||||
})
|
||||
if (!patched.ok) return
|
||||
onChangeMethodProfileJson(patched.json)
|
||||
setPresetHint(null)
|
||||
}
|
||||
|
||||
const runCircuitPreset = (presetId) => {
|
||||
const r = patchMethodProfile(methodProfileJson || '{}', (draft) => {
|
||||
const pr = applyCircuitRotateQuickRatio(draft, presetId)
|
||||
if (!pr.ok) setPresetHint(pr.error || '')
|
||||
else setPresetHint(null)
|
||||
})
|
||||
if (!r.ok) return
|
||||
onChangeMethodProfileJson(r.json)
|
||||
}
|
||||
|
||||
const runIntervalPreset = (presetId) => {
|
||||
const r = patchMethodProfile(methodProfileJson || '{}', (draft) => {
|
||||
const pr = applyIntervalDomainQuickRatio(draft, presetId)
|
||||
if (!pr.ok) setPresetHint(pr.error || '')
|
||||
else setPresetHint(null)
|
||||
})
|
||||
if (!r.ok) return
|
||||
onChangeMethodProfileJson(r.json)
|
||||
}
|
||||
|
||||
const archeLabel = arch ? combinationArchetypeLabel(arch) : null
|
||||
|
||||
const openAdvanced = () => {
|
||||
setRawOpenError(null)
|
||||
const p = parseProfileJson(methodProfileJson || '{}')
|
||||
setRawDraft(p.ok ? JSON.stringify(p.obj, null, 2) : String(methodProfileJson || ''))
|
||||
}
|
||||
|
||||
const showExpertSection = allowExpertJson && !plannerMode
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: '10px' }}>
|
||||
{presetHint ? (
|
||||
<p style={{ fontSize: '12px', color: 'var(--danger)', margin: '0 0 8px', lineHeight: 1.4 }}>{presetHint}</p>
|
||||
) : null}
|
||||
|
||||
{arch ? (
|
||||
<p style={{ fontSize: '12px', color: 'var(--text2)', lineHeight: 1.48, margin: '0 0 12px' }}>
|
||||
<strong style={{ color: 'var(--text1)' }}>
|
||||
Coach & Planung:{' '}
|
||||
{archeLabel && archeLabel !== arch ? `${archeLabel} · ` : ''}
|
||||
</strong>
|
||||
{archetypeCoachHint(arch)}
|
||||
</p>
|
||||
) : (
|
||||
<p style={{ fontSize: '12px', color: 'var(--text3)', margin: '0 0 12px' }}>
|
||||
Wähle einen Methoden‑Archetyp — besonders beim <strong>freien Methodenblock</strong> stehen alle
|
||||
typischen Stations‑Zeiten zur Verfügung. Ohne Archetyp keine geführten Eingaben.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!parseState.ok ? (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '13px', marginBottom: '10px' }}>{parseState.error}</p>
|
||||
) : null}
|
||||
|
||||
{fields && fields.length > 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
|
||||
{arch === 'circuit_rotate_time' ? (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '6px',
|
||||
marginBottom: '4px',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: '11px', color: 'var(--text3)', marginRight: '6px' }}>Schnellwahl:</span>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => runCircuitPreset('transition_equals_work')}>
|
||||
Wechsel ≈ Arbeit
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => runCircuitPreset('round_rest_equals_work')}>
|
||||
Runden‑Pause ≈ Arbeit
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => runCircuitPreset('round_rest_two_thirds_work')}>
|
||||
Runden‑Pause ≈ ⅔ Arbeit
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{arch === 'time_domain_interval' ? (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '6px',
|
||||
marginBottom: '4px',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: '11px', color: 'var(--text3)', marginRight: '6px' }}>Schnellwahl:</span>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => runIntervalPreset('rest_equals_work')}>
|
||||
Erholung = Belastung
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => runIntervalPreset('rest_two_thirds_work')}>
|
||||
Erholung ≈ ⅔ Belastung
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{fields.map((def) => {
|
||||
if (def.kind === 'bool') {
|
||||
const ck = !!profileObj[def.key]
|
||||
return (
|
||||
<label
|
||||
key={def.key}
|
||||
style={{ display: 'flex', gap: '8px', alignItems: 'center', cursor: 'pointer', fontSize: '0.9rem' }}
|
||||
>
|
||||
<input type="checkbox" checked={ck} onChange={(e) => applyGuided(def.key, e.target.checked, 'bool')} />
|
||||
<span>{def.label}</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
const v = profileObj[def.key]
|
||||
const str =
|
||||
v === undefined || v === null ? '' : typeof v === 'number' && Number.isFinite(v) ? String(v) : String(v)
|
||||
|
||||
return (
|
||||
<div className="form-row" key={def.key}>
|
||||
<label className="form-label" style={{ fontSize: '12px' }}>
|
||||
{def.label}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
min={def.min}
|
||||
max={def.max}
|
||||
value={str}
|
||||
placeholder="optional"
|
||||
onChange={(e) => {
|
||||
const t = e.target.value
|
||||
if (t.trim() === '') applyGuided(def.key, '', 'int')
|
||||
else applyGuided(def.key, parseInt(t, 10), 'int')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : arch && fields && fields.length === 0 ? (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<p style={{ fontSize: '12px', color: 'var(--text3)', margin: '0 0 10px', lineHeight: 1.45 }}>
|
||||
Dieser Archetyp ist für <strong>maximal flexible</strong> Stationsblöcke gedacht — die Zeit‑Eckdaten sind
|
||||
unten je Station möglich. Freitexte der Kombination beschreiben alles Organisatorische, was nicht in
|
||||
Sekunden gefasst wird.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showSlotTiming ? (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '6px',
|
||||
marginBottom: '14px',
|
||||
padding: '12px 14px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '0.88rem', fontWeight: 700, marginBottom: '10px', color: 'var(--text1)' }}>
|
||||
Pro Station / Slot — Steuerung & Sekunden
|
||||
</div>
|
||||
<p style={{ fontSize: '11px', color: 'var(--text3)', margin: '0 0 12px', lineHeight: 1.45 }}>
|
||||
<strong>Steuerung:</strong> zeitlich (Arbeits‑Countdown), Zielzahl Wiederholungen oder Coach‑geführt ohne
|
||||
Arbeitsuhr. Pausen/Wechsel bleiben unabhängig planbar. Felder können leer bleiben — z. B. nutzt der
|
||||
Zirkel erst die globalen Arbeit‑Sekunden.
|
||||
</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
|
||||
{outlineSorted.map((slot, ordIdx) => {
|
||||
const siRaw = slot.slot_index
|
||||
const si =
|
||||
siRaw === '' || siRaw == null ? null : typeof siRaw === 'number' ? siRaw : parseInt(String(siRaw), 10)
|
||||
if (!Number.isFinite(si)) return null
|
||||
const row = lookupSlotTiming(si)
|
||||
const ttl = ((slot.title || '').trim() || `Station ${ordIdx + 1}`).trim()
|
||||
const slotAdv = normalizeAdvanceMode(row.advance_mode)
|
||||
const serieLabel =
|
||||
slotAdv === 'timed' ? 'Wdh. ohne Wechsel' : slotAdv === 'rep' ? 'Wdh. / Serie' : 'Richtwert'
|
||||
const showMultiSeries = slotAdv === 'rep' || slotAdv === 'manual'
|
||||
const serienUi = parseComboRepSeriesCountUi(row.rep_series_count)
|
||||
const showInterSeriesPause = showMultiSeries && serienUi >= 2
|
||||
const intraLabel = slotAdv === 'timed' ? 'Pause zwischen Wdh.' : 'Pause zw. Serien'
|
||||
return (
|
||||
<div
|
||||
key={`slot-timing-${si}`}
|
||||
style={{
|
||||
padding: '10px',
|
||||
borderRadius: '10px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<div style={{ marginBottom: '10px', fontWeight: 700, color: 'var(--text1)', fontSize: '0.9rem' }}>{ttl}</div>
|
||||
<div className="form-row" style={{ marginBottom: '10px', maxWidth: '22rem' }}>
|
||||
<label className="form-label" style={{ fontSize: '11px' }}>
|
||||
Steuerung
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ fontSize: '0.8125rem' }}
|
||||
value={slotAdv}
|
||||
onChange={(e) => onSlotAdvanceChange(si, e.target.value)}
|
||||
>
|
||||
<option value="timed">Zeit (Arbeit in Sekunden)</option>
|
||||
<option value="rep">Wiederholungen (Ziel)</option>
|
||||
<option value="manual">Coach (ohne Arbeitsuhr)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))',
|
||||
gap: '10px',
|
||||
alignItems: 'end',
|
||||
}}
|
||||
>
|
||||
{slotAdv === 'timed' ? (
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label" style={{ fontSize: '11px' }}>
|
||||
Belastung (s)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
className="form-input"
|
||||
placeholder="–"
|
||||
value={row.load_sec != null ? String(row.load_sec) : ''}
|
||||
onChange={(e) => onSlotField(si, 'load_sec', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label" style={{ fontSize: '11px' }}>
|
||||
{serieLabel}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={slotAdv === 'rep' ? 1 : undefined}
|
||||
className="form-input"
|
||||
placeholder={slotAdv === 'manual' ? 'optional' : 'oft 1'}
|
||||
value={row.consecutive_reps != null ? String(row.consecutive_reps) : ''}
|
||||
onChange={(e) => onSlotField(si, 'consecutive_reps', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{showMultiSeries ? (
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label
|
||||
className="form-label"
|
||||
style={{ fontSize: '11px' }}
|
||||
title="Wie oft die Wdh.-Zahl pro Serie hintereinander (mit Pause zwischen den Serien)?"
|
||||
>
|
||||
Serien
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={slotAdv === 'rep' ? 1 : undefined}
|
||||
className="form-input"
|
||||
placeholder="1"
|
||||
value={String(parseComboRepSeriesCountUi(row.rep_series_count))}
|
||||
onChange={(e) => onSlotRepSeriesCount(si, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{slotAdv === 'timed' || showInterSeriesPause ? (
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label" style={{ fontSize: '11px' }}>
|
||||
{intraLabel} (s)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
className="form-input"
|
||||
placeholder="–"
|
||||
value={row.intra_rep_rest_sec != null ? String(row.intra_rep_rest_sec) : ''}
|
||||
onChange={(e) => onSlotField(si, 'intra_rep_rest_sec', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label" style={{ fontSize: '11px' }}>
|
||||
Wechsel (s)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
className="form-input"
|
||||
placeholder="–"
|
||||
value={row.transition_after_sec != null ? String(row.transition_after_sec) : ''}
|
||||
onChange={(e) => onSlotField(si, 'transition_after_sec', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{showMultiSeries && serienUi < 2 ? (
|
||||
<p style={{ fontSize: '10px', color: 'var(--text3)', margin: '6px 0 0', lineHeight: 1.38 }}>
|
||||
<strong>Wechsel (s)</strong> zur <strong>nächsten Station</strong>. „Pause zw. Serien“ nur ab 2
|
||||
Serien.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showExpertSection ? (
|
||||
<details
|
||||
style={{
|
||||
marginTop: '4px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
padding: '8px 10px',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
onToggle={(ev) => {
|
||||
if (ev.target.open) openAdvanced()
|
||||
}}
|
||||
>
|
||||
<summary style={{ cursor: 'pointer', fontSize: '0.82rem', fontWeight: 600 }}>
|
||||
Support / Entwicklung: Rohdaten (JSON)
|
||||
</summary>
|
||||
<p style={{ fontSize: '11px', color: 'var(--text3)', margin: '8px 0 6px', lineHeight: 1.4 }}>
|
||||
Für Migrationen und Sonderfälle. Geführte Felder setzen weiterhin gültige Standardschlüssel.
|
||||
</p>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={8}
|
||||
style={{ fontFamily: 'Consolas,monospace', fontSize: '12px' }}
|
||||
value={rawDraft != null ? rawDraft : methodProfileJson || '{}'}
|
||||
onChange={(e) => {
|
||||
setRawDraft(e.target.value)
|
||||
setRawOpenError(null)
|
||||
}}
|
||||
spellCheck={false}
|
||||
onBlur={() => {
|
||||
const src = rawDraft != null ? rawDraft : methodProfileJson
|
||||
const res = setFullProfileRawJson(src || '{}')
|
||||
if (!res.ok) {
|
||||
setRawOpenError(res.error)
|
||||
return
|
||||
}
|
||||
setRawOpenError(null)
|
||||
setRawDraft(null)
|
||||
onChangeMethodProfileJson(res.json)
|
||||
}}
|
||||
/>
|
||||
{rawOpenError ? (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '12px', marginTop: '6px' }}>{rawOpenError}</p>
|
||||
) : null}
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Kombination: konsolidierte Darstellung globales Profil + Stationen mit Zeiten (Vorschau, Plan-Ansicht, Druck).
|
||||
*/
|
||||
import React, { useMemo } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
archetypeCoachHint,
|
||||
combinationArchetypeLabel,
|
||||
sortCombinationSlotsForDisplay,
|
||||
} from '../constants/combinationArchetypes'
|
||||
import {
|
||||
describeGlobalComboProfile,
|
||||
effectiveStationTimingSummary,
|
||||
readSlotProfilesV1,
|
||||
stationPrimaryLoadLabel,
|
||||
} from '../utils/combinationMethodProfileUi'
|
||||
|
||||
/** @returns {{ exerciseId: number, label: string }[]} */
|
||||
export function normalizeCombinationSlotCandidates(slot) {
|
||||
const out = []
|
||||
const cands =
|
||||
slot.candidates && slot.candidates.length
|
||||
? slot.candidates
|
||||
: (slot.candidate_exercise_ids || []).map((id) => ({ exercise_id: id, title: null }))
|
||||
for (const c of cands) {
|
||||
const rawId = c.exercise_id
|
||||
if (rawId == null) continue
|
||||
const n = typeof rawId === 'number' ? rawId : parseInt(String(rawId), 10)
|
||||
if (!Number.isFinite(n)) continue
|
||||
const label = ((c.title || '').trim() || `Übung #${n}`).trim()
|
||||
out.push({ exerciseId: n, label })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export default function CombinationPlanBracket({
|
||||
methodArchetype,
|
||||
methodProfile,
|
||||
combinationSlots,
|
||||
planningAdjusted = false,
|
||||
/** 'none' | 'link' (Router) | 'button' (z. B. ExercisePeekModal / PWA-sicher) */
|
||||
candidateInteraction = 'none',
|
||||
onCandidatePeek,
|
||||
className,
|
||||
}) {
|
||||
const arch = typeof methodArchetype === 'string' ? methodArchetype.trim() : ''
|
||||
const archLabel = arch ? combinationArchetypeLabel(arch) : null
|
||||
const globals = describeGlobalComboProfile(arch, methodProfile || {})
|
||||
const slotsSorted = useMemo(() => sortCombinationSlotsForDisplay(combinationSlots || []), [combinationSlots])
|
||||
const timingByIx = useMemo(() => {
|
||||
const mp = methodProfile || {}
|
||||
const rows = readSlotProfilesV1(mp)
|
||||
const m = new Map()
|
||||
for (const r of rows) {
|
||||
m.set(Number(r.slot_index), r)
|
||||
}
|
||||
return m
|
||||
}, [methodProfile])
|
||||
|
||||
const coachHint = arch ? archetypeCoachHint(arch) : ''
|
||||
|
||||
return (
|
||||
<div className={['combo-plan-bracket', className].filter(Boolean).join(' ')}>
|
||||
<div className="combo-plan-bracket__accent" aria-hidden />
|
||||
<div className="combo-plan-bracket__body">
|
||||
<header className="combo-plan-bracket__head">
|
||||
<div className="combo-plan-bracket__head-main">
|
||||
<span className="combo-plan-bracket__kicker">Kombinations‑Plan</span>
|
||||
<span className="combo-plan-bracket__archetype">{archLabel || arch || 'Archetyp'}</span>
|
||||
{planningAdjusted ? (
|
||||
<span className="combo-plan-bracket__badge">Planung angepasst</span>
|
||||
) : null}
|
||||
</div>
|
||||
{coachHint ? <p className="combo-plan-bracket__hint">{coachHint}</p> : null}
|
||||
</header>
|
||||
|
||||
{globals.length > 0 ? (
|
||||
<section className="combo-plan-bracket__globals" aria-label="Globale Eckdaten">
|
||||
<div className="combo-plan-bracket__globals-title">Runden · Zeiten · Pausen (global)</div>
|
||||
<ul className="combo-plan-bracket__chip-row">
|
||||
{globals.map((g) => (
|
||||
<li key={g.key} className="combo-plan-bracket__chip" title={g.detailLabel}>
|
||||
<span className="combo-plan-bracket__chip-cap">{g.caption}</span>
|
||||
<span className="combo-plan-bracket__chip-val">{g.value}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : (
|
||||
<p className="combo-plan-bracket__globals-empty">
|
||||
Keine globalen Zahlenfelder gesetzt — Steuerung erfolgt nur je Station oder über den Freitext der Kombination.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<ol className="combo-plan-bracket__stations">
|
||||
{slotsSorted.map((slot, si) => {
|
||||
const siRaw = slot.slot_index
|
||||
const ixParsed =
|
||||
siRaw === '' || siRaw == null ? si : typeof siRaw === 'number' ? siRaw : parseInt(String(siRaw), 10)
|
||||
const stationIx = Number.isFinite(ixParsed) ? ixParsed : si
|
||||
const displayStep = si + 1
|
||||
const stationTitle = ((slot.title || '').trim() || `Station ${displayStep}`).trim()
|
||||
const candRows = normalizeCombinationSlotCandidates(slot)
|
||||
const names = candRows.length ? candRows.map((r) => r.label).join(' ↔ ') : ''
|
||||
const slotProfRow = timingByIx.get(stationIx)
|
||||
const loadBadge = stationPrimaryLoadLabel(slotProfRow)
|
||||
const timing = effectiveStationTimingSummary(arch, methodProfile || {}, slotProfRow)
|
||||
|
||||
return (
|
||||
<li key={`slot-${stationIx}-${si}`} className="combo-plan-bracket__station">
|
||||
<div
|
||||
className="combo-plan-bracket__station-load"
|
||||
title={loadBadge ? 'Belastung je Station (Sekunden oder Wiederholungen)' : undefined}
|
||||
>
|
||||
{loadBadge || '—'}
|
||||
</div>
|
||||
<div className="combo-plan-bracket__station-main">
|
||||
<div className="combo-plan-bracket__station-title">{stationTitle}</div>
|
||||
{candidateInteraction === 'button' && typeof onCandidatePeek === 'function' && candRows.length > 0 ? (
|
||||
<div className="combo-plan-bracket__station-exercises combo-plan-bracket__station-exercises--interactive">
|
||||
{candRows.map((c, ci) => (
|
||||
<span key={`${c.exerciseId}-${ci}`} className="combo-plan-bracket__cand-inline">
|
||||
{ci > 0 ? <span className="combo-plan-bracket__cand-sep">↔</span> : null}
|
||||
<button
|
||||
type="button"
|
||||
className="combo-plan-bracket__cand-btn"
|
||||
onClick={() => onCandidatePeek(c.exerciseId, c.label)}
|
||||
>
|
||||
{c.label}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : candidateInteraction === 'link' && candRows.length > 0 ? (
|
||||
<div className="combo-plan-bracket__station-exercises combo-plan-bracket__station-exercises--interactive">
|
||||
{candRows.map((c, ci) => (
|
||||
<span key={`${c.exerciseId}-${ci}`} className="combo-plan-bracket__cand-inline">
|
||||
{ci > 0 ? <span className="combo-plan-bracket__cand-sep">↔</span> : null}
|
||||
<Link to={`/exercises/${c.exerciseId}`} className="combo-plan-bracket__cand-link">
|
||||
{c.label}
|
||||
</Link>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="combo-plan-bracket__station-exercises">{names || '(keine Einzelübung)'}</div>
|
||||
)}
|
||||
{timing ? (
|
||||
<div className="combo-plan-bracket__station-timing">
|
||||
<span className="combo-plan-bracket__timing-label">Zeit / Steuerung</span>
|
||||
<span>{timing}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="combo-plan-bracket__station-timing combo-plan-bracket__station-timing--muted">
|
||||
Keine eigene Stations‑Zeit im Profil — ggf. nur globale Vorgaben oder Freitext.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { NavLink, useLocation } from 'react-router-dom'
|
||||
import { NavLink, Link, useLocation } from 'react-router-dom'
|
||||
import { LogOut } from 'lucide-react'
|
||||
import { getMainNavItems } from '../config/appNav'
|
||||
import { useOrgInbox } from '../context/OrgInboxContext'
|
||||
@@ -92,6 +92,20 @@ export default function DesktopSidebar({
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
padding: '0.5rem 1rem 0.75rem',
|
||||
display: 'flex',
|
||||
gap: '0.6rem',
|
||||
flexWrap: 'wrap',
|
||||
fontSize: '0.7rem',
|
||||
}}
|
||||
>
|
||||
<Link to="/impressum" style={{ color: 'var(--text3)' }}>Impressum</Link>
|
||||
<Link to="/datenschutz" style={{ color: 'var(--text3)' }}>Datenschutz</Link>
|
||||
<Link to="/nutzungsbedingungen" style={{ color: 'var(--text3)' }}>Nutzungsbedingungen</Link>
|
||||
<Link to="/medienrichtlinie" style={{ color: 'var(--text3)' }}>Medienrichtlinie</Link>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -4,10 +4,10 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
|
||||
import ExerciseMediaThumbTile from './ExerciseMediaThumbTile'
|
||||
import MediaPreviewModal from './MediaPreviewModal'
|
||||
import ReportContentModal from './ReportContentModal'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import {
|
||||
collectInlineExerciseMediaIdsFromExercise,
|
||||
} from '../utils/exerciseInlineMediaRefs'
|
||||
import { collectInlineExerciseMediaIdsFromExercise } from '../utils/exerciseInlineMediaRefs'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
|
||||
@@ -15,6 +15,7 @@ function isTrashHidden(m) {
|
||||
|
||||
export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
|
||||
const [preview, setPreview] = useState(null)
|
||||
const [reportTarget, setReportTarget] = useState(null)
|
||||
const inlineIds = useMemo(() => collectInlineExerciseMediaIdsFromExercise(exercise), [exercise])
|
||||
|
||||
const orphans = useMemo(() => {
|
||||
@@ -60,63 +61,31 @@ export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{preview && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Medienvorschau"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.55)',
|
||||
zIndex: 1001,
|
||||
overflow: 'auto',
|
||||
padding: '16px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
onClick={() => setPreview(null)}
|
||||
onKeyDown={(e) => e.key === 'Escape' && setPreview(null)}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{ maxWidth: 720, width: '100%', maxHeight: '90vh', overflow: 'auto' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h3 style={{ marginTop: 0, fontSize: '1.05rem' }}>Vorschau</h3>
|
||||
{preview.embed_url ? (
|
||||
<p style={{ fontSize: '14px', wordBreak: 'break-all' }}>
|
||||
<a href={preview.embed_url} target="_blank" rel="noreferrer">
|
||||
{preview.embed_url}
|
||||
</a>
|
||||
</p>
|
||||
) : preview.mime_type?.startsWith('video/') || preview.media_type === 'video' ? (
|
||||
<video
|
||||
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
controls
|
||||
style={{ width: '100%', borderRadius: '8px', maxHeight: '70vh' }}
|
||||
/>
|
||||
) : preview.mime_type?.startsWith('image/') || preview.media_type === 'image' ? (
|
||||
<img
|
||||
alt=""
|
||||
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', maxHeight: '70vh', objectFit: 'contain' }}
|
||||
/>
|
||||
) : (
|
||||
<p style={{ fontSize: '14px' }}>
|
||||
<a href={resolveExerciseMediaFileUrl(exerciseId, preview)} target="_blank" rel="noreferrer">
|
||||
Datei öffnen
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: '16px' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setPreview(null)}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<MediaPreviewModal
|
||||
title={(preview.title || '').trim() || preview.original_filename || `Medium #${preview.id}`}
|
||||
media={preview}
|
||||
fileUrl={preview.embed_url ? null : resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
onClose={() => setPreview(null)}
|
||||
onReport={
|
||||
(preview.asset_lifecycle_state || 'active') === 'active' && !preview.asset_legal_hold_active
|
||||
? () => {
|
||||
setReportTarget(preview)
|
||||
setPreview(null)
|
||||
}
|
||||
: null
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{reportTarget && (
|
||||
<ReportContentModal
|
||||
targetType="media_asset"
|
||||
targetId={reportTarget.media_asset_id || reportTarget.id}
|
||||
targetLabel={reportTarget.title || reportTarget.original_filename || `Medium #${reportTarget.id}`}
|
||||
onClose={() => setReportTarget(null)}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* Voller Katalog-Inhalt einer Übung (Lesemodus für Coach/Mobile).
|
||||
* Optional: geplante Variante (`variantId`) — Beschreibung und Durchführungsänderungen oben.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import CombinationCoachSlots from './CombinationCoachSlots'
|
||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||
|
||||
function TagRow({ exercise }) {
|
||||
const tags = []
|
||||
@@ -51,9 +54,18 @@ function metaParts(exercise) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ exercise?: object|null, loading?: boolean, error?: string|null, exerciseId?: number }} props
|
||||
* @param {{ exercise?: object|null, loading?: boolean, error?: string|null, exerciseId?: number, variantId?: number|string|null, planningComboMethodProfile?: object|null, catalogMethodProfileSnapshot?: object|null, onCandidateExercisePeek?: (exerciseId: number) => void }} props
|
||||
*/
|
||||
export default function ExerciseFullContent({ exercise, loading, error, exerciseId }) {
|
||||
export default function ExerciseFullContent({
|
||||
exercise,
|
||||
loading,
|
||||
error,
|
||||
exerciseId,
|
||||
variantId,
|
||||
planningComboMethodProfile,
|
||||
catalogMethodProfileSnapshot,
|
||||
onCandidateExercisePeek,
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '1rem' }}>
|
||||
@@ -70,8 +82,65 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
const resolvedId = exercise.id ?? exerciseId
|
||||
const meta = metaParts(exercise)
|
||||
|
||||
const variant =
|
||||
variantId != null && variantId !== '' && Array.isArray(exercise.variants) && exercise.variants.length
|
||||
? exercise.variants.find((v) => String(v.id) === String(variantId)) || null
|
||||
: null
|
||||
|
||||
const isCombination =
|
||||
String(exercise.exercise_kind || 'simple').toLowerCase().trim() === 'combination'
|
||||
|
||||
const catalogFromExercise =
|
||||
exercise.method_profile && typeof exercise.method_profile === 'object' && !Array.isArray(exercise.method_profile)
|
||||
? exercise.method_profile
|
||||
: {}
|
||||
const catalogFromUnit =
|
||||
catalogMethodProfileSnapshot && typeof catalogMethodProfileSnapshot === 'object' && !Array.isArray(catalogMethodProfileSnapshot)
|
||||
? catalogMethodProfileSnapshot
|
||||
: {}
|
||||
|
||||
const coachComboProfile = isCombination
|
||||
? effectiveComboMethodProfile({ ...catalogFromExercise, ...catalogFromUnit }, planningComboMethodProfile)
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="exercise-coach-catalog" style={{ fontSize: '0.93rem', lineHeight: 1.5 }}>
|
||||
{variant ? (
|
||||
<section
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '14px',
|
||||
padding: '12px 14px',
|
||||
borderLeft: '3px solid var(--accent)',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ fontSize: '0.72rem', textTransform: 'uppercase', color: 'var(--text3)', margin: '0 0 6px', letterSpacing: '0.04em' }}>
|
||||
Geplante Variante
|
||||
</h3>
|
||||
<p style={{ margin: '0 0 10px', fontSize: '1.05rem', fontWeight: 700 }}>{variant.variant_name || `Variante #${variant.id}`}</p>
|
||||
{variant.description ? (
|
||||
<div style={{ marginBottom: variant.execution_changes ? '12px' : 0 }}>
|
||||
<h4 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Zur Variante</h4>
|
||||
<ExerciseRichTextBlock html={variant.description} exerciseId={resolvedId} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
{variant.execution_changes ? (
|
||||
<div>
|
||||
<h4 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Durchführung (Variante)</h4>
|
||||
<ExerciseRichTextBlock html={variant.execution_changes} exerciseId={resolvedId} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
{isCombination && Array.isArray(exercise.combination_slots) ? (
|
||||
<CombinationCoachSlots
|
||||
combinationSlots={exercise.combination_slots}
|
||||
methodArchetype={exercise.method_archetype}
|
||||
methodProfile={coachComboProfile}
|
||||
onOpenCandidatePeek={onCandidateExercisePeek}
|
||||
/>
|
||||
) : null}
|
||||
<h2 style={{ margin: '0 0 8px', fontSize: '1.2rem', lineHeight: 1.35 }}>{exercise.title}</h2>
|
||||
{meta.length > 0 && (
|
||||
<p className="exercise-meta-line" style={{ marginBottom: '10px', color: 'var(--text3)', fontSize: '0.86rem' }}>
|
||||
|
||||
@@ -10,6 +10,45 @@ import {
|
||||
} from '../constants/inlineExerciseMedia'
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
|
||||
const DECL_INIT = {
|
||||
copyright_notice: '',
|
||||
rights_holder_confirmed: false,
|
||||
contains_identifiable_persons: null,
|
||||
person_consent_confirmed: false,
|
||||
person_consent_context: '',
|
||||
contains_minors: null,
|
||||
parental_consent_confirmed: false,
|
||||
parental_consent_context: '',
|
||||
contains_music: null,
|
||||
music_rights_confirmed: false,
|
||||
music_rights_context: '',
|
||||
contains_third_party_content: null,
|
||||
third_party_rights_confirmed: false,
|
||||
third_party_rights_context: '',
|
||||
}
|
||||
|
||||
function validateDecl(decl) {
|
||||
if (!decl.rights_holder_confirmed)
|
||||
return 'Bitte bestätigen, dass du die erforderlichen Rechte an diesem Medium besitzt.'
|
||||
if (decl.contains_identifiable_persons === null)
|
||||
return 'Bitte angeben, ob erkennbare Personen abgebildet sind.'
|
||||
if (decl.contains_identifiable_persons && !decl.person_consent_confirmed)
|
||||
return 'Bitte bestätigen, dass die Einwilligungen aller erkennbaren Personen vorliegen.'
|
||||
if (decl.contains_minors === null)
|
||||
return 'Bitte angeben, ob Minderjährige abgebildet sind.'
|
||||
if (decl.contains_minors && !decl.parental_consent_confirmed)
|
||||
return 'Bitte bestätigen, dass die Einwilligungen der Sorgeberechtigten vorliegen.'
|
||||
if (decl.contains_music === null)
|
||||
return 'Bitte angeben, ob das Medium Musik enthält.'
|
||||
if (decl.contains_music && !decl.music_rights_confirmed)
|
||||
return 'Bitte bestätigen, dass die erforderlichen Musikrechte vorliegen.'
|
||||
if (decl.contains_third_party_content === null)
|
||||
return 'Bitte angeben, ob fremde geschützte Inhalte enthalten sind.'
|
||||
if (decl.contains_third_party_content && !decl.third_party_rights_confirmed)
|
||||
return 'Bitte bestätigen, dass die Rechte an allen enthaltenen Fremdmaterialien vorliegen.'
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* open: boolean,
|
||||
@@ -30,12 +69,18 @@ export default function ExerciseInlineEmbedModal({
|
||||
const [title, setTitle] = useState('')
|
||||
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [decl, setDecl] = useState({ ...DECL_INIT })
|
||||
const [declErr, setDeclErr] = useState('')
|
||||
|
||||
const setDeclField = (key, val) => setDecl((d) => ({ ...d, [key]: val }))
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setUrl('')
|
||||
setTitle('')
|
||||
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
setDecl({ ...DECL_INIT })
|
||||
setDeclErr('')
|
||||
}, [open])
|
||||
|
||||
const submit = async () => {
|
||||
@@ -44,6 +89,12 @@ export default function ExerciseInlineEmbedModal({
|
||||
alert('Bitte eine Embed-URL eingeben (https://…).')
|
||||
return
|
||||
}
|
||||
const validErr = validateDecl(decl)
|
||||
if (validErr) {
|
||||
setDeclErr(validErr)
|
||||
return
|
||||
}
|
||||
setDeclErr('')
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const fd = new FormData()
|
||||
fd.append('embed_url', u)
|
||||
@@ -52,6 +103,9 @@ export default function ExerciseInlineEmbedModal({
|
||||
fd.append('description', '')
|
||||
fd.append('context', 'ablauf')
|
||||
fd.append('is_primary', 'false')
|
||||
for (const [k, v] of Object.entries(decl)) {
|
||||
fd.append(k, String(v))
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const row = await api.uploadExerciseMedia(exerciseId, fd)
|
||||
@@ -81,7 +135,7 @@ export default function ExerciseInlineEmbedModal({
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="rte-inline-embed-title"
|
||||
style={{ maxWidth: '480px', width: '100%' }}
|
||||
style={{ maxWidth: '480px', width: '100%', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
@@ -92,7 +146,7 @@ export default function ExerciseInlineEmbedModal({
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ padding: '14px 16px' }}>
|
||||
<div style={{ overflowY: 'auto', flex: 1, padding: '14px 16px' }}>
|
||||
<label className="form-label">Embed-URL</label>
|
||||
<input
|
||||
type="url"
|
||||
@@ -122,7 +176,109 @@ export default function ExerciseInlineEmbedModal({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="button" className="btn btn-primary btn-full" style={{ marginTop: '16px' }} disabled={busy} onClick={submit}>
|
||||
|
||||
{/* P-06 Rechte-Erklärung */}
|
||||
<div style={{ marginTop: '18px', paddingTop: '14px', borderTop: '1px solid var(--border)' }}>
|
||||
<p style={{ fontSize: '0.82rem', fontWeight: 600, marginBottom: '10px', color: 'var(--text2)' }}>
|
||||
Rechte-Erklärung <span style={{ fontWeight: 400, color: 'var(--text3)' }}>(VORLÄUFIG – p06-v1-conservative)</span>
|
||||
</p>
|
||||
|
||||
<div style={{ marginBottom: '10px' }}>
|
||||
<label htmlFor="emb-cr" style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '3px' }}>Copyright-Angabe (optional)</label>
|
||||
<input id="emb-cr" type="text" className="form-input" placeholder="z.B. © 2026 Lars Stommer, CC BY-NC"
|
||||
value={decl.copyright_notice} onChange={(e) => setDeclField('copyright_notice', e.target.value)}
|
||||
disabled={busy} style={{ fontSize: '0.85rem' }} />
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '10px' }}>
|
||||
<input type="checkbox" id="emb-rhc" checked={decl.rights_holder_confirmed}
|
||||
onChange={(e) => setDeclField('rights_holder_confirmed', e.target.checked)}
|
||||
disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="emb-rhc" style={{ fontSize: '0.85rem' }}>
|
||||
Ich bestätige, dass ich die erforderlichen Rechte an diesem Medium besitze oder zur Veröffentlichung berechtigt bin. *
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Erkennbare Personen abgebildet? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cip" checked={decl.contains_identifiable_persons === true} onChange={() => setDeclField('contains_identifiable_persons', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cip" checked={decl.contains_identifiable_persons === false} onChange={() => setDeclField('contains_identifiable_persons', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_identifiable_persons === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="emb-pcc" checked={decl.person_consent_confirmed} onChange={(e) => setDeclField('person_consent_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="emb-pcc" style={{ fontSize: '0.85rem' }}>Einwilligungen aller erkennbaren Personen liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Einwilligungskontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Schriftliche Einwilligung vom 2026-05-01" value={decl.person_consent_context} onChange={(e) => setDeclField('person_consent_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Minderjährige abgebildet? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cm" checked={decl.contains_minors === true} onChange={() => setDeclField('contains_minors', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cm" checked={decl.contains_minors === false} onChange={() => setDeclField('contains_minors', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_minors === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="emb-pcc2" checked={decl.parental_consent_confirmed} onChange={(e) => setDeclField('parental_consent_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="emb-pcc2" style={{ fontSize: '0.85rem' }}>Einwilligungen der Sorgeberechtigten liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Einwilligungskontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Elterliche Einwilligung per E-Mail vom 2026-04-15" value={decl.parental_consent_context} onChange={(e) => setDeclField('parental_consent_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Musik enthalten? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cmu" checked={decl.contains_music === true} onChange={() => setDeclField('contains_music', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-cmu" checked={decl.contains_music === false} onChange={() => setDeclField('contains_music', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_music === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="emb-mrc" checked={decl.music_rights_confirmed} onChange={(e) => setDeclField('music_rights_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="emb-mrc" style={{ fontSize: '0.85rem' }}>Musikrechte (GEMA / Lizenz) liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Lizenz / GEMA-Kontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. CC BY 4.0 oder GEMA-Freimeldung Nr. …" value={decl.music_rights_context} onChange={(e) => setDeclField('music_rights_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '4px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Fremde geschützte Inhalte (Logos, Grafiken, Fotos Dritter)? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-ctpc" checked={decl.contains_third_party_content === true} onChange={() => setDeclField('contains_third_party_content', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="emb-ctpc" checked={decl.contains_third_party_content === false} onChange={() => setDeclField('contains_third_party_content', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_third_party_content === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="emb-tprc" checked={decl.third_party_rights_confirmed} onChange={(e) => setDeclField('third_party_rights_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="emb-tprc" style={{ fontSize: '0.85rem' }}>Rechte an allen enthaltenen Fremdmaterialien liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Rechtsgrundlage (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Verbandslogo mit Genehmigung vom 2026-03-10" value={decl.third_party_rights_context} onChange={(e) => setDeclField('third_party_rights_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{declErr && (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '0.85rem', marginTop: '8px' }}>{declErr}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
||||
<button type="button" className="btn btn-primary btn-full" disabled={busy} onClick={submit}>
|
||||
{busy ? 'Speichern…' : 'Hinzufügen & in Text einfügen'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -60,6 +60,45 @@ function inferExerciseMediaType(file) {
|
||||
return 'image'
|
||||
}
|
||||
|
||||
const DECL_INIT = {
|
||||
copyright_notice: '',
|
||||
rights_holder_confirmed: false,
|
||||
contains_identifiable_persons: null,
|
||||
person_consent_confirmed: false,
|
||||
person_consent_context: '',
|
||||
contains_minors: null,
|
||||
parental_consent_confirmed: false,
|
||||
parental_consent_context: '',
|
||||
contains_music: null,
|
||||
music_rights_confirmed: false,
|
||||
music_rights_context: '',
|
||||
contains_third_party_content: null,
|
||||
third_party_rights_confirmed: false,
|
||||
third_party_rights_context: '',
|
||||
}
|
||||
|
||||
function validateDecl(decl) {
|
||||
if (!decl.rights_holder_confirmed)
|
||||
return 'Bitte bestätigen, dass du die erforderlichen Rechte an diesem Medium besitzt.'
|
||||
if (decl.contains_identifiable_persons === null)
|
||||
return 'Bitte angeben, ob erkennbare Personen abgebildet sind.'
|
||||
if (decl.contains_identifiable_persons && !decl.person_consent_confirmed)
|
||||
return 'Bitte bestätigen, dass die Einwilligungen aller erkennbaren Personen vorliegen.'
|
||||
if (decl.contains_minors === null)
|
||||
return 'Bitte angeben, ob Minderjährige abgebildet sind.'
|
||||
if (decl.contains_minors && !decl.parental_consent_confirmed)
|
||||
return 'Bitte bestätigen, dass die Einwilligungen der Sorgeberechtigten vorliegen.'
|
||||
if (decl.contains_music === null)
|
||||
return 'Bitte angeben, ob das Medium Musik enthält.'
|
||||
if (decl.contains_music && !decl.music_rights_confirmed)
|
||||
return 'Bitte bestätigen, dass die erforderlichen Musikrechte vorliegen.'
|
||||
if (decl.contains_third_party_content === null)
|
||||
return 'Bitte angeben, ob fremde geschützte Inhalte enthalten sind.'
|
||||
if (decl.contains_third_party_content && !decl.third_party_rights_confirmed)
|
||||
return 'Bitte bestätigen, dass die Rechte an allen enthaltenen Fremdmaterialien vorliegen.'
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* open: boolean,
|
||||
@@ -89,6 +128,10 @@ export default function ExerciseInlineFileMediaModal({
|
||||
const [uploadTitle, setUploadTitle] = useState('')
|
||||
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
const [uploadInputKey, setUploadInputKey] = useState(0)
|
||||
const [decl, setDecl] = useState({ ...DECL_INIT })
|
||||
const [declErr, setDeclErr] = useState('')
|
||||
|
||||
const setDeclField = (key, val) => setDecl((d) => ({ ...d, [key]: val }))
|
||||
|
||||
const assetToExerciseMedia = useMemo(() => {
|
||||
const m = new Map()
|
||||
@@ -108,7 +151,7 @@ export default function ExerciseInlineFileMediaModal({
|
||||
limit: 48,
|
||||
lifecycle: 'active',
|
||||
})
|
||||
setItems(Array.isArray(res.items) ? res.items : [])
|
||||
setItems(Array.isArray(res.items) ? res.items.filter(a => !a.legal_hold_active) : [])
|
||||
} catch (e) {
|
||||
setErr(e.message || String(e))
|
||||
setItems([])
|
||||
@@ -126,6 +169,8 @@ export default function ExerciseInlineFileMediaModal({
|
||||
setUploadInputKey((k) => k + 1)
|
||||
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
setErr(null)
|
||||
setDecl({ ...DECL_INIT })
|
||||
setDeclErr('')
|
||||
const t = setTimeout(loadAssets, 280)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
@@ -187,6 +232,12 @@ export default function ExerciseInlineFileMediaModal({
|
||||
alert('Bitte eine Datei wählen.')
|
||||
return
|
||||
}
|
||||
const validErr = validateDecl(decl)
|
||||
if (validErr) {
|
||||
setDeclErr(validErr)
|
||||
return
|
||||
}
|
||||
setDeclErr('')
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const inferred = inferExerciseMediaType(uploadFile)
|
||||
const fd = new FormData()
|
||||
@@ -196,6 +247,9 @@ export default function ExerciseInlineFileMediaModal({
|
||||
fd.append('description', '')
|
||||
fd.append('context', 'ablauf')
|
||||
fd.append('is_primary', 'false')
|
||||
for (const [k, v] of Object.entries(decl)) {
|
||||
fd.append(k, String(v))
|
||||
}
|
||||
setBusy(true)
|
||||
setErr(null)
|
||||
try {
|
||||
@@ -321,7 +375,7 @@ export default function ExerciseInlineFileMediaModal({
|
||||
})}
|
||||
</div>
|
||||
{!loading && items.length === 0 ? (
|
||||
<p style={{ color: 'var(--text3)', marginTop: '12px' }}>Keine Treffer — Suche anpassen oder „Neu hochladen“.</p>
|
||||
<p style={{ color: 'var(--text3)', marginTop: '12px' }}>Keine Treffer — Suche anpassen oder „Neu hochladen".</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
@@ -358,6 +412,107 @@ export default function ExerciseInlineFileMediaModal({
|
||||
onChange={(e) => setUploadTitle(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
|
||||
{/* P-06 Rechte-Erklärung */}
|
||||
<div style={{ marginTop: '18px', paddingTop: '14px', borderTop: '1px solid var(--border)' }}>
|
||||
<p style={{ fontSize: '0.82rem', fontWeight: 600, marginBottom: '10px', color: 'var(--text2)' }}>
|
||||
Rechte-Erklärung <span style={{ fontWeight: 400, color: 'var(--text3)' }}>(VORLÄUFIG – p06-v1-conservative)</span>
|
||||
</p>
|
||||
|
||||
<div style={{ marginBottom: '10px' }}>
|
||||
<label htmlFor="up-cr" style={{ display: 'block', fontSize: '0.82rem', fontWeight: 600, marginBottom: '3px' }}>Copyright-Angabe (optional)</label>
|
||||
<input id="up-cr" type="text" className="form-input"
|
||||
placeholder="z.B. © 2026 Lars Stommer, CC BY-NC"
|
||||
value={decl.copyright_notice}
|
||||
onChange={(e) => setDeclField('copyright_notice', e.target.value)}
|
||||
disabled={busy} style={{ fontSize: '0.85rem' }} />
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '10px' }}>
|
||||
<input type="checkbox" id="up-rhc" checked={decl.rights_holder_confirmed}
|
||||
onChange={(e) => setDeclField('rights_holder_confirmed', e.target.checked)}
|
||||
disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="up-rhc" style={{ fontSize: '0.85rem' }}>
|
||||
Ich bestätige, dass ich die erforderlichen Rechte an diesem Medium besitze oder zur Veröffentlichung berechtigt bin. *
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Erkennbare Personen abgebildet? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cip" checked={decl.contains_identifiable_persons === true} onChange={() => setDeclField('contains_identifiable_persons', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cip" checked={decl.contains_identifiable_persons === false} onChange={() => setDeclField('contains_identifiable_persons', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_identifiable_persons === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="up-pcc" checked={decl.person_consent_confirmed} onChange={(e) => setDeclField('person_consent_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="up-pcc" style={{ fontSize: '0.85rem' }}>Einwilligungen aller erkennbaren Personen liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Einwilligungskontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Schriftliche Einwilligung vom 2026-05-01" value={decl.person_consent_context} onChange={(e) => setDeclField('person_consent_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Minderjährige abgebildet? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cm" checked={decl.contains_minors === true} onChange={() => setDeclField('contains_minors', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cm" checked={decl.contains_minors === false} onChange={() => setDeclField('contains_minors', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_minors === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="up-pcc2" checked={decl.parental_consent_confirmed} onChange={(e) => setDeclField('parental_consent_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="up-pcc2" style={{ fontSize: '0.85rem' }}>Einwilligungen der Sorgeberechtigten liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Einwilligungskontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Elterliche Einwilligung per E-Mail vom 2026-04-15" value={decl.parental_consent_context} onChange={(e) => setDeclField('parental_consent_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '10px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Musik enthalten? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cmu" checked={decl.contains_music === true} onChange={() => setDeclField('contains_music', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-cmu" checked={decl.contains_music === false} onChange={() => setDeclField('contains_music', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_music === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="up-mrc" checked={decl.music_rights_confirmed} onChange={(e) => setDeclField('music_rights_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="up-mrc" style={{ fontSize: '0.85rem' }}>Musikrechte (GEMA / Lizenz) liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Lizenz / GEMA-Kontext (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. CC BY 4.0 oder GEMA-Freimeldung Nr. …" value={decl.music_rights_context} onChange={(e) => setDeclField('music_rights_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, marginBottom: '4px' }}>
|
||||
<legend style={{ fontSize: '0.85rem', fontWeight: 600, marginBottom: '4px' }}>Fremde geschützte Inhalte (Logos, Grafiken, Fotos Dritter)? *</legend>
|
||||
<div style={{ display: 'flex', gap: '14px', marginBottom: '4px' }}>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-ctpc" checked={decl.contains_third_party_content === true} onChange={() => setDeclField('contains_third_party_content', true)} disabled={busy} /> Ja</label>
|
||||
<label style={{ fontSize: '0.85rem' }}><input type="radio" name="up-ctpc" checked={decl.contains_third_party_content === false} onChange={() => setDeclField('contains_third_party_content', false)} disabled={busy} /> Nein</label>
|
||||
</div>
|
||||
{decl.contains_third_party_content === true && (
|
||||
<div style={{ paddingLeft: 2 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '4px' }}>
|
||||
<input type="checkbox" id="up-tprc" checked={decl.third_party_rights_confirmed} onChange={(e) => setDeclField('third_party_rights_confirmed', e.target.checked)} disabled={busy} style={{ marginTop: '3px', flexShrink: 0 }} />
|
||||
<label htmlFor="up-tprc" style={{ fontSize: '0.85rem' }}>Rechte an allen enthaltenen Fremdmaterialien liegen vor. *</label>
|
||||
</div>
|
||||
<label style={{ display: 'block', fontSize: '0.8rem', color: 'var(--text2)', marginBottom: '2px' }}>Rechtsgrundlage (optional)</label>
|
||||
<textarea className="form-input" rows={2} placeholder="z.B. Verbandslogo mit Genehmigung vom 2026-03-10" value={decl.third_party_rights_context} onChange={(e) => setDeclField('third_party_rights_context', e.target.value)} disabled={busy} style={{ fontSize: '0.82rem', resize: 'vertical' }} />
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{declErr && (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '0.85rem', marginTop: '8px' }}>{declErr}</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,15 @@ export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'me
|
||||
: { maxWidth: 'min(560px, 85vw)', marginTop: '0.5rem' }
|
||||
|
||||
if (!media || exerciseId == null) return null
|
||||
|
||||
if (media.asset_legal_hold_active) {
|
||||
return (
|
||||
<div style={{ ...box, color: 'var(--danger)', fontSize: '0.85rem', padding: '8px 0' }}>
|
||||
Medium nicht verfügbar (gesperrt)
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (media.embed_url) {
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -11,6 +11,32 @@ export default function ExerciseMediaThumbTile({ exerciseId, media, onOpenPrevie
|
||||
height: '100%',
|
||||
objectFit: 'cover',
|
||||
}
|
||||
|
||||
if (media.asset_legal_hold_active) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
flexShrink: 0,
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden',
|
||||
background: 'rgba(216, 90, 48, 0.10)',
|
||||
border: '1px solid rgba(216, 90, 48, 0.35)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
title: 'Gesperrt',
|
||||
}}
|
||||
title="Medium gesperrt"
|
||||
>
|
||||
<span style={{ fontSize: '11px', color: 'var(--danger)', textAlign: 'center', padding: '4px' }}>
|
||||
Gesperrt
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* Schnellansicht einer Übung aus dem Katalog (ohne die Planungsseite zu verlassen).
|
||||
* Unterstützt Drill-down zu Kandidaten-Übungen bei Kombinationen inkl. „Zurück“ (PWA-sicher).
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import CombinationPlanBracket from './CombinationPlanBracket'
|
||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||
|
||||
function TagMini({ exercise }) {
|
||||
const parts = []
|
||||
@@ -23,30 +26,51 @@ function TagMini({ exercise }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** @typedef {{ exerciseId: number, variantId?: number | null, peekExtras?: object | null }} PeekStackEntry */
|
||||
|
||||
export default function ExercisePeekModal({
|
||||
open,
|
||||
exerciseId,
|
||||
variantId,
|
||||
onClose,
|
||||
titleFallback,
|
||||
/** Nur Planung: effektives method_profile aus Zeilen-Katalog + Planungs-Override */
|
||||
peekExtras,
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [err, setErr] = useState(null)
|
||||
const [exercise, setExercise] = useState(null)
|
||||
/** @type {[PeekStackEntry[], React.Dispatch<React.SetStateAction<PeekStackEntry[]>>]} */
|
||||
const [stack, setStack] = useState([])
|
||||
|
||||
const variant =
|
||||
variantId != null && variantId !== '' && exercise?.variants?.length
|
||||
? exercise.variants.find((v) => String(v.id) === String(variantId)) || null
|
||||
: null
|
||||
/** @type {React.MutableRefObject<boolean>} */
|
||||
const wasOpenRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setExercise(null)
|
||||
setErr(null)
|
||||
setStack([])
|
||||
wasOpenRef.current = false
|
||||
return
|
||||
}
|
||||
if (!exerciseId) {
|
||||
setErr('Keine Übung gewählt')
|
||||
if (exerciseId == null || exerciseId === '') return
|
||||
if (!wasOpenRef.current) {
|
||||
wasOpenRef.current = true
|
||||
setStack([
|
||||
{
|
||||
exerciseId: Number(exerciseId),
|
||||
variantId: variantId ?? null,
|
||||
peekExtras: peekExtras ?? null,
|
||||
},
|
||||
])
|
||||
}
|
||||
}, [open, exerciseId, variantId, peekExtras])
|
||||
|
||||
const top = stack.length ? stack[stack.length - 1] : null
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !top?.exerciseId) {
|
||||
setExercise(null)
|
||||
setErr(null)
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
@@ -54,7 +78,7 @@ export default function ExercisePeekModal({
|
||||
setLoading(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const data = await api.getExercise(exerciseId)
|
||||
const data = await api.getExercise(top.exerciseId)
|
||||
if (!cancelled) setExercise(data)
|
||||
} catch (e) {
|
||||
if (!cancelled) setErr(e.message || 'Laden fehlgeschlagen')
|
||||
@@ -65,10 +89,45 @@ export default function ExercisePeekModal({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, exerciseId, variantId])
|
||||
}, [open, top?.exerciseId])
|
||||
|
||||
const variant =
|
||||
top?.variantId != null &&
|
||||
top.variantId !== '' &&
|
||||
exercise?.variants?.length
|
||||
? exercise.variants.find((v) => String(v.id) === String(top.variantId)) || null
|
||||
: null
|
||||
|
||||
const isCombination =
|
||||
exercise && String(exercise.exercise_kind || 'simple').toLowerCase().trim() === 'combination'
|
||||
|
||||
const comboMethodProfileEffective = useMemo(() => {
|
||||
if (!exercise || !isCombination) return {}
|
||||
const fromPeek =
|
||||
top?.peekExtras?.catalog_method_profile &&
|
||||
typeof top.peekExtras.catalog_method_profile === 'object' &&
|
||||
!Array.isArray(top.peekExtras.catalog_method_profile) &&
|
||||
Object.keys(top.peekExtras.catalog_method_profile).length > 0
|
||||
? top.peekExtras.catalog_method_profile
|
||||
: exercise.method_profile || {}
|
||||
return effectiveComboMethodProfile(fromPeek, top?.peekExtras?.planning_method_profile ?? null)
|
||||
}, [exercise, isCombination, top?.peekExtras])
|
||||
|
||||
const planningAdjustedBadge =
|
||||
top?.peekExtras?.planning_method_profile != null &&
|
||||
typeof top.peekExtras.planning_method_profile === 'object' &&
|
||||
!Array.isArray(top.peekExtras.planning_method_profile)
|
||||
|
||||
const pushCandidatePeek = (id) => {
|
||||
const n = Number(id)
|
||||
if (!Number.isFinite(n)) return
|
||||
setStack((s) => [...s, { exerciseId: n, variantId: null, peekExtras: null }])
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const sheetWide = Boolean(isCombination && exercise && !loading)
|
||||
|
||||
return (
|
||||
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div
|
||||
@@ -77,7 +136,7 @@ export default function ExercisePeekModal({
|
||||
aria-modal="true"
|
||||
aria-labelledby="exercise-peek-title"
|
||||
style={{
|
||||
maxWidth: '620px',
|
||||
maxWidth: sheetWide ? 'min(840px, 96vw)' : '620px',
|
||||
width: '100%',
|
||||
maxHeight: '88vh',
|
||||
display: 'flex',
|
||||
@@ -85,9 +144,19 @@ export default function ExercisePeekModal({
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="exercise-peek-title" className="admin-modal-sheet__title">
|
||||
{loading ? '…' : exercise?.title || titleFallback || `Übung #${exerciseId}`}
|
||||
<div className="admin-modal-sheet__header" style={{ gap: '8px', flexWrap: 'wrap' }}>
|
||||
{stack.length > 1 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ flexShrink: 0, fontWeight: 600 }}
|
||||
onClick={() => setStack((s) => (s.length > 1 ? s.slice(0, -1) : s))}
|
||||
>
|
||||
← Zurück
|
||||
</button>
|
||||
) : null}
|
||||
<h3 id="exercise-peek-title" className="admin-modal-sheet__title" style={{ flex: '1 1 200px', minWidth: 0 }}>
|
||||
{loading ? '…' : exercise?.title || titleFallback || (top?.exerciseId != null ? `Übung #${top.exerciseId}` : 'Übung')}
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" onClick={onClose}>
|
||||
Schließen
|
||||
@@ -103,6 +172,20 @@ export default function ExercisePeekModal({
|
||||
{!loading && err && <p style={{ color: 'var(--danger)' }}>{err}</p>}
|
||||
{!loading && exercise && (
|
||||
<>
|
||||
{isCombination ? (
|
||||
<>
|
||||
<CombinationPlanBracket
|
||||
methodArchetype={exercise.method_archetype || ''}
|
||||
methodProfile={comboMethodProfileEffective}
|
||||
combinationSlots={Array.isArray(exercise.combination_slots) ? exercise.combination_slots : []}
|
||||
planningAdjusted={planningAdjustedBadge}
|
||||
candidateInteraction="button"
|
||||
onCandidatePeek={pushCandidatePeek}
|
||||
/>
|
||||
<hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '1rem 0' }} />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{variant ? (
|
||||
<div
|
||||
style={{
|
||||
@@ -170,13 +253,17 @@ export default function ExercisePeekModal({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{exerciseId && (
|
||||
{top?.exerciseId != null ? (
|
||||
<div style={{ padding: '0 1rem 1rem', flexShrink: 0 }}>
|
||||
<Link to={`/exercises/${exerciseId}`} className="btn btn-secondary" style={{ width: '100%', textDecoration: 'none', textAlign: 'center', display: 'block' }}>
|
||||
<Link
|
||||
to={`/exercises/${top.exerciseId}`}
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%', textDecoration: 'none', textAlign: 'center', display: 'block' }}
|
||||
>
|
||||
Vollständige Übungsseite öffnen
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* Übungssuche mit Volltext-, KI-/Semantikfeld (aktuell gleiche Engine wie Suche) und erweiterten Filtern.
|
||||
* Paginierung bis max. 100 Treffer pro Request (API-Limit).
|
||||
*/
|
||||
import React, { useState, useEffect, useMemo, useCallback } from 'react'
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
||||
@@ -32,6 +33,8 @@ export default function ExercisePickerModal({
|
||||
multiSelect = false,
|
||||
onSelectExercises = null,
|
||||
enableQuickCreateDraft = false,
|
||||
/** Wenn gesetzt: z. B. ['simple'] oder ['combination'] — sonst alle Übungsarten */
|
||||
exerciseKindAny = undefined,
|
||||
}) {
|
||||
const { user } = useAuth()
|
||||
const [catalogs, setCatalogs] = useState({
|
||||
@@ -51,13 +54,13 @@ export default function ExercisePickerModal({
|
||||
const [list, setList] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [multiPicked, setMultiPicked] = useState([])
|
||||
const [quickOpen, setQuickOpen] = useState(false)
|
||||
const [quickTitle, setQuickTitle] = useState('')
|
||||
const [quickSummary, setQuickSummary] = useState('')
|
||||
const [quickSaving, setQuickSaving] = useState(false)
|
||||
const pickerScrollRef = useRef(null)
|
||||
|
||||
const toggleMultiPick = (ex) => {
|
||||
setMultiPicked((prev) =>
|
||||
@@ -116,7 +119,6 @@ export default function ExercisePickerModal({
|
||||
setFilters({ ...INITIAL_FILTERS })
|
||||
setFilterOpen(false)
|
||||
setList([])
|
||||
setOffset(0)
|
||||
setHasMore(false)
|
||||
setMultiPicked([])
|
||||
setQuickOpen(false)
|
||||
@@ -213,13 +215,18 @@ export default function ExercisePickerModal({
|
||||
if (filters.include_archived) q.include_archived = true
|
||||
if (debouncedSearch) q.search = debouncedSearch
|
||||
if (debouncedAi) q.ai_search = debouncedAi
|
||||
if (
|
||||
Array.isArray(exerciseKindAny) &&
|
||||
exerciseKindAny.length > 0
|
||||
) {
|
||||
q.exercise_kind_any = exerciseKindAny
|
||||
}
|
||||
return q
|
||||
}, [filters, debouncedSearch, debouncedAi])
|
||||
}, [filters, debouncedSearch, debouncedAi, exerciseKindAny])
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
if (!open || !catalogsReady) return
|
||||
setLoading(true)
|
||||
setOffset(0)
|
||||
try {
|
||||
const batch = await api.listExercises({
|
||||
...queryBase,
|
||||
@@ -230,7 +237,6 @@ export default function ExercisePickerModal({
|
||||
})
|
||||
setList(Array.isArray(batch) ? batch : [])
|
||||
setHasMore(batch?.length === PAGE_SIZE)
|
||||
setOffset(batch?.length ?? 0)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert(e.message || 'Laden fehlgeschlagen')
|
||||
@@ -247,6 +253,8 @@ export default function ExercisePickerModal({
|
||||
|
||||
const loadMore = async () => {
|
||||
if (!hasMore || loadingMore || loading) return
|
||||
const last = list[list.length - 1]
|
||||
if (!last?.id || last.updated_at == null) return
|
||||
setLoadingMore(true)
|
||||
try {
|
||||
const batch = await api.listExercises({
|
||||
@@ -254,11 +262,14 @@ export default function ExercisePickerModal({
|
||||
include_archived: true,
|
||||
include_variants: true,
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
cursor_updated_at:
|
||||
typeof last.updated_at === 'string'
|
||||
? last.updated_at
|
||||
: new Date(last.updated_at).toISOString(),
|
||||
cursor_id: last.id,
|
||||
})
|
||||
setList((prev) => [...prev, ...(Array.isArray(batch) ? batch : [])])
|
||||
setHasMore(batch?.length === PAGE_SIZE)
|
||||
setOffset((o) => o + (batch?.length ?? 0))
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert(e.message || 'Mehr laden fehlgeschlagen')
|
||||
@@ -267,6 +278,14 @@ export default function ExercisePickerModal({
|
||||
}
|
||||
}
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: list.length,
|
||||
getScrollElement: () => pickerScrollRef.current,
|
||||
estimateSize: () => 88,
|
||||
overscan: 8,
|
||||
getItemKey: (index) => String(list[index]?.id ?? index),
|
||||
})
|
||||
|
||||
const resetFilters = () => setFilters({ ...INITIAL_FILTERS })
|
||||
|
||||
const submitQuickCreate = async () => {
|
||||
@@ -576,7 +595,11 @@ export default function ExercisePickerModal({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 1rem' }}>
|
||||
<div
|
||||
ref={pickerScrollRef}
|
||||
data-testid="exercise-picker-scroll"
|
||||
style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 1rem' }}
|
||||
>
|
||||
{!catalogsReady || (loading && list.length === 0) ? (
|
||||
<div style={{ textAlign: 'center', padding: '2rem' }}>
|
||||
<div className="spinner" />
|
||||
@@ -588,8 +611,18 @@ export default function ExercisePickerModal({
|
||||
<p style={{ fontSize: '13px', color: 'var(--text2)', marginBottom: 10 }}>
|
||||
{list.length} angezeigt{hasMore ? ' · weiter unten „Mehr laden“' : ''}
|
||||
</p>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{list.map((ex) => {
|
||||
<div
|
||||
role="list"
|
||||
aria-label="Übungstreffer"
|
||||
style={{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
height: rowVirtualizer.getTotalSize(),
|
||||
}}
|
||||
>
|
||||
{rowVirtualizer.getVirtualItems().map((vi) => {
|
||||
const ex = list[vi.index]
|
||||
if (!ex) return null
|
||||
const picked = multiPicked.some((p) => p.id === ex.id)
|
||||
const rowInner = (
|
||||
<>
|
||||
@@ -606,11 +639,37 @@ export default function ExercisePickerModal({
|
||||
{ex.focus_area}
|
||||
</span>
|
||||
)}
|
||||
{(ex.exercise_kind || '').toLowerCase().trim() === 'combination' ? (
|
||||
<span
|
||||
className="exercise-tag"
|
||||
style={{
|
||||
marginTop: 6,
|
||||
marginLeft: 6,
|
||||
background: 'var(--accent-soft)',
|
||||
color: 'var(--accent-dark)',
|
||||
}}
|
||||
>
|
||||
Kombination
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
if (multiSelect) {
|
||||
return (
|
||||
<li key={ex.id}>
|
||||
return (
|
||||
<div
|
||||
key={vi.key}
|
||||
role="listitem"
|
||||
data-index={vi.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
transform: `translateY(${vi.start}px)`,
|
||||
paddingBottom: 8,
|
||||
}}
|
||||
>
|
||||
{multiSelect ? (
|
||||
<label
|
||||
className="tu-ex-picker-multi-row"
|
||||
style={{
|
||||
@@ -620,7 +679,6 @@ export default function ExercisePickerModal({
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
marginBottom: 8,
|
||||
borderRadius: '8px',
|
||||
border: picked ? '2px solid var(--accent)' : '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
@@ -637,34 +695,30 @@ export default function ExercisePickerModal({
|
||||
/>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>{rowInner}</div>
|
||||
</label>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<li key={ex.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelectExercise(ex)
|
||||
onClose()
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
marginBottom: 8,
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{rowInner}
|
||||
</button>
|
||||
</li>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelectExercise(ex)
|
||||
onClose()
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{rowInner}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
{hasMore && (
|
||||
<div style={{ textAlign: 'center', marginTop: 12 }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={loadingMore} onClick={loadMore}>
|
||||
|
||||
@@ -6,6 +6,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import ExercisePickerModal from './ExercisePickerModal'
|
||||
|
||||
const VIS_OPTIONS = [
|
||||
@@ -102,6 +103,8 @@ export default function ExerciseProgressionGraphPanel({
|
||||
}) {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
|
||||
const filteredGraphVisOptions = useMemo(
|
||||
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
||||
[isSuperadmin],
|
||||
@@ -134,6 +137,10 @@ export default function ExerciseProgressionGraphPanel({
|
||||
const [notesDraft, setNotesDraft] = useState('')
|
||||
const [uiTab, setUiTab] = useState('overview')
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedGraphId(null)
|
||||
}, [tenantClubDepKey])
|
||||
|
||||
const refreshGraphs = useCallback(async () => {
|
||||
const list = await api.listExerciseProgressionGraphs()
|
||||
setGraphs(Array.isArray(list) ? list : [])
|
||||
@@ -171,7 +178,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [refreshGraphs])
|
||||
}, [refreshGraphs, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedGraphId) {
|
||||
@@ -1055,7 +1062,12 @@ export default function ExerciseProgressionGraphPanel({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ExercisePickerModal open={pickerOpen} onClose={() => setPickContext(null)} onSelectExercise={applyPickedExercise} />
|
||||
<ExercisePickerModal
|
||||
open={pickerOpen}
|
||||
onClose={() => setPickContext(null)}
|
||||
onSelectExercise={applyPickedExercise}
|
||||
exerciseKindAny={['simple']}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
|
||||
/**
|
||||
* Rechtstext-Absatz aus Markdown (ohne Roht-HTML; Links mit target=_blank).
|
||||
*/
|
||||
export default function LegalDocumentBody({ content, muted }) {
|
||||
if (content == null || content === '') return null
|
||||
return (
|
||||
<div className={`legal-doc-body ${muted ? 'legal-doc-body--muted' : ''}`}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkBreaks]}
|
||||
components={{
|
||||
a: ({ href, children }) => (
|
||||
<a href={href} target="_blank" rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useEffect } from 'react'
|
||||
import LegalDocumentBody from './LegalDocumentBody'
|
||||
import { legalSectionNumber } from '../utils/legalPdfExport'
|
||||
|
||||
/** Inhalt wie auf der öffentlichen Rechtstextseite (inkl. §-Nummerierung). */
|
||||
export function LegalDocumentPublicPreviewContent({
|
||||
title,
|
||||
sections,
|
||||
showDraftNotice = true,
|
||||
metaLine,
|
||||
}) {
|
||||
const safeTitle = (title || '').trim() || 'Ohne Titel'
|
||||
|
||||
return (
|
||||
<div className="legal-admin-preview-inner">
|
||||
{showDraftNotice && (
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1.25rem',
|
||||
borderLeft: '4px solid var(--warn)',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
<strong style={{ color: 'var(--text1)' }}>Vorschau</strong>
|
||||
<p style={{ margin: '0.35rem 0 0', fontSize: '0.88rem', color: 'var(--text2)' }}>
|
||||
So erscheint der Text für Besucher nach Veröffentlichung (Markdown wird gerendert, §-Nummern wie online).
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{metaLine && (
|
||||
<p style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '0 0 1rem' }}>{metaLine}</p>
|
||||
)}
|
||||
<h1 style={{ margin: '0 0 1.5rem', color: 'var(--text1)', fontSize: '1.5rem' }}>{safeTitle}</h1>
|
||||
{(sections || []).map((section, i) => (
|
||||
<div key={i} style={{ marginBottom: '1.75rem' }}>
|
||||
<h2 style={{ fontSize: '1.05rem', marginBottom: '0.4rem', color: 'var(--text1)' }}>
|
||||
{section.heading?.trim()
|
||||
? `${legalSectionNumber(i)} ${section.heading}`
|
||||
: legalSectionNumber(i)}
|
||||
</h2>
|
||||
<LegalDocumentBody content={section.content} />
|
||||
</div>
|
||||
))}
|
||||
{sections?.length === 0 && (
|
||||
<p style={{ color: 'var(--text3)', fontSize: '0.9rem' }}>Noch keine Abschnitte.</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Modal: gerenderte Rechtstext-Vorschau (Editor oder gespeicherte Version).
|
||||
*/
|
||||
export function LegalPreviewModal({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
sections,
|
||||
metaLine,
|
||||
loading,
|
||||
showDraftNotice = true,
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="legal-preview-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="legal-preview-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="legal-preview-modal-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="legal-preview-modal__header">
|
||||
<h3 id="legal-preview-modal-title" style={{ margin: 0, fontSize: '1.05rem' }}>
|
||||
Öffentliche Darstellung
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div className="legal-preview-modal__body">
|
||||
{loading ? (
|
||||
<div className="spinner" style={{ margin: '2rem auto' }} />
|
||||
) : (
|
||||
<LegalDocumentPublicPreviewContent
|
||||
title={title}
|
||||
sections={sections}
|
||||
metaLine={metaLine}
|
||||
showDraftNotice={showDraftNotice}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Gemeinsamer Medienvorschau-Dialog.
|
||||
*
|
||||
* Props:
|
||||
* title – Anzeigename des Mediums (Dateiname o.ä.)
|
||||
* media – Medienobjekt (mime_type, embed_url, asset_legal_hold_active, media_type)
|
||||
* fileUrl – Bereits aufgelöste Datei-URL (null für Embed-only-Medien)
|
||||
* onClose – Pflicht
|
||||
* onReport – optional; wenn gesetzt, erscheint "Melden"-Button
|
||||
* onEdit – optional; wenn gesetzt, erscheint "Bearbeiten"-Button
|
||||
*/
|
||||
import React from 'react'
|
||||
|
||||
export default function MediaPreviewModal({ title, media, fileUrl, onClose, onReport, onEdit }) {
|
||||
const mlow = (media?.mime_type || '').toLowerCase()
|
||||
const isHeic = mlow.includes('heic') || mlow.includes('heif')
|
||||
const isImage = !isHeic && (media?.mime_type?.startsWith('image/') || media?.media_type === 'image')
|
||||
const isVideo = media?.mime_type?.startsWith('video/') || media?.media_type === 'video'
|
||||
const isPdf = mlow.includes('pdf')
|
||||
const isLegalHold = !!media?.asset_legal_hold_active
|
||||
const canReport = onReport && !isLegalHold
|
||||
|
||||
function handleBackdrop(e) {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}
|
||||
|
||||
function handleKeyDown(e) {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Medienvorschau"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.55)',
|
||||
zIndex: 1100,
|
||||
overflow: 'auto',
|
||||
padding: '16px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
onClick={handleBackdrop}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{ maxWidth: 720, width: '100%', maxHeight: '90vh', overflow: 'auto', padding: '1.25rem' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', gap: '0.5rem' }}>
|
||||
<h3 style={{ margin: 0, fontSize: '1rem', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{title || 'Vorschau'}
|
||||
</h3>
|
||||
<div style={{ display: 'flex', gap: '0.4rem', flexShrink: 0 }}>
|
||||
{canReport && (
|
||||
<button type="button" className="btn btn-secondary" style={{ fontSize: '0.85rem', padding: '5px 10px' }} onClick={onReport}>
|
||||
Melden
|
||||
</button>
|
||||
)}
|
||||
{onEdit && (
|
||||
<button type="button" className="btn btn-secondary" style={{ fontSize: '0.85rem', padding: '5px 10px' }} onClick={onEdit}>
|
||||
Bearbeiten
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '0.85rem', padding: '5px 10px' }}
|
||||
onClick={onClose}
|
||||
aria-label="Schließen"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
{isLegalHold ? (
|
||||
<p style={{ color: 'var(--danger)', fontSize: '0.9rem' }}>
|
||||
Dieses Medium ist gesperrt und steht nicht zur Verfügung.
|
||||
</p>
|
||||
) : media?.embed_url ? (
|
||||
<p style={{ fontSize: '14px', wordBreak: 'break-all' }}>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">{media.embed_url}</a>
|
||||
</p>
|
||||
) : isHeic ? (
|
||||
<div>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>
|
||||
HEIC/HEIF — in diesem Browser oft keine eingebettete Vorschau. Zum Ansehen herunterladen oder im neuen Tab öffnen.
|
||||
</p>
|
||||
{fileUrl && (
|
||||
<a className="btn btn-secondary" href={fileUrl} target="_blank" rel="noopener noreferrer">
|
||||
Datei öffnen
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
) : isImage ? (
|
||||
<img
|
||||
key={media?.id}
|
||||
alt=""
|
||||
src={fileUrl}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', maxHeight: '70vh', objectFit: 'contain', display: 'block' }}
|
||||
/>
|
||||
) : isVideo ? (
|
||||
<video
|
||||
key={media?.id}
|
||||
src={fileUrl}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
style={{ width: '100%', borderRadius: '8px', maxHeight: '70vh' }}
|
||||
>
|
||||
Wiedergabe nicht unterstützt.
|
||||
</video>
|
||||
) : isPdf ? (
|
||||
<div>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>PDF — zur Ansicht im neuen Tab öffnen.</p>
|
||||
{fileUrl && (
|
||||
<a className="btn btn-secondary" href={fileUrl} target="_blank" rel="noopener noreferrer">
|
||||
PDF öffnen
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
) : fileUrl ? (
|
||||
<p style={{ fontSize: '14px' }}>
|
||||
<a href={fileUrl} target="_blank" rel="noreferrer">Datei öffnen</a>
|
||||
</p>
|
||||
) : (
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>Keine Vorschau verfügbar.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user