Compare commits
130
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81d1e9bdfd | ||
|
|
85163ad440 | ||
|
|
502dddd3b3 | ||
|
|
00edc7a93d | ||
|
|
d50bed428b | ||
|
|
49adb395dd | ||
|
|
3214055531 | ||
|
|
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 | ||
|
|
4c974620d8 | ||
|
|
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 | ||
|
|
3134160003 | ||
|
|
01be9ffcd4 | ||
|
|
b19940c997 | ||
|
|
30c1c259d2 | ||
|
|
24c70c5ea0 | ||
|
|
624c19dcba | ||
|
|
f54372d7b5 | ||
|
|
c46f5f99be | ||
|
|
58a38702b9 | ||
|
|
dbc9057601 | ||
|
|
59fb8a5527 | ||
|
|
6136813f60 | ||
|
|
a7cecca36f | ||
|
|
d82b805ffa | ||
|
|
bab9b178a4 | ||
|
|
c8c40474d1 | ||
|
|
5cf775c920 | ||
|
|
337f29401b | ||
|
|
311a106d93 | ||
|
|
979e328cef | ||
|
|
cc51b0f08f | ||
|
|
f035b5bb0b | ||
|
|
f745e5d082 | ||
|
|
b6de1f15ea | ||
|
|
3ff47779e0 | ||
|
|
d3055f6f2f | ||
|
|
f354bd9f77 | ||
|
|
01636b5baf | ||
|
|
3e4fa0dc39 | ||
|
|
8d85649cf8 | ||
|
|
3f0d02edab | ||
|
|
4fb77d6927 | ||
|
|
696cb09bf4 | ||
|
|
33fedd5ec6 | ||
|
|
c8a08f8a94 | ||
|
|
d04ebee1f6 | ||
|
|
0c1fbab0ef | ||
|
|
a7d68c0646 | ||
|
|
a34dc19f5d | ||
|
|
9227b98431 | ||
|
|
390b0ecb73 | ||
|
|
7e7adfab54 | ||
|
|
bce235b9f6 | ||
|
|
5334836207 | ||
|
|
38d78abc3b | ||
|
|
a143532486 | ||
|
|
2f54fef88e |
No files matched your search
@@ -1,37 +1,42 @@
|
||||
# Shinkan Jinkendo - Projekt-Status
|
||||
|
||||
**Stand:** 2026-05-07
|
||||
**Version (Code):** 0.8.48 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260507045` (u. a. `media_assets`, `platform_media_storage`)
|
||||
**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):** **Medienbibliothek `/media`** ergänzt den Archiv-Picker: **Lifecycle-Filter** (aktiv / Papierkorb / ausgeblendet), **Copyright bearbeiten** (`PATCH`), **Vorschau** inkl. Papierkorb bei Verwaltungsrecht; API-Liste `copyright_notice`; zuvor **§4.2 Promotion official** (Übung + Medien).
|
||||
**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) · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)
|
||||
**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** (neu priorisiert, Stand 2026-05-07):
|
||||
**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`): Filter, Copyright, Lifecycle-Aktionen; Ausbau: Sichtbarkeit bearbeiten, Bulk, Quotas.
|
||||
3. **Tests & Observability:** gezielte pytest-Abdeckung für Archiv/Verknüpfen; optional Retention-Job-Dry-Run dokumentieren.
|
||||
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
|
||||
3. **Tests & Observability:** gezielte pytest-Abdeckung für Archiv/Verknüpfen/Lifecycle; Retention-Job (`scripts/media_retention_job.py`) in Betrieb/Doku verankern.
|
||||
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
|
||||
5. **Inline-Medien im Fließtext** (Spec §11) — bewusst **nach** Promotion/Copyright und tragfähigem Archiv-Workflow.
|
||||
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:** Leitplanken in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; kein Big-Bang vor stabiler Archiv-/Governance-Basis.
|
||||
**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`.
|
||||
|
||||
---
|
||||
|
||||
@@ -50,7 +55,7 @@
|
||||
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
|
||||
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
|
||||
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
|
||||
| **040–045** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets`, Plattform-Speicherpfad** | ✅ | 🔲 |
|
||||
| **040–046** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets` (046 z. B. Tags/GIN), Plattform-Speicherpfad** | ✅ Dev | 🔲 Prod |
|
||||
|
||||
---
|
||||
|
||||
@@ -103,10 +108,11 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
### 🔲 In Arbeit / Backlog
|
||||
|
||||
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (Release 0.8.42 ff.)
|
||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` (Spec §4.2) — 0.8.47
|
||||
- [x] **Medien:** Medienbibliothek `/media` (Lifecycle-Filter, Copyright PATCH, Vorschau); Ausbau Manager/Bulk/S3 — Roadmap
|
||||
- [ ] **Medien:** Inline im Fließtext — nach Spec §11, nach Promotion/Archiv-Reife
|
||||
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (0.8.42 ff.)
|
||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
|
||||
- [x] **Medien:** Medienbibliothek `/media` (Filter, Tags, Copyright, Bulk-Lifecycle/PATCH, Lesemodus für eingeschränkte Rollen bei `official`)
|
||||
- [x] **Medien:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
|
||||
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
|
||||
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
||||
- [ ] Responsive Design / Dark Mode / PWA
|
||||
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
||||
@@ -137,7 +143,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
### Dev
|
||||
|
||||
Branch `develop`; Migrations bis mindestens **045** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
|
||||
Branch `develop`; Migrations bis mindestens **046** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
|
||||
|
||||
### Prod
|
||||
|
||||
@@ -149,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-05 | ✅ Aktualisiert (u. a. 036–037) |
|
||||
| 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 |
|
||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-05 | ✅ Aktualisiert (037) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-05 | ✅ Aktualisiert |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-30 | ✅ Ergänzt Progressions-API |
|
||||
| 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-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-04-27 | ✅ Aktualisiert (Limits) |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-07 | ✅ §11 Inline-Plan, Drift-Tab |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-07 | ✅ Medien-Meilenstein aktualisiert |
|
||||
| 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-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
|
||||
|
||||
---
|
||||
|
||||
@@ -170,4 +177,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-07
|
||||
**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.3
|
||||
**Stand:** 2026-05-05 (Migration **036–037:** Rahmen nur Bibliothek; Slot‑Inhalt über Blueprint‑`training_units` + Sektionen/Items wie Planung — siehe `TRAINING_FRAMEWORK_SPEC.md` §2)
|
||||
**Version:** 0.4.5
|
||||
**Stand:** 2026-05-12 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||
|
||||
---
|
||||
@@ -476,6 +476,16 @@ skill_level_definitions (
|
||||
|
||||
---
|
||||
|
||||
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||
|
||||
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
|
||||
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
|
||||
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
|
||||
- **Geplant:** **Inline-Verweise** in Fließtextfeldern auf dieselbe Verknüpfung (`exercise_media.id`) — **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
|
||||
|
||||
---
|
||||
|
||||
## Methodenbezug (§11.5)
|
||||
|
||||
**Prinzip:** Genau EINE Hauptmethode, optional weitere Nebenmethoden.
|
||||
|
||||
@@ -4,10 +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 (Abschnitt 11.2) |
|
||||
| [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):** siehe [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md) und [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.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,9 +1,9 @@
|
||||
# Gelieferte Features & technische Basis (Q2 2026)
|
||||
|
||||
**Stand:** 2026-05-05
|
||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.10**, **DB_SCHEMA_VERSION 20260505037**
|
||||
**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**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
|
||||
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/`.
|
||||
|
||||
---
|
||||
|
||||
@@ -17,7 +17,7 @@ Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren**
|
||||
| **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL |
|
||||
| **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** |
|
||||
| **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` |
|
||||
| **037** | **`training_units.framework_slot_id`**, strukturierter Ablauf wie Planung; Entfall **`training_framework_slot_exercises`**; **`origin_framework_slot_id`** |
|
||||
| **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
|
||||
---
|
||||
|
||||
@@ -79,7 +79,7 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`)
|
||||
|
||||
- **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante.
|
||||
- **Medien** wie zuvor (Formularteil).
|
||||
- **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
|
||||
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
|
||||
|
||||
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
|
||||
@@ -123,16 +123,44 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
|
||||
---
|
||||
|
||||
## 12. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
||||
|
||||
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
||||
|
||||
### 12.1 Datenbank & Router
|
||||
|
||||
- **`media_assets`**, **`platform_media_storage`**, **`exercise_media.media_asset_id`** (Dedupe `sha256` + Sichtbarkeit + `club_id` je nach Policy).
|
||||
- Router **`media_assets.py`**: Listen, PATCH, Lifecycle, Dateiauslieferung, Bulk; Integration in **`exercises.py`** (Upload, `from-asset`, Promotion/Copyright-Regeln bei `official` / Vereinsübungen).
|
||||
|
||||
### 12.2 Funktional (Ist)
|
||||
|
||||
- Zentrale **Medienbibliothek** Frontend **`/media`**: Filter (Lifecycle, Medientyp, Verein für Admins), Suche, Tags, Copyright bearbeiten (rollengerecht), Kacheln/Liste, Nutzungs-Hinweise (Übungen/Planung wo implementiert).
|
||||
- **Papierkorb** mehrstufig (`trash_soft` / `trash_hidden`), Recovery, Superadmin-Purge; strukturierte Fehlercodes bei Governance (u. a. Übung **`CLUB_MEDIA_*`**).
|
||||
- **Speicher:** Pfadkonvention **`library/{vereinssegment}/…`** mit Medienkind-Unterordnern; Umzug bei Sichtbarkeits-/Vereinsänderung; effektives Wurzelverzeichnis `MEDIA_ROOT` + Superadmin-`local_relative_root`.
|
||||
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
|
||||
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
|
||||
|
||||
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
|
||||
|
||||
- Platzhalter-Syntax: `{{exerciseMedia:id}}` (normalisiert auf `data-shinkan-exercise-media`), Validierung gegen `exercise_media` der aktuellen Übung.
|
||||
- Zentraler Anzeigepfad über `ExerciseRichTextBlock` inkl. Sanitize und Lifecycle-Hinweisen.
|
||||
- RTE-Workflow: Modal „Medien im Text“ (Mediathek + Upload), separates „Embed im Text“-Modal, Größenwahl (`small|medium|full`) und sprechende Platzhalter-Captions.
|
||||
- Bearbeiten: kompakte Medien-Kacheln + Drag&Drop in Textfelder; Auto-Scroll beim Drag aktiv.
|
||||
- UX-Schutz: Warnung bei Wechsel „Ansehen“ mit ungespeicherten Änderungen; Detailseite bietet Rückweg zur Bearbeitung.
|
||||
|
||||
---
|
||||
|
||||
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
|
||||
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
||||
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
|
||||
|
||||
---
|
||||
|
||||
## 13. Verweise
|
||||
## 14. Verweise
|
||||
|
||||
| Thema | Dokument |
|
||||
|--------|----------|
|
||||
@@ -140,5 +168,7 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
||||
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||
| Upload formal | `technical/MEDIA_UPLOAD_SPEC.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` |
|
||||
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
|
||||
|
||||
**Version:** 0.5.2
|
||||
**Stand:** 2026-05-05
|
||||
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints in `training_units`; Entfall `training_framework_slot_exercises`) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`).
|
||||
**Version:** 0.5.3
|
||||
**Stand:** 2026-05-07
|
||||
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints) und für Medien-Archiv bis **045+** (`media_assets`, …) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`) und **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
---
|
||||
|
||||
@@ -47,8 +47,7 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
|
||||
| **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ |
|
||||
| **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ |
|
||||
| **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ |
|
||||
|
||||
---
|
||||
| **040–046** | **2026-05** | **Mitgliedschaft/Anträge, Übungs-Governance-Erweiterungen, `media_assets`, `platform_media_storage`, `exercise_media.media_asset_id`, Tags/GIN u. a.** — exakte Nummern: `backend/migrations/`; fachliche Norm Medien: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** | ✅ je Umgebung |
|
||||
|
||||
## Migration 022: Skills Schema Complete (BREAKING CHANGE)
|
||||
|
||||
@@ -267,9 +266,11 @@ exercise_skills (
|
||||
UNIQUE (exercise_id, skill_id) -- Migration 020
|
||||
)
|
||||
|
||||
-- Varianten & Medien
|
||||
-- Varianten & Medien (028+ Embed/Datei; 045+ optional media_asset_id → media_assets)
|
||||
exercise_variants (id, exercise_id, name, description, ...)
|
||||
exercise_media (id, exercise_id, type, url, title, description, ...)
|
||||
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
||||
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
||||
platform_media_storage (id, local_relative_root, …)
|
||||
```
|
||||
|
||||
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# Exercises API Specification
|
||||
|
||||
**Version:** 1.4
|
||||
**Datum:** 2026-04-30
|
||||
**Version:** 1.5
|
||||
**Datum:** 2026-05-08
|
||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
|
||||
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
||||
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
||||
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||
@@ -335,7 +336,8 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
|
||||
### `PUT /exercises/{id}`
|
||||
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Inline-Hinweis:** Rich-Text-Felder (`summary`, `goal`, `execution`, `preparation`, `trainer_notes` sowie `execution_changes` bei Varianten) unterstützen Platzhalter `{{exerciseMedia:id}}`, die serverseitig auf kanonisches Span-Markup normalisiert werden. Beim erstmaligen Anlegen ohne vorhandene `exercise_media` wird dies mit 400 abgelehnt.
|
||||
|
||||
**Response:** `200 OK` (full exercise object)
|
||||
|
||||
@@ -459,7 +461,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
- `media_type` (enum, required) - `image | video | document | sketch`
|
||||
- `title` (string, optional)
|
||||
- `description` (string, optional)
|
||||
- `context` (enum, optional) - `ablauf | detail | trainer_hint`
|
||||
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
|
||||
|
||||
**Entweder `file` ODER `embed_url` (nicht beides).**
|
||||
|
||||
@@ -505,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
{
|
||||
"title": "Neuer Titel",
|
||||
"description": "Neue Beschreibung",
|
||||
"is_primary": true,
|
||||
"context": "detail"
|
||||
"is_primary": true
|
||||
}
|
||||
```
|
||||
|
||||
`context` bleibt backendseitig kompatibel, wird in aktuellen Bearbeitungsflüssen jedoch nicht mehr aktiv zur UI-Zuordnung verwendet (Inline-Platzhalter priorisiert).
|
||||
|
||||
**Response:** `200 OK` (media object)
|
||||
|
||||
---
|
||||
@@ -893,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
- File size: max 50MB
|
||||
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
||||
- Embed platforms: `youtube, instagram, vimeo`
|
||||
- Inline-Rich-Text: `{{exerciseMedia:id}}` bzw. `data-shinkan-exercise-media="<id>"`; optional `data-shinkan-exercise-media-size="small|medium|full"` für Layout.
|
||||
|
||||
### Exercise Block
|
||||
- `name`: 3-200 chars
|
||||
@@ -947,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0
|
||||
**Letzte Änderung:** 2026-04-24
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Version:** 1.5
|
||||
**Letzte Änderung:** 2026-05-08
|
||||
**Status:** Living Spec
|
||||
@@ -1,7 +1,7 @@
|
||||
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
|
||||
|
||||
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
|
||||
**Stand:** 2026-05-07 (§11 Inline-Plan ergänzt)
|
||||
**Stand:** 2026-05-08 (Ist-Changelog Medien bis 0.8.64; §11 Inline umgesetzt und erweitert)
|
||||
**ersetzt/ergänzt:** operatives Upload-Format/Größen siehe weiterhin `MEDIA_UPLOAD_SPEC.md`
|
||||
**normative Governance:** Sichtbarkeit & Mandanten wie `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`; bei Abweichung zwischen Dokumenten hat der Zugriffsplan Vorrang, **außer** dieses Dokument präzisiert explizit nur den Medien-Domain.
|
||||
|
||||
@@ -186,26 +186,33 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung mit Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
|
||||
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Zeitpunkt der Umsetzung; Drift-Vermeidung ohne jetzigen Vollbau. |
|
||||
| 2026-05-08 | **0.8.64:** Bearbeiten-UX erweitert: Drag&Drop mit Auto-Scroll in Richtung Rich-Text, Medienliste in Kachel-Grid, Warnhinweis vor Wechsel „Ansehen“ bei ungespeicherten Änderungen + Rückweg „Zurück zur Bearbeitung“, Katalogvorschau ohne separaten Anhangs-Medienstreifen. |
|
||||
| 2026-05-08 | **0.8.63:** Inline-Medien-Picker als Modal (Mediathek/Upload + separates Embed-Modal), Größenwahl `small|medium|full`, Platzhalter-Caption (`data-shinkan-exercise-media-caption`), Wiederverwendung bereits verknüpfter Assets im Picker, kompakter Medienbereich mit Drag&Drop in Textfelder. |
|
||||
| 2026-05-08 | **0.8.60 §11:** Inline in Übungstexten (`{{exerciseMedia:id}}` / `data-shinkan-exercise-media`); Server-Normalisierung + Validierung; Client-Sanitize und zentraler Block-Renderer (`ExerciseRichTextBlock`); CREATE ohne bestehende `exercise_media` lehnt Platzhalter ab. |
|
||||
| 2026-05-07 | **0.8.59:** Dokumentation — Aktiver Verein (Profil/Header/`effective_club_id`) für Plattform-Admin und UI-Dropdown synchron; kein fachliches Archiv-Schema-Change. |
|
||||
| 2026-05-07 | **0.8.58:** Medien **`official`:** Lifecycle schwerpunktmäßig **Superadmin** (nicht Plattform-Admin); Bearbeitungsdialog Bibliothek für andere Rollen **Lesemodus**; Superadmin-Upload: Vereinskontext folgt aktiv gesetztem Verein / `effective_club_id`. |
|
||||
| 2026-05-07 | **0.8.47–0.8.57 (Auszug):** Übung **`official`** nur Superadmin; Vereinsübungen mit File-Assets: **Copyright-Pflicht**; Speicherpfade **`library/`** mit Vereinsordner (Name+c{id}), Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeit; Bibliothek-GET mit Filtern/Tags/Nutzungs-Anzeige; Bulk-Lifecycle/PATCH; Lesemodus/Kacheln; Konflikt **409** bei Upload-Dedupe vs. Papierkorb + UI-Reaktivierung. |
|
||||
| 2026-05-07 | **0.8.42–0.8.43:** Papierkorb-Lifecycle API, Retention-Skript; **`POST …/exercises/{id}/media/from-asset`**; Übungs-UI Archiv verknüpfen / Vorschau. |
|
||||
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
|
||||
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Umsetzung **nach** tragfähigem Archiv — siehe **`docs/HANDOVER.md`** §5. |
|
||||
| 2026-05-07 | **Medienmanager (Basis):** `GET /api/media-assets?lifecycle=…`, `copyright_notice` in Response; `PATCH` Copyright; `GET …/file` für Papierkorb-Zeilen bei Verwaltungsrecht; UI-Route `/media` (Medienbibliothek). |
|
||||
|
||||
---
|
||||
|
||||
## 11. Inline-Medien im Fließtext (Planung, Leitplanken)
|
||||
## 11. Inline-Medien im Fließtext (Umsetzung & Leitplanken)
|
||||
|
||||
**Status:** nicht implementiert; verbindlich nur als **Richtschnur**, damit später **kein Big-Bang-Refactor** nötig ist.
|
||||
**Status:** Frontend-Renderer und API-Validierung/Normalisierung umgesetzt (App ≥ 0.8.60); verbindliche Leitplanken unten.
|
||||
|
||||
### 11.1 Ziel
|
||||
|
||||
- Medien (Player, Bild) sollen **an definierter Stelle** in Feldern wie Ablauf / Ziel / Notizen erscheinen können – zusätzlich oder statt reiner Zuordnung zu den Sektionen `ablauf` / `detail` / `trainer_hint`.
|
||||
- **Keine zweite Sichtbarkeit:** Inline verweist immer auf dieselbe **Übungs-Medium-Zeile** (`exercise_media.id`) bzw. indirekt auf das gleiche Asset wie die Medienliste; **Lesen/Ausliefern** nur nach **bestehender** Übungs- + Medien-Governance (§4.1).
|
||||
|
||||
### 11.2 Platzhalter-Konvention (Vorschlag für spätere Umsetzung)
|
||||
### 11.2 Platzhalter-Konvention (**festgelegt**)
|
||||
|
||||
- Beim **Speichern** im Rich-Text: markierter Verweis, z. B.
|
||||
`data-shinkan-exercise-media="<numerische exercise_media.id>"` auf einem **neutralen** Element (`span`/`figure`), **oder** eine interne Kurzsyntax (`{{exerciseMedia:123}}`), die der Server beim Speichern in eine **kanonische** HTML-Form überführt.
|
||||
- **Final festlegen** beim Start der Implementierung (ein Format, nicht mehrere parallele).
|
||||
- **Kanonisches Markup nach Speichern:** `<span data-shinkan-exercise-media="<numerische exercise_media.id>" class="shinkan-inline-media"></span>`.
|
||||
- **Erweiterung (UI/Lesbarkeit):** optionales Attribut `data-shinkan-exercise-media-size="small|medium|full"` (Default `medium`) und optional `data-shinkan-exercise-media-caption="..."` für sprechende Platzhalter-Chips im Editor.
|
||||
- **Kurzsyntax (Eingabe/Import):** `{{exerciseMedia:123}}` — Server normalisiert beim Speichern (PUT Übung / Varianten) in das kanonische `span`; **CREATE** ohne bestehende `exercise_media`-Zeilen verwirft Platzhalter mit **400**.
|
||||
|
||||
### 11.3 Rendering & Sicherheit
|
||||
|
||||
@@ -214,14 +221,15 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
||||
|
||||
### 11.4 Koexistenz mit Sektions-Medien
|
||||
|
||||
- **Liste + Inline** dürfen dasselbe `exercise_media` referenzieren (ein Player an zwei Stellen) – Produktentscheidung: später optional „Duplikat vermeiden“-Hinweis in der UI.
|
||||
- **Liste + Inline** dürfen dasselbe `exercise_media` referenzieren (ein Player an zwei Stellen).
|
||||
- Stand 0.8.64: Katalog-/Vorschaupfade priorisieren Inline-Darstellung; ein zusätzlicher Anhangsblock wird dort nicht mehr parallel erzwungen.
|
||||
- Import/Wiki: vor großen Content-Migrationen **Syntax festlegen**, damit nicht irreversibel „falsches“ HTML importiert wird.
|
||||
|
||||
### 11.5 Wann umsetzen (Reihenfolge)
|
||||
|
||||
1. **Vorher:** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Basis-Papierkorb (§5) – jeweils stabil.
|
||||
2. **Danach:** Inline implementieren, sobald Trainer-Feedback oder Content-Menge den Bedarf **konkret** bestätigt (typisch nach 1–2 Beta-Zyklen).
|
||||
3. **Nicht nötig:** vorher kompletten Block-Editor einführen; **Platzhalter im bestehenden RTE** ist der vorgesehene **schlanke** Einstieg.
|
||||
1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
|
||||
2. **Umgesetzt (Stand 0.8.64):** Platzhalter/Kurzsyntax + zentraler Frontend-Render-Pfad + Server-Validierung gemäß §11.1–11.4; Editor-Einstieg „Medium einfügen“ inkl. Modal-Picker (Mediathek/Upload), separates Embed-Modal, Größenwahl und Drag&Drop aus der Medienliste.
|
||||
3. **Editor:** kein Zwang zum vollen Block-Editor vorab; **Platzhalter im bestehenden RTE** ist der vorgesehene schlanke Einstieg.
|
||||
|
||||
### 11.6 Refactor-Vermeidung (jetzt schon)
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
# Media Upload & Embed Specification
|
||||
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-04-27
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
|
||||
**Version:** 1.2
|
||||
**Datum:** 2026-05-07
|
||||
**Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
|
||||
|
||||
> **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:**
|
||||
> Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung).
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
# 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`) |
|
||||
| `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,7 @@ 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 |
|
||||
| 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 +37,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-12 — Trainingsmodule (`/api/training-modules*`); Governance wie Planungsbibliothek.
|
||||
|
||||
---
|
||||
|
||||
### Changelog (Fortführung)
|
||||
|
||||
- **2026-05-12:** `training_modules` Router 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.
|
||||
@@ -1,11 +1,14 @@
|
||||
# Session Handover (Verweis)
|
||||
|
||||
**Dieses Dokument ist veraltet.** Der aktuelle Entwicklungsstand und die Handover-Basis stehen hier:
|
||||
**Aktuelle Handover-Basis (Stand Implementierung + Medien):**
|
||||
|
||||
👉 **`docs/HANDOVER.md`** (Projektroot: `c:\Dev\shinkan-jinkendo\docs\HANDOVER.md`)
|
||||
👉 **`docs/HANDOVER.md`** (Projektroot)
|
||||
|
||||
Dort: Fähigkeits-/Reifegrad-Stand (Bindings, Resolve, Export/Import, Matrix-Stack), Verweise auf `.claude/docs` für Anforderungen, und **nächste Priorität Übungen (UI/CRUD/Medien)**.
|
||||
Dort: **Medien-Archiv/Medienbibliothek (Ist)**, **geplante Inline-Medienverlinkung (§11 Spec)**, Reifegrad/Matrix, Rahmenprogramm, nächste sinnvolle Arbeitspakete für neue Sessions.
|
||||
|
||||
**Projektstatus-Kachel:** `.claude/docs/PROJECT_STATUS.md`
|
||||
**Medien Single Source of Truth:** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
|
||||
---
|
||||
|
||||
*Historischer Inhalt aus April 2026 wurde durch `docs/HANDOVER.md` ersetzt.*
|
||||
*Die historische „Übungen Lücke“-Fassung (2026-04) ist überholt; Medien-UI und Archiv sind seit 0.8.41+ weitgehend umgesetzt — Details `docs/HANDOVER.md` §4.*
|
||||
@@ -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.
|
||||
@@ -58,7 +58,8 @@ return {"message": "Fehler", "success": False}
|
||||
### 1.4 Mandanten & Zugriffsschicht (Shinkan / ACCESS_LAYER)
|
||||
|
||||
**Verbindlicher Rahmen:** `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
|
||||
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher, geplante Inline-Verlinkung §11):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
**Session-Handover (Ist + nächste Schritte):** `docs/HANDOVER.md`
|
||||
**Fortlaufendes Inventar:** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
|
||||
|
||||
**Definition of Done für neue oder geänderte geschützte APIs**, sobald Daten **Verein**, **Sichtbarkeit** oder **mandantenbezogene Listen** betreffen:
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
|
||||
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
|
||||
3. Spez-Index: **`.claude/docs/README.md`**
|
||||
4. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
4. **Session-Handover (aktuelle Prioritäten, Medien-Ist):** **`docs/HANDOVER.md`**
|
||||
5. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ ENVIRONMENT=production
|
||||
|
||||
# Medien (Docker Compose): SHINKAN_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
|
||||
# MEDIA_ROOT = gleicher Pfad im Container (muss mit dem Mount-Ziel übereinstimmen — FastAPI).
|
||||
# Prod: Verzeichnis VOR erstem "docker compose up" anlegen (z. B. sudo mkdir -p …/prod).
|
||||
# Wenn Docker meldet "chown … operation not permitted": oft NAS/NFS oder Rechte — lokalen Pfad nutzen.
|
||||
SHINKAN_MEDIA_HOST=/shinkan-media
|
||||
MEDIA_ROOT=/app/media
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
|
||||
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
||||
> | Medien-Archiv, Lifecycle, Promotion | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.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`** |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
@@ -57,7 +59,7 @@ backend/
|
||||
└── routers/ # Router-Module
|
||||
auth · profiles · clubs · groups · skills · methods
|
||||
exercises · exercise_progression_graphs · training_units · training_programs
|
||||
planning · import_wiki · admin · membership
|
||||
planning · import_wiki · admin · membership · media_assets
|
||||
|
||||
frontend/src/
|
||||
├── App.jsx # Root, Auth-Gates, Navigation
|
||||
@@ -82,10 +84,11 @@ frontend/src/
|
||||
|
||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||
|
||||
Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**; Kern: Übungen, Varianten, Medien, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md` und `TRAINING_FRAMEWORK_SPEC.md` §2.
|
||||
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)
|
||||
|
||||
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
|
||||
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
|
||||
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
|
||||
|
||||
@@ -106,7 +109,7 @@ Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**
|
||||
- `exercises` - Übungen (Kernobjekt)
|
||||
- `exercise_variants` - Übungsvarianten
|
||||
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
||||
- `exercise_media` - Medien (Bilder, Videos); Zielbild Archiv & Lifecycle: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. **Inline im Fließtext** (Übungstexte): geplant §11 derselben Spec — Anker `exercise_media.id`, einheitlicher Render-Pfad; noch nicht implementiert.
|
||||
- `exercise_media` - Medien (Bilder, Videos); Zielbild Archiv & Lifecycle: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. **Inline im Fließtext** (Übungstexte) ist implementiert (Spec §11): Anker `exercise_media.id`, einheitlicher Render-Pfad.
|
||||
|
||||
**Trainingsplanung / Rahmen:**
|
||||
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
||||
|
||||
@@ -13,6 +13,7 @@ Shinkan ist eine moderne Web- und Mobile-App für Kampfsport-Trainer und Vereine
|
||||
- **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten
|
||||
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
|
||||
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
|
||||
- **Medien:** Zentrale **Medienbibliothek** (`/media`), Archiv mit Lifecycle/Papierkorb, Verknüpfung in Übungen — Norm: `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` · Einstieg: `docs/HANDOVER.md`
|
||||
|
||||
## Nicht in Shinkan
|
||||
|
||||
|
||||
+48
-23
@@ -91,7 +91,12 @@ def can_manage_club_org(cur, profile_id: int, club_id: int, global_role: Optiona
|
||||
|
||||
|
||||
def can_plan_in_club(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
|
||||
"""Trainingsgruppen anlegen / planen: Admin-Rollen im Verein oder Plattform."""
|
||||
"""Trainingsgruppe anlegen u.Ä.; Vereins-rollentrainer, Content-Editor, Spartenleitung …
|
||||
|
||||
Hinweis: ``content_editor`` ist derzeit zusammen mit ``trainer``/``division_lead`` in diesem
|
||||
gemeinsamen Strang gebündelt — u.a. Vereinsübungen bearbeiten (s. exercises) und
|
||||
Trainingsgruppen unter ``clubs``. Es gibt noch keine eigene Nur-Content-Guard pro Endpunkt.
|
||||
"""
|
||||
if is_platform_admin(global_role):
|
||||
return True
|
||||
return has_club_role(
|
||||
@@ -157,13 +162,13 @@ def assert_valid_governance_visibility(
|
||||
visibility: str,
|
||||
club_id: Optional[int],
|
||||
) -> None:
|
||||
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Plattform-Admin."""
|
||||
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Superadmin."""
|
||||
if visibility not in _GOVERNANCE_VISIBILITY:
|
||||
raise HTTPException(status_code=400, detail="Ungültige visibility")
|
||||
if visibility == "official" and not is_platform_admin(role):
|
||||
if visibility == "official" and not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Plattform-Admins dürfen offizielle Inhalte setzen",
|
||||
detail="Nur Superadmins dürfen offizielle Inhalte setzen",
|
||||
)
|
||||
if visibility == "club":
|
||||
if club_id is None:
|
||||
@@ -198,25 +203,45 @@ def exercise_visible_to_profile(
|
||||
created_by: Optional[int],
|
||||
global_role: Optional[str],
|
||||
) -> bool:
|
||||
"""Leserechte einer Übung. Für neue Codepfade lieber `library_content_visible_to_profile` verwenden."""
|
||||
if is_platform_admin(global_role):
|
||||
"""
|
||||
Leserechte einer Übung (und analoger Bibliotheksobjekte).
|
||||
|
||||
Vereinsbezogene Inhalte (visibility club): aktiv nur mit **aktiver** Mitgliedschaft in diesem Verein.
|
||||
Mitgliedschaft mit status **inactive** sperrt — auch für Plattform-/Super-Admins — solange eine
|
||||
Mitgliedschaft existiert.
|
||||
|
||||
Ist man kein Mitglied dieses Vereins, behalten Plattform-Admins den bisherigen „Audit“-Zugang
|
||||
zum Vereinskontext ohne eigene Mitgliedschaft.
|
||||
"""
|
||||
vis = (visibility or "").strip().lower()
|
||||
plat = is_platform_admin(global_role)
|
||||
pid = int(profile_id)
|
||||
|
||||
if vis == "official":
|
||||
return True
|
||||
if visibility == "official":
|
||||
if created_by is not None and int(created_by) == pid:
|
||||
return True
|
||||
if created_by is not None and created_by == profile_id:
|
||||
return True
|
||||
if visibility == "private":
|
||||
if vis == "private":
|
||||
return plat
|
||||
if vis != "club":
|
||||
return False
|
||||
if visibility == "club":
|
||||
if exercise_club_id is None:
|
||||
return False
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(profile_id, exercise_club_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
return False
|
||||
if exercise_club_id is None:
|
||||
return False
|
||||
try:
|
||||
ecid = int(exercise_club_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.status
|
||||
FROM club_members cm
|
||||
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(pid, ecid),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return plat
|
||||
st_raw = row["status"] if isinstance(row, dict) else row[0]
|
||||
return str(st_raw or "active").strip().lower() == "active"
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
Übungs-Fließtext: Inline-Verweise auf exercise_media.id (MEDIA_ASSETS_AND_ARCHIVE_SPEC §11).
|
||||
|
||||
- Kurzsyntax beim Speichern → kanonisches <span data-shinkan-exercise-media="…">.
|
||||
- Verweise müssen für die betreffende Übung gültige exercise_media-Zeilen sein.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import FrozenSet, Optional, Set
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
# {{exerciseMedia:123}} (Whitespace tolerant, case-insensitive Schlüssel)
|
||||
_BRACE_PATTERN = re.compile(r"\{\{\s*exerciseMedia\s*:\s*(\d+)\s*\}\}", re.IGNORECASE)
|
||||
# bereits gespeichertes Markup (einfache Anführungszeichen-varianten durch Regex abgedeckt)
|
||||
_DATA_ATTR_PATTERN = re.compile(r'data-shinkan-exercise-media\s*=\s*["\']?(\d+)["\']?', re.IGNORECASE)
|
||||
|
||||
RICH_HTML_EXERCISE_FIELDS: FrozenSet[str] = frozenset(
|
||||
{"summary", "goal", "execution", "preparation", "trainer_notes"}
|
||||
)
|
||||
|
||||
|
||||
def normalize_inline_exercise_media_markup(html: Optional[str]) -> Optional[str]:
|
||||
"""Wandelt {{exerciseMedia:id}} in kanonisches span mit data-shinkan-exercise-media."""
|
||||
|
||||
if html is None:
|
||||
return None
|
||||
if not isinstance(html, str):
|
||||
html = str(html)
|
||||
stripped = html.strip()
|
||||
if not stripped:
|
||||
return html
|
||||
|
||||
def _repl(match: re.Match) -> str:
|
||||
mid = int(match.group(1))
|
||||
return (
|
||||
f'<span data-shinkan-exercise-media="{mid}" data-shinkan-exercise-media-size="medium" '
|
||||
f'class="shinkan-inline-media"></span>'
|
||||
)
|
||||
|
||||
return _BRACE_PATTERN.sub(_repl, html)
|
||||
|
||||
|
||||
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
|
||||
"""Sammelt alle referenzierten exercise_media.ids aus Kurzsyntax und kanonischem Span."""
|
||||
if html is None or not isinstance(html, str):
|
||||
return set()
|
||||
if not html.strip():
|
||||
return set()
|
||||
ids: Set[int] = set()
|
||||
ids.update(int(m) for m in _BRACE_PATTERN.findall(html))
|
||||
ids.update(int(m) for m in _DATA_ATTR_PATTERN.findall(html))
|
||||
return ids
|
||||
|
||||
|
||||
def assert_no_inline_media_references_on_create(ids: Set[int]) -> None:
|
||||
"""Neue Übung hat noch keine exercise_media-Zeilen — Platzhalter verboten."""
|
||||
|
||||
if not ids:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "INLINE_EXERCISE_MEDIA_ON_CREATE",
|
||||
"message": (
|
||||
"Medienverweise im Fließtext sind beim ersten Anlegen der Übung nicht möglich. "
|
||||
"Bitte Übung ohne Platzhalter speichern, Medien hochladen oder verknüpfen "
|
||||
"und die Verweise dann bearbeiten ({{exerciseMedia:id}} oder „Medium einfügen“)."
|
||||
),
|
||||
"invalid_exercise_media_ids": sorted(ids),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def validate_inline_exercise_media_ids_for_exercise(cur, exercise_id: int, ids: Set[int]) -> None:
|
||||
"""Prüft, dass jede genannte exercise_media.id zu dieser Übung gehört."""
|
||||
|
||||
if not ids:
|
||||
return
|
||||
sid = sorted(ids)
|
||||
ph = ",".join(["%s"] * len(sid))
|
||||
cur.execute(
|
||||
f"SELECT id FROM exercise_media WHERE exercise_id = %s AND id IN ({ph})",
|
||||
(exercise_id, *sid),
|
||||
)
|
||||
found = set()
|
||||
for row in cur.fetchall():
|
||||
rid = row["id"] if isinstance(row, dict) else row[0]
|
||||
found.add(int(rid))
|
||||
missing = ids - found
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "INLINE_EXERCISE_MEDIA_INVALID",
|
||||
"message": "Ein oder mehrere eingebettete Medien-Verweise gehören nicht zu dieser Übung.",
|
||||
"invalid_exercise_media_ids": sorted(missing),
|
||||
},
|
||||
)
|
||||
+8
-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, 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,19 @@ 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(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
|
||||
+26
-10
@@ -21,26 +21,33 @@ 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:
|
||||
"""
|
||||
Papierkorb Stufe 2 / Recovery / Reaktivierung — nicht für trash_soft (siehe assert_can_trash_soft).
|
||||
§5.2: official nur Plattform-Admin; club Vereinsorga; privat nur Uploader.
|
||||
§5.2: official nur Superadmin; club Vereinsorga; privat nur Uploader (Plattform-Admin sonst wie bisher).
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = (tenant.global_role or "").strip().lower()
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Offizielle Medien dürfen nur von Superadmins geändert oder gelöscht werden",
|
||||
)
|
||||
return
|
||||
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
uid = asset.get("uploaded_by_profile_id")
|
||||
if vis == "private":
|
||||
if uid is not None and int(uid) == int(profile_id):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||
if vis == "official":
|
||||
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
|
||||
if vis == "club":
|
||||
cid = asset.get("club_id")
|
||||
if cid is None:
|
||||
@@ -54,15 +61,20 @@ def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict)
|
||||
def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
"""
|
||||
Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads.
|
||||
Vereinsmedien: Vereinsorga; official: Plattform-Admin; Superadmin: immer.
|
||||
Vereinsmedien: Vereinsorga; official: nur Superadmin; Plattform-Admin: sonst wie Verein/privat.
|
||||
"""
|
||||
role_raw = tenant.global_role
|
||||
role = (role_raw or "").strip().lower()
|
||||
if is_superadmin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Offizielle Medien dürfen nur von Superadmins in den Papierkorb gelegt werden",
|
||||
)
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
uid = asset.get("uploaded_by_profile_id")
|
||||
cid = asset.get("club_id")
|
||||
pid = int(tenant.profile_id)
|
||||
@@ -80,8 +92,6 @@ def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
status_code=403,
|
||||
detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen",
|
||||
)
|
||||
if vis == "official":
|
||||
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||
|
||||
|
||||
@@ -269,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(
|
||||
@@ -276,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),
|
||||
)
|
||||
@@ -284,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),
|
||||
)
|
||||
@@ -3,9 +3,23 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
_CLUB_SLUG_TRANS = str.maketrans(
|
||||
{
|
||||
"ä": "ae",
|
||||
"ö": "oe",
|
||||
"ü": "ue",
|
||||
"ß": "ss",
|
||||
"Ä": "ae",
|
||||
"Ö": "oe",
|
||||
"Ü": "ue",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _default_media_root() -> Path:
|
||||
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
|
||||
@@ -44,6 +58,70 @@ def get_effective_media_root(cur: Any) -> Path:
|
||||
return (base / rel).resolve()
|
||||
|
||||
|
||||
def library_media_kind_dir(mime_type: Optional[str], ext: str) -> str:
|
||||
"""
|
||||
Unterordner unter library/* — an API-Filter media_kind angelehnt (image/video/pdf/other).
|
||||
|
||||
Bei fehlendem MIME wird anhand der Dateiendung geraten (letzte Instanz: other).
|
||||
"""
|
||||
m = (mime_type or "").strip().lower()
|
||||
x = (ext or "").strip().lower()
|
||||
if x and not x.startswith("."):
|
||||
x = "." + x
|
||||
|
||||
if m.startswith("image/"):
|
||||
return "image"
|
||||
if m.startswith("video/"):
|
||||
return "video"
|
||||
if m == "application/pdf" or (m and "pdf" in m):
|
||||
return "pdf"
|
||||
|
||||
if x in (
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".webp",
|
||||
".heic",
|
||||
".heif",
|
||||
".bmp",
|
||||
".svg",
|
||||
".avif",
|
||||
):
|
||||
return "image"
|
||||
if x in (".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"):
|
||||
return "video"
|
||||
if x == ".pdf":
|
||||
return "pdf"
|
||||
return "other"
|
||||
|
||||
|
||||
def library_club_path_segment(club_id: int, club_name: Optional[str]) -> str:
|
||||
"""
|
||||
Ein Verzeichnissegment pro Verein: aus Anzeigenamen abgeleitet + „-c{id}“ für Eindeutigkeit
|
||||
(Umbenennung, Kollisionen nach Slugify). Nur [a-z0-9-], keine Pfad-Sonderzeichen.
|
||||
Fehlt der Name / Slug leer → „verein-c{id}“.
|
||||
"""
|
||||
cid = int(club_id)
|
||||
if cid < 1:
|
||||
raise ValueError("club_id muss eine positive Ganzzahl sein")
|
||||
|
||||
raw = unicodedata.normalize("NFKC", (club_name or "").strip()).translate(_CLUB_SLUG_TRANS).lower()
|
||||
raw = re.sub(r"[^a-z0-9]+", "-", raw)
|
||||
raw = raw.strip("-")
|
||||
if len(raw) > 48:
|
||||
raw = raw[:48].rstrip("-")
|
||||
|
||||
if not raw:
|
||||
base = f"verein-c{cid}"
|
||||
else:
|
||||
base = f"{raw}-c{cid}"
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", base):
|
||||
raise ValueError("Ungültiger abgeleiteter Vereins-Ordnername")
|
||||
return base
|
||||
|
||||
|
||||
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
|
||||
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
|
||||
key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
|
||||
@@ -55,3 +133,97 @@ def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
|
||||
except ValueError:
|
||||
return None
|
||||
return p
|
||||
|
||||
|
||||
def library_storage_key(
|
||||
visibility: str,
|
||||
club_id: Optional[int],
|
||||
sha256_hex: str,
|
||||
ext: str,
|
||||
*,
|
||||
uploader_profile_id: Optional[int] = None,
|
||||
mime_type: Optional[str] = None,
|
||||
club_name: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Relativer Speicherpfad unter MEDIA_ROOT für lokale media_assets.
|
||||
|
||||
- official → library/official/{kind}/{sha256}{ext}
|
||||
- club (vereinsgeteilt) → library/{vereins-segment}/{kind}/{sha256}{ext}
|
||||
- private → dieselbe Ordnerlogik wie Verein: library/{vereins-segment}/{kind}/{sha}.u{profile}{ext}
|
||||
|
||||
Dateiname bei private: „{sha}.u{profile_id}{ext}“ (nicht Unterordner u{…}), damit Ordnerstruktur wie bei „Verein“.
|
||||
|
||||
Vereins-Segment: aus club_name abgeleitet + „-c{club_id}“ — siehe library_club_path_segment.
|
||||
|
||||
kind ∈ {image, video, pdf, other} — siehe library_media_kind_dir.
|
||||
|
||||
Kein Ordnername „private“ auf der Platte. Private Dateien unterscheiden sich nur im Dateinamen (.u{Profil} vor Endung).
|
||||
"""
|
||||
vis = (visibility or "private").strip().lower()
|
||||
if vis not in ("private", "club", "official"):
|
||||
raise ValueError(f"Ungültige Sichtbarkeit für Speicherpfad: {visibility!r}")
|
||||
|
||||
sha = (sha256_hex or "").strip().lower()
|
||||
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
||||
raise ValueError("sha256_hex muss 64 Hex-Zeichen sein")
|
||||
|
||||
e = (ext or "").strip()
|
||||
if not e:
|
||||
e = ".bin"
|
||||
if not e.startswith("."):
|
||||
e = "." + e
|
||||
if ".." in e or "/" in e or "\\" in e or "\x00" in e:
|
||||
raise ValueError("Ungültige Dateiendung")
|
||||
|
||||
kind = library_media_kind_dir(mime_type, e)
|
||||
e = e[:16]
|
||||
club_blob = f"{kind}/{sha}{e}"
|
||||
if vis == "official":
|
||||
return f"library/official/{club_blob}"
|
||||
if club_id is None:
|
||||
raise ValueError("Verein (club_id) ist für diese Sichtbarkeit auf der Platte erforderlich")
|
||||
cid = int(club_id)
|
||||
if cid < 1:
|
||||
raise ValueError("club_id muss eine positive Ganzzahl sein")
|
||||
club_seg = library_club_path_segment(cid, club_name)
|
||||
if vis == "club":
|
||||
return f"library/{club_seg}/{club_blob}"
|
||||
if uploader_profile_id is None:
|
||||
raise ValueError("uploader_profile_id ist für private Archiv-Medien erforderlich")
|
||||
up = int(uploader_profile_id)
|
||||
if up < 1:
|
||||
raise ValueError("uploader_profile_id muss positiv sein")
|
||||
priv_name = f"{sha}.u{up}{e}"
|
||||
return f"library/{club_seg}/{kind}/{priv_name}"
|
||||
|
||||
|
||||
def relocate_local_media_file(media_root: Path, old_storage_key: str, new_storage_key: str) -> None:
|
||||
"""
|
||||
Physisches Verschieben bei geändertem library_*-Pfad (z. B. nach PATCH visibility/club_id).
|
||||
|
||||
- Kein Op, wenn Quelle fehlt aber Ziel bereits existiert (idempotent).
|
||||
- Erwartet storage_backend=local; Aufrufer prüft das.
|
||||
"""
|
||||
if (old_storage_key or "").replace("\\", "/").lstrip("/") == (new_storage_key or "").replace(
|
||||
"\\", "/"
|
||||
).lstrip("/"):
|
||||
return
|
||||
|
||||
old_p = path_under_media_root(media_root, old_storage_key)
|
||||
new_p = path_under_media_root(media_root, new_storage_key)
|
||||
if old_p is None or new_p is None:
|
||||
raise ValueError("Ungültiger Speicherpfad (Path-Traversal)")
|
||||
|
||||
if new_p.is_file():
|
||||
if not old_p.is_file():
|
||||
return
|
||||
if old_p.resolve() == new_p.resolve():
|
||||
return
|
||||
raise FileExistsError(f"Zieldatei existiert bereits: {new_storage_key}")
|
||||
|
||||
if not old_p.is_file():
|
||||
raise FileNotFoundError(f"Medien-Quelldatei nicht gefunden: {old_storage_key}")
|
||||
|
||||
new_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(old_p), str(new_p))
|
||||
@@ -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.';
|
||||
+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
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Gemeinsame Passwort-Link-Erzeugung (Sessions) + Mailtext — wie /auth/forgot-password."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
RESET_TOKEN_PREFIX = "reset_"
|
||||
|
||||
|
||||
def public_reset_link(token: str) -> str:
|
||||
base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
return f"{base}/reset-password?token={token}"
|
||||
|
||||
|
||||
def revoke_pending_password_resets_for_profile(cur: Any, profile_id: int) -> None:
|
||||
"""Entfernt alte Reset-Sessions eines Profils, damit nur der neueste Link aktiv ist."""
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE profile_id = %s AND token LIKE %s
|
||||
""",
|
||||
(profile_id, f"{RESET_TOKEN_PREFIX}%"),
|
||||
)
|
||||
|
||||
|
||||
def insert_password_reset_session(cur: Any, profile_id: int, *, hours_valid: int = 1) -> str:
|
||||
"""
|
||||
Legt reset_<token>-Session an. Gibt den Klartext-Token zurück (wie bei forgot-password).
|
||||
"""
|
||||
raw = secrets.token_urlsafe(32)
|
||||
expires = datetime.now() + timedelta(hours=hours_valid)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token, profile_id, expires_at, created_at)
|
||||
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
|
||||
""",
|
||||
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def password_reset_email_body(*, recipient_name: str | None, token: str, intro: str) -> str:
|
||||
name = (recipient_name or "").strip() or "Kollege/Kollegin"
|
||||
link = public_reset_link(token)
|
||||
return f"""Hallo {name},
|
||||
|
||||
{intro}
|
||||
|
||||
Neues Passwort setzen:
|
||||
{link}
|
||||
|
||||
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
|
||||
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
|
||||
|
||||
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
|
||||
|
||||
def issue_password_reset_via_email(cur: Any, send_email_fn, *, profile_id: int, email: str, name: str | None, intro: str) -> bool:
|
||||
"""Session anlegen und Mail schicken (send_email_fn wie routers.auth.send_email)."""
|
||||
revoke_pending_password_resets_for_profile(cur, profile_id)
|
||||
raw_token = insert_password_reset_session(cur, profile_id)
|
||||
body = password_reset_email_body(recipient_name=name, token=raw_token, intro=intro)
|
||||
return send_email_fn(email, "Passwort-Link – Shinkan Jinkendo", body)
|
||||
+14
-23
@@ -20,6 +20,11 @@ from slowapi.util import get_remote_address
|
||||
from db import get_db, get_cursor
|
||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
||||
from password_reset_mail import (
|
||||
insert_password_reset_session,
|
||||
password_reset_email_body,
|
||||
revoke_pending_password_resets_for_profile,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
@@ -93,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:
|
||||
@@ -116,28 +121,14 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
|
||||
if not prof:
|
||||
# Don't reveal if email exists
|
||||
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||
revoke_pending_password_resets_for_profile(cur, prof["id"])
|
||||
raw_token = insert_password_reset_session(cur, prof["id"])
|
||||
|
||||
# Generate reset token
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now() + timedelta(hours=1)
|
||||
|
||||
# Store in sessions table (reuse mechanism)
|
||||
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||
(f"reset_{token}", prof['id'], expires.isoformat()))
|
||||
|
||||
app_base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
reset_body = f"""Hallo {prof['name']},
|
||||
|
||||
Du hast einen Passwort-Reset angefordert.
|
||||
|
||||
Reset-Link: {app_base}/reset-password?token={token}
|
||||
|
||||
Der Link ist 1 Stunde gültig.
|
||||
|
||||
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
reset_body = password_reset_email_body(
|
||||
recipient_name=prof.get("name"),
|
||||
token=raw_token,
|
||||
intro="Du hast einen Passwort-Reset angefordert.",
|
||||
)
|
||||
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
||||
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import can_manage_club_org
|
||||
from club_tenancy import can_manage_club_org, is_platform_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
@@ -106,6 +106,72 @@ def _response_one(cur, req_id: int, viewer_profile_id: int) -> Dict[str, Any]:
|
||||
return r2d(row)
|
||||
|
||||
|
||||
def _can_access_org_inbox(cur, profile_id: int, global_role: Optional[str]) -> bool:
|
||||
"""Posteingang (Beitrittsanträge bearbeiten): Plattform-Admin oder Vereinsadmin in mind. einem Verein."""
|
||||
if is_platform_admin(global_role):
|
||||
return True
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _club_ids_manageable_by_user(cur, profile_id: int, global_role: Optional[str]) -> List[int]:
|
||||
"""Club-IDs, für die der Nutzer Beitrittsanträge sehen darf."""
|
||||
if is_platform_admin(global_role):
|
||||
cur.execute("SELECT id FROM clubs WHERE status = 'active' ORDER BY name")
|
||||
return [int(r["id"]) for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT cm.club_id
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active'
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
return [int(r["club_id"]) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/me/inbox/join-requests")
|
||||
def list_inbox_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""
|
||||
Alle offenen Beitrittsanträge, die der Nutzer bearbeiten darf:
|
||||
Plattform-Admin: alle Vereine; sonst nur Vereine mit Rolle club_admin.
|
||||
"""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _can_access_org_inbox(cur, pid, role):
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff auf den Organisations-Posteingang")
|
||||
club_ids = _club_ids_manageable_by_user(cur, pid, role)
|
||||
if not club_ids:
|
||||
return []
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT r.id, r.profile_id, r.club_id, r.status, r.message, r.created_at,
|
||||
c.name AS club_name, c.abbreviation AS club_abbreviation,
|
||||
p.name AS applicant_name, p.email AS applicant_email
|
||||
FROM club_membership_requests r
|
||||
INNER JOIN clubs c ON c.id = r.club_id
|
||||
INNER JOIN profiles p ON p.id = r.profile_id
|
||||
WHERE r.status = 'pending'
|
||||
AND r.club_id = ANY(%s)
|
||||
ORDER BY r.created_at ASC
|
||||
""",
|
||||
(club_ids,),
|
||||
)
|
||||
return [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/me/club-join-requests")
|
||||
def get_my_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
pid = tenant.profile_id
|
||||
|
||||
@@ -50,6 +50,44 @@ def _club_exists(cur, club_id: int) -> bool:
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _count_other_active_club_admins(cur, club_id: int, exclude_profile_id: int) -> int:
|
||||
"""Aktive Vereinsadmins im Verein, außer exclude_profile_id."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(DISTINCT cm.profile_id)::int AS n
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.club_id = %s AND cm.status = 'active' AND cm.profile_id <> %s
|
||||
""",
|
||||
(club_id, exclude_profile_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
try:
|
||||
return int(row["n"]) if row is not None else 0
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _member_is_active_club_admin(cur, club_id: int, profile_id: int) -> bool:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.club_id = %s AND cm.profile_id = %s AND cm.status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(club_id, profile_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
_LAST_CLUB_ADMIN_MSG = (
|
||||
"Mindestens ein aktiver Vereinsadmin muss im Verein verbleiben. "
|
||||
"Weise die Rolle zuerst einem anderen Mitglied zu oder aktiviere einen anderen Vereinsadmin."
|
||||
)
|
||||
|
||||
|
||||
class ClubMemberUpsert(BaseModel):
|
||||
profile_id: int = Field(..., ge=1)
|
||||
roles: List[str] = Field(default_factory=list, description="Mindestens eine Vereinsrolle")
|
||||
@@ -77,7 +115,8 @@ def list_club_members(
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
||||
p.email, p.name,
|
||||
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
|
||||
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
|
||||
COALESCE(
|
||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
@@ -86,7 +125,7 @@ def list_club_members(
|
||||
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.club_id = %s {status_clause}
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
|
||||
ORDER BY p.name NULLS LAST, p.email
|
||||
""",
|
||||
(club_id,),
|
||||
@@ -153,7 +192,8 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
||||
p.email, p.name,
|
||||
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
|
||||
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
|
||||
COALESCE(
|
||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
@@ -162,7 +202,7 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
|
||||
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.club_id = %s AND cm.profile_id = %s
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
|
||||
""",
|
||||
(club_id, profile_id),
|
||||
)
|
||||
@@ -217,21 +257,50 @@ def update_club_member(
|
||||
if body.roles is None and body.status is None:
|
||||
return _one_member(cur, club_id, profile_id)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.status,
|
||||
COALESCE(
|
||||
ARRAY_AGG(r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
) AS roles
|
||||
FROM club_members cm
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.id = %s
|
||||
GROUP BY cm.status
|
||||
""",
|
||||
(cm_id,),
|
||||
)
|
||||
cur_row = cur.fetchone()
|
||||
current_status = (cur_row["status"] or "active").strip().lower() if cur_row else "active"
|
||||
cr = cur_row.get("roles") if cur_row else []
|
||||
if hasattr(cr, "tolist"):
|
||||
cr = cr.tolist()
|
||||
current_roles = list(cr)
|
||||
|
||||
new_status = body.status.strip().lower() if body.status is not None else current_status
|
||||
if body.status is not None and new_status not in _ALLOWED_STATUS:
|
||||
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
|
||||
|
||||
new_roles = _normalize_roles(body.roles) if body.roles is not None else current_roles
|
||||
if not new_roles:
|
||||
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||
|
||||
effective_admin = new_status == "active" and "club_admin" in set(new_roles)
|
||||
if not effective_admin:
|
||||
others = _count_other_active_club_admins(cur, club_id, profile_id)
|
||||
if others < 1:
|
||||
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
|
||||
|
||||
if body.status is not None:
|
||||
st = body.status.strip().lower()
|
||||
if st not in _ALLOWED_STATUS:
|
||||
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
|
||||
cur.execute(
|
||||
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
|
||||
(st, cm_id),
|
||||
(new_status, cm_id),
|
||||
)
|
||||
|
||||
if body.roles is not None:
|
||||
roles = _normalize_roles(body.roles)
|
||||
if not roles:
|
||||
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
|
||||
for rc in roles:
|
||||
for rc in new_roles:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||
@@ -258,6 +327,10 @@ def delete_club_member(
|
||||
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||
_assert_manage(cur, tenant, club_id)
|
||||
|
||||
if _member_is_active_club_admin(cur, club_id, profile_id):
|
||||
if _count_other_active_club_admins(cur, club_id, profile_id) < 1:
|
||||
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
|
||||
|
||||
cur.execute(
|
||||
"DELETE FROM club_members WHERE club_id = %s AND profile_id = %s RETURNING id",
|
||||
(club_id, profile_id),
|
||||
|
||||
+83
-27
@@ -5,6 +5,7 @@ Handles CRUD operations for clubs, divisions, and training groups.
|
||||
"""
|
||||
from typing import Any, List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
@@ -19,6 +20,53 @@ from club_tenancy import (
|
||||
router = APIRouter(prefix="/api", tags=["clubs"])
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> Any:
|
||||
"""Frontend sendet häufig '' für optionale Felder — ungültig für PostgreSQL TIME/INTEGER."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == "":
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _optional_int(value: Any) -> Optional[int]:
|
||||
v = _blank_to_none(value)
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
i = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return i if i > 0 else None
|
||||
|
||||
|
||||
def _normalize_co_trainer_ids(val: Any) -> List[int]:
|
||||
"""Listen von Profil-IDs für JSONB; ungültige Einträge werden verworfen."""
|
||||
if val is None:
|
||||
raw: List[Any] = []
|
||||
elif isinstance(val, list):
|
||||
raw = val
|
||||
else:
|
||||
raw = []
|
||||
out: List[int] = []
|
||||
seen = set()
|
||||
for x in raw:
|
||||
try:
|
||||
i = int(x)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if i <= 0 or i in seen:
|
||||
continue
|
||||
seen.add(i)
|
||||
out.append(i)
|
||||
return out
|
||||
|
||||
|
||||
def _co_trainer_ids_jsonb(val: Any) -> Json:
|
||||
"""psycopg2: reine list/dict für JSONB → ProgrammingError ohne Json()."""
|
||||
return Json(_normalize_co_trainer_ids(val))
|
||||
|
||||
|
||||
# ── List Clubs ────────────────────────────────────────────────────────
|
||||
@router.get("/clubs")
|
||||
def list_clubs(
|
||||
@@ -581,9 +629,15 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
||||
if not club_id or not name:
|
||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||
|
||||
trainer_id = data.get("trainer_id")
|
||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
||||
trainer_id = profile_id
|
||||
raw_tid = data.get("trainer_id")
|
||||
if role in ("trainer", "user"):
|
||||
parsed_tid = _optional_int(raw_tid)
|
||||
trainer_id = parsed_tid if parsed_tid is not None else profile_id
|
||||
else:
|
||||
trainer_id = _optional_int(raw_tid)
|
||||
|
||||
division_id = _optional_int(data.get("division_id"))
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -606,23 +660,23 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
%s, %s::jsonb, %s
|
||||
) RETURNING id
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
data.get("division_id"),
|
||||
int(club_id),
|
||||
division_id,
|
||||
name,
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
trainer_id,
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status", "active"),
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -662,6 +716,8 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
||||
if not allowed:
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE training_groups SET
|
||||
@@ -675,24 +731,24 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
||||
time_end = %s,
|
||||
location = %s,
|
||||
trainer_id = %s,
|
||||
co_trainer_ids = %s,
|
||||
co_trainer_ids = %s::jsonb,
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("division_id"),
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
data.get("trainer_id"),
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status"),
|
||||
_optional_int(data.get("division_id")),
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
_optional_int(data.get("trainer_id")),
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
group_id,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -206,32 +206,22 @@ def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context))
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if is_platform_admin(role):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
"""
|
||||
)
|
||||
else:
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
|
||||
+714
-37
File diff suppressed because it is too large.
Load diff
@@ -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]
|
||||
+1100
-73
File diff suppressed because it is too large.
Load diff
+140
-3
@@ -11,15 +11,81 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, hash_pin
|
||||
from club_tenancy import assert_club_member, memberships_with_roles, is_platform_admin
|
||||
from club_tenancy import (
|
||||
assert_club_member,
|
||||
club_ids_for_profile_with_roles,
|
||||
is_platform_admin,
|
||||
is_superadmin,
|
||||
memberships_with_roles,
|
||||
)
|
||||
from tenant_context import resolve_tenant_context, TenantContext, get_tenant_context
|
||||
from models import ProfileCreate, ProfileUpdate
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||
|
||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
||||
|
||||
|
||||
class ManagementPasswordResetBody(BaseModel):
|
||||
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
|
||||
|
||||
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
|
||||
|
||||
@field_validator("new_password", mode="before")
|
||||
@classmethod
|
||||
def _empty_pw_none(cls, v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, str) and not v.strip():
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def _target_portal_role_lower(cur, target_pid: int) -> str:
|
||||
cur.execute("SELECT lower(trim(COALESCE(role, ''))) AS r FROM profiles WHERE id = %s", (target_pid,))
|
||||
row = cur.fetchone()
|
||||
return (row.get("r") or "user") if row else "user"
|
||||
|
||||
|
||||
def _assert_can_management_password_help(cur, tenant: TenantContext, target_pid: int, *, via_email: bool) -> None:
|
||||
"""
|
||||
Wer darf eines anderen Accounts Passwort-Helfer nutzen (E-Mail-Link oder — nur Superadmin — direktes Setzen)?
|
||||
Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied in gemeinsam verwaltetem Verein.
|
||||
"""
|
||||
viewer_pid = int(tenant.profile_id)
|
||||
if target_pid == viewer_pid:
|
||||
raise HTTPException(status_code=400, detail="Eigenes Passwort unter Einstellungen ändern")
|
||||
role_raw = tenant.global_role or ""
|
||||
if is_superadmin(role_raw):
|
||||
return
|
||||
if is_platform_admin(role_raw):
|
||||
return
|
||||
managed = club_ids_for_profile_with_roles(cur, viewer_pid, "club_admin")
|
||||
if not managed:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = ANY(%s) AND status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(target_pid, list(managed)),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur für Nutzer, die in mindestens einem deiner Vereine (als Admin) aktiv sind",
|
||||
)
|
||||
if via_email and _target_portal_role_lower(cur, target_pid) in _CLUB_BLOCKED_PORTAL_TARGETS:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Für Konten mit Portal-Administrator- oder Super-Administrator-Rolle ist das nur für Super-Admins möglich",
|
||||
)
|
||||
|
||||
|
||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||
@@ -28,7 +94,7 @@ def get_current_profile(
|
||||
session=Depends(require_auth),
|
||||
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||
):
|
||||
"""Profil inkl. Vereinsmitgliedschaften; effective_club_id = aufgelöster Request-Kontext (Header vor Profilfeld)."""
|
||||
"""Profil inkl. Vereinsmitgliedschaften (aktive und temporär deaktivierte Zugänge); effective_club_id nur bei aktivem Vereinszugang."""
|
||||
profile_id = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -38,7 +104,7 @@ def get_current_profile(
|
||||
raise HTTPException(404, "Profil nicht gefunden")
|
||||
data = r2d(row)
|
||||
data.pop("pin_hash", None)
|
||||
clubs = memberships_with_roles(cur, profile_id)
|
||||
clubs = memberships_with_roles(cur, profile_id, active_only=False)
|
||||
data["clubs"] = clubs
|
||||
ac_raw = data.get("active_club_id")
|
||||
stored_ac = int(ac_raw) if ac_raw is not None and ac_raw != "" else None
|
||||
@@ -136,6 +202,68 @@ def profile_document(pid: str) -> dict:
|
||||
return d
|
||||
|
||||
|
||||
@router.post("/profiles/{pid}/management-password-reset")
|
||||
def management_password_reset(
|
||||
pid: str,
|
||||
body: ManagementPasswordResetBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Standard: E-Mail mit Reset-Link wie „Passwort vergessen“ — der PIN-Hash bleibt bis zur Bestätigung unverändert.
|
||||
Nur Super-Admins können optional `new_password` setzen (Ausnahme).
|
||||
"""
|
||||
from routers.auth import send_email
|
||||
from password_reset_mail import issue_password_reset_via_email
|
||||
|
||||
try:
|
||||
target = int(pid)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||
|
||||
direct = body.new_password is not None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id, email, name FROM profiles WHERE id = %s", (target,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
|
||||
if direct:
|
||||
role_raw = tenant.global_role or ""
|
||||
if not is_superadmin(role_raw):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Direktes Setzen eines Passworts ist nur Super-Admins vorbehalten. Bitte E-Mail-Link verwenden.",
|
||||
)
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
||||
new_hash = hash_pin(body.new_password)
|
||||
cur.execute(
|
||||
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
|
||||
(new_hash, target),
|
||||
)
|
||||
return {"ok": True, "mode": "direct"}
|
||||
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
||||
email = (row.get("email") or "").strip()
|
||||
if not email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Für dieses Profil ist keine E-Mail-Adresse hinterlegt; ein Reset-Link kann nicht versendet werden.",
|
||||
)
|
||||
name = row.get("name")
|
||||
intro = "Ein Administrator hat für dein Konto einen sicheren Link zum Setzen eines neuen Passworts angefordert."
|
||||
sent = issue_password_reset_via_email(
|
||||
cur,
|
||||
send_email,
|
||||
profile_id=target,
|
||||
email=email.lower(),
|
||||
name=name,
|
||||
intro=intro,
|
||||
)
|
||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||
|
||||
|
||||
@router.get("/profiles/{pid}")
|
||||
def get_profile(pid: str, session=Depends(require_auth)):
|
||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
||||
@@ -256,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":
|
||||
|
||||
@@ -350,21 +350,18 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
|
||||
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||
"""
|
||||
if is_platform_admin(role):
|
||||
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
|
||||
else:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
base_sel
|
||||
+ f""" WHERE ({vis_clause})
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
base_sel
|
||||
+ f""" WHERE ({vis_clause})
|
||||
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
||||
vis_params,
|
||||
)
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
|
||||
@@ -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}
|
||||
@@ -8,6 +8,7 @@ from datetime import date, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from psycopg2.extras import Json as PsycopgJson
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
@@ -17,6 +18,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"])
|
||||
|
||||
@@ -39,12 +43,28 @@ def _optional_positive_int(val, field_name: str) -> Optional[int]:
|
||||
|
||||
|
||||
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 +410,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,6 +435,19 @@ _ORIGIN_LINEAGE_FIELDS = """
|
||||
"""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _fetch_sections(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
@@ -420,7 +465,10 @@ def _fetch_sections(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
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,16 +476,34 @@ 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()]
|
||||
for it in sec["items"]:
|
||||
if it.get("item_type") != "exercise":
|
||||
continue
|
||||
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"] = []
|
||||
secs.append(sec)
|
||||
return secs
|
||||
|
||||
@@ -452,28 +518,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"),
|
||||
@@ -568,6 +639,94 @@ def _hydrate_training_unit_payload(cur, unit: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return unit
|
||||
|
||||
|
||||
def _resolve_training_unit_section_id(cur, unit_id: int, section_order_index: int) -> int:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM training_unit_sections
|
||||
WHERE training_unit_id = %s AND order_index = %s
|
||||
""",
|
||||
(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 +741,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 +763,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,6 +794,8 @@ 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,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -896,25 +1069,14 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if is_platform_admin(role):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT t.*,
|
||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||
AS sections_count
|
||||
FROM training_plan_templates t
|
||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||
"""
|
||||
)
|
||||
else:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="t",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="t",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT t.*,
|
||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||
AS sections_count
|
||||
@@ -922,8 +1084,8 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@@ -1454,6 +1616,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
|
||||
|
||||
@@ -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",
|
||||
|
||||
+60
-19
@@ -21,6 +21,22 @@ def _club_exists(cur, club_id: int) -> bool:
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def memberships_for_tenant_resolution(
|
||||
memberships: List[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Nur Zeilen mit aktivem Vereinszugang (cm.status = 'active').
|
||||
Wird genutzt, wenn /profiles/me alle Mitgliedschaften inkl. inaktiver liefert.
|
||||
"""
|
||||
out: List[Dict[str, Any]] = []
|
||||
for r in memberships:
|
||||
st_raw = r.get("membership_status")
|
||||
st = str(st_raw if st_raw is not None else "active").strip().lower()
|
||||
if st == "active":
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def parse_active_club_header(raw: Optional[str]) -> Optional[int]:
|
||||
"""Parst X-Active-Club-Id; leer → None. Ungültig → HTTP 400."""
|
||||
if raw is None:
|
||||
@@ -45,21 +61,36 @@ def library_content_visibility_sql(
|
||||
effective_club_id: Optional[int],
|
||||
) -> tuple[str, List[Any]]:
|
||||
"""
|
||||
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme):
|
||||
official, eigene private, club nur im aktiven Vereinskontext (effective_club_id).
|
||||
Plattform-Admin: keine Einschränkung (TRUE).
|
||||
Ohne effective_club_id: kein club-Zweig (nur official + private).
|
||||
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme, …):
|
||||
|
||||
- official immer
|
||||
- private: eigene (Norm) bzw. alle (Plattform-Admin/Superadmin)
|
||||
- club: nur mit **aktivem** Vereinszugang; Existenz einer nur **inactive** Mitgliedschaft schließt
|
||||
aus — auch bei Plattform-Rolle. Ist man **kein** Mitglied des Vereins, behalten Plattform-Admins
|
||||
Zugriff (Audit).
|
||||
Für Nicht-Plattform: club-Zweig nur mit effective_club_id (Mandantenfilter).
|
||||
"""
|
||||
if is_platform_admin(role):
|
||||
return "TRUE", []
|
||||
plat = is_platform_admin(role)
|
||||
parts: List[str] = [f"{alias}.visibility = 'official'"]
|
||||
params: List[Any] = []
|
||||
|
||||
parts: List[str] = [
|
||||
f"{alias}.visibility = 'official'",
|
||||
f"({alias}.visibility = 'private' AND {alias}.created_by = %s)",
|
||||
]
|
||||
params: List[Any] = [profile_id]
|
||||
if plat:
|
||||
parts.append(f"({alias}.visibility = 'private')")
|
||||
else:
|
||||
parts.append(f"({alias}.visibility = 'private' AND {alias}.created_by = %s)")
|
||||
params.append(profile_id)
|
||||
|
||||
if effective_club_id is not None:
|
||||
club_ok_plat = (
|
||||
f"({alias}.visibility = 'club' AND {alias}.club_id IS NOT NULL AND ("
|
||||
f"EXISTS (SELECT 1 FROM club_members cm WHERE cm.profile_id = %s AND cm.club_id = {alias}.club_id "
|
||||
f"AND cm.status = 'active') OR NOT EXISTS (SELECT 1 FROM club_members cm2 WHERE cm2.profile_id = %s "
|
||||
f"AND cm2.club_id = {alias}.club_id)))"
|
||||
)
|
||||
|
||||
if plat:
|
||||
parts.append(club_ok_plat)
|
||||
params.extend([profile_id, profile_id])
|
||||
elif effective_club_id is not None:
|
||||
parts.append(
|
||||
f"""(
|
||||
{alias}.visibility = 'club'
|
||||
@@ -80,7 +111,7 @@ def library_content_visibility_sql(
|
||||
class TenantContext:
|
||||
profile_id: int
|
||||
global_role: str
|
||||
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header oft None
|
||||
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header: Profil-Verein wenn existent
|
||||
effective_club_id: Optional[int]
|
||||
club_ids: frozenset[int]
|
||||
memberships: List[Dict[str, Any]]
|
||||
@@ -97,10 +128,13 @@ def resolve_tenant_context(
|
||||
invalid_header_policy: str = "reject",
|
||||
) -> TenantContext:
|
||||
"""
|
||||
Mitgliedschaften: wenn nicht übergeben, wird aus der DB geladen (aktive Mitgliedschaften).
|
||||
Mitgliedschaften: wenn nicht übergeben, lädt ``active_only=True`` aus der DB.
|
||||
Übergabe z. B. von ``/profiles/me``: Liste darf auch **deaktivierte** Vereinszugänge
|
||||
(`membership_status` = inactive) enthalten — für ``club_ids`` und Mandantenwahl werden nur aktive verwendet.
|
||||
|
||||
Auflösung effective_club_id:
|
||||
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → None.
|
||||
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
|
||||
active_club_id falls der Verein existiert, sonst None.
|
||||
- Sonst: gültiger Header zwingend Mitgliedschaft — bei ``reject`` sonst 403, bei ``ignore`` wie ohne Header.
|
||||
Ohne gültigen Header: gespeichertes active_club_id wenn Mitglied; sonst einziger Verein;
|
||||
bei mehreren ohne gültige Vorgabe → min(club_ids) (Fallback).
|
||||
@@ -109,15 +143,22 @@ def resolve_tenant_context(
|
||||
header_cid = parse_active_club_header(header_raw)
|
||||
|
||||
if memberships is None:
|
||||
memberships = memberships_with_roles(cur, profile_id, active_only=True)
|
||||
membership_rows = memberships_with_roles(cur, profile_id, active_only=True)
|
||||
else:
|
||||
membership_rows = memberships_for_tenant_resolution(memberships)
|
||||
|
||||
club_ids = frozenset(int(r["id"]) for r in memberships if r.get("id") is not None)
|
||||
club_ids = frozenset(int(r["id"]) for r in membership_rows if r.get("id") is not None)
|
||||
|
||||
if is_platform_admin(role_lc):
|
||||
if header_cid is not None:
|
||||
if not _club_exists(cur, header_cid):
|
||||
raise HTTPException(status_code=400, detail="Verein nicht gefunden")
|
||||
effective = header_cid
|
||||
elif (
|
||||
stored_active_club_id is not None
|
||||
and _club_exists(cur, stored_active_club_id)
|
||||
):
|
||||
effective = stored_active_club_id
|
||||
else:
|
||||
effective = None
|
||||
return TenantContext(
|
||||
@@ -125,7 +166,7 @@ def resolve_tenant_context(
|
||||
global_role=role_lc,
|
||||
effective_club_id=effective,
|
||||
club_ids=club_ids,
|
||||
memberships=memberships,
|
||||
memberships=membership_rows,
|
||||
)
|
||||
|
||||
chosen_header = header_cid
|
||||
@@ -153,7 +194,7 @@ def resolve_tenant_context(
|
||||
global_role=role_lc,
|
||||
effective_club_id=effective,
|
||||
club_ids=club_ids,
|
||||
memberships=memberships,
|
||||
memberships=membership_rows,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -2,29 +2,30 @@
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from tenant_context import library_content_visibility_sql, parse_active_club_header
|
||||
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
|
||||
|
||||
|
||||
def test_library_visibility_sql_platform_admin_no_filter():
|
||||
def test_library_visibility_sql_platform_admin_restricts_club_by_membership():
|
||||
sql, params = library_content_visibility_sql(
|
||||
alias="e",
|
||||
profile_id=1,
|
||||
role="admin",
|
||||
effective_club_id=None,
|
||||
)
|
||||
assert sql == "TRUE"
|
||||
assert params == []
|
||||
assert "e.visibility = 'official'" in sql
|
||||
assert "club_members" in sql
|
||||
assert params == [1, 1]
|
||||
|
||||
|
||||
def test_library_visibility_sql_superadmin():
|
||||
def test_library_visibility_sql_superadmin_uses_membership_clause_for_club_visibility():
|
||||
sql, params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=2,
|
||||
role="superadmin",
|
||||
effective_club_id=100,
|
||||
)
|
||||
assert sql == "TRUE"
|
||||
assert params == []
|
||||
assert "club_members" in sql
|
||||
assert params == [2, 2]
|
||||
|
||||
|
||||
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
|
||||
@@ -74,3 +75,88 @@ def test_parse_active_club_header_non_positive():
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
parse_active_club_header("0")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
|
||||
def test_resolve_platform_admin_uses_stored_club_without_header(monkeypatch):
|
||||
"""Ohne X-Active-Club-Id: effective wie gespeichertes Profil (Sync mit Dropdown/DB)."""
|
||||
cur = object()
|
||||
|
||||
def fake_exists(c, cid):
|
||||
return cid == 99
|
||||
|
||||
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="admin",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 10}],
|
||||
stored_active_club_id=99,
|
||||
)
|
||||
assert ctx.effective_club_id == 99
|
||||
|
||||
|
||||
def test_resolve_platform_admin_header_overrides_stored(monkeypatch):
|
||||
cur = object()
|
||||
|
||||
def fake_exists(c, cid):
|
||||
return cid in (5, 99)
|
||||
|
||||
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="superadmin",
|
||||
header_raw="5",
|
||||
memberships=[{"id": 10}],
|
||||
stored_active_club_id=99,
|
||||
)
|
||||
assert ctx.effective_club_id == 5
|
||||
|
||||
|
||||
def test_resolve_platform_admin_no_header_stored_invalid(monkeypatch):
|
||||
cur = object()
|
||||
monkeypatch.setattr("tenant_context._club_exists", lambda c, cid: False)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="admin",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 1}],
|
||||
stored_active_club_id=123,
|
||||
)
|
||||
assert ctx.effective_club_id is None
|
||||
|
||||
|
||||
def test_resolve_trainer_club_ids_excludes_inactive_memberships():
|
||||
"""Nur aktive Vereinszugänge zählen für Mandant / Header-Validierung."""
|
||||
cur = object()
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=9,
|
||||
global_role="user",
|
||||
header_raw=None,
|
||||
memberships=[
|
||||
{"id": 10, "membership_status": "inactive"},
|
||||
{"id": 20, "membership_status": "active"},
|
||||
],
|
||||
stored_active_club_id=None,
|
||||
invalid_header_policy="ignore",
|
||||
)
|
||||
assert ctx.club_ids == frozenset({20})
|
||||
assert ctx.effective_club_id == 20
|
||||
|
||||
|
||||
def test_resolve_all_memberships_inactive_no_effective_club():
|
||||
cur = object()
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=9,
|
||||
global_role="user",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 10, "membership_status": "inactive"}],
|
||||
stored_active_club_id=10,
|
||||
invalid_header_policy="ignore",
|
||||
)
|
||||
assert ctx.club_ids == frozenset()
|
||||
assert ctx.effective_club_id is None
|
||||
@@ -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,108 @@
|
||||
"""Vereins-Übung: Copyright-Pflicht für angehängte Archiv-Dateien."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import routers.exercises as exercises_mod
|
||||
from routers.exercises import apply_club_exercise_media_copyright_rules
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_skips_non_club() -> None:
|
||||
apply_club_exercise_media_copyright_rules(object(), 1, "private")
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_missing_copyright() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, eid: int):
|
||||
assert eid == 42
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
assert ei.value.status_code == 422
|
||||
d = ei.value.detail
|
||||
assert isinstance(d, dict)
|
||||
assert d.get("code") == "CLUB_MEDIA_COPYRIGHT_REQUIRED"
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_ok() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Verein 2026",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_applies_default() -> None:
|
||||
"""Nach Bestätigung setzt der Client default_club_media_copyright — Backend schreibt auf Assets."""
|
||||
orig_fetch = exercises_mod._fetch_exercise_linked_file_assets
|
||||
calls = {"n": 0}
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Testverein",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
class MockCur:
|
||||
def execute(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(
|
||||
MockCur(),
|
||||
42,
|
||||
"club",
|
||||
default_club_media_copyright="© Testverein",
|
||||
)
|
||||
assert calls["n"] == 2
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig_fetch
|
||||
@@ -0,0 +1,51 @@
|
||||
"""POST /api/exercises: keine Inline-Medien-Platzhalter beim ersten Anlegen (§11)."""
|
||||
|
||||
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_post_exercise_rejects_inline_media_placeholder(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=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.post(
|
||||
"/api/exercises",
|
||||
json={
|
||||
"title": "Mit Inline",
|
||||
"goal": "<p>Hallo {{exerciseMedia:7}}</p>",
|
||||
"execution": "<p>Schritt</p>",
|
||||
"visibility": "private",
|
||||
"status": "draft",
|
||||
},
|
||||
headers={"X-Auth-Token": "x"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
j = r.json()
|
||||
assert j.get("detail", {}).get("code") == "INLINE_EXERCISE_MEDIA_ON_CREATE"
|
||||
@@ -0,0 +1,44 @@
|
||||
"""exercise_rich_text: §11 Normalisierung und ID-Sammlung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from exercise_rich_text import (
|
||||
assert_no_inline_media_references_on_create,
|
||||
collect_inline_exercise_media_ids,
|
||||
normalize_inline_exercise_media_markup,
|
||||
validate_inline_exercise_media_ids_for_exercise,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_curly_to_span() -> None:
|
||||
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
|
||||
out = normalize_inline_exercise_media_markup(s)
|
||||
assert 'data-shinkan-exercise-media="42"' in out
|
||||
assert 'data-shinkan-exercise-media-size="medium"' in out
|
||||
assert "{{" not in out
|
||||
|
||||
|
||||
def test_collect_merges_braces_and_data_attr() -> None:
|
||||
html = '{{ExercisemEDIA: 1}}\n<span data-shinkan-exercise-media="2"></span>'
|
||||
assert collect_inline_exercise_media_ids(html) == {1, 2}
|
||||
|
||||
|
||||
def test_assert_no_inline_on_create_raises() -> None:
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
assert_no_inline_media_references_on_create({5})
|
||||
assert ei.value.status_code == 400
|
||||
body = ei.value.detail
|
||||
assert isinstance(body, dict)
|
||||
assert body["code"] == "INLINE_EXERCISE_MEDIA_ON_CREATE"
|
||||
|
||||
|
||||
def test_validate_ids_sql_mock() -> None:
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.return_value = [{"id": 1}]
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
validate_inline_exercise_media_ids_for_exercise(mock_cur, 100, {1, 99})
|
||||
assert ei.value.detail["invalid_exercise_media_ids"] == [99]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
|
||||
|
||||
_HEX64 = "a" * 64
|
||||
|
||||
|
||||
def test_library_media_kind_dir_mime_overrides_ext() -> None:
|
||||
assert library_media_kind_dir("image/png", ".bin") == "image"
|
||||
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
|
||||
|
||||
|
||||
def test_library_club_path_segment_slug_and_fallback() -> None:
|
||||
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
|
||||
assert library_club_path_segment(3, None) == "verein-c3"
|
||||
assert library_club_path_segment(3, " ") == "verein-c3"
|
||||
assert library_club_path_segment(12, "東道場") == "verein-c12"
|
||||
|
||||
|
||||
def test_library_club_path_segment_long_name_truncated() -> None:
|
||||
long = "a" * 80
|
||||
seg = library_club_path_segment(5, long)
|
||||
assert seg == "a" * 48 + "-c5"
|
||||
|
||||
|
||||
def test_library_storage_key_private_is_uploader_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key(
|
||||
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
|
||||
)
|
||||
== f"library/ost-dojo-muenchen-c7/image/{_HEX64}.u99.jpg"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_club_flat_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
|
||||
== f"library/demo-verein-c42/image/{_HEX64}.png"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_official() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
|
||||
== f"library/official/video/{_HEX64}.mp4"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_normalizes_visibility() -> None:
|
||||
assert (
|
||||
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
|
||||
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_other_bin() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
|
||||
== f"library/official/other/{_HEX64}.bin"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_uploader() -> None:
|
||||
with pytest.raises(ValueError, match="uploader_profile_id"):
|
||||
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_club() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
|
||||
|
||||
|
||||
def test_library_storage_key_club_requires_id() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_club_id_positive() -> None:
|
||||
with pytest.raises(ValueError, match="positiv"):
|
||||
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_visibility() -> None:
|
||||
with pytest.raises(ValueError, match="Sichtbarkeit"):
|
||||
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_sha() -> None:
|
||||
with pytest.raises(ValueError, match="64"):
|
||||
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_extension() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
library_storage_key(
|
||||
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_no_club_name_fallback() -> None:
|
||||
assert (
|
||||
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
|
||||
== f"library/verein-c2/image/{_HEX64}.u3.jpg"
|
||||
)
|
||||
@@ -15,6 +15,11 @@ from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
|
||||
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
|
||||
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
|
||||
_SK_PRIV_C = f"library/verein-c1/video/{'c' * 64}.u1.mp4"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
@@ -125,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",
|
||||
@@ -136,15 +141,16 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": "exercises/x.jpg",
|
||||
},
|
||||
{"id": 1},
|
||||
"storage_key": _SK_OFF_A,
|
||||
}, # 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"},
|
||||
@@ -175,7 +181,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
"id": 99,
|
||||
"exercise_id": 3,
|
||||
"media_type": "image",
|
||||
"file_path": "/media/exercises/h.jpg",
|
||||
"file_path": f"/media/{_SK_OFF_B}",
|
||||
"file_size": 10,
|
||||
"mime_type": "image/jpeg",
|
||||
"original_filename": "h.jpg",
|
||||
@@ -191,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",
|
||||
@@ -202,16 +208,17 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": "exercises/h.jpg",
|
||||
},
|
||||
None,
|
||||
inserted,
|
||||
"storage_key": _SK_OFF_B,
|
||||
}, # 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"},
|
||||
@@ -326,10 +333,10 @@ def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
|
||||
{
|
||||
"id": 5,
|
||||
"visibility": "private",
|
||||
"club_id": None,
|
||||
"club_id": 1,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "trash_soft",
|
||||
"storage_key": "exercises/a.mp4",
|
||||
"storage_key": _SK_PRIV_C,
|
||||
"storage_backend": "local",
|
||||
"trash_soft_at": None,
|
||||
"trash_hidden_at": None,
|
||||
|
||||
@@ -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
|
||||
+485
-9
@@ -1,34 +1,510 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.51"
|
||||
BUILD_DATE = "2026-05-07"
|
||||
DB_SCHEMA_VERSION = "20260507046"
|
||||
APP_VERSION = "0.8.110"
|
||||
BUILD_DATE = "2026-05-12"
|
||||
DB_SCHEMA_VERSION = "20260512057"
|
||||
|
||||
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()
|
||||
"tenant_context": "1.0.4", # pytest: Unit test_access_layer.py + optional Integration test_access_layer_integration (PostgreSQL)
|
||||
"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.5.1", # usage: training_unit_exercises optional (Schema ohne planning-Tabelle)
|
||||
"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.16.0", # §4.2 official: angehängte media_assets + Copyright (PUT + bulk-metadata)
|
||||
"exercises": "2.27.3", # load_combination_slots_for_exercise (gemeinsam mit GET Übung); Hydrate für Planung
|
||||
"training_units": "0.2.0",
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||
"planning": "0.9.3", # GET training-units/:id Sektions-Items: combination_slots + Kandidaten-Titel für Druck/Run
|
||||
"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.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",
|
||||
"changes": [
|
||||
"Übung auf Verein: fehlende Copyrights an Datei-Assets wieder per Bestätigung + Eingabe beim Speichern setzbar (PUT default_club_media_copyright; Bulk-PATCH ebenfalls)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.64",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Übung bearbeiten: Auto-Scroll beim Drag von Medien zu Textfeldern; Medien-Kacheln mehrspaltig; Sektion/Ablauf-Zuordnung an Medien entfernt (nur noch Titel bearbeiten); Picker: Video-Vorschau-Frame; Katalogvorschau ohne Anhangs-Medienliste; Ansehen mit Speichern-Hinweis + Zurück zur Bearbeitung von der Ansicht",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.63",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE/Übung Medien: Picker-Thumbnails; Dateiauswahl-Anzeige; bereits verknüpfte Archive-Medien ins Fließtext einfügen; Platzhalter-Caption data-shinkan-exercise-media-caption + Caret nach ZWSP; Lesemodus: Medienliste nur für nicht eingebettete Anhänge; bearbeiten: kompakte Kacheln mit Drag-and-Drop in Textfelder, Upload unter Medien entfällt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.62",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE Inline-Medien: Modals Mediathek+Hochladen + „Embed im Text“; Darstellungsgröße small|medium|full (data-shinkan-exercise-media-size); Lesemodus begrenzt Bild/Video-Breite",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.61",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE „Bild/Video im Text“: eingebaute Hilfe (Caret + insertHTML/Fallback); sichtbarer 📎-Chip im Editor; Hinweis bei fehlgeschlagener Einfügung/Prompt-ID",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.60",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Inline-Medien im Übungs-Fließtext (MEDIA_SPEC §11): {{exerciseMedia:id}} → kanonisches span; nur exercise_media dieser Übung; create ohne Platzhalter",
|
||||
"Frontend: ExerciseRichTextBlock mit Allowlist-Sanitize + Embed; Toolbar „Bild/Video im Text“ im RichTextEditor wenn Medien an der Übung; Detail/Katalog/Liste konsistent",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.59",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Aktiver Verein: Backend resolve_tenant_context für Plattform-Admin ohne X-Active-Club-Id nutzt gespeichertes active_club_id wenn der Verein existiert (kein effective=null nach hartem Reload mehr)",
|
||||
"Frontend: Nach Vereinswechsel Profil neu laden; Dropdown-Wert aus effective_club_id / active_club_id / LocalStorage abgestimmt (getResolvedActiveClubIdForUi)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.58",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek offiziell: Ändern/Lifecycle nur Superadmin (nicht Plattform-Admin); Bearbeiten-Dialog für andere nur Lesemodus; Superadmin: Vereinsauswahl beim Archiv-Upload folgt aktiv/gesetzt effective_club_id",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.57",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Governance: visibility=official nur noch Superadmin (nicht Plattform-Admin)",
|
||||
"Medienarchiv: private Uploads als Plattform-Admin erfordern explizites club_id; gleiche Ordnerstruktur wie „Verein“, private Kopien mit .u{Profil} vor Dateiendung",
|
||||
"Übung visibility=Verein: angebundene Archiv-Dateien müssen aktiv sein und Copyright (≥3 Zeichen) haben; UI- und API-Fehlercodes CLUB_MEDIA_*",
|
||||
"Frontend: „Offiziell“ nur Superadmin (Bibliothek, Übungsformular, Bulk-Sichtbarkeit, Progressionsgraphen)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.56",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: Vereinsmedien unter library/{aus Name abgeleitet}-c{club_id}/ statt festem library/club/c{id}/; Sonderzeichen/Umlaute zu sicheren Ordnernamen; fehlender Name → verein-c{id}; Governance-Umzug liest aktuellen Vereinsnamen aus DB",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.55",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: Speicherpfad library/* mit Medientyp-Unterordnern (image, video, pdf, other) vor SHA-Dateinamen; Umzug bei Governance-PATCH nutzt mime_type aus DB",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.54",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Medienpfade: vereinsgeteilt (club) direkt unter library/club/c{id}/; private unter library/club/c{id}/u{profile}/ (kein Ordner „private“/„shared“); Dedupe private inkl. uploaded_by_profile_id",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.53",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Medienablage vereinsbezogen: private → library/club/c{id}/private, Vereinssichtbarkeit → …/shared, official unverändert; private Archiv-Upload: club_id oder X-Active-Club-Id; DB club_id bei private gesetzt; PATCH/Bulk: club_id für private nicht mehr blind auf NULL",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.52",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Neue lokale media_assets: hierarchische library/* Pfade; Dedupe nach sha+visibility+club_id; bei PATCH/Bulk-Patch Sichtbarkeit/Verein: Datei umziehen, exercise_media.file_path aktualisieren (Details siehe 0.8.53)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.51",
|
||||
"date": "2026-05-07",
|
||||
|
||||
@@ -54,6 +54,8 @@ services:
|
||||
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
||||
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
# Bind-Mount: Verzeichnis muss auf dem Host existieren und chown für den Docker-Daemon
|
||||
# zulassen (lokale Platte). Bei NFS/SMB oft "chown … operation not permitted" → anderen Pfad.
|
||||
volumes:
|
||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
||||
ports:
|
||||
@@ -79,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`. |
|
||||
+114
-34
@@ -1,9 +1,9 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-05
|
||||
**App-Version / DB-Schema:** siehe `backend/version.py`
|
||||
**Stand:** 2026-05-12
|
||||
**App-Version / DB-Schema:** App **0.8.110**, DB-Schema **`20260512057`** (`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** und **nächste Baustellen**.
|
||||
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**.
|
||||
|
||||
### Produktion: `relation … does not exist` (z. B. `skill_main_categories`)
|
||||
|
||||
@@ -21,11 +21,20 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Thema | Pfad |
|
||||
|--------|------|
|
||||
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
| Projekt-Status (Skills, Wiki, Stats) | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| Übungen: API, DB, Architektur, Routing | `.claude/docs/technical/EXERCISES_API_SPEC.md`, `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_FRONTEND_ROUTING.md` |
|
||||
| Media / Upload | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Media / Upload-Limits / Embed | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
|
||||
| Rahmenprogramm · Planung (`training_units` Blueprints), Progressionsgraph | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md`; Überblick DB → `.claude/docs/technical/DATABASE_SCHEMA.md`; Domäne → `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| 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`** |
|
||||
|
||||
---
|
||||
|
||||
@@ -36,73 +45,144 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **`maturity_models`**, **`model_levels`**, **`model_skills`**, **`model_skill_levels`**: Matrix-Inhalt pro Modell.
|
||||
- **Kontext am Modell (Legacy, M:N):** `maturity_model_focus_areas`, `maturity_model_style_directions`, `maturity_model_target_groups` (Migration 025).
|
||||
- **Hierarchische Kontext-Zuordnung (Resolve):** `maturity_model_context_bindings` mit optional `style_direction_id`, `training_type_id` (Migration 026, 027).
|
||||
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
|
||||
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
|
||||
|
||||
### 2.2 Resolve-Logik (Backend)
|
||||
|
||||
- **`GET /api/maturity-models/resolve`**: Bindings zum Fokus, die zur Anfrage passen; Merge nach Spezifität (weniger spezifisch zuerst); spezifischere Zeilen überschreiben Zelltexte.
|
||||
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard (z. B. Fokus+Trainingsstil gilt für alle Stilrichtungen, aber nur für diesen Trainingsstil).
|
||||
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert. Sonst bei fehlendem Treffer **`null`** (kein stilles Legacy mit falschem Trainingsstil).
|
||||
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard.
|
||||
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert.
|
||||
|
||||
### 2.3 Export / Import (einzelnes Modell & aufgelöst)
|
||||
|
||||
- **`GET /api/maturity-models/{id}/export`**: `shinkan.maturity_model.v1` inkl. `context_bindings_for_model` (IDs).
|
||||
- **`GET /api/maturity-models/export-resolved`**: `shinkan.maturity_matrix_resolved.v1` (Query: `focus_area_id`, optional `style_direction_id`, `training_type_id`).
|
||||
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings` (nur bei `maturity_model.v1`).
|
||||
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings`.
|
||||
|
||||
### 2.4 Komplett-Stack Test → Prod
|
||||
|
||||
- **`GET /api/admin/matrix-stack/export`**: `shinkan.matrix_stack.v1` – Katalog (`skill_main_categories`, `skill_categories`, `skills`, `skill_level_definitions`) + alle Reifegradmodelle + Bindings mit **Namen** (Fokus/Stil/Trainingsstil).
|
||||
- **`POST /api/admin/matrix-stack/import`**: Upsert Katalog per Slug; Skills per Kategorie+Name; Modelle neu anlegen; Bindings per Katalognamen. Optional **`replace_all_maturity_models`** + **`confirm_replace_all: "DELETE_MATURITY_STACK"`** (nur Superadmin).
|
||||
- Router: `backend/routers/matrix_stack_bundle.py`, in `main.py` registriert.
|
||||
- **`GET /api/admin/matrix-stack/export`**, **`POST /api/admin/matrix-stack/import`** — siehe `matrix_stack_bundle.py`.
|
||||
|
||||
### 2.5 Frontend (Admin)
|
||||
|
||||
- **`frontend/src/pages/AdminMaturityModelsPage.jsx`**: Tabs u. a. Katalog, Modelle, Kontext-Zuordnung, **Matrix-Ansicht und Export**.
|
||||
- **`MaturityModelBindingsAdmin.jsx`**: Bindings CRUD, Erklärung Merge/Legacy.
|
||||
- **`MaturityMatrixToolsAdmin.jsx`**: Kontext auflösen, hierarchische Matrix-Ansicht, Export einzelnes Modell / aufgelöst, Einzelmodell-Import; **Komplett-Stack** mit eigenem Export-Button und **eigenem Dateifeld für Stack-Import** (`POST /api/admin/matrix-stack/import`).
|
||||
- **`frontend/src/utils/api.js`**: u. a. `exportMatrixStackBundle`, `importMatrixStackBundle`, Reifegrad-APIs.
|
||||
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
|
||||
|
||||
- **Migration 036:** Rahmenkopf nur Bibliothek (Kontext: Fokusbereich, Stilrichtung; M:N Trainingsarten/Zielgruppen); keine `plan_mode`/keine Kopf‑`group_id`.
|
||||
- **Migration 037:** Pro Rahmen‑Slot eine **`training_units`‑Zeile mit `framework_slot_id`**; strukturierter Ablauf wie echte Einheiten (`training_unit_sections` / `training_unit_section_items`). Tabelle **`training_framework_slot_exercises`** entfällt.
|
||||
- **API:** Rahmen unter **`/api/training-framework-programs`** (Slots liefern u. a. **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`**); Kalenderliste **`GET /api/training-units`** ohne Blueprints; Übernahme **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `backend/routers/training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**; **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
- **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.110**)
|
||||
|
||||
- **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: Übungen (Lücke für nächste Session)
|
||||
## 4. Stand: Medien-Management (Ist, 2026-05-07)
|
||||
|
||||
**Ist (laut Projektdoku und aktuellem Produktziel):**
|
||||
**Datenmodell (Kurz):**
|
||||
|
||||
- Backend: Übungen-CRUD, M:N, Suche, Blöcke, Medien-Struktur u. a. sind in `PROJECT_STATUS.md` als umgesetzt geführt; viele Übungen stammen aus **MediaWiki-Import** (Wiki-Tracking-Tabellen).
|
||||
- **Soll / Nutzerfeedback:** In der Praxis fehlt oder ist unzureichend: **stabile Liste**, **gerenderte Detailansicht**, **Bearbeiten/Anlegen**, **Medien zuweisen/Upload** – konkrete Fehler (404, leere Liste, falsche Route) sind vor Ort zu verifizieren.
|
||||
- **`media_assets`:** Physische oder logische Archiv-Datei (u. a. `sha256`, `visibility`, `club_id`, `lifecycle_state`, `copyright_notice`, Speicherpfad/`storage_key`, `tags` ab passender Migration).
|
||||
- **`exercise_media`:** optional **`media_asset_id`**; weiterhin Embeds ohne Asset; Kontext/Sortierung/Titel wie bisher.
|
||||
- **`platform_media_storage`:** Superadmin — relativer Unterpfad unter `MEDIA_ROOT`.
|
||||
|
||||
**Nächste Session sollte:**
|
||||
**API (Auszug):**
|
||||
|
||||
1. Aktuelle Routen und Seiten prüfen (`App.jsx`, `EXERCISES_FRONTEND_ROUTING.md`).
|
||||
2. `GET /api/exercises` (Filter, Auth) und eine Beispiel-Übung gegen die Dev-DB testen.
|
||||
3. UI schrittweise: Liste → Detail → Formular → Medien (an Specs in `.claude/docs/technical/` ausrichten).
|
||||
- **`GET /api/media-assets`**, Filter (Lifecycle, `media_kind`, Verein, Suche, Tags), Berechtigungen pro Zeile.
|
||||
- **`PATCH /api/media-assets/{id}`** / Bulk-PATCH, **Lifecycle** (`POST …/lifecycle`, Bulk).
|
||||
- **`GET …/media-assets/{id}/file`** (inkl. Kontext `ssetoken` wo vorgesehen).
|
||||
- **`POST /api/exercises/{id}/media/from-asset`:** bestehendes Asset verknüpfen.
|
||||
- Übungs-Uploads erzeugen/verknüpfen **`media_assets`**; Governance wie **`library_content_*`** / TenantContext.
|
||||
|
||||
**Frontend:**
|
||||
|
||||
- Route **`/media`** (Medienbibliothek): Kacheln/Liste, Filter, Copyright, Lifecycle-Actions (Rollen gemäß Spec; **`official`:** bearbeiten/Lifecycle im Wesentlichen **Superadmin**, andere Rollen **Lesemodus** im Bearbeiten-Dialog).
|
||||
- Übungsformular: Archiv-Picker, Vorschau, Reaktivierung bei Dedupe-Konflikt (Papierkorb).
|
||||
|
||||
**Speicher & Pfade:**
|
||||
|
||||
- Struktur unter **`library/`** mit Vereinssegment (aus Vereinsname abgeleitet + `c{id}`), Unterordner nach Medienkind (`image`/`video`/`pdf`/`other`), Dateiname z. B. SHA-basiert — Details und Drift-Vermeidung in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
**Governance & Mandant:**
|
||||
|
||||
- **`visibility=official`** für Übungen: nur **Superadmin**; Medien **`official`:** Lifecycle/PATCH schwerpunktmäßig Superadmin (Plattform-Admin nicht gleich Superadmin).
|
||||
- **Aktiver Verein:** `profiles.active_club_id`, Header **`X-Active-Club-Id`**, Response **`effective_club_id`** — nach **0.8.59** konsistent inkl. Plattform-Admin beim Reload (Backend **`tenant_context`**, Frontend **`getResolvedActiveClubIdForUi`** + Profil-Refresh nach Vereinswechsel).
|
||||
|
||||
---
|
||||
|
||||
## 5. Technische Referenz (kurz)
|
||||
## 5. Inline-Medien im Fließtext (Spec Abschnitt 11 — umgesetzt)
|
||||
|
||||
**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`**.
|
||||
|
||||
**Weiteres:** UX-Politik, ggf. strategische Vereinheitlichung der Referenzmodellierung (reine Asset-Referenz vs. `exercise_media`) — siehe Nächste Schritte in **`PROJECT_STATUS.md`**.
|
||||
|
||||
---
|
||||
|
||||
## 6. P-13: Content-Meldeverfahren (vollständig implementiert, 2026-05-11)
|
||||
|
||||
**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. 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`; Router u. a. **`training_framework_programs.py`**, **`training_planning.py`**, `maturity_models.py`, `matrix_stack_bundle.py`, `exercises.py`, `catalogs.py`, `skills.py` |
|
||||
| Migrationen | `backend/migrations/` (u. a. 024–027 Reifegrad/Bindings; **035–037** Rahmenprogramm / Slot‑Blueprint) |
|
||||
| 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` |
|
||||
| Version / Changelog | `backend/version.py` |
|
||||
|
||||
---
|
||||
|
||||
## 6. Veraltete Hinweise
|
||||
## 9. Veraltete Hinweise
|
||||
|
||||
Die Datei `.claude/docs/working/HANDOVER_NEXT_SESSION.md` (2026-04-22) ist **historisch**; für den aktuellen Stand gilt **`docs/HANDOVER.md`**.
|
||||
`.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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.*
|
||||
+14
-3
@@ -13,9 +13,20 @@ server {
|
||||
# — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
# Uploads (Übungsmedien) und API erreichen Clients unter derselben Host-URL wie die SPA —
|
||||
# dafür muss Nginx zur FastAPI-Instanz im Compose-Netz weiterleiten.
|
||||
client_max_body_size 64m;
|
||||
# Uploads (Übungsmedien, Medienarchiv-Bulk) — Limit muss >= größte Einzeldatei und
|
||||
# bei multipart ggf. Summe mehrerer Dateien sein (Backend praxis: bis 1024 MB Admin).
|
||||
client_max_body_size 1024m;
|
||||
|
||||
# Medienbibliothek (React /media) — vor location ^~ /media/: sonst liefert ein Reload
|
||||
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
|
||||
location = /media {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
location = /media/ {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
set $docker_backend_svc backend;
|
||||
|
||||
@@ -8,10 +8,14 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"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",
|
||||
|
||||
+138
-60
@@ -1,14 +1,15 @@
|
||||
import React 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'
|
||||
@@ -20,10 +21,13 @@ 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 TrainingModulesListPage from './pages/TrainingModulesListPage'
|
||||
import TrainingModuleEditPage from './pages/TrainingModuleEditPage'
|
||||
import TrainingUnitRunPage from './pages/TrainingUnitRunPage'
|
||||
import TrainingCoachPage from './pages/TrainingCoachPage'
|
||||
import AdminCatalogsPage from './pages/AdminCatalogsPage'
|
||||
@@ -32,13 +36,25 @@ 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 LegalPage from './pages/LegalPage'
|
||||
import AdminLegalDocumentsPage from './pages/AdminLegalDocumentsPage'
|
||||
import SettingsLegalPage from './pages/SettingsLegalPage'
|
||||
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
||||
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
|
||||
import './app.css'
|
||||
|
||||
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||
function computeShowAdminNav(currentUser) {
|
||||
return currentUser?.role === 'superadmin'
|
||||
}
|
||||
|
||||
// Bottom Navigation (Mobile)
|
||||
function Nav({ isAdmin }) {
|
||||
const items = getMainNavItems(isAdmin)
|
||||
function Nav({ showAdminNav }) {
|
||||
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||
const loc = useLocation()
|
||||
|
||||
const navItemActive = (pathname, item, routerIsActive) => {
|
||||
@@ -58,6 +74,11 @@ function Nav({ isAdmin }) {
|
||||
}
|
||||
>
|
||||
<item.Icon size={26} strokeWidth={2} />
|
||||
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||
<span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
|
||||
{inboxCount > 99 ? '99+' : inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
<span>{item.shortLabel || item.label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
@@ -95,11 +116,11 @@ function ProtectedLayout() {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
const isAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const showAdminNav = computeShowAdminNav(user)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DesktopSidebar isAdmin={isAdmin} user={user} onLogout={handleLogout} />
|
||||
<OrgInboxProvider user={user}>
|
||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||
<div className="app-shell">
|
||||
<div className="app-shell__column">
|
||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||
@@ -109,12 +130,13 @@ function ProtectedLayout() {
|
||||
<ActiveClubSwitcher variant="mobile" />
|
||||
</div>
|
||||
<div className="app-main">
|
||||
<InactiveMembershipBanner />
|
||||
<Outlet />
|
||||
</div>
|
||||
<Nav isAdmin={isAdmin} />
|
||||
<Nav showAdminNav={showAdminNav} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</OrgInboxProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -140,60 +162,116 @@ 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="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={<Navigate to="/admin/hierarchy" replace />} />
|
||||
<Route path="admin/users" element={<AdminUsersPage />} />
|
||||
<Route path="admin/hierarchy" element={<AdminHierarchyPage />} />
|
||||
<Route path="admin/maturity-models" element={<AdminMaturityModelsPage />} />
|
||||
<Route path="admin/catalogs" element={<AdminCatalogsPage />} />
|
||||
<Route path="admin/mediawiki-import" element={<MediaWikiImportPage />} />
|
||||
<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>
|
||||
<RouterProvider router={appRouter} />
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
|
||||
+1578
-1
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { activeClubMemberships, getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
||||
|
||||
/**
|
||||
* Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
|
||||
@@ -6,13 +7,10 @@ import { useAuth } from '../context/AuthContext'
|
||||
*/
|
||||
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
|
||||
const { user, setActiveClub } = useAuth()
|
||||
const clubs = user?.clubs || []
|
||||
const clubs = activeClubMemberships(user?.clubs)
|
||||
if (clubs.length <= 1) return null
|
||||
|
||||
const selectClubId =
|
||||
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
|
||||
? user.active_club_id
|
||||
: clubs[0]?.id
|
||||
const selectClubId = getResolvedActiveClubIdForUi(user)
|
||||
|
||||
const isMobile = variant === 'mobile'
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export default function AdminHomeRedirect() {
|
||||
const { user } = useAuth()
|
||||
const isSuper = user?.role === 'superadmin'
|
||||
return <Navigate to={isSuper ? '/admin/hierarchy' : '/'} replace />
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Images } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal)
|
||||
* Wechselt zwischen verschiedenen Admin-Seiten
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
*/
|
||||
export default function AdminPageNav() {
|
||||
const pages = [
|
||||
@@ -11,8 +10,8 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/users', label: 'Nutzer', icon: Users },
|
||||
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
|
||||
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
|
||||
{ to: '/media', label: 'Medien', icon: Images },
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download }
|
||||
{ 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,165 @@
|
||||
/**
|
||||
* 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,
|
||||
}) {
|
||||
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">
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Inbox } from 'lucide-react'
|
||||
import { useOrgInbox } from '../context/OrgInboxContext'
|
||||
|
||||
/**
|
||||
* Desktop-Dashboard: Hinweis auf offene Beitrittsanträge (nur ab 1024px sichtbar via CSS).
|
||||
*/
|
||||
export default function DashboardOrgInboxWidget() {
|
||||
const { canAccessOrgInbox, inboxJoinRequests, inboxCount } = useOrgInbox()
|
||||
|
||||
if (!canAccessOrgInbox) return null
|
||||
|
||||
const preview = (inboxJoinRequests || []).slice(0, 5)
|
||||
|
||||
return (
|
||||
<section
|
||||
className="dashboard-org-inbox-widget"
|
||||
aria-labelledby="dash-org-inbox-title"
|
||||
>
|
||||
<div className="dashboard-org-inbox-widget__inner card">
|
||||
<div className="dashboard-org-inbox-widget__head">
|
||||
<h2 id="dash-org-inbox-title" className="dashboard-org-inbox-widget__title">
|
||||
<Inbox size={20} strokeWidth={2} aria-hidden className="dashboard-org-inbox-widget__icon" />
|
||||
Posteingang
|
||||
</h2>
|
||||
{inboxCount > 0 ? (
|
||||
<span className="dashboard-org-inbox-widget__badge" aria-live="polite">
|
||||
{inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="muted dashboard-org-inbox-widget__lead">
|
||||
{inboxCount === 0
|
||||
? 'Keine offenen Beitrittsanträge.'
|
||||
: `${inboxCount} offene Beitrittsantrag${inboxCount === 1 ? '' : 'e'}.`}
|
||||
</p>
|
||||
{preview.length > 0 ? (
|
||||
<ul className="dashboard-org-inbox-widget__list">
|
||||
{preview.map((req) => (
|
||||
<li key={`${req.club_id}-${req.id}`} className="dashboard-org-inbox-widget__item">
|
||||
<span className="dashboard-org-inbox-widget__club">{req.club_name || 'Verein'}</span>
|
||||
<span className="dashboard-org-inbox-widget__applicant">
|
||||
{req.applicant_name || req.applicant_email || 'Bewerber/in'}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<div className="dashboard-org-inbox-widget__footer">
|
||||
<Link to="/inbox" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
|
||||
Zum Posteingang
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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'
|
||||
import ActiveClubSwitcher from './ActiveClubSwitcher'
|
||||
|
||||
function sidebarLinkActive(pathname, item, routerIsActive) {
|
||||
@@ -12,12 +13,13 @@ function sidebarLinkActive(pathname, item, routerIsActive) {
|
||||
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
|
||||
*/
|
||||
export default function DesktopSidebar({
|
||||
isAdmin,
|
||||
showAdminNav,
|
||||
user,
|
||||
onLogout
|
||||
}) {
|
||||
const loc = useLocation()
|
||||
const items = getMainNavItems(isAdmin)
|
||||
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||
const tier = user?.tier || ''
|
||||
|
||||
return (
|
||||
@@ -42,6 +44,11 @@ export default function DesktopSidebar({
|
||||
>
|
||||
<item.Icon size={20} strokeWidth={2} />
|
||||
<span>{item.label}</span>
|
||||
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||
<span className="desktop-sidebar__badge" aria-label={`${inboxCount} offen`}>
|
||||
{inboxCount > 99 ? '99+' : inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
@@ -85,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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Nur Medien, die noch nicht im Fließtext eingebettet sind — ohne Doppel-Darstellung.
|
||||
*/
|
||||
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'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
|
||||
}
|
||||
|
||||
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(() => {
|
||||
const list = (exercise?.media || []).filter((m) => m && !isTrashHidden(m))
|
||||
return list.filter((m) => !inlineIds.has(Number(m.id)))
|
||||
}, [exercise, inlineIds])
|
||||
|
||||
if (!orphans.length || exerciseId == null) return null
|
||||
|
||||
return (
|
||||
<section className="card exercise-detail-section exercise-attachment-media-strip">
|
||||
<h2>Angehängte Medien</h2>
|
||||
<p style={{ marginTop: '6px', color: 'var(--text2)', fontSize: '0.88rem' }}>
|
||||
Hier erscheinen nur Verknüpfungen, die noch nicht im Fließtext eingebettet sind (reine Material-Anhänge).
|
||||
</p>
|
||||
<div className="exercise-orphan-media-grid">
|
||||
{orphans.map((m) => {
|
||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
||||
const caption = (m.title || '').trim() || (m.original_filename || '').trim() || `Medium #${m.id}`
|
||||
return (
|
||||
<article key={m.id} className="exercise-orphan-media-card">
|
||||
<div className="exercise-orphan-media-card__head">
|
||||
<ExerciseMediaThumbTile
|
||||
exerciseId={exerciseId}
|
||||
media={m}
|
||||
onOpenPreview={setPreview}
|
||||
size={88}
|
||||
/>
|
||||
<div className="exercise-orphan-media-card__meta">
|
||||
<strong className="exercise-orphan-media-card__title">{caption}</strong>
|
||||
<span className="exercise-orphan-media-card__sub">
|
||||
#{m.id}
|
||||
{m.embed_platform ? ` · ${m.embed_platform}` : ''}
|
||||
{m.media_type ? ` · ${m.media_type}` : ''}
|
||||
</span>
|
||||
{lc === 'trash_soft' && (
|
||||
<span className="exercise-orphan-media-card__warn">Papierkorb (Stufe 1)</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ExerciseMediaEmbed exerciseId={exerciseId} media={m} layoutSize="medium" />
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{preview && (
|
||||
<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,54 +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 { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
|
||||
function HtmlBlock({ html, className = '' }) {
|
||||
if (!html || !String(html).trim()) return null
|
||||
const safe = sanitizeTrainerHtml(html)
|
||||
return (
|
||||
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
|
||||
)
|
||||
}
|
||||
|
||||
function MediaBlock({ media, exerciseId }) {
|
||||
if (media.embed_url) {
|
||||
return (
|
||||
<div style={{ marginTop: '0.5rem' }}>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">
|
||||
{media.embed_url}
|
||||
</a>
|
||||
{media.embed_platform && (
|
||||
<span style={{ color: 'var(--text2)', marginLeft: '0.5rem', fontSize: '0.8rem' }}>
|
||||
({media.embed_platform})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt={media.title || media.original_filename || ''}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', marginTop: '0.5rem' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
|
||||
return <video src={src} controls style={{ width: '100%', marginTop: '0.5rem', borderRadius: '8px' }} />
|
||||
}
|
||||
return (
|
||||
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.5rem' }}>
|
||||
{media.title || media.original_filename || 'Datei öffnen'}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import CombinationCoachSlots from './CombinationCoachSlots'
|
||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||
|
||||
function TagRow({ exercise }) {
|
||||
const tags = []
|
||||
@@ -96,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' }}>
|
||||
@@ -112,14 +79,68 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
}
|
||||
if (!exercise) return null
|
||||
|
||||
const resolvedId = exercise.id ?? exerciseId
|
||||
const meta = metaParts(exercise)
|
||||
const visibleMedia = (exercise.media || []).filter((m) => {
|
||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
||||
return lc !== 'trash_hidden'
|
||||
})
|
||||
|
||||
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' }}>
|
||||
@@ -132,13 +153,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px', letterSpacing: '0.04em' }}>
|
||||
Kurzbeschreibung
|
||||
</h3>
|
||||
<HtmlBlock html={exercise.summary} />
|
||||
<ExerciseRichTextBlock html={exercise.summary} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.goal && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ziel</h3>
|
||||
<HtmlBlock html={exercise.goal} />
|
||||
<ExerciseRichTextBlock html={exercise.goal} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{(exercise.equipment || []).length > 0 && (
|
||||
@@ -156,32 +177,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
{exercise.preparation && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Vorbereitung</h3>
|
||||
<HtmlBlock html={exercise.preparation} />
|
||||
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.execution && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ablauf</h3>
|
||||
<HtmlBlock html={exercise.execution} />
|
||||
</section>
|
||||
)}
|
||||
{visibleMedia.length > 0 && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||
Medien
|
||||
</h3>
|
||||
{visibleMedia.map((m) => (
|
||||
<div key={m.id} style={{ marginBottom: '12px' }}>
|
||||
<strong style={{ fontSize: '0.9rem' }}>{m.title || m.original_filename || m.media_type}</strong>
|
||||
{String(m.asset_lifecycle_state || 'active').toLowerCase() === 'trash_soft' && (
|
||||
<p style={{ fontSize: '0.75rem', color: 'var(--danger)', margin: '4px 0 0' }}>
|
||||
Hinweis: Dieses Medium ist im Papierkorb und steht künftig nicht mehr zur Verfügung.
|
||||
</p>
|
||||
)}
|
||||
{m.description && <p style={{ color: 'var(--text2)', fontSize: '0.82rem', marginTop: '4px' }}>{m.description}</p>}
|
||||
<MediaBlock media={m} exerciseId={exercise.id ?? exerciseId} />
|
||||
</div>
|
||||
))}
|
||||
<ExerciseRichTextBlock html={exercise.execution} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.trainer_notes && (
|
||||
@@ -189,7 +191,7 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||
Hinweise Trainer (Katalog)
|
||||
</h3>
|
||||
<HtmlBlock html={exercise.trainer_notes} />
|
||||
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exerciseId != null && (
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Modal: Embed-URL als exercise_media anlegen und §11-Platzhalter einfügen.
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
import {
|
||||
INLINE_MEDIA_SIZES,
|
||||
DEFAULT_INLINE_MEDIA_SIZE,
|
||||
sanitizeInlineMediaSize,
|
||||
} 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,
|
||||
* onClose: () => void,
|
||||
* exerciseId: number,
|
||||
* onMediaListChanged: () => Promise<void>,
|
||||
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
|
||||
* }} props
|
||||
*/
|
||||
export default function ExerciseInlineEmbedModal({
|
||||
open,
|
||||
onClose,
|
||||
exerciseId,
|
||||
onMediaListChanged,
|
||||
onInserted,
|
||||
}) {
|
||||
const [url, setUrl] = useState('')
|
||||
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 () => {
|
||||
const u = url.trim()
|
||||
if (!u) {
|
||||
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)
|
||||
fd.append('media_type', 'video')
|
||||
fd.append('title', title.trim())
|
||||
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)
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
const cap = sanitizeInlineMediaCaption(
|
||||
title.trim() || u.replace(/^https?:\/\//i, '').slice(0, 96),
|
||||
)
|
||||
onInserted(Number(mid), size, cap)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
|
||||
<div
|
||||
className="admin-modal-sheet"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="rte-inline-embed-title"
|
||||
style={{ maxWidth: '480px', width: '100%', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="rte-inline-embed-title" className="admin-modal-sheet__title">
|
||||
Embed im Textfeld
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ overflowY: 'auto', flex: 1, padding: '14px 16px' }}>
|
||||
<label className="form-label">Embed-URL</label>
|
||||
<input
|
||||
type="url"
|
||||
className="form-input"
|
||||
placeholder="https://…"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Titel (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Darstellung im Text
|
||||
</label>
|
||||
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
|
||||
{INLINE_MEDIA_SIZES.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{/* 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>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
/**
|
||||
* Modal: Medium aus Archiv verknüpfen oder neue Datei hochladen, dann Inline-Platzhalter §11 einfügen.
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback, useMemo } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import {
|
||||
INLINE_MEDIA_SIZES,
|
||||
DEFAULT_INLINE_MEDIA_SIZE,
|
||||
sanitizeInlineMediaSize,
|
||||
} from '../constants/inlineExerciseMedia'
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
|
||||
function RtePickerAssetThumb({ asset }) {
|
||||
const id = asset.id
|
||||
const src = resolveMediaAssetFileUrl(id)
|
||||
const mt = (asset.mime_type || '').toLowerCase()
|
||||
if (mt.startsWith('image/') && src) {
|
||||
return <img alt="" src={src} className="rte-inline-asset-tile__thumb-img" />
|
||||
}
|
||||
if (mt.startsWith('video/') && src) {
|
||||
return (
|
||||
<video
|
||||
key={`v-${id}`}
|
||||
className="rte-inline-asset-tile__thumb-video"
|
||||
src={src}
|
||||
muted
|
||||
playsInline
|
||||
preload="metadata"
|
||||
onLoadedMetadata={(e) => {
|
||||
try {
|
||||
const el = e.currentTarget
|
||||
const d = el.duration
|
||||
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const nameLow = String(asset.original_filename || '').toLowerCase()
|
||||
if (mt.includes('pdf') || nameLow.endsWith('.pdf')) {
|
||||
return <span className="rte-inline-asset-tile__thumb-fallback">PDF</span>
|
||||
}
|
||||
return <span className="rte-inline-asset-tile__thumb-fallback">Datei</span>
|
||||
}
|
||||
|
||||
/** MIME/Dateiname → Übungs-media_type */
|
||||
function inferExerciseMediaType(file) {
|
||||
if (!file) return 'image'
|
||||
const mime = (file.type || '').toLowerCase()
|
||||
if (mime.startsWith('image/')) return 'image'
|
||||
if (mime.startsWith('video/')) return 'video'
|
||||
if (mime === 'application/pdf' || mime.includes('pdf')) return 'document'
|
||||
const name = (file.name || '').toLowerCase()
|
||||
if (/\.(mp4|webm|mov|mkv|avi|m4v|mpeg|mpg)$/.test(name)) return 'video'
|
||||
if (/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/.test(name)) return 'image'
|
||||
if (/\.pdf$/.test(name)) return 'document'
|
||||
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,
|
||||
* onClose: () => void,
|
||||
* exerciseId: number,
|
||||
* linkedExerciseMedia?: object[],
|
||||
* onMediaListChanged: () => Promise<void>,
|
||||
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
|
||||
* }} props
|
||||
*/
|
||||
export default function ExerciseInlineFileMediaModal({
|
||||
open,
|
||||
onClose,
|
||||
exerciseId,
|
||||
linkedExerciseMedia = [],
|
||||
onMediaListChanged,
|
||||
onInserted,
|
||||
}) {
|
||||
const [tab, setTab] = useState('library')
|
||||
const [q, setQ] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [items, setItems] = useState([])
|
||||
const [err, setErr] = useState(null)
|
||||
const [selectedAssetId, setSelectedAssetId] = useState(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [uploadFile, setUploadFile] = useState(null)
|
||||
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()
|
||||
for (const row of linkedExerciseMedia || []) {
|
||||
const aid = row?.media_asset_id
|
||||
if (aid != null) m.set(Number(aid), row)
|
||||
}
|
||||
return m
|
||||
}, [linkedExerciseMedia])
|
||||
|
||||
const loadAssets = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const res = await api.listMediaAssets({
|
||||
q: q.trim() || undefined,
|
||||
limit: 48,
|
||||
lifecycle: 'active',
|
||||
})
|
||||
setItems(Array.isArray(res.items) ? res.items.filter(a => !a.legal_hold_active) : [])
|
||||
} catch (e) {
|
||||
setErr(e.message || String(e))
|
||||
setItems([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [q])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return undefined
|
||||
setTab('library')
|
||||
setSelectedAssetId(null)
|
||||
setUploadFile(null)
|
||||
setUploadTitle('')
|
||||
setUploadInputKey((k) => k + 1)
|
||||
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
setErr(null)
|
||||
setDecl({ ...DECL_INIT })
|
||||
setDeclErr('')
|
||||
const t = setTimeout(loadAssets, 280)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || tab !== 'library') return undefined
|
||||
const t = setTimeout(loadAssets, 300)
|
||||
return () => clearTimeout(t)
|
||||
}, [q, open, tab, loadAssets])
|
||||
|
||||
const handleLinkSelected = async () => {
|
||||
if (!selectedAssetId) {
|
||||
alert('Bitte ein Archiv-Medium auswählen.')
|
||||
return
|
||||
}
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const assetMeta = items.find((x) => x.id === selectedAssetId)
|
||||
const capFromExisting = (row) =>
|
||||
sanitizeInlineMediaCaption(row?.original_filename || row?.title || assetMeta?.original_filename || '')
|
||||
|
||||
const existing = assetToExerciseMedia.get(Number(selectedAssetId))
|
||||
if (existing?.id != null) {
|
||||
onInserted(Number(existing.id), size, capFromExisting(existing))
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
setBusy(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const row = await api.attachExerciseMediaFromAsset(exerciseId, {
|
||||
media_asset_id: selectedAssetId,
|
||||
title: '',
|
||||
description: '',
|
||||
context: 'ablauf',
|
||||
is_primary: false,
|
||||
})
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
onInserted(
|
||||
Number(mid),
|
||||
size,
|
||||
sanitizeInlineMediaCaption(assetMeta?.original_filename || ''),
|
||||
)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
const msg = e.message || String(e)
|
||||
setErr(msg)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadAndInsert = async () => {
|
||||
if (!uploadFile) {
|
||||
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()
|
||||
fd.append('file', uploadFile)
|
||||
fd.append('media_type', inferred)
|
||||
fd.append('title', uploadTitle.trim())
|
||||
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 {
|
||||
const row = await api.uploadExerciseMedia(exerciseId, fd)
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
const cap = sanitizeInlineMediaCaption(
|
||||
uploadTitle.trim() || uploadFile.name || '',
|
||||
)
|
||||
onInserted(Number(mid), size, cap)
|
||||
setUploadFile(null)
|
||||
setUploadTitle('')
|
||||
setUploadInputKey((k) => k + 1)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
if (e.code === 'MEDIA_ASSET_IN_TRASH' && e.payload?.media_asset_id != null) {
|
||||
alert(
|
||||
'Dieselbe Datei existiert bereits im Papierkorb — bitte in der Medienbibliothek reaktivieren oder eine andere Datei wählen.',
|
||||
)
|
||||
} else {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
setErr(e.message || String(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedLinked = selectedAssetId != null && assetToExerciseMedia.has(Number(selectedAssetId))
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
|
||||
<div
|
||||
className="admin-modal-sheet rte-inline-media-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="rte-inline-file-title"
|
||||
style={{
|
||||
maxWidth: '560px',
|
||||
width: '100%',
|
||||
maxHeight: '90vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="rte-inline-file-title" className="admin-modal-sheet__title">
|
||||
Medium im Textfeld
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-secondary ${tab === 'library' ? 'rte-tab--active' : ''}`}
|
||||
style={{ fontSize: '13px' }}
|
||||
onClick={() => setTab('library')}
|
||||
disabled={busy}
|
||||
>
|
||||
Aus Mediathek
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-secondary ${tab === 'upload' ? 'rte-tab--active' : ''}`}
|
||||
style={{ fontSize: '13px' }}
|
||||
onClick={() => setTab('upload')}
|
||||
disabled={busy}
|
||||
>
|
||||
Neu hochladen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ overflowY: 'auto', flex: 1, padding: '12px 14px' }}>
|
||||
{err && !loading ? (
|
||||
<p style={{ color: 'var(--danger)', marginTop: '0', marginBottom: '12px', fontSize: '0.9rem' }}>{err}</p>
|
||||
) : null}
|
||||
{tab === 'library' && (
|
||||
<>
|
||||
<label className="form-label">Suche in der Bibliothek</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Name, Tag, © …"
|
||||
disabled={busy}
|
||||
/>
|
||||
{loading ? <p style={{ color: 'var(--text3)', marginTop: '12px' }}>Laden…</p> : null}
|
||||
<div className="rte-inline-asset-grid" style={{ marginTop: '14px' }}>
|
||||
{items.map((it) => {
|
||||
const id = it.id
|
||||
const selected = selectedAssetId === id
|
||||
const label = it.original_filename || it.copyright_notice || `Archiv #${id}`
|
||||
const linked = assetToExerciseMedia.has(Number(id))
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
className={`rte-inline-asset-tile${selected ? ' rte-inline-asset-tile--selected' : ''}`}
|
||||
onClick={() => setSelectedAssetId(id)}
|
||||
disabled={busy}
|
||||
>
|
||||
<div className="rte-inline-asset-tile__thumb" aria-hidden>
|
||||
<RtePickerAssetThumb asset={it} />
|
||||
</div>
|
||||
{linked ? (
|
||||
<span className="rte-inline-asset-tile__badge">Bereits verknüpft</span>
|
||||
) : null}
|
||||
<span className="rte-inline-asset-tile__meta">
|
||||
{(it.mime_type || '').split('/')[0] || 'datei'}
|
||||
</span>
|
||||
<span className="rte-inline-asset-tile__name">{label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{!loading && items.length === 0 ? (
|
||||
<p style={{ color: 'var(--text3)', marginTop: '12px' }}>Keine Treffer — Suche anpassen oder „Neu hochladen".</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'upload' && (
|
||||
<>
|
||||
<label className="form-label">Datei</label>
|
||||
<div className="rte-inline-file-row">
|
||||
<input
|
||||
key={uploadInputKey}
|
||||
id="rte-inline-file-upload-input"
|
||||
type="file"
|
||||
accept="image/*,video/*,application/pdf"
|
||||
className="rte-inline-file-input-hidden"
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0] || null
|
||||
setUploadFile(f)
|
||||
}}
|
||||
/>
|
||||
<label htmlFor="rte-inline-file-upload-input" className="btn btn-secondary rte-inline-file-pick-btn">
|
||||
Datei auswählen
|
||||
</label>
|
||||
<span className="rte-inline-file-name" title={uploadFile?.name || ''}>
|
||||
{uploadFile ? uploadFile.name : 'Keine Datei ausgewählt'}
|
||||
</span>
|
||||
</div>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Titel (optional)
|
||||
</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={uploadTitle}
|
||||
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>
|
||||
|
||||
<div style={{ padding: '12px 14px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
||||
<div className="form-row" style={{ marginBottom: '12px' }}>
|
||||
<label className="form-label" style={{ marginBottom: '4px' }}>
|
||||
Darstellung im Text
|
||||
</label>
|
||||
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
|
||||
{INLINE_MEDIA_SIZES.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{tab === 'library' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-full"
|
||||
disabled={busy || !selectedAssetId}
|
||||
onClick={handleLinkSelected}
|
||||
>
|
||||
{busy ? 'Bitte warten…' : selectedLinked ? 'In Text einfügen (bereits verknüpft)' : 'Verknüpfen & in Text einfügen'}
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn btn-primary btn-full" disabled={busy || !uploadFile} onClick={handleUploadAndInsert}>
|
||||
{busy ? 'Hochladen…' : 'Hochladen & in Text einfügen'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'
|
||||
|
||||
/**
|
||||
* Ein ausgeliefertes exercise_media für Übungslisten (Liste + Inline gleiche Darstellung).
|
||||
* @param {{ media: object, exerciseId: number, layoutSize?: string }} props
|
||||
*/
|
||||
export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'medium' }) {
|
||||
const sz = sanitizeInlineMediaSize(layoutSize)
|
||||
const box =
|
||||
sz === 'small'
|
||||
? { maxWidth: 'min(280px, 33vw)', marginTop: '0.5rem' }
|
||||
: sz === 'full'
|
||||
? { maxWidth: '100%', marginTop: '0.5rem' }
|
||||
: { 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
|
||||
style={{
|
||||
...box,
|
||||
wordBreak: 'break-word',
|
||||
overflowWrap: 'anywhere',
|
||||
fontSize: sz === 'small' ? '0.88rem' : undefined,
|
||||
}}
|
||||
>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">
|
||||
{media.title?.trim() || media.embed_url}
|
||||
</a>
|
||||
{media.embed_platform && (
|
||||
<span style={{ color: 'var(--text2)', marginLeft: '0.35rem', fontSize: '0.82rem', display: 'inline' }}>
|
||||
({media.embed_platform})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
<div style={box}>
|
||||
<img
|
||||
src={src}
|
||||
alt={media.title || media.original_filename || ''}
|
||||
style={{ width: '100%', maxWidth: '100%', height: 'auto', borderRadius: '8px', display: 'block' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
|
||||
return (
|
||||
<div style={box}>
|
||||
<video
|
||||
src={src}
|
||||
controls
|
||||
style={{ width: '100%', maxWidth: '100%', borderRadius: '8px', verticalAlign: 'top' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div style={box}>
|
||||
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.25rem' }}>
|
||||
{media.title || media.original_filename || 'Datei öffnen'}
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Kachelvorschau: Video nutzt ersten Frame (metadata), Bild = img, Embed = Label.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
|
||||
export default function ExerciseMediaThumbTile({ exerciseId, media, onOpenPreview, size = 72 }) {
|
||||
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media) : null
|
||||
const commonStyle = {
|
||||
width: '100%',
|
||||
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"
|
||||
tabIndex={0}
|
||||
title="Vorschau"
|
||||
onClick={() => onOpenPreview(media)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
onOpenPreview(media)
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
flexShrink: 0,
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden',
|
||||
background: 'var(--surface2, rgba(127,127,127,0.12))',
|
||||
border: '1px solid var(--border)',
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{media.embed_url ? (
|
||||
<span style={{ fontSize: '11px', padding: '4px', color: 'var(--text2)', textAlign: 'center' }}>
|
||||
{media.embed_platform || 'Embed'}
|
||||
</span>
|
||||
) : (media.mime_type?.startsWith('image/') || media.media_type === 'image') && src ? (
|
||||
<img alt="" src={src} style={commonStyle} />
|
||||
) : (media.mime_type?.startsWith('video/') || media.media_type === 'video') && src ? (
|
||||
<video
|
||||
src={src}
|
||||
muted
|
||||
playsInline
|
||||
preload="metadata"
|
||||
style={{ ...commonStyle, pointerEvents: 'none' }}
|
||||
onLoadedMetadata={(e) => {
|
||||
try {
|
||||
const el = e.currentTarget
|
||||
const d = el.duration
|
||||
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ fontSize: '11px', color: 'var(--text2)' }}>Datei</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,18 +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 { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
||||
|
||||
function HtmlBlock({ html, className = '' }) {
|
||||
if (!html || !String(html).trim()) return null
|
||||
const safe = sanitizeTrainerHtml(html)
|
||||
return (
|
||||
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
|
||||
)
|
||||
}
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import CombinationPlanBracket from './CombinationPlanBracket'
|
||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||
|
||||
function TagMini({ exercise }) {
|
||||
const parts = []
|
||||
@@ -31,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
|
||||
@@ -62,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')
|
||||
@@ -73,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
|
||||
@@ -85,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',
|
||||
@@ -93,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
|
||||
@@ -111,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={{
|
||||
@@ -129,7 +204,7 @@ export default function ExercisePeekModal({
|
||||
</div>
|
||||
{variant.description ? (
|
||||
<div style={{ marginTop: 8, fontSize: '0.9rem', color: 'var(--text2)' }}>
|
||||
<HtmlBlock html={variant.description} />
|
||||
<ExerciseRichTextBlock html={variant.description} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
{variant.execution_changes ? (
|
||||
@@ -137,14 +212,14 @@ export default function ExercisePeekModal({
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>
|
||||
Durchführung (Variante)
|
||||
</h4>
|
||||
<HtmlBlock html={variant.execution_changes} />
|
||||
<ExerciseRichTextBlock html={variant.execution_changes} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{exercise.summary && (
|
||||
<div style={{ fontSize: '0.95rem', color: 'var(--text2)' }}>
|
||||
<HtmlBlock html={exercise.summary} />
|
||||
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
)}
|
||||
<TagMini exercise={exercise} />
|
||||
@@ -154,37 +229,41 @@ export default function ExercisePeekModal({
|
||||
{exercise.goal && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>Ziel</h4>
|
||||
<HtmlBlock html={exercise.goal} />
|
||||
<ExerciseRichTextBlock html={exercise.goal} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.preparation && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Vorbereitung</h4>
|
||||
<HtmlBlock html={exercise.preparation} />
|
||||
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.execution && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Ablauf</h4>
|
||||
<HtmlBlock html={exercise.execution} />
|
||||
<ExerciseRichTextBlock html={exercise.execution} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.trainer_notes && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Trainer-Hinweise</h4>
|
||||
<HtmlBlock html={exercise.trainer_notes} />
|
||||
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</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>
|
||||
)
|
||||
|
||||
@@ -32,6 +32,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({
|
||||
@@ -213,8 +215,14 @@ 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
|
||||
@@ -606,6 +614,19 @@ 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) {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
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 = [
|
||||
@@ -99,6 +101,15 @@ export default function ExerciseProgressionGraphPanel({
|
||||
anchorExerciseId = null,
|
||||
anchorTitle = null,
|
||||
}) {
|
||||
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],
|
||||
)
|
||||
|
||||
const [graphs, setGraphs] = useState([])
|
||||
const [selectedGraphId, setSelectedGraphId] = useState(null)
|
||||
const [edges, setEdges] = useState([])
|
||||
@@ -126,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 : [])
|
||||
@@ -163,7 +178,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [refreshGraphs])
|
||||
}, [refreshGraphs, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedGraphId) {
|
||||
@@ -566,7 +581,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
value={newGraphVisibility}
|
||||
onChange={(e) => setNewGraphVisibility(e.target.value)}
|
||||
>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{filteredGraphVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
@@ -599,7 +614,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
<div className="form-row">
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{filteredGraphVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
@@ -1047,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,107 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { sanitizeExerciseRichDisplayHtml } from '../utils/exerciseRichTextSanitize'
|
||||
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
|
||||
}
|
||||
|
||||
function buildVisibleMediaMap(mediaList) {
|
||||
const map = new Map()
|
||||
for (const m of mediaList || []) {
|
||||
if (!m || m.id == null || isTrashHidden(m)) continue
|
||||
map.set(Number(m.id), m)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function domToReactNodes(node, exerciseId, mediaById, path) {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const t = node.textContent
|
||||
return t ? t : null
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) return null
|
||||
|
||||
const el = node
|
||||
const tag = el.tagName.toLowerCase()
|
||||
const key = path.join('.')
|
||||
|
||||
if (tag === 'span' && el.getAttribute('data-shinkan-exercise-media')) {
|
||||
const raw = el.getAttribute('data-shinkan-exercise-media')
|
||||
const mid = parseInt(raw, 10)
|
||||
if (!Number.isFinite(mid) || mid < 1) {
|
||||
return (
|
||||
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
|
||||
[Ungültiger Medienverweis]
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const media = mediaById.get(mid)
|
||||
if (!media) {
|
||||
return (
|
||||
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
|
||||
[Medium nicht verfügbar]
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const rawSize = (el.getAttribute('data-shinkan-exercise-media-size') || 'medium').toLowerCase().trim()
|
||||
const layoutSize = rawSize === 'small' || rawSize === 'full' ? rawSize : 'medium'
|
||||
const wrapClass =
|
||||
layoutSize === 'small'
|
||||
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--sm'
|
||||
: layoutSize === 'full'
|
||||
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--full'
|
||||
: 'shinkan-inline-media-wrap shinkan-inline-media-wrap--md'
|
||||
const lc = String(media.asset_lifecycle_state || 'active').toLowerCase()
|
||||
return (
|
||||
<span key={key} className={wrapClass} style={{ display: 'inline-block', verticalAlign: 'top' }}>
|
||||
{lc === 'trash_soft' && (
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--danger)', display: 'block', marginBottom: '4px' }}>
|
||||
Dieses Medium ist im Papierkorb.
|
||||
</span>
|
||||
)}
|
||||
<ExerciseMediaEmbed exerciseId={exerciseId} media={media} layoutSize={layoutSize} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const children = []
|
||||
const childNodes = Array.from(el.childNodes)
|
||||
childNodes.forEach((ch, i) => {
|
||||
const sub = domToReactNodes(ch, exerciseId, mediaById, [...path, String(i)])
|
||||
if (sub != null && sub !== false) children.push(sub)
|
||||
})
|
||||
|
||||
const props = { key }
|
||||
if (tag === 'a' && el.getAttribute('href')) {
|
||||
props.href = el.getAttribute('href')
|
||||
props.target = '_blank'
|
||||
props.rel = 'noreferrer'
|
||||
}
|
||||
return React.createElement(tag, props, children.length ? children : null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentraler Anzeige-Pfad für Übungs-Rich-Text inkl. §11 Inline-Medien.
|
||||
* @param {{ html?: string|null, exerciseId?: number|null, media?: object[]|null, className?: string }} props
|
||||
*/
|
||||
export default function ExerciseRichTextBlock({ html, exerciseId, media, className = '' }) {
|
||||
const safe = useMemo(() => sanitizeExerciseRichDisplayHtml(html), [html])
|
||||
const mediaById = useMemo(() => buildVisibleMediaMap(media), [media])
|
||||
|
||||
const body = useMemo(() => {
|
||||
if (!safe.trim()) return null
|
||||
const tpl = document.createElement('template')
|
||||
tpl.innerHTML = safe
|
||||
const nodes = []
|
||||
Array.from(tpl.content.childNodes).forEach((ch, i) => {
|
||||
const r = domToReactNodes(ch, exerciseId, mediaById, [String(i)])
|
||||
if (r != null) nodes.push(r)
|
||||
})
|
||||
return nodes
|
||||
}, [safe, exerciseId, mediaById])
|
||||
|
||||
if (!body || body.length === 0) return null
|
||||
|
||||
return <div className={`rich-text-content ${className}`.trim()}>{body}</div>
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
/**
|
||||
* Hinweis, wenn der Vereinszugang (Mitgliedschaft) deaktiviert wurde — Login bleibt möglich.
|
||||
*/
|
||||
export default function InactiveMembershipBanner() {
|
||||
const { user } = useAuth()
|
||||
const inactive = (user?.clubs || []).filter(
|
||||
(c) => (c.membership_status || '').toString().trim().toLowerCase() === 'inactive'
|
||||
)
|
||||
if (!inactive.length) return null
|
||||
|
||||
const names = inactive.map((c) => c.name || `Verein #${c.id}`).join(', ')
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="inactive-membership-banner"
|
||||
style={{
|
||||
marginBottom: '0.75rem',
|
||||
padding: '0.65rem 0.85rem',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface2, #2a2a2a)',
|
||||
border: '1px solid color-mix(in srgb, var(--warning, #d4a012) 45%, transparent)',
|
||||
color: 'var(--text1)',
|
||||
fontSize: '0.88rem',
|
||||
lineHeight: 1.45,
|
||||
}}
|
||||
>
|
||||
<strong>Vereinszugang vorübergehend deaktiviert</strong>
|
||||
<span style={{ display: 'block', marginTop: '0.35rem' }}>
|
||||
Für {inactive.length === 1 ? 'den Verein' : 'die Vereine'}{' '}
|
||||
<strong>{names}</strong>{' '}
|
||||
ist der Zugang zu Vereinsinhalten ausgesetzt — du kannst dich weiterhin anmelden und z. B.
|
||||
öffentliche Inhalte oder andere Vereine nutzen. Bei Fragen wende dich an eine:n Vereinsadministrator:in.
|
||||
</span>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user