Compare commits
223
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d34c0a73d | ||
|
|
ae51d201bc | ||
|
|
220a16429c | ||
|
|
e759076a6c | ||
|
|
8175e239b4 | ||
|
|
8f5af49a6f | ||
|
|
e7dc6a6cd3 | ||
|
|
e09a2284e9 | ||
|
|
b0faa4bfab | ||
|
|
a1a3f2e0a1 | ||
|
|
45bc049c0d | ||
|
|
e4e362b0a9 | ||
|
|
300d916fad | ||
|
|
1631bd2e02 | ||
|
|
2e105a99b8 | ||
|
|
4235246cd7 | ||
|
|
57a8957c93 | ||
|
|
930a786315 | ||
|
|
9da29a2231 | ||
|
|
b06d026dd0 | ||
|
|
32ba008660 | ||
|
|
657fcc241a | ||
|
|
c69edc6952 | ||
|
|
789b640ad0 | ||
|
|
14cf8a1a53 | ||
|
|
ea4c1f87f6 | ||
|
|
2fa1db55fd | ||
|
|
75ddd06d6a | ||
|
|
597486bef1 | ||
|
|
ebad8025f4 | ||
|
|
c7650cac2f | ||
|
|
4b2848c7c3 | ||
|
|
255fa45e90 | ||
|
|
7043addd15 | ||
|
|
1c268555f6 | ||
|
|
85163ad440 | ||
|
|
502dddd3b3 | ||
|
|
00edc7a93d | ||
|
|
d50bed428b | ||
|
|
49adb395dd | ||
|
|
81fd7d9b3b | ||
|
|
3898e8bc2c | ||
|
|
d3ddc52118 | ||
|
|
79dabbca5a | ||
|
|
ed15f73727 | ||
|
|
a8942a9e4e | ||
|
|
5dc93d9a8c | ||
|
|
805ad3c5a5 | ||
|
|
13efce6e36 | ||
|
|
cf9932990e | ||
|
|
38d84ecdf6 | ||
|
|
ce63d46cf4 | ||
|
|
435da7f17a | ||
|
|
4e654e50c0 | ||
|
|
12fd3926b2 | ||
|
|
919910d52a | ||
|
|
3dc4c9c79e | ||
|
|
8a9f9f960f | ||
|
|
f4f5642c21 | ||
|
|
05042ee9ec | ||
|
|
e96951728d | ||
|
|
bfaf532ab2 | ||
|
|
e41908af73 | ||
|
|
c1243651bb | ||
|
|
59d53d6154 | ||
|
|
98edb282ed | ||
|
|
81b9e8f601 | ||
|
|
04663e090a | ||
|
|
56fc6d853d | ||
|
|
5cf61289ec | ||
|
|
9af28faa35 | ||
|
|
34e93101f1 | ||
|
|
bb4d927090 | ||
|
|
8dd748e7d9 | ||
|
|
bacba311ae | ||
|
|
24bf3f7035 | ||
|
|
0dbcd4175c | ||
|
|
2f7e1e50ad | ||
|
|
60709df615 | ||
|
|
3c0e63757c | ||
|
|
ee54f8380f | ||
|
|
f79f83e8f9 | ||
|
|
fb8837574e | ||
|
|
1ce6d929ce | ||
|
|
1640fe6045 | ||
|
|
61baf26da6 | ||
|
|
0edc86e05a | ||
|
|
b2b7bd423d | ||
|
|
56e952f084 | ||
|
|
6586d3b68b | ||
|
|
fff30b49e1 | ||
|
|
f544975a6c | ||
|
|
4bc24b4caf | ||
|
|
42aec79ad1 | ||
|
|
9ac8200b41 | ||
|
|
000e78e976 | ||
|
|
34235ef46d | ||
|
|
8cda5c27ec | ||
|
|
aff3020b13 | ||
|
|
456ead72b6 | ||
|
|
030eb41429 | ||
|
|
5db8f8588c | ||
|
|
8992c300f1 | ||
|
|
b9adf6da84 | ||
|
|
80936b226d | ||
|
|
8bed0199b6 | ||
|
|
cfab5c2d69 | ||
|
|
8261fa4420 | ||
|
|
75d6a40817 | ||
|
|
d7ed0c0e9b | ||
|
|
d73ed13f87 | ||
|
|
6abc911e94 | ||
|
|
28ca64b5b4 | ||
|
|
fc33bfbdeb | ||
|
|
be0385922d | ||
|
|
01be9ffcd4 | ||
|
|
30c1c259d2 | ||
|
|
24c70c5ea0 | ||
|
|
624c19dcba | ||
|
|
f54372d7b5 | ||
|
|
c46f5f99be | ||
|
|
58a38702b9 | ||
|
|
59fb8a5527 | ||
|
|
a7cecca36f | ||
|
|
bab9b178a4 | ||
|
|
5cf775c920 | ||
|
|
337f29401b | ||
|
|
311a106d93 | ||
|
|
979e328cef | ||
|
|
cc51b0f08f | ||
|
|
f745e5d082 | ||
|
|
b6de1f15ea | ||
|
|
3ff47779e0 | ||
|
|
d3055f6f2f | ||
|
|
f354bd9f77 | ||
|
|
01636b5baf | ||
|
|
3e4fa0dc39 | ||
|
|
8d85649cf8 | ||
|
|
3f0d02edab | ||
|
|
4fb77d6927 | ||
|
|
b8842cf98e | ||
|
|
f8a7247ccc | ||
|
|
d758de3852 | ||
|
|
c1d1c2d7e0 | ||
|
|
bebcf5af73 | ||
|
|
5b13a0a526 | ||
|
|
c921f0dd8f | ||
|
|
ceef6f09e2 | ||
|
|
cc4e621f95 | ||
|
|
d213746bd2 | ||
|
|
f9e6e61244 | ||
|
|
4f64cb105b | ||
|
|
a8667f4757 | ||
|
|
084ac38c2e | ||
|
|
1bc7ea95fb | ||
|
|
3d321857ec | ||
|
|
b8453f3f07 | ||
|
|
0a1816e38b | ||
|
|
95f5b0b2d7 | ||
|
|
88fb60e244 | ||
|
|
da368222e0 | ||
|
|
e2964a077d | ||
|
|
631ba1cb43 | ||
|
|
8ac723eafe | ||
|
|
ece08ec1a1 | ||
|
|
7284c577d7 | ||
|
|
161d520329 | ||
|
|
9365125969 | ||
|
|
b752883392 | ||
|
|
c2d9eac151 | ||
|
|
18fa4de055 | ||
|
|
fe703ca414 | ||
|
|
f9d518fb78 | ||
|
|
c6a7d668c5 | ||
|
|
ff8fd78a31 | ||
|
|
40a3b4b8e6 | ||
|
|
3bf0af001a | ||
|
|
3210796139 | ||
|
|
b9d27b59b0 | ||
|
|
518918a6e5 | ||
|
|
cfd40889ac | ||
|
|
585ee8c90d | ||
|
|
8eec145393 | ||
|
|
db8af53652 | ||
|
|
1e1fd80fb7 | ||
|
|
b9ef0395c1 | ||
|
|
5096eec16b | ||
|
|
68923b0364 | ||
|
|
657f73d2c5 | ||
|
|
8b86021293 | ||
|
|
35a3f6e18d | ||
|
|
18a58cb5a5 | ||
|
|
14884e6e55 | ||
|
|
2007f3f659 | ||
|
|
d4b9db9520 | ||
|
|
00b22a756f | ||
|
|
56ea36ea25 | ||
|
|
9dbd3cbd5f | ||
|
|
9e759a28c6 | ||
|
|
c778d21b26 | ||
|
|
14745b347d | ||
|
|
35b14fe1a6 | ||
|
|
caab9f2863 | ||
|
|
f03330bf77 | ||
|
|
61e3b3a6b1 | ||
|
|
347af0c36e | ||
|
|
dc310b38eb | ||
|
|
e0ecfe927f | ||
|
|
abee6171df | ||
|
|
5aee9c52fc | ||
|
|
870a7611dc | ||
|
|
0181575962 | ||
|
|
c919e02441 | ||
|
|
4b6fd49940 | ||
|
|
413a096432 | ||
|
|
f48b573a63 | ||
|
|
b661d0edb2 | ||
|
|
9afcd762d0 | ||
|
|
0f08e8df58 | ||
|
|
7d476268b8 | ||
|
|
c7bf7dcd9d | ||
|
|
e69aca51f6 | ||
|
|
0c044249d9 |
No files matched your search
@@ -1,30 +1,42 @@
|
|||||||
# Shinkan Jinkendo - Projekt-Status
|
# Shinkan Jinkendo - Projekt-Status
|
||||||
|
|
||||||
**Stand:** 2026-05-05
|
**Stand:** 2026-05-12
|
||||||
**Version (Code):** 0.8.10 (`backend/version.py`, APP_VERSION)
|
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
|
||||||
**DB-Schema-Version:** `20260505037`
|
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||||
**Branch:** develop
|
**Branch:** develop
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
**Aktueller Meilenstein:** **Trainingsrahmenprogramm Bibliothek + Slot‑Blueprint** (DB **036–037**): Rahmenkopf nur als Vorlage mit Kontext‑Stammdaten; pro Slot genau eine **Blueprint‑`training_unit`** mit **`framework_unit_sections`/`_items`** wie die Planung; Kalenderliste blendet Blueprints aus; **`POST /api/training-units/from-framework-slot`** materialisiert Kopien mit **`origin_framework_slot_id`**. Parallel: **Progressionsgraph** (032–034) bleibt unterstützend (**`TRAINING_FRAMEWORK_SPEC.md`** §3–§4).
|
**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.
|
||||||
|
|
||||||
**Letzte dokumentierte Änderungen (Mai 2026):**
|
**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`).
|
||||||
|
|
||||||
- ✅ Migration **036:** Rahmen nur Bibliothek; Fokus/Stil + M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`/`group_id` am Kopf.
|
**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).
|
||||||
- ✅ Migration **037:** `training_units.framework_slot_id` / `origin_framework_slot_id`; Migration Entfall **`training_framework_slot_exercises`**.
|
|
||||||
- ✅ APIs: erweiterte Rahmen‑Hydration (`sections`, `exercises`, `blueprint_training_unit_id`); Planung siehe **`TRAINING_FRAMEWORK_SPEC.md`** §2.4.
|
|
||||||
- ✅ Frontend: `createTrainingUnitFromFrameworkSlot` in `api.js`.
|
|
||||||
|
|
||||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) · Rahmen/Graph: [`technical/TRAINING_FRAMEWORK_SPEC.md`](technical/TRAINING_FRAMEWORK_SPEC.md)
|
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||||
|
|
||||||
**Nächste Schritte (Auszug):**
|
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
||||||
|
|
||||||
|
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-12, für **neue Session**):
|
||||||
|
|
||||||
|
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
|
||||||
|
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
|
||||||
|
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)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
|
||||||
|
|
||||||
|
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** Abschnitt 11; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Nächste Schritte (Auszug — Planung/Rahmen & Kombination):**
|
||||||
|
|
||||||
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
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).
|
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**).
|
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`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -43,6 +55,7 @@
|
|||||||
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
|
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
|
||||||
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
|
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
|
||||||
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
|
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
|
||||||
|
| **040–046** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets` (046 z. B. Tags/GIN), Plattform-Speicherpfad** | ✅ Dev | 🔲 Prod |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -95,6 +108,11 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
|||||||
|
|
||||||
### 🔲 In Arbeit / Backlog
|
### 🔲 In Arbeit / Backlog
|
||||||
|
|
||||||
|
- [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
|
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
||||||
- [ ] Responsive Design / Dark Mode / PWA
|
- [ ] Responsive Design / Dark Mode / PWA
|
||||||
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
||||||
@@ -125,7 +143,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
|||||||
|
|
||||||
### Dev
|
### Dev
|
||||||
|
|
||||||
Branch `develop`; Migrations bis mindestens **037** 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
|
### Prod
|
||||||
|
|
||||||
@@ -137,16 +155,18 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
| Dokument | Pfad | Stand | Status |
|
| 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 |
|
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
|
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
|
||||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-05 | ✅ Aktualisiert (037) |
|
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-05 | ✅ Aktualisiert |
|
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
|
||||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-30 | ✅ Ergänzt Progressions-API |
|
| 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 |
|
| 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) |
|
| 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) |
|
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-05 | ✅ Diese Datei |
|
| 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 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -157,4 +177,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Letzte Aktualisierung:** 2026-05-05
|
**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
|
# Shinkan Jinkendo - Fachliches Domänenmodell
|
||||||
|
|
||||||
**Version:** 0.4.3
|
**Version:** 0.4.6
|
||||||
**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)
|
**Stand:** 2026-05-14 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||||
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -474,6 +474,26 @@ skill_level_definitions (
|
|||||||
|
|
||||||
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
|
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
|
||||||
|
|
||||||
|
### Parallele Trainingsstreams (Breakout, Entwurf)
|
||||||
|
|
||||||
|
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
|
||||||
|
|
||||||
|
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
|
||||||
|
|
||||||
|
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||||
|
|
||||||
|
**Schema-Hinweis (2026-05):** Tabelle `training_unit_sections` hat **`UNIQUE (training_unit_id, order_index)`** (Migration 031). Damit sind **zwei gleichzeitige „Spuren“ mit jeweils eigener Sektion auf derselben `order_index`** nicht abbildbar — Voraussetzung für Parallele Streams ist eine **geplante Migrations-/Constraint-Anpassung** (partielle Uniques pro Phase/Stream); siehe Arbeitsdokument `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`. **Keine invasive Migration ohne explizite Freigabe.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||||
|
|
||||||
|
- **`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)
|
## Methodenbezug (§11.5)
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Parallele Trainingsstreams (Breakout) — Fachkonzept
|
||||||
|
|
||||||
|
**Status:** Entwurf zur Abstimmung · **Stand:** 2026-05-14
|
||||||
|
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
|
||||||
|
|
||||||
|
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||||
|
**Domänenbegriffe (Überblick):** `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ausgangslage und Problem
|
||||||
|
|
||||||
|
In Kinder- und Breitensport-Training ist ein typischer Ablauf:
|
||||||
|
|
||||||
|
1. **Gemeinsam:** Aufwärmen, Koordination, Ansagen.
|
||||||
|
2. **Getrennt:** Kinder in mehrere Gruppen teilen; **Co-Trainer** leiten jeweils eigene Inhalte **gleichzeitig**.
|
||||||
|
3. **Gemeinsam:** Abschluss, gemeinsame Übungen, Verabschiedung.
|
||||||
|
|
||||||
|
Die aktuelle Shinkan-Planung modelliert pro Termin **eine lineare Folge von Abschnitten und Übungen** pro Einheit. Das genügt nicht, wenn **mehrere gleichzeitige „Unter-Sessions“** mit unterschiedlichen Plänen dokumentiert und auf der Matte geführt werden sollen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Ziele (fachlich)
|
||||||
|
|
||||||
|
| ID | Ziel |
|
||||||
|
|----|------|
|
||||||
|
| PT‑01 | Eine **Kalender-Einheit** bleibt **ein** Termin (eine Halle, eine Gruppe, ein Datum) — kein Splitten in künstlich mehrere Kalendereinträge nur für Parallelität. |
|
||||||
|
| PT‑02 | **Unbegrenzte** Anzahl paralleler **Streams** (Teilstrecken) in einer oder mehreren **Parallelphasen**. |
|
||||||
|
| PT‑03 | **Phasenmodell:** klar erkennbar **Gemeinsam** vs. **Parallel** vs. wieder **Gemeinsam** (auch mehrfach hintereinander möglich). |
|
||||||
|
| PT‑04 | **Rollen:** Leitung (Haupttrainer) und Co-Trainer; Zuordnung der Co-Trainer **soll** an konkrete Streams anschließbar sein (heute: nur flache Liste pro Einheit — siehe technische Spec). |
|
||||||
|
| PT‑05 | **Sonderfall Stationen:** rotierender Ablauf (z. B. Wechsel alle 20 Min.) **inhaltlich** unterscheiden zwischen (a) Rotation **innerhalb** einer Teilstrecke und (b) **synchron** getakteter Hallen-Rotation — siehe §5. |
|
||||||
|
| PT‑06 | **Durchführung:** Trainer können „ihre“ Spur auf dem Gerät abarbeiten; Fortschritt pro Spur nachvollziehbar. |
|
||||||
|
|
||||||
|
**Nicht-Ziel (frühe Stufen):** Echtzeit-Synchronisation mehrerer Geräte; individuelles Athleten-Tracking; automatische Raumbelegung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Begriffe
|
||||||
|
|
||||||
|
| Begriff | Definition |
|
||||||
|
|---------|------------|
|
||||||
|
| **Einheit / Termin** | Geplante `training_unit` für Gruppe und Datum — übergeordneter Rahmen des Abends. |
|
||||||
|
| **Phase** | Organisatorischer Block innerhalb der Einheit: entweder **ganze Gruppe** oder **parallel**. |
|
||||||
|
| **Stream / Teilstrecke** | Innerhalb einer Parallelphase: eine von N **gleichzeitig** stattfindenden Unter-Abläufen mit **eigenem** Miniplan (Abschnitte, Übungen, Notizen — analog heutiger Planung). |
|
||||||
|
| **Synchronisationspunkt** | Fachlich: alle treffen sich wieder (Beginn einer **Gemeinschaftsphase** nach Parallelität). |
|
||||||
|
| **Station (Rotation)** | Inhaltlicher Fokus oder Platz, den Teilnehmer **wechselnd** anlaufen; kann als Kombinations-/Zirkellogik oder als koordinierter Hallenrhythmus modelliert werden (§5). |
|
||||||
|
|
||||||
|
**Abgrenzung „Rahmenprogramm-Slot“:** Ein Slot im **Rahmenprogramm** ist eine **Session in einer Serie** (z. B. Woche 1 vs. Woche 2), **nicht** „Teilgruppe A gleichzeitig mit Teilgruppe B in derselben Stunde“. Parallele Streams sind **innerhalb einer Einheit**, orthogonal zum Rahmen-Slot.
|
||||||
|
|
||||||
|
**Abgrenzung **Kombinationsübung**:** Eine Kombi-Übung bündelt **mehrere Einzelübungen** mit Methodenprofil (Archetyp, ggf. Rotation) **in einem Plan-Item**. Sie ersetzt **nicht** mehrere Trainer mit **jeweils eigenem Gesamtablauf**, kann aber **pro Stream** für Stationslogik genutzt werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Szenarien
|
||||||
|
|
||||||
|
### 4.1 Klassischer Breakout
|
||||||
|
|
||||||
|
30 Min. gemeinsam → 25 Min. drei parallele Streams (Gruppe an Matte / an Schlagsack / Fußarbeit) → 15 Min. gemeinsam.
|
||||||
|
|
||||||
|
### 4.2 Viele Kinder, mehrere Co-Trainer
|
||||||
|
|
||||||
|
Haupttrainer plant die Gesamtstruktur; jeder Co-Trainer sieht in der Durchführung primär die zugewiesene Teilstrecke.
|
||||||
|
|
||||||
|
### 4.3 Rollierendes Stationssystem
|
||||||
|
|
||||||
|
Alle Gruppen arbeiten an **verschiedenen Schwerpunkten** und **wechseln** nach festem Intervall die Station — entweder **nur innerhalb einer Spur** oder **hallenweit synchron** (offene fachliche Präzisierung in MVP vs. später, §5).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Sonderfall: Stationen und Kombinationsübungen
|
||||||
|
|
||||||
|
### 5.1 Variante A — Rotation innerhalb einer Teilstrecke
|
||||||
|
|
||||||
|
Eine Teilgruppe rotiert durch mehrere Übungen (Zeit oder Runden). Das liegt nah an einer **Kombinationsübung** mit Archetyp z. B. „Zirkel / zeitgesteuerte Rotation“ und Parametern (Wechselintervall). **Empfehlung:** Diese Variante über **bestehendes** Kombinationsübungs-Konzept in der jeweiligen **Stream-Planung** abbilden (`planning_method_profile`).
|
||||||
|
|
||||||
|
### 5.2 Variante B — Synchron getaktete Hallen-Rotation
|
||||||
|
|
||||||
|
Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächsten Station; Startstation kann pro Teilgruppe **versetzt** sein. Das ist **organisatorisch** schwerer: es braucht entweder **Phasen-Metadaten** (globaler Takt) oder eine explizite **Rot/Matrix**. **Empfehlung:** In einer **zweiten Ausbaustufe** abbilden; MVP kann bei Variante A starten, sofern fachlich ausreichend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Rollen und Verantwortlichkeiten
|
||||||
|
|
||||||
|
- **Leitungstrainer:** Hält den Faden, startet Gemeinschaftsphasen, koordiniert Parallelbeginn/-ende (fachlich; ggf. später UI-Hinweise).
|
||||||
|
- **Co-Trainer:** Verantwortlich für **zugeteilte** Streams; Zuordnung soll **pro Stream** möglich werden (Erweiterung gegenüber reiner Einheits-Co-Trainer-Liste).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Offene fachliche Entscheidungen
|
||||||
|
|
||||||
|
1. **MVP Umfang:** Reicht **freie Parallelität** ohne **synchronen** Hallenwechsel (Variante B)?
|
||||||
|
2. **Dauer:** Sollen Phasen oder Streams **Soll-Minuten** tragen (nur Anzeige vs. später Timer)?
|
||||||
|
3. **Vorlagen:** Müssen `training_plan_templates` parallel-fähig werden **vor** oder **mit** der ersten Implementierung?
|
||||||
|
4. **Sichtbarkeit:** Dürfen alle Co-Trainer alle Streams sehen, oder „nur meine Spur“?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Verwandte Dokumente
|
||||||
|
|
||||||
|
| Dokument | Bezug |
|
||||||
|
|----------|--------|
|
||||||
|
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slots = Serien-Sessions, **nicht** Intra-Einheit-Parallelität |
|
||||||
|
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
|
||||||
|
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
|
||||||
|
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
|
||||||
|
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
|
||||||
@@ -4,9 +4,15 @@ Ausführliche fachliche Inhalte:
|
|||||||
|
|
||||||
| Dokument | Inhalt |
|
| 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 |
|
| [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.
|
`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)
|
# Gelieferte Features & technische Basis (Q2 2026)
|
||||||
|
|
||||||
**Stand:** 2026-05-05
|
**Stand:** 2026-05-12
|
||||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.10**, **DB_SCHEMA_VERSION 20260505037**
|
**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 |
|
| **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`** |
|
| **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` |
|
| **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`)
|
## 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.
|
- **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.
|
- 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).
|
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).
|
- 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).
|
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
- 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 |
|
| Thema | Dokument |
|
||||||
|--------|----------|
|
|--------|----------|
|
||||||
@@ -140,5 +168,7 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
|||||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
||||||
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
||||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.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` |
|
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# Einheitliche Zugriffsschicht & Governance – Umsetzungsplan
|
||||||
|
|
||||||
|
**Status:** verbindliche Umsetzungsreihenfolge (nachgelagert zum Zielbild in `MULTI_TENANCY_RBAC_ARCHITECTURE.md`)
|
||||||
|
**Stand:** 2026-05-06
|
||||||
|
**Zweck:** Drift vermeiden – eine nachvollziehbare Schicht für Mandanten-Kontext, Sichtbarkeit und Berechtigungen, auf die alle inhaltsbezogenen Module konsistent aufbauen.
|
||||||
|
|
||||||
|
**Explizit zurückgestellt (wie vereinbart):** kostenpflichtiges Vereins-Membership / Tier-Limits pro Verein (`club_subscriptions` o. Ä.) – kommt nach stabiler Zugriffs- und Datenisolationsbasis.
|
||||||
|
|
||||||
|
**Separates späteres Konzept:** durch Vereinsadmins definierbare Rollen mit feingranularen Rechten (Capability-Bundles in DB/UI); dieser Plan bereitet nur die **Capability-Idee** und **Erweiterungspunkte** vor.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Leitprinzipien
|
||||||
|
|
||||||
|
1. **Ein Mandant für Datenisolierung:** `club_id` ist die Grenze für „vereinsgeteilte“ Inhalte. Nur Ausnahmen: explizit **plattformweite/offizielle** Objekte und **privat**e Objekte des Erstellers.
|
||||||
|
2. **Ein Kontext pro HTTP-Request:** Mitgliedschaft und gewählter aktiver Verein werden einmal aufgelöst und validiert; Folgelogik nutzt nur noch dieses Objekt (kein verteiltes erneutes „Rates“ aus Headers).
|
||||||
|
3. **Eine fachliche Sichtbarkeits-Semantik** über alle Bibliotheks- und Planungsartefakte (Übungen, Vorlagen, Rahmenprogramme, …): gleiche Enums, gleiche Leseprüfung, angepasste Listenfilter.
|
||||||
|
4. **Sparte optional verschärfen:** `division_id` auf Objekten und später auf Rollenzuweisung ausgewertet – ohne Vereinsgrenze zu sprengen.
|
||||||
|
5. **Community später additive:** neue Freigabeebene oder Flags ergänzen die bestehende Semantik, ohne `club`-Isolation zu ersetzen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Architektur der Zugriffsschicht (Schichtenmodell)
|
||||||
|
|
||||||
|
| Schicht | Verantwortung |
|
||||||
|
|---------|----------------|
|
||||||
|
| **Authentifizierung** | Session / Token → `profile_id`, globale `role` (`require_auth`, bestehend). |
|
||||||
|
| **TenantContext** (neu, zentral) | Aus `profile_id` + Header `X-Active-Club-Id` (optional) + DB `profiles.active_club_id`: effektive **`effective_club_id`** nur wenn Mitgliedschaft aktiv existiert; sonch klaren Fehler (403/400 nach Konvention). Optional: Cache der Mitgliedschaftszeilen/Rollen **einmal pro Request**. |
|
||||||
|
| **Governance / Objekt contra Account** | Für jedes geschützte Objekt: `visibility`, `club_id`, `division_id` (nullable), `created_by` → **eine** zentrale Entscheidung `can_read` / `can_write` (interne Module, keine Copy-Paste-Logik pro Router). |
|
||||||
|
| **Funktions-/Feature-Rechte** | „Darf dieser Nutzer im Verein X Trainergruppe anlegen?“ → Capability-Checks (`can_manage_club_org`, `can_plan_in_club`, …); später durch dynamische Rollen → gleiche Capability-Namen. |
|
||||||
|
|
||||||
|
**Ziel:** Router werden dünn: laden Daten nur noch durch Hilfen, die **TenantContext** und **Governance** bereits berücksichtigen oder explizit prüfen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Scope- und Sichtbarkeitsmodell (einheitlich)
|
||||||
|
|
||||||
|
Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
|
||||||
|
|
||||||
|
**Zielbild (phasenweise DB/API-Anpassung):**
|
||||||
|
|
||||||
|
| Wert | Lesende Regel (kurz) |
|
||||||
|
|------|----------------------|
|
||||||
|
| `private` | Nur `created_by` (+ Plattform-Admin nach Policy); keine Vereinsliste ohne Ownership. |
|
||||||
|
| `club` | Nur aktive Mitglieder des Objekt-`club_id`; **Cross-Verein nie**. |
|
||||||
|
| `division` *(optional neue Stufe oder `club` + Pflicht `division_id`)* | Nur Mitglieder, die dieser Sparte zugeordnet sind (Regeln gesondert spezifizieren: Mitgliedschaft vs. Gruppe vs. Rolle `division_lead`). |
|
||||||
|
| `official` | Plattform-weit lesbar (Superadmin publiziert/pflegt); weiterhin strikt von `club`-Daten getrennt. |
|
||||||
|
| `community` *(reserviert)* | Noch nicht implementieren; Design nur additive Felder/Enum-Einträge dokumentieren, wenn erste Stories starten. |
|
||||||
|
|
||||||
|
**Trainer-Flow:** „Privat anlegen, dann im Verein teilen“ = Transition von `private` zu `club` (oder Kopie + neue Visibility – Produktentscheidung; technisch muss `club_id` gesetzt und Mitgliedschaft geprüft werden).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Roadmap (verbindliche Reihenfolge)
|
||||||
|
|
||||||
|
### Stufe A – Foundations & Audit
|
||||||
|
|
||||||
|
- **Router-Inventar:** Liste aller Endpoints mit Zugriff auf `club_id`, `visibility`, organisationalem Bezug oder Listenfiltern (Excel/Markdown-Tabelle im Repo oder unter `.claude/docs/working/`).
|
||||||
|
- **Definition of Done je Endpoint:** „Default deny“ für tenant-sensitive Listen wenn Kontext fehlt/ungültig.
|
||||||
|
- TenantContext-Spezifikation festhalten (Feldnamen, HTTP-Fehlercodes, Superadmin-Ausnahmen).
|
||||||
|
|
||||||
|
### Stufe B – TenantContext (Backend zentral)
|
||||||
|
|
||||||
|
- FastAPI-Dependency z. B. `get_tenant_context(session, x_active_club_id)` → Objekt mit `profile_id`, `global_role`, `effective_club_id`, `club_memberships` (optional gekürzt).
|
||||||
|
- Alle neuen und bestehenden sicherheitsrelevanten Änderungen **nur** über diese Dependency oder darauf aufbauende Helfer.
|
||||||
|
- Abgleich mit Frontend: `X-Active-Club-Id` und Persistenz `active_club_id` (bereits vorhanden) als einzige variabler Vereinskontext-Quellen.
|
||||||
|
|
||||||
|
### Stufe C – Governance vereinheitlichen
|
||||||
|
|
||||||
|
- **Eine** interne API-Stilebene (auch wenn mehrere Python-Funktionen):
|
||||||
|
`content_readable(...)`, `content_writable(...)` oder zweischichtig „Governance“ vs „Org-Rechte“.
|
||||||
|
- Module angleichen: **Übungen**, **Trainingsplanung**, **Rahmenprogramme**, **Vorlagen** – gleiche Regeln für `club`/`official`/`private`; **`division`** dort einführen, wo fachlich nötig (einheitliche Filter-Chips in UI).
|
||||||
|
- Regressionstests: **zwei Vereine, zwei Nutzer**, kein Kreuzzugriff auf `club`-Objekte; Superadmin/Global-Path weiterhin getrennt testen.
|
||||||
|
|
||||||
|
### Stufe D – Sparten-Durchsetzung
|
||||||
|
|
||||||
|
- `division_lead` und optional `division_id` auf Mitgliedschaft/Rolle auswerten bei Schreib-/Lesevorgängen für Objekte mit `division_id`.
|
||||||
|
- Dokumentieren: Was gilt für Objekte mit `division_id=NULL` innerhalb eines Vereins (vereinsweit vs. nur „ohne Sparte“).
|
||||||
|
|
||||||
|
### Stufe E – Capabilities dokumentieren (ohne UI für Custom Roles)
|
||||||
|
|
||||||
|
- Markdown-Tabelle **Capability-Fingerprint**: Kennungen wie `content.share_club`, `planning.edit_unit`, `org.manage_members`, … mit Zuordnung zu den **heutigen** festen Vereinsrollen.
|
||||||
|
- Ziel: später `club_custom_roles` nur noch andere Kombination derselben Kennungen – keine zweite Philosophie.
|
||||||
|
|
||||||
|
### Stufe F – Community (eigenes Epic)
|
||||||
|
|
||||||
|
- Konzept: Freigabe **additiv** (Flag oder Enum), Moderation, Sichtbarkeit „öffentlich außerhalb meines Vereins“ ohne bestehende `club`-Isolation zu brechen.
|
||||||
|
|
||||||
|
### Zurückgestellt – Vereinsabo / Limits
|
||||||
|
|
||||||
|
- Wiederöffnen wenn ACCESS_LAYER Stufe C/D stabil; dann Enforcement vor ausgewählten Writes an einen Billing-Stripe binden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Drift vermeiden (Arbeitsdisziplin)
|
||||||
|
|
||||||
|
| Mechanismus | Inhalt |
|
||||||
|
|-------------|--------|
|
||||||
|
| **Cursor / IDE** | Projektregel `.cursor/rules/access-layer.mdc` (Router); Agents sollen nicht auf „nur require_auth“ ausweichen. |
|
||||||
|
| **Heuristik-Check** | `python backend/scripts/check_access_layer_hints.py`; CI optional mit `ACCESS_LAYER_STRICT=1`. Optional danach: `cd backend && pytest tests/` (nach `pip install -r requirements-dev.txt`). |
|
||||||
|
| **PR-Checkliste** | Neuer/changed Endpoint: TenantContext verwendet? Governance für Listen + Detail? Tests für zweiten Verein? |
|
||||||
|
| **Single Source of Truth** | Sichtbarkeitsregeln nur in Zugriffsmodul(en), nicht in Routers dupliziert. |
|
||||||
|
| **Änderungen am Enum** | Nur zusammen mit Migration + Kurzbeschreibung in diesem Dokument (Datum/Changelog-Zeile). |
|
||||||
|
| **Beziehung zu MULTI_TENANCY-Doc** | Zielbild und Gap-Analyse §3 dort pflegen (**§3.0** = aktueller Umsetzungsstand); **operative Reihenfolge** hier. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Nächste konkrete Artefakte (nach diesem Plan)
|
||||||
|
|
||||||
|
1. **TenantContext-Spezifikation** (ein Abschnitt in diesem Dokument oder Kurz-ADR): Request-Lebenszyklus, Fehlerbilder, Superadmin.
|
||||||
|
2. **Endpoint-Audit-Tabelle** (Working-Dokument, bei jedem Merge pflegen bis Stufe C abgeschlossen).
|
||||||
|
3. **Testplan „Cross-Tenant“** (manuell oder pytest): Minimalsetup zweier Vereine — Unit-Tests `backend/tests/test_access_layer.py`; Integration `backend/tests/test_access_layer_integration.py` bei `ACCESS_LAYER_INTEGRATION=1` / CI im Backend-Container.
|
||||||
|
|
||||||
|
**Audit-Tabelle (fortlaufend):** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Referenzen
|
||||||
|
|
||||||
|
- `.claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md` – übergeordnetes Zielbild & Begriffe.
|
||||||
|
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` – verbindliche Domänenregeln für **Medien-Assets** (gleiche Sichtbarkeit wie Übungen, Promotion-Kopplung, Copyright, Papierkorb/Lebenszyklus, externer Speicher). Bei Widerspruch zur Sichtbarkeits-Tabelle in §3 dieses Dokuments: §3 für Enums/`library_content_*`-Semantik, Medien-Spez für Asset-spezifische Zusatzregeln.
|
||||||
|
- `backend/club_tenancy.py` – bestehende Bausteine (`assert_club_member`, `exercise_visible_to_profile`, …); Ziel ist Deren schrittweise Zusammenführung unter die neue Zugriffsschicht ohne Big-Bang.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Letzte Aktualisierung:** 2026-05-07
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
|
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
|
||||||
|
|
||||||
**Version:** 0.5.2
|
**Version:** 0.5.3
|
||||||
**Stand:** 2026-05-05
|
**Stand:** 2026-05-07
|
||||||
**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`).
|
**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` | ✅ |
|
| **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` | ✅ |
|
| **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`** | ✅ |
|
| **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)
|
## Migration 022: Skills Schema Complete (BREAKING CHANGE)
|
||||||
|
|
||||||
@@ -267,9 +266,11 @@ exercise_skills (
|
|||||||
UNIQUE (exercise_id, skill_id) -- Migration 020
|
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_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**)
|
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
# Exercises API Specification
|
# Exercises API Specification
|
||||||
|
|
||||||
**Version:** 1.4
|
**Version:** 1.5
|
||||||
**Datum:** 2026-04-30
|
**Datum:** 2026-05-08
|
||||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||||
**Autor:** Claude 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.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.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.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
|
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||||
@@ -336,6 +337,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
|||||||
### `PUT /exercises/{id}`
|
### `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)
|
**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`
|
- `media_type` (enum, required) - `image | video | document | sketch`
|
||||||
- `title` (string, optional)
|
- `title` (string, optional)
|
||||||
- `description` (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).**
|
**Entweder `file` ODER `embed_url` (nicht beides).**
|
||||||
|
|
||||||
@@ -505,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
|||||||
{
|
{
|
||||||
"title": "Neuer Titel",
|
"title": "Neuer Titel",
|
||||||
"description": "Neue Beschreibung",
|
"description": "Neue Beschreibung",
|
||||||
"is_primary": true,
|
"is_primary": true
|
||||||
"context": "detail"
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`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)
|
**Response:** `200 OK` (media object)
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -893,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
|
|||||||
- File size: max 50MB
|
- File size: max 50MB
|
||||||
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
||||||
- Embed platforms: `youtube, instagram, vimeo`
|
- 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
|
### Exercise Block
|
||||||
- `name`: 3-200 chars
|
- `name`: 3-200 chars
|
||||||
@@ -947,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Version:** 1.0
|
**Version:** 1.5
|
||||||
**Letzte Änderung:** 2026-04-24
|
**Letzte Änderung:** 2026-05-08
|
||||||
**Status:** DRAFT - Awaiting Review
|
**Status:** Living Spec
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
|
||||||
|
|
||||||
|
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
|
||||||
|
**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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck und Abgrenzung
|
||||||
|
|
||||||
|
### 1.1 Zweck
|
||||||
|
|
||||||
|
- **Ein physisches Medium** („Datei-Asset“) wird **einmal** gespeichert und **mehrfach** mit Übungen verknüpft (Wiederverwendung, keine Dubletten auf der Platte).
|
||||||
|
- **Sichtbarkeit** von Datei-Assets folgt **derselben Semantik** wie bei Übungen (`private` \| `club` \| `official` – ggf. spätere Enum-Erweiterungen nur gemeinsam mit Migration + ACCESS_LAYER-Doku).
|
||||||
|
- **Superadmin** kann Medien **global** freigeben (fachlich: Stufe wie „offiziell“ / plattformweit lesbar gemäß `library_content_*`-Regeln).
|
||||||
|
- **Copyright:** pro Asset sind **Vermerke** vorgesehen und an `official` / Vereinsnutzung anzubinden (Validierungsstufen in Umsetzung festlegen).
|
||||||
|
- **Externer Speicher:** Speicherung darf **lokal/NAS** (Filesystem) oder **extern** (z. B. S3-kompatibler Dienst) erfolgen – die App arbeitet über eine **Speicher-Abstraktion** (Interface), nicht mit verstreuten `Path`-Annahmen.
|
||||||
|
- **Papierkorb & Retention:** mehrstufiger Lebenszyklus mit **automatischen** und **manuellen** Übergängen, siehe §5.
|
||||||
|
|
||||||
|
### 1.2 Abgrenzung
|
||||||
|
|
||||||
|
- **Embeds** (reine externe URL, kein Upload) bleiben pro **Verknüpfung zur Übung** möglich (`embed_url` o. Ä.); sie haben **keinen** physischen Lebenszyklus wie Datei-Assets (kein Papierkorb „Stufe 3 physische Löschung“). Trotzdem: UI kann „Link ungültig“ o. Ä. separat abbilden.
|
||||||
|
- **Übungs-Governance** (wer eine Übung bearbeiten darf) **bleibt maßgeblich** für **Anlegen/Entfernen/Umsortieren** von Medien **in dieser Übung**; Medien erzwingen **keine** schärfere Edit-Policy als die Übung selbst.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Begriffe
|
||||||
|
|
||||||
|
| Begriff | Bedeutung |
|
||||||
|
|--------|-----------|
|
||||||
|
| **Media Asset** | Logische Entität für eine **hochgeladene Datei** inkl. Metadaten, Sichtbarkeit, Copyright, Speicherreferenz, Lifecycle-Status. |
|
||||||
|
| **Übungs-Medium / Attachment** | Verknüpfung **Übung ↔ Asset** oder reines Embed; enthält u. a. `context` (Sektion), `sort_order`, übungsspezifischen Titel/Beschreibung, `is_primary`. |
|
||||||
|
| **Medienmanager / Archiv** | Verwaltungs-UI/API für Assets (Suche, Metadaten, Lifecycle, ggf. Superadmin-global). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Zieldatenmodell (Überblick)
|
||||||
|
|
||||||
|
> Konkrete Tabellennamen/Migrationen beim Implementierungsstart festziehen; dieses Kapitel ist die **fachliche Norm**.
|
||||||
|
|
||||||
|
### 3.1 Tabelle `media_assets` (oder gleichwertiger Name)
|
||||||
|
|
||||||
|
**Pflichtidee:**
|
||||||
|
|
||||||
|
- Identität, technische Metadaten: `id`, `mime_type`, `byte_size`, `sha256` (vollständig), `original_filename`, `created_at`, `updated_at`.
|
||||||
|
- Mandant & Governance: `visibility`, `club_id` (nullable je nach Semantik wie bei Übungen), `uploaded_by_profile_id`.
|
||||||
|
- Copyright: mindestens `copyright_notice` (TEXT); optional `license`, `attribution`, `source_url`.
|
||||||
|
- Speicher: `storage_backend` (Enum/String: z. B. `local`, `s3`, …), `storage_key` (relativer oder bucket-key), optional `storage_url` nur für interne Zwecke – **keine** öffentlichen Secrets in der DB.
|
||||||
|
- Lifecycle: `lifecycle_state` (siehe §5), Timestamps für Übergänge und geplante Purge-Termine.
|
||||||
|
|
||||||
|
**Deduplizierung:** Innerhalb sinnvoller Grenze (z. B. **pro Verein** bei `club`, global nur mit Superadmin-Policy) über `sha256` + `club_id`/`visibility`; Konflikt bei Upload → bestehendes Asset verknüpfen oder expliziter Nutzerdialog (Umsetzungsdetail).
|
||||||
|
|
||||||
|
### 3.2 Verknüpfung (heute `exercise_media`)
|
||||||
|
|
||||||
|
- Erweiterung um **`media_asset_id`** (FK, nullable wenn reines Embed).
|
||||||
|
- Embed-Zeilen: `media_asset_id IS NULL`, `embed_url`/`embed_platform` gesetzt wie heute.
|
||||||
|
- Übungsspezifische Felder: `context` (`ablauf` \| `detail` \| `trainer_hint`), `sort_order`, `title`, `description`, `is_primary`.
|
||||||
|
|
||||||
|
### 3.3 Referenzen & physisches Löschen
|
||||||
|
|
||||||
|
- Vor **physischem** Löschen muss die Referenzanzahl aller aktiven/nicht-purged Links **0** sein (oder Quarantäne-Policy); siehe §5.3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Sichtbarkeit, Lesen und Übungs-Promotion
|
||||||
|
|
||||||
|
### 4.1 Leseregel Datei-Asset
|
||||||
|
|
||||||
|
- Zentrale Entscheidung analog `library_content_visible_to_profile` / TenantContext: **Profil darf Asset lesen** nur wenn Visibility+`club_id`+`created_by` zum Objekt passen (gleiche Philosophie wie Übungen).
|
||||||
|
- **GET Download / Stream:** muss **Asset-Governance** prüfen; wenn der Aufruf **im Kontext einer Übung** erfolgt, zusätzlich (oder als Schnittmenge) **Übung lesbar** – verbindlich **ohne Seitenkanal** (kein Download nur mit Übungs-ID, wenn Asset für Nutzer unsichtbar wäre).
|
||||||
|
|
||||||
|
### 4.2 Promotion Übung → `official` (bzw. global)
|
||||||
|
|
||||||
|
Beim Speichern/Promoten einer Übung auf **`official`** (oder vergleichbare globale Stufe):
|
||||||
|
|
||||||
|
1. **Pflicht-Dialog:** Hinweis, dass **alle zugeordneten Datei-Assets**, die noch **nicht** diese Sichtbarkeit haben, **mit angehoben** werden (oder die Aktion schlägt fehl / erfordert Anpassung).
|
||||||
|
2. **Abbruch:** Nutzer kann abbrechen oder einzelne Assets vor Freigabe anpassen / entkoppeln.
|
||||||
|
3. **Copyright:** Für `official` sind leere oder unzureichende Copyright-Felder **nicht** akzeptabel (genaue Regel in Umsetzung + Validierung).
|
||||||
|
|
||||||
|
Superadmin kann Medien **explizit** global/offiziell machen (Archiv-Pfad), unabhängig von einer einzelnen Übung – konsistent zur Rolle.
|
||||||
|
|
||||||
|
### 4.3 Bearbeitung Medien in der Übung
|
||||||
|
|
||||||
|
Wer die Übung **bearbeiten** darf (bestehende oder künftig erweiterte Regel), darf für diese Übung:
|
||||||
|
|
||||||
|
- Medien **hinzufügen** (Upload neu oder Verknüpfung aus Archiv),
|
||||||
|
- **Reihenfolge** / **Sektion** / **Titel** ändern,
|
||||||
|
- **Verknüpfung** entfernen (Asset bleibt im Archiv, sofern nicht anderweitig gelöscht),
|
||||||
|
- Embeds pflegen.
|
||||||
|
|
||||||
|
Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **global** zu Trash/ Purge zu bewegen, darf trotzdem die **Verknüpfung** in „seiner“ Übung lösen, solange die Übungs-Edit-Policy das erlaubt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Lebenszyklus (Papierkorb) – Norm
|
||||||
|
|
||||||
|
### 5.1 Zustände
|
||||||
|
|
||||||
|
| Zustand | Code (Beispiel) | Neue Zuordnung zu Übungen | Anzeige in Übung (Lesemodus) | Anzeige Bearbeiten |
|
||||||
|
|---------|-----------------|---------------------------|------------------------------|-------------------|
|
||||||
|
| Aktiv | `active` | ja | normal | normal |
|
||||||
|
| Stufe 1 – Papierkorb | `trash_soft` | **nein** | ja + **Warnhinweis** („wird abgeschafft“) | ja + Warnhinweis |
|
||||||
|
| Stufe 2 – Ausblendung | `trash_hidden` | nein | **nein** (Platzhalter/„nicht verfügbar“) | Recovery-Aktion sichtbar |
|
||||||
|
| Stufe 3 – purgiert | `purged` / Zeile entfernt | nein | nein | nur noch historischer Hinweis nach Policy |
|
||||||
|
|
||||||
|
**Default-Retention (automatisch):**
|
||||||
|
|
||||||
|
- Stufe 1 → Stufe 2: **ca. 30 Tage** nach Eintritt in Stufe 1 (konfigurierbar).
|
||||||
|
- Stufe 2 → Stufe 3 **physisches Löschen**: **ca. 90 Tage** (3 Monate) nach Eintritt in Stufe 2 (konfigurierbar).
|
||||||
|
|
||||||
|
**Manuell:** Berechtigte Rollen dürfen Übergänge **vorziehen** (Stufe 1 erzwingen, Stufe 2 erzwingen, Purge erzwingen) gemäß §5.2 – ggf. **Tier-Gates** (§6).
|
||||||
|
|
||||||
|
### 5.2 Wer darf Lifecycle-Transitionen?
|
||||||
|
|
||||||
|
| Aktion | Vereins-Asset (`club`, Owner-Verein) | Privates Asset (`private`, Uploader) | `official` / plattformweit |
|
||||||
|
|--------|--------------------------------------|--------------------------------------|-----------------------------|
|
||||||
|
| Stufe 1 (Papierkorb) | **Vereinsadmin** + **Superadmin** | **Uploader** + **Superadmin** | **Superadmin** |
|
||||||
|
| Stufe 2 vorziehen / erzwingen | Vereinsadmin + Superadmin | Uploader + Superadmin | Superadmin |
|
||||||
|
| Recovery Stufe 2 → 1 | wie Stufe 1-Eintritt, ggf. Tier | wie links | Superadmin |
|
||||||
|
| Physisches Löschen (3) | Vereinsadmin + Superadmin; Systemjob nach Frist | Uploader + Superadmin | Superadmin |
|
||||||
|
|
||||||
|
**Superadmin / Systemadmin** ist immer **Override** (Klarstellung zur „systemadmin“-Formulierung).
|
||||||
|
|
||||||
|
### 5.3 Konsistenz mit bestehenden Übungen
|
||||||
|
|
||||||
|
- In **Stufe 1** bleiben Verknüpfungen funktional für Anzeige bestehen; Nutzer sehen **Warnung**.
|
||||||
|
- In **Stufe 2** wird das Medium in der **öffentlichen Übungsansicht nicht gerendert**; im **Bearbeitungsmodus** gibt es einen **Recovery-Link**, der das Asset zurück auf **Stufe 1** setzt (Policy: nur wer nach §5.2 Stufe 1 setzen darf, oder erweiterte Regel – bei Konflikt ACCESS_LAYER + dieses Dokument anpassen).
|
||||||
|
- **Physisches Löschen:** nur nach Stufe 2-Frist oder manueller Purge-Aktion; Backend entfernt Datei über Speicher-Backend und markiert Asset endgültig.
|
||||||
|
|
||||||
|
### 5.4 Hintergrundjobs
|
||||||
|
|
||||||
|
- Geplanter Job (täglich o. Ä.): Transitionen 1→2 und 2→3 gemäß Timestamps.
|
||||||
|
- Alle Zeiten **konfigurierbar** (Umgebungsvariablen oder DB-Config), Defaults wie §5.1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Tier & Features
|
||||||
|
|
||||||
|
- **Tier** kann erlauben oder verbieten: **manuelles** Vorziehen von Stufe 2 oder Purge, zusätzliche Speicherquoten, externes Backend, etc.
|
||||||
|
- Tier ändert **nicht** die Übungs-Sichtbarkeit an sich; es **limitiert** nur Medien-spezifische Aktionen (Löschstufen, Archiv-Größe, …). Konkrete Feature-Keys in Umsetzung in `features` / `tier_limits` ergänzen und hier im **Changelog** dieses Dokuments verlinken.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Externe Speicherung (Server / S3)
|
||||||
|
|
||||||
|
- Abstraktion **StorageAdapter**: `put`, `get`, `delete`, ggf. `exists`.
|
||||||
|
- Konfiguration über ENV (z. B. Endpoint, Bucket, Credentials) – nie im Frontend.
|
||||||
|
- **NAS / anderer Rechner als App-Host:** In der Praxis `MEDIA_ROOT` in Compose/ENV auf den **Mount-Punkt** des NAS (oder NFS/SMB) setzen – die App läuft z. B. auf dem Raspberry, die Bytes liegen auf dem Speichersystem. Kein »Mediaserver« mit eigener Geschäftslogik nötig.
|
||||||
|
- **Pfadkonvention** auf der Platte z. B. `clubs/{club_id}/…` für Mandantentrennung (Umsetzung schrittweise; neue Uploads können zuerst unter `exercises/{sha256}{ext}` liegen).
|
||||||
|
|
||||||
|
### 7.1 Konfiguration: Bootstrap vs. Superadmin (Laufzeit)
|
||||||
|
|
||||||
|
| Ebene | Inhalt | Wer / Wo |
|
||||||
|
|-------|--------|----------|
|
||||||
|
| **Bootstrap** | Basis-Verzeichnis `MEDIA_ROOT` (Container/Host), ggf. S3-Secrets | Deployment (`.env`, Docker Compose) – Container muss ohne UI starten können |
|
||||||
|
| **Laufzeit (nicht-geheim)** | Zusätzlicher **relativer Unterpfad** unter `MEDIA_ROOT` (`local_relative_root`), später: aktives Backend `local` \| `s3`, öffentlicher Endpoint/Bucket-Name | **Superadmin** über Tabelle `platform_media_storage` + API; keine Secrets für S3 im Klartext in der DB (Keys nur ENV/Vault) |
|
||||||
|
| **Effektives Wurzelverzeichnis** | `Path(MEDIA_ROOT) / local_relative_root` nach Normalisierung (kein `..`, kein absoluter Pfad im relativen Segment) | berechnet im Backend bei jedem Zugriff |
|
||||||
|
|
||||||
|
**Hinweis Beta:** Primär ein Verein, Videos auf separatem physischen System → typischerweise **ein NAS-Mount** als `MEDIA_ROOT`; Superadmin kann bei Bedarf einen **Unterordner** setzen, ohne neues Image zu bauen.
|
||||||
|
|
||||||
|
**Drift:** Jede Änderung an Speicher-Konfiguration oder Asset-Schema → Migration + Eintrag **§10 Changelog** + bei neuen Endpoints **ACCESS_LAYER_ENDPOINT_AUDIT.md**. Änderungen an **Inline-Platzhaltern** (§11) → ebenfalls Changelog + ggf. Frontend-Sanitize-Regeln dokumentieren.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Embeds & Streaming-Plattformen
|
||||||
|
|
||||||
|
- Embeds **bleiben** erste Klasse; bestehende Plattform-Erkennung erweiterbar (`embed_platform`).
|
||||||
|
- Roadmap: weitere Hosts (Player-Komponente, oEmbed, CSP) – **ohne** Änderung am Asset-Lifecycle-Modell.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Pflichten zur Drift-Vermeidung
|
||||||
|
|
||||||
|
| Änderung an … | Pflegepflicht |
|
||||||
|
|---------------|---------------|
|
||||||
|
| DB-Schema Medien | Neue Migration + **Abschnitt/Changelog in diesem Dokument** (Datum, Kurzbeschreibung) |
|
||||||
|
| Sichtbarkeit / Enums | Zuerst `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`, dann dieses Dokument synchron halten |
|
||||||
|
| Neue Endpoints Medien/Archiv | `ACCESS_LAYER_ENDPOINT_AUDIT.md` + `get_tenant_context`/Governance |
|
||||||
|
| **Inline-Referenzen** in Übungstexten (§11) | Renderer/Sanitizer-Regeln + dieses Dokument §11; kein zweites Rechtemodell |
|
||||||
|
| Implementierungs-Meilenstein | `backend/version.py` (`MODULE_VERSIONS` / Schema-Kommentar) und bei größerem Release `PROJECT_STATUS.md` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Changelog
|
||||||
|
|
||||||
|
| Datum | Änderung |
|
||||||
|
|-------|----------|
|
||||||
|
| 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 (Umsetzung & Leitplanken)
|
||||||
|
|
||||||
|
**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 (**festgelegt**)
|
||||||
|
|
||||||
|
- **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
|
||||||
|
|
||||||
|
- **Ein zentraler Pfad** „Übungstext für Anzeige aufbereiten“: HTML sanitizen (Allowlist), erlaubte Platzhalter auflösen, **ID gehört zur aktuellen Übung** und Medium ist für den Nutzer **sichtbar** – sonst Platzhalter mit neutralem Hinweis oder ausblenden.
|
||||||
|
- **XSS/CSP:** keine rohen `iframe`/Skripte aus Nutzer-HTML ohne Kontrolle; eingebettete Player nur über kontrollierte Komponenten.
|
||||||
|
|
||||||
|
### 11.4 Koexistenz mit Sektions-Medien
|
||||||
|
|
||||||
|
- **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. ~~**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)
|
||||||
|
|
||||||
|
- Neue Features **nicht** so bauen, dass HTML aus Übungstexten an **vielen** Stellen „roh“ gerendert wird – **ein** wiederverwendbarer Renderer vorbereiten (schrittweise einziehen).
|
||||||
|
- Medien immer über **stabile IDs** anbinden, nicht nur über Datei-URLs im Text.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Referenzen
|
||||||
|
|
||||||
|
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
|
||||||
|
- `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` (Limits, MIME, Embed-Typen im aktuellen Backend)
|
||||||
|
- `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
|
||||||
|
- `backend/routers/exercises.py` – Ist-Zustand `exercise_media` bis Refactor
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
# Media Upload & Embed Specification
|
# Media Upload & Embed Specification
|
||||||
|
|
||||||
**Version:** 1.1
|
**Version:** 1.2
|
||||||
**Datum:** 2026-04-27
|
**Datum:** 2026-05-07
|
||||||
**Status:** DRAFT - Awaiting Review
|
**Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
|
||||||
**Autor:** Claude Code
|
|
||||||
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
|
> **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).
|
||||||
|
> Dieses Dokument bleibt maßgeblich für **konkrete Upload-Limits, MIME-Liste und Embed-Hosting** des aktuellen Stands bis zum Refactor.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
# Multi-Tenancy, Vereins-Membership und Rollenmodell – Zielarchitektur & Umsetzungsplan
|
||||||
|
|
||||||
|
**Status:** verbindliche Zielrichtung (Architekturpapier)
|
||||||
|
**Stand:** 2026-05-06
|
||||||
|
**Bezug:** `functional/shinkan_anforderungsdokument_entwurf.md` §5, §17–18 · `functional/DOMAIN_MODEL.md` (Sichtbarkeit §5.5) · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR-004–008)
|
||||||
|
|
||||||
|
**Operative Reihenfolge & einheitliche Zugriffsschicht:** [`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`](./ACCESS_LAYER_AND_GOVERNANCE_PLAN.md) – dort sind Stufen A–F, Drift-Prävention und die Zurückstellung von Vereinsabo/Limits festgehalten; dieses Dokument bleibt das übergeordnete **Zielbild**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zweck
|
||||||
|
|
||||||
|
Dieses Dokument fasst den **Soll-Zustand** für Mandantenfähigkeit (Verein = Mandant), **rollenbasierte Zugriffskontrolle auf Vereinsebene** und ein **Membership-/Limitsystem** zusammen – und definiert einen **phasenweisen Umsetzungsplan**, der mit dem bestehenden Governance-Kern (`visibility`, `club_id`, `created_by`) konsistent bleibt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Abgleich mit vorhandener Dokumentation
|
||||||
|
|
||||||
|
| Quelle | Inhalt relevant für Tenancy/Rollen | Konsistenz mit Zielbild |
|
||||||
|
|--------|-----------------------------------|-------------------------|
|
||||||
|
| `shinkan_anforderungsdokument_entwurf.md` §5.4 | Rollen: Superadmin, Vereinsadmin, Trainer, Co-Trainer, Redakteur | Deckt sich; „Superadmin“ entspricht fachlich **Systemadmin** |
|
||||||
|
| §17.1 | Erweiterung: Systemadmin, Spartenadmin | Entspricht den gewünschten **Spartenverantwortlichen** |
|
||||||
|
| §5.5 / §17 | Sichtbarkeit: privat, Verein, Sparte, global, offiziell | DOMAIN_MODEL listet ähnliche Stufen; Bibliothek **`private` \| `club` \| `official`** technisch über Zugriffsschicht durchgesetzt; **Sparte/community** folgt |
|
||||||
|
| §18.5 | MVP: Datenmodell mandantenfähig, Rechte zunächst einfach | Bestätigt schrittweise Verschärfung |
|
||||||
|
| `DOMAIN_MODEL.md` §5.5 | Freigabeebenen inkl. Sparte | Zielbild; DB/API nutzen derzeit überwiegend `private` \| `club` \| `official` |
|
||||||
|
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | CURR-004–008: Governance-Kern, spätere Policy | Datenfelder vorbereitet; **Policy/Erzwingung** folgt |
|
||||||
|
| `working/SHINKAN_PROJECT_SETUP.md` §6 | „Multi-Tenant-Administration“ ausgeschlossen (MVP-Liste) | Historisch; **technische Mandanten** sind dennoch Ziel – UI-Komplexität kontrolliert einführen |
|
||||||
|
|
||||||
|
**Fazit:** Die fachlichen Rollen und Sichtbarkeitsebenen sind **in den funktionalen Docs skizziert**. Für die **Kernteile Bibliothek und Vereinskontext** ist eine **technische Zugriffsschicht** (`TenantContext`, `club_members`, einheitliche Sichtbarkeits-SQL/-Prüfungen) umgesetzt — Details und Restarbeit (**Sparte**, Konsolidierung der Hilfen, Planungs-/Admin-Flows) siehe §3 und `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Ist-Stand im Code (Gap-Analyse)
|
||||||
|
|
||||||
|
> **Hinweis:** Die Unterabschnitte **3.1–3.6** enthalten weiterhin **historische Problemstellungen** (Ausgangsbild). Ergänzend beschreibt **3.0** den **aktualisierten Umsetzungsstand** nach Mitgliedschafts-, Tenant- und Bibliotheksarbeit. Verbindliche **offene Arbeit und Reihenfolge:** [`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`](./ACCESS_LAYER_AND_GOVERNANCE_PLAN.md).
|
||||||
|
|
||||||
|
### 3.0 Aktualisierung des Umsetzungsstands (kurz)
|
||||||
|
|
||||||
|
- **Mitgliedschaft:** Tabellen `club_members` und `club_member_roles`; aktiver Verein über Profilfeld und Header `X-Active-Club-Id`; Auflösung in **`TenantContext`** (`tenant_context.py`).
|
||||||
|
- **Bibliothek** (Übungen, Trainingsplan-Vorlagen, Rahmenprogramme u. a.): gemeinsame Leselogik **`library_content_visibility_sql`** / **`library_content_visible_to_profile`** — Vereinsinhalte **`club`** nur bei passendem **`club_id`** und **aktiver Mitgliedschaft** im Objekt-Verein (normale Nutzer ohne gültigen Vereinskontext: kein „beliebiges club“).
|
||||||
|
- **`GET /api/clubs`:** Nicht-Admins sehen nur Vereine mit Mitgliedschaft; **`POST /api/clubs`:** nur **Plattform-Admin**, mit Pflicht **`primary_admin_profile_id`**.
|
||||||
|
- **Organisation** (Sparten/Gruppen): Schreibzugriff über **`can_manage_club_org`** / **`can_plan_in_club`** auf Basis von **`club_member_roles`** (nicht mehr nur globales `admin`).
|
||||||
|
- **Profil-API:** eingeschränktes **`GET /profiles/{id}`**, **`DELETE`**, **`POST /profiles`** (Plattform-Admin / Selbstzugriff) — Details `backend/routers/profiles.py`.
|
||||||
|
- **Tests:** pytest inkl. optionaler Mandanten-Integration (`ACCESS_LAYER_INTEGRATION`); CI-Anbindung siehe `.gitea/workflows/test.yml` (Ausführung im Backend-Container wie Schwesterprojekt).
|
||||||
|
|
||||||
|
### 3.1 Identität und Rollen
|
||||||
|
|
||||||
|
- `profiles.role` ist eine **globale** Kennzeichnung (`admin`, `superadmin`, `trainer`, `user`, …).
|
||||||
|
- *(Historisch)* Fehlende Abbildung von Vereinsrollen **ohne** eigene Tabellen.
|
||||||
|
- **Ist:** Zusätzlich **`club_member_roles`** pro Verein (z. B. `club_admin`, `trainer`, …); Sessions liefern weiter **`profile_id`** + globale **`role`** (`auth.py` → `get_session`), Vereinsrechte werden aus Mitgliedschaft abgeleitet.
|
||||||
|
|
||||||
|
**Konsequenz:** Globale Rolle und Vereinsrollen **koexistieren**; Produkt und Code sollten langfristig klar trennen, was nur global vs. nur über Mitgliedschaft gilt (vgl. Zielarchitektur §4).
|
||||||
|
|
||||||
|
### 3.2 Organisation & APIs
|
||||||
|
|
||||||
|
- *(Historisch)* Zu offene Vereinsliste und Club-Anlage für jeden Trainer/User.
|
||||||
|
- **Ist:** siehe **3.0** — gefilterte Liste, eingeschränktes Anlegen, kontextbezogene Organisationsrechte.
|
||||||
|
|
||||||
|
**Konsequenz:** Offene Punkte verlagern sich in **feine Produktregeln** und **Sparten-/Community-Stufen** (ACCESS_LAYER Stufe D bzw. spätere Epics).
|
||||||
|
|
||||||
|
### 3.3 Trainingsplanung
|
||||||
|
|
||||||
|
- Zugriff auf Einheiten weiterhin stark **gruppenbezogen** (`training_groups`, optional **`lead_trainer_profile_id`** auf Einheiten).
|
||||||
|
- Mitgliedschaft/`TenantContext` unterstützen andere Endpoints; **`GET /training-units`** hat **keinen** impliziten Filter nur auf **`effective_club_id`** (Multi-Verein-Kalender; bei Bedarf Query **`club_id`**).
|
||||||
|
|
||||||
|
**Konsequenz:** Vereinsweite oder „Administrations“-Planungsaufgaben können weiter ausgebaut werden (eigenes Produkt-Thema; nicht identisch mit Bibliotheks-Governance).
|
||||||
|
|
||||||
|
### 3.4 Governance / Sichtbarkeit (Bibliothek)
|
||||||
|
|
||||||
|
- *(Historisch)* Risiko: **`club`**-Objekte ohne Bindung an **`club_id`** / Mitgliedschaft → mögliche Cross-Tenant-Sicht.
|
||||||
|
- **Ist:** Listen und Detail für die genannten Bibliotheksmodule nutzen die **einheitliche** Logik in **`club_tenancy`** / **`tenant_context`** (siehe **3.0**).
|
||||||
|
|
||||||
|
**Konsequenz:** Die historische „Leak“-Diagnose für **Übungen und Rahmenprogramme** in dieser Form ist **überholt**. Verbleibend: **Konsolidierung auf wenige Hilfsfunktionen** (ACCESS_LAYER Stufe C), **Sparte** als eigene Stufe, ggf. **community**.
|
||||||
|
|
||||||
|
### 3.5 Frontend
|
||||||
|
|
||||||
|
- `GET /api/profiles/me` liefert u. a. **`clubs[]`**, **`active_club_id`**; Client setzt **`X-Active-Club-Id`**. Geschützte Backend-Routen nutzen **`Depends(get_tenant_context)`** wo im Audit festgehalten.
|
||||||
|
|
||||||
|
### 3.6 Membership (kommerziell/limits)
|
||||||
|
|
||||||
|
- Mitai-artige Tabellen (`tiers`, `subscriptions`, `tier_limits`, …) sind **nutzerbezogen**, nicht **vereinsbezogen**.
|
||||||
|
- Kein konzipiertes **`club_subscription` / `club_plan`** im Schema — bewusst nach ACCESS_LAYER-Plan zurückgestellt.
|
||||||
|
|
||||||
|
**Letzte Überarbeitung dieses Abschnitts (3.x):** 2026-05-06.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Zielarchitektur
|
||||||
|
|
||||||
|
### 4.1 Begriffe
|
||||||
|
|
||||||
|
| Begriff | Definition |
|
||||||
|
|---------|------------|
|
||||||
|
| **Mandant** | Immer ein **Verein** (`clubs.id`). |
|
||||||
|
| **Systemadmin** | Global (`profiles.role` oder dediziertes Flag); darf Plattform-weite Objekte und **Vereinslifecycle** (Anlegen, Zuweisen Hauptverwalter). |
|
||||||
|
| **Vereinskontext** | Pro Session gewählter aktiver Verein (`active_club_id`), wenn der User Mitglied ist. |
|
||||||
|
| **Vereinsmitgliedschaft** | Zeile in einer Junction: User ↔ Verein ↔ **eine oder mehrere Rollen**. |
|
||||||
|
| **Effektive Berechtigung** | Funktion aus: globale Rolle, Mitgliedschaft im aktiven Verein, optional Sparte/Gruppe, Sichtbarkeit des Objekts. |
|
||||||
|
|
||||||
|
### 4.2 Rollenmodell (Schichten)
|
||||||
|
|
||||||
|
**Schicht A – Plattform (global, kleine Menge)**
|
||||||
|
|
||||||
|
- `system_admin` / `superadmin` (bestehende Semantik konsolidieren und benennen).
|
||||||
|
|
||||||
|
**Schicht B – Verein (pro Mitgliedschaft, mehrere Rollen möglich)**
|
||||||
|
|
||||||
|
- `club_admin` – Hauptverwalter:in (ein Verein **genau eine** „primäre“ Admin-Zuweisung empfohlen, siehe 4.4).
|
||||||
|
- `division_lead` – Spartenverantwortliche:r (Scope: `division_id` optional an Mitgliedschaft gebunden).
|
||||||
|
- `trainer` – Trainer/Übungsleitung (Abgrenzung zu Co-Trainer siehe Gruppe).
|
||||||
|
- `content_editor` – Redakteur:in / Inhaltsverantwortliche:r (fachlich wie Anforderungsdoc).
|
||||||
|
|
||||||
|
**Schicht C – Abgeleitet aus Trainingsgruppe (bereits teilweise vorhanden)**
|
||||||
|
|
||||||
|
- Haupttrainer / Co-Trainer über `training_groups.trainer_id` und `co_trainer_ids` (und ggf. `lead_trainer_profile_id` auf Einheit).
|
||||||
|
|
||||||
|
**Mapping Alt → Neu:** Bestehendes `profiles.role` kann Übergangsweise als „Default-Rolle für Pilotverein“ dienen, soll aber mittelfristig **nicht** die einzige Quelle für Vereinsrechte sein.
|
||||||
|
|
||||||
|
### 4.3 Mitgliedschaft und aktiver Verein
|
||||||
|
|
||||||
|
- Neue Kernstruktur (konzeptionell):
|
||||||
|
**`club_members`** (`profile_id`, `club_id`, `status`, `created_at`, …)
|
||||||
|
**`club_member_roles`** (`club_member_id`, `role_code`, optional `division_id` für spartenbezogene Rollen).
|
||||||
|
|
||||||
|
- **Aktiver Verein:**
|
||||||
|
- Persistenz: Nutzereinstellung (`profiles.default_club_id` oder eigene Tabelle `profile_preferences`).
|
||||||
|
- Pro Request: Header **`X-Active-Club-Id`** oder Query (einheitlich dokumentieren); Server validiert Mitgliedschaft.
|
||||||
|
|
||||||
|
- **Tenant-Switch UI:** Bei Mitgliedschaft in >1 Verein Auswahl im Frontend; alle Listen/Aktionen verwenden aktiven Kontext.
|
||||||
|
|
||||||
|
### 4.4 Vereins-Lebenszyklus
|
||||||
|
|
||||||
|
- Neuer Verein: **nur Systemadmin**; Pflichtfelder: Name, initialer `club_admin` (bestehendes Profil zuweisen oder Einladungsflow später).
|
||||||
|
- Vereinsadmin verwaltet in „Mein Verein“: Sparten, Gruppen, Trainerzuordnungen, Einladungen (später), interne Sichtbarkeit – **ohne** andere Vereine zu sehen.
|
||||||
|
|
||||||
|
### 4.5 Daten- und Funktionssicht
|
||||||
|
|
||||||
|
| Datenklasse | Leseregel (Ziel) |
|
||||||
|
|-------------|------------------|
|
||||||
|
| Global offiziell | Alle authentifizierten (ggf. später thematisch eingeschränkt). |
|
||||||
|
| Verein (`visibility=club`, `club_id` gesetzt) | Nur Profile mit Mitgliedschaft in **diesem** `club_id`; optional zusätzlich Sparte, wenn `division_id` am Objekt gepflegt wird. |
|
||||||
|
| Privat | Nur `created_by` (und explizite Shares später). |
|
||||||
|
| Geplante Einheiten | Wie heute über Gruppe + Trainer/Co; zusätzlich Vereinskontext zur Navigation/Audit. |
|
||||||
|
|
||||||
|
**Einheitlicher Governance-Kern** bleibt wie in CURR-005; Ergänzung: **`division_id`** auf Bibliotheksobjekten, wenn „Sparte“ technisch durchgesetzt werden soll (DOMAIN_MODEL / §17).
|
||||||
|
|
||||||
|
### 4.6 Membership-System (Vereinsabo / Limits) – Konzept
|
||||||
|
|
||||||
|
Ziel: **vereinszentrierte** Vertrags- und Limitlogik, analog zur bestehenden Tier-Infrastuktur, aber an **`club_id`** gebunden.
|
||||||
|
|
||||||
|
**Empfohlene Bausteine:**
|
||||||
|
|
||||||
|
1. **`club_plans`** – Produktdefinition (Name, Features, implizite Limits).
|
||||||
|
2. **`club_subscriptions`** – (`club_id`, `plan_id`, Status, Laufzeit).
|
||||||
|
3. **`club_usage_counters`** oder Ableitung aus DB – z. B. aktive Nutzer, aktive Trainingsgruppen (periodisch oder on-write).
|
||||||
|
4. **Enforcement-Schicht** – zentrale Funktion `assert_club_limit(club_id, metric)` vor `/groups`-POST, Einladungen, etc.
|
||||||
|
|
||||||
|
**Offene Produktentscheidungen** (vor Implementierung festlegen):
|
||||||
|
|
||||||
|
- Zählen „Nutzer“ alle Mitglieder oder nur aktive Trainer?
|
||||||
|
- Soft-Limits vs. Hard-Stops; Übergang für Pilotverein.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Umsetzungsplan (Phasen)
|
||||||
|
|
||||||
|
### Phase 0 – Foundations (kurz, risikoarm)
|
||||||
|
|
||||||
|
- Begriffe und Enums in einem Ort dokumentieren (dieses Dokument + Eintrag in `DATABASE_SCHEMA.md` nach Migration).
|
||||||
|
- Audit-Liste aller Router mit `club_id` / `visibility` / Listen-Endpunkten.
|
||||||
|
|
||||||
|
### Phase 1 – Datenmodell Mitgliedschaft & Hauptverwalter
|
||||||
|
|
||||||
|
- Migration: `club_members`, `club_member_roles`; optional `clubs.primary_admin_profile_id` (oder Primär-Flag auf Mitgliedschaft).
|
||||||
|
- Backfill: bestehende Trainer aus `training_groups` → minimale Mitgliedschaft `trainer` im jeweiligen Verein (Skript/Migration mit dokumentierter Annahme CURR-008).
|
||||||
|
- **Breaking/API:** keine – nur erweiterte Datenbasis.
|
||||||
|
|
||||||
|
### Phase 2 – Aktiver Vereinskontext & API-Kontrakte
|
||||||
|
|
||||||
|
- Backend: Validierung `X-Active-Club-Id` gegen Mitgliedschaft; Hilfsfunktion `get_effective_club_context(session, header)`.
|
||||||
|
- `GET /api/clubs` für Nicht-Systemadmins: **nur Vereine mit Mitgliedschaft**.
|
||||||
|
- `POST /api/clubs`: nur Systemadmin; Vergabe `club_admin`-Mitgliedschaft.
|
||||||
|
- Frontend: Club-Switcher + Persistenz.
|
||||||
|
|
||||||
|
### Phase 3 – Effektive Berechtigungen (RBAC)
|
||||||
|
|
||||||
|
- **Mitgliederverwaltung per API (ohne UI):** `GET/POST /api/clubs/{club_id}/members`, `GET/PUT/DELETE /api/clubs/{club_id}/members/{profile_id}` — nur Plattform-Admin oder `club_admin` im Zielverein (Stand Code **0.8.16**).
|
||||||
|
- Zentrale Modulfunktion z. B. `authorization/club_permissions.py`:
|
||||||
|
`can(club_id, profile_id, permission, division_id=None)` — optional später; aktuell `club_tenancy.can_manage_club_org` / `has_club_role`.
|
||||||
|
- Router schrittweise umbinden: Sparten/Gruppen CRUD nach Rolle `club_admin` im Kontext; Systemadmin unverändert Vollzugriff.
|
||||||
|
|
||||||
|
### Phase 4 – Sichtbarkeit & Leaks schließen
|
||||||
|
|
||||||
|
- **Übungen:** `club`-Sichtbarkeit nur bei Übereinstimmung `exercise.club_id` mit Mitgliedschaft (und später `division`).
|
||||||
|
- **Trainingsplan-Vorlagen** (`training_plan_templates`) und **Rahmenprogramme** (`training_framework_programs`): gleiches Muster für Listen/GET (Stand **0.8.17**); Schreiben weiterhin nur Ersteller oder Plattform-Admin.
|
||||||
|
- Gleiches Muster für Progressionsgraphen, ggf. Medien (offen).
|
||||||
|
- Tests: zwei Vereine, zwei Nutzer, keine Kreuzzugriffe.
|
||||||
|
|
||||||
|
### Phase 5 – Mitgliedschaft / Limits
|
||||||
|
|
||||||
|
- Tabellen `club_plans`, `club_subscriptions`; Integration mit Enforcement vor relevanten Writes.
|
||||||
|
- UI „Mein Verein“: Kennzahlenteaser oder Hinweise bei Limit (minimal).
|
||||||
|
|
||||||
|
### Phase 6 – Verfeinerung
|
||||||
|
|
||||||
|
- Einladungsflow (E-Mail), Mehrfachrollen-UI, Audit-Log für Admin-Aktionen.
|
||||||
|
- Optionale thematische Sperren (Karate vs. Gewaltschutz) als eigene Policy-Schicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Abhängigkeiten und Risiken
|
||||||
|
|
||||||
|
- **Übergang:** Pilot mit einem Verein nutzt weiterhin einfache Defaults; Multi-Verein erfordert Pflicht **aktiver Kontext**.
|
||||||
|
- **Performance:** Mitgliedschaft und Rolle sollten **einmal pro Request** geladen und gecacht werden (Request-Scope).
|
||||||
|
- **Konsistenz mit Mitai:** Nutzer-Tiers können parallel bleiben; **vereinsbezogene** Limits sind die neue Quelle für Shinkan-spezifische Kaufmotive.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Nächste konkrete Artefakte
|
||||||
|
|
||||||
|
1. TenantContext-Spezifikation & Endpoint-Audit (siehe `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` §6).
|
||||||
|
2. Aktualisierung `DATABASE_SCHEMA.md` bei neuen Governance-/Scope-Feldern.
|
||||||
|
3. Sicherheits-Review der `list_*`-Endpunkte mit `club`-Visibility (fortlaufend bis Governance vereinheitlicht).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Verwandtes Dokument
|
||||||
|
|
||||||
|
- **`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`** – verbindliche Umsetzungsstufen A–F, einheitliche Zugriffsschicht, Scope-Erweiterung (`division`, später Community), Capability-Vorbereitung ohne Custom-Rollen-UI; Vereinsabo explizit zurückgestellt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Letzte Aktualisierung:** 2026-05-05
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
|
||||||
|
|
||||||
|
**Status:** Entwurf · **Stand:** 2026-05-14
|
||||||
|
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand Analyse 2026-05-14): eine `training_unit` mit **`training_unit_sections`** und **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung **`TrainingUnitRunPage`** (sequentiell über Sektionen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ist-Stand (relevant)
|
||||||
|
|
||||||
|
| Bereich | Aktuell |
|
||||||
|
|---------|---------|
|
||||||
|
| Planstruktur | **Eine** lineare Liste `training_unit_sections` je `training_unit_id`; Items in `training_unit_section_items`. |
|
||||||
|
| Rahmenprogramm | `training_framework_slots` verweisen auf **Blueprint**-`training_units` — Slots = **Serien-Spalten**, nicht simultane Breakouts in **einer** Halle. |
|
||||||
|
| Kombinationsübung | Ein **Item** kann Kombi sein; `planning_method_profile` = Snapshot; Coaching-UI teilweise (`CombinationPlanBracket` in Run/Peek). |
|
||||||
|
| Trainer-Zuweisung | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am **`training_units`**-Kopf; **keine** Zuordnung zu „welcher parallelen Spur“. |
|
||||||
|
| Run-Modus | `TrainingUnitRunPage`: sortierte Sektionen/Items, Checkliste, Fortschritt in `sessionStorage` pro Einheit. |
|
||||||
|
|
||||||
|
**Konsequenz:** Parallele Streams erfordern ein **erweitertes konzeptionelles „Gefäß“** unterhalb der Einheit (Phasen und/oder Streams) und eine **Verknüpfung** bestehender Sektionen mit diesem Gefäß — oder eine **Migration** zu einem neuen Pflicht-Container (siehe §3).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Zielarchitektur (logisch)
|
||||||
|
|
||||||
|
```
|
||||||
|
training_unit (Kalender-Einheit)
|
||||||
|
├── phase (order, kind: whole_group | parallel, optional Metadaten)
|
||||||
|
│ ├── [whole_group] → sections[] → items[] (wie heute)
|
||||||
|
│ └── [parallel] → stream (order, label, optional trainer_ids[])
|
||||||
|
│ └── sections[] → items[]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Abwärtskompatibilität:** Einheiten **ohne** explizite Phasen/Streams verhalten sich wie heute: **implizit** eine einzige „Gemeinschaftsphase“ mit den vorhandenen Sektionen (Migration: alle bestehenden Sektionen an diese Default-Hülle hängen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Datenmodell — Optionen
|
||||||
|
|
||||||
|
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
|
||||||
|
|
||||||
|
Neue Tabellen (Namen bei Implementierung final festlegen):
|
||||||
|
|
||||||
|
| Tabelle | Zweck |
|
||||||
|
|---------|--------|
|
||||||
|
| `training_unit_phases` | `training_unit_id`, `order_index`, `phase_kind` (`whole_group` \| `parallel`), optional `title`, `guidance_notes`, optional `planned_duration_min` |
|
||||||
|
| `training_unit_parallel_streams` | `phase_id` (FK, nur wenn parent parallel), `order_index`, `title`/`label`, optional `notes`, optional `assigned_trainer_profile_ids` JSONB (oder 1:n-Hilfstabelle) |
|
||||||
|
|
||||||
|
**Anpassung `training_unit_sections`:** Zusätzliche FK-Spalte(n), z. B.:
|
||||||
|
|
||||||
|
- `phase_id` **NULL** und `parallel_stream_id` **NULL** → **Legacy / Default-Einheitsphase** (Migration setzt Default-Phase); oder
|
||||||
|
- genau einer von `phase_id` (whole group) oder `parallel_stream_id` gesetzt.
|
||||||
|
|
||||||
|
**Constraints:** CHECK: nicht beide gesetzt; bei `phase_kind = parallel` Sektionen nur unter `parallel_stream_id`; bei `whole_group` nur unter `phase_id`.
|
||||||
|
|
||||||
|
**Vorteil:** Klare Semantik, Reporting, API-Shape konsistent.
|
||||||
|
|
||||||
|
### 3.2 Minimalvariante (nicht ideal fachlich)
|
||||||
|
|
||||||
|
Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; Phasen implizit durch „Marker“-Sektionen oder Konvention. **Nicht empfohlen**, erschwert UI und Erklärbarkeit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. API
|
||||||
|
|
||||||
|
- **`GET /api/training-units/:id`** (und Listen-Payloads wo vollständiger Plan nötig): verschachtelte Struktur **Phasen → Streams → sections → items** oder flache `sections` mit ausgefüllten `phase_id` / `parallel_stream_id` (Frontend kann normalisieren).
|
||||||
|
- **`PUT/PATCH`:** Atomares Ersetzen der Phasen/Streams/Sektionen analog zu bestehendem `_replace_unit_sections`-Muster; **Validierung** der CHECK-Regeln serverseitig.
|
||||||
|
- **Blueprint / Rahmen:** Blueprint-`training_units` dürfen dieselbe Struktur tragen; `GET` Kalenderliste blendet Blueprints weiter aus (`framework_slot_id IS NOT NULL`).
|
||||||
|
|
||||||
|
**Governance / Mandant:** Unverändert über Einheit → `group_id`; keine neuen Mandanten-Entitäten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Frontend
|
||||||
|
|
||||||
|
### 5.1 Planung (`TrainingPlanningPage`)
|
||||||
|
|
||||||
|
- Darstellung als **vertikale Phasen**: Gemeinschaftsblöcke + Parallelphase mit **N Spalten** (Streams).
|
||||||
|
- **Wiederverwendung:** `TrainingUnitSectionsEditor` **pro Stream** und pro Gemeinschaftsphase — analog zur Wiederverwendung **pro Rahmen-Slot** in `TrainingFrameworkProgramEditPage`.
|
||||||
|
- **Co-Trainer:** UI pro Stream (`assigned_trainer_profile_ids`); Regel zur **Kopfliste** `assistant_trainer_profile_ids` festlegen (z. B. Union aller Stream-Zuweisungen für „Wer ist heute dabei“ + Rückwärtskompatibilität wenn Stream-Felder leer).
|
||||||
|
|
||||||
|
### 5.2 Durchführung (`TrainingUnitRunPage`)
|
||||||
|
|
||||||
|
- Gemeinschaftsphasen: heutiges **lineares** Verhalten.
|
||||||
|
- Parallelphase: **Tabs, Akkordeon oder Swipe** zwischen Streams; Fortschritt **pro Stream** (Storage-Key z. B. `${unitId}:${streamId}`).
|
||||||
|
- Kombi-Items: unverändert `CombinationPlanBracket` / `effectiveComboMethodProfile`.
|
||||||
|
- Optional später: Filter „nur meine Spur“ anhand Session-Profil vs. Stream-Zuweisung.
|
||||||
|
|
||||||
|
### 5.3 Vorlagen (`training_plan_templates`)
|
||||||
|
|
||||||
|
- Erweiterung um **dieselbe** Phasen/Streams-Semantik (Kindtabellen oder serialisiertes JSON — Abgleich mit Kopierlogik aus Vorlage in Einheit).
|
||||||
|
- **Kein** Live-Spiegel: weiterhin Materialisierung beim Anwenden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Bezug Kombinationsübungen
|
||||||
|
|
||||||
|
- **Variante A** (Rotation innerhalb einer Teilstrecke): ein oder mehrere **Items** vom Typ Kombi im jeweiligen Stream; Archetyp und Parameter wie in `TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`.
|
||||||
|
- **Variante B** (synchron Hallenweit): erweiterte **Phasen-** oder **Stream-übergreifende** Metadaten — **nicht** in MVP-Zwang; eigenes Teilpaket nach fachlicher Freigabe (`PARALLEL_TRAINING_STREAMS_CONCEPT.md` §5.2).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Migration und Risiken
|
||||||
|
|
||||||
|
1. **Datenmigration:** Alle existierenden `training_unit_sections` einer Einheit einer **Default-Phase** `whole_group` zuordnen.
|
||||||
|
2. **API-Versionierung:** Clients, die nur flache `sections` erwarten, müssen angepasst werden (oder Server liefert **beides** kurzzeitig — nur wenn nötig).
|
||||||
|
3. **Performance:** Tiefe Kopien (Rahmen-Slot, Duplikat Einheit) müssen rekursiv Phasen/Streams mitsamt Sektionen/Items kopieren.
|
||||||
|
4. **Tests:** pytest für PUT/GET mit gemischten Phasen; ggf. Playwright-Smoke für Planung/Run.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Implementierungsphasen (Vorschlag)
|
||||||
|
|
||||||
|
| Phase | Inhalt |
|
||||||
|
|-------|--------|
|
||||||
|
| **P1** | Schema Phasen + Streams; Migration; GET/PATCH Einheit verschachtelt; Planungs-UI; Run-UI mit Stream-Tabs |
|
||||||
|
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert |
|
||||||
|
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Verwandte Dokumente
|
||||||
|
|
||||||
|
| Dokument | Bezug |
|
||||||
|
|----------|--------|
|
||||||
|
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md` | Fachziele, Begriffe, Entscheidungsfragen |
|
||||||
|
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
|
||||||
|
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
|
||||||
|
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
|
||||||
|
| `frontend/src/pages/TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Ist-UI |
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
|
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
|
||||||
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
|
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
|
||||||
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
|
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
|
||||||
|
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | **Parallele Streams / Breakout innerhalb einer Einheit** — orthogonale Domäne zu **Rahmen‑Slots** (Serien‑Sessions). |
|
||||||
|
|
||||||
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
|
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# Trainingsmodule und Kombinationsübungen — Spezifikation (Entwurf)
|
||||||
|
|
||||||
|
**Status:** Entwurf zur fachlichen und technischen Abstimmung · **Stand:** 2026-05-12 (Code **0.8.110**, siehe `backend/version.py`)
|
||||||
|
**Zweck:** Rahmen für Umsetzung, Integration in Planung/Rahmenprogramm und Durchführung im assistierten Training (Coaching-Modus). Dieses Dokument ist **nicht** implementierungsbindend, bis die markierten **offenen Entscheidungen** geschlossen und der Status angehoben wurde.
|
||||||
|
|
||||||
|
**Abgleich mit Code (Drift vermeiden):**
|
||||||
|
|
||||||
|
- **Kanonische Archetyp-IDs:** fest in `backend/routers/exercises.py` (`COMBINATION_ARCHETYPE_IDS`); fachliche Tabelle und UI-Labels in `frontend/src/constants/combinationArchetypes.js` — die **fachliche Master-Zuordnung** Name↔ID steht in `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` § 10.2.1. **Administrierbare Archetypen** (DB/UI) gibt es **nicht**; Erweiterungen nur per Code-Release — Fachspez **§ 10.6**.
|
||||||
|
- **Planungs-Override:** `planning_method_profile` (Migration **057**) speichert einen **Snapshot**; **Merge** mit Katalogprofil erfolgt im Frontend (`frontend/src/utils/comboPlanningMethodProfile.js` — `effectiveComboMethodProfile`), nicht als serverseitiger Join. Payload-Sanitisierung vor PUT; Backend speichert JSONB zuverlässig (`Json()`).
|
||||||
|
- **Coaching:** Stufe **A** — Slots, Kandidaten, Archetyp-Hilfstext, **Label** für globale Eckdaten (`describeGlobalComboProfile` in `combinationMethodProfileUi.js`), visuelle Klammer (`CombinationPlanBracket`) in Peek/Run; Stufen **B/C** (archetypgesteuerte Zeitleiste/Takt) **offen** — Fachspez § 10.4, **§ 10.6**, **Anhang A**.
|
||||||
|
- **Umsetzungsplan:** `working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase 2/4 „teilweise“; Pakete **4e–4g** für Admin, Vorbelegung, Validierung).
|
||||||
|
|
||||||
|
**Verwandte Dokumente:**
|
||||||
|
|
||||||
|
| Dokument | Bezug |
|
||||||
|
|----------|--------|
|
||||||
|
| `TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Bibliothek, Slot-Blueprint, Kopiersemantik (`from-framework-slot`) |
|
||||||
|
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | Parallele Teilstrecken **innerhalb einer Einheit**; Kombi-Übungen weiter nutzbar **pro Stream** für Stationsrotation |
|
||||||
|
| `DATABASE_SCHEMA.md` | Aktueller Stand `training_units`, Sektionen, Items |
|
||||||
|
| `functional/DOMAIN_MODEL.md` | Domänenbegriffe (bei Bedarf zu erweitern) |
|
||||||
|
| `EXERCISES_*` (Katalog) | Einzelübungen, Varianten |
|
||||||
|
| `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` | Sichtbarkeit, Mandant, Rollen bei neuen Bibliotheks-Entitäten |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zielbild und Abgrenzung
|
||||||
|
|
||||||
|
### 1.1 Problem
|
||||||
|
|
||||||
|
Die Trainingsplanung unterstützt Einheiten mit Sektionen und einzelnen Übungen (inkl. Notizen) sowie Rahmenprogramme mit Blueprint-Einheiten pro Slot. Es fehlen:
|
||||||
|
|
||||||
|
- **Wiederverwendbare Übungsfolgen** („Trainingsmodule“), die sich wie Bausteine in eine Einheit einfügen lassen (ganze Sektion oder Block innerhalb einer Sektion), inkl. kopierbasierter Integration analog zum Rahmen.
|
||||||
|
- **Strukturierte Kombinationsformen** (z. B. Zirkel mit Stationstausch, Parcour), bei denen **mehrere Einzelübungen** Slots oder Rollen einnehmen und die **Trainingsmethode** den Ablauf (Rotation, parallele Stationen, Zeitmodell) bestimmt.
|
||||||
|
- Ein durchgängiges Konzept für den **Coaching- bzw. Assistenzmodus**, in dem derselbe Plan je nach Archetyp **unterschiedlich gesteuert** wird (Beispiel Zirkel: Erklärphase vs. parallele Nutzung aller Stationen).
|
||||||
|
|
||||||
|
### 1.2 Nicht-Ziele (für erste Ausbaustufe)
|
||||||
|
|
||||||
|
- **Individuelles Athleten-Tracking** oder Leistungsmessung pro Person (außerhalb Shinkan-MVP, siehe Produktabgrenzung).
|
||||||
|
- Automatische **Synchronisation** zwischen Bibliotheksexemplar und bereits geplanten historischen Einheiten (bewusst: **Kopie** statt Live-Spiegel, konsistent mit Rahmen-Konzept).
|
||||||
|
|
||||||
|
### 1.3 Zwei Bausteine (fachliche Trennung)
|
||||||
|
|
||||||
|
| Baustein | Kurzname | Einordnung | Kurzbeschreibung |
|
||||||
|
|----------|-----------|------------|------------------|
|
||||||
|
| **Typ 1** | **Kombinationsübung** | Übungskatalog (Sonderform einer **Übung**) | Eine logische Übung mit **1–n Slots**; Slots können einzelne Übungen oder **Pools** auswählbarer Übungen tragen; **Methodenprofil / Archetyp** steuert später den Durchlauf. |
|
||||||
|
| **Typ 2** | **Trainingsmodul** | Planung / Bibliothek | Gespeicherte, wiederverwendbare **Sequenz** von Elementen (Einzelübungen, optional Kombinationsübungen, Notizen); Einbindung per **Kopie** in konkrete `training_units` oder in Rahmen-Slot-Blueprints. |
|
||||||
|
|
||||||
|
**Abgrenzung Rahmenprogramm:** Das Rahmenprogramm strukturiert **mehrere Einheiten** (Slots) auf Programm-Ebene. Ein Trainingsmodul strukturiert typischerweise **Inhalt einer Einheit** oder eines Teils davon, nicht den Wochen-/Periodenrahmen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Begriffe
|
||||||
|
|
||||||
|
| Begriff | Definition |
|
||||||
|
|---------|------------|
|
||||||
|
| **Bibliotheksexemplar** | Gespeicherte Vorlage (Modul oder Kombinationsübung-Definition) mit Governance (z. B. global, Verein, privat). |
|
||||||
|
| **Instanz in der Planung** | In `training_unit_section_items` (und ggf. ergänzende Tabellen) materialisierter Ablauf für einen **konkreten Termin** bzw. eine **geplante Einheit**. |
|
||||||
|
| **Slot (Typ 1)** | Position innerhalb einer Kombinationsübung; kann genau eine gewählte Übung oder einen **Pool** (mehrere Kandidaten) referenzieren. |
|
||||||
|
| **Methodenprofil / Archetyp** | Maschinenlesbare Semantik **wie** trainiert wird (Zeit, Rotation, Parallelität), ergänzend zum bestehenden Katalog `training_methods` (Beschreibung **was** für eine Didaktik/Kondition gilt). |
|
||||||
|
| **Coaching-Modus** | UI- und Zustandslogik zur Durchführung einer geplanten Einheit (Timer, Phasen, Stationen). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Trainingsmethoden und Archetypen (Typ 1)
|
||||||
|
|
||||||
|
### 3.1 Bestehende Basis
|
||||||
|
|
||||||
|
Der Katalog `training_methods` (Migration 003) enthält u. a. **Zirkeltraining** (`category` u. a. `zirkel`, `kondition`). Er beschreibt die Methode **inhaltlich**, nicht aber Parameter wie Wechselintervalle oder parallele vs. rotierende Nutzung.
|
||||||
|
|
||||||
|
### 3.2 Erweiterung: Archetyp
|
||||||
|
|
||||||
|
Jede Kombinationsübung (und optional der Methodendatensatz als Default) erhält ein Feld **`method_archetype`** (Enum/Wertliste). Der Archetyp legt fest, welche **Parameter** am Methodenprofil relevant sind und wie der **Coaching-Modus** den Ablauf interpretiert.
|
||||||
|
|
||||||
|
**Vorschlagsliste (erweiterbar, zu verbindlich machen):**
|
||||||
|
|
||||||
|
| Archetyp-ID (Vorschlag) | Beschreibung Planungslogik | Coaching (Intent) |
|
||||||
|
|-------------------------|----------------------------|---------------------|
|
||||||
|
| `circuit_rotate_time` | n Stationen; Wechsel nach Ablaufzeit, optional globale Rundenanzahl | Rotierender oder gemeinsamer Takt; Umlauf zur nächsten Station |
|
||||||
|
| `circuit_all_parallel` | n Stationen; **kein** Umlauf als fachlicher Kern, alle Stationen gleichzeitig aktiv | Erklärphase (alle Inhalte vorher), dann **parallel** alle Stationen |
|
||||||
|
| `sequence_linear` | feste Reihenfolge; Aufbau, keine Kreisrotation | Schrittliste / Timer optional pro Schritt |
|
||||||
|
| `station_parcour` | Stationsbezogener Pfad, Reihenfolge kann variieren | Navigation / Abhaken eher als ein globaler Umlauf-Takt |
|
||||||
|
| `pair_superset` | zwei (oder wenige) Blöcke im Wechsel | Partnerlogik, gekoppelte Timer |
|
||||||
|
| `time_domain_interval` | AMRAP/EMOM-ähnliche Zeitdomäne | Globale Uhr, Runden-/Intervallzähler |
|
||||||
|
|
||||||
|
### 3.3 Parameter des Methodenprofils
|
||||||
|
|
||||||
|
Zu präzisieren (JSON-Dokument vs. normalisierte Spalten):
|
||||||
|
|
||||||
|
- Zeit: `work_seconds`, `rest_seconds`, `transition_seconds`, `rounds`
|
||||||
|
- Organisation: `station_count`, `rotation_direction`, Flags `explain_all_before_start`, `stations_operate_simultaneously`
|
||||||
|
- ggf. `intensity_profile` (skalar oder Enum), nur wenn für MVP nötig
|
||||||
|
|
||||||
|
**Offen:** Welche Parameter sind **Pflicht pro Archetyp** (Validierung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Datenmodell (Zielarchitektur, Entwurf)
|
||||||
|
|
||||||
|
### 4.1 Typ 2 — Trainingsmodule
|
||||||
|
|
||||||
|
**Entwurfstabellen (Namen können bei Implementierung angeglichen werden):**
|
||||||
|
|
||||||
|
- `training_modules` — Kopf: Titel, Beschreibung, Metadaten, `visibility`, `club_id`, `created_by`, Timestamps
|
||||||
|
- optional `training_module_sections` — falls ein Modul mehrere semantische Blöcke abbilden soll
|
||||||
|
- `training_module_items` — Reihenfolge, Verweis auf:
|
||||||
|
- Einzelübung (`exercise_id`, `exercise_variant_id`)
|
||||||
|
- Kombinationsübung (`combination_exercise_id` / `exercise_id` mit `kind=combination`)
|
||||||
|
- Freitext-Notiz (analog `note` bei Einheiten)
|
||||||
|
|
||||||
|
Semantik: **Bibliotheksbaum**, keine Bindung an Kalender oder Gruppe.
|
||||||
|
|
||||||
|
### 4.2 Typ 1 — Kombinationsübungen
|
||||||
|
|
||||||
|
**Option A (Embedding in `exercises`):** Spalte `exercise_kind` = `simple` | `combination` und Kindtabellen für Slots/Pools.
|
||||||
|
|
||||||
|
**Option B (Separate Kopf-Tabelle):** 1:1-Beziehung zwischen `exercises` und `combination_exercises`.
|
||||||
|
|
||||||
|
**Slot-Pools:** mindestens M:N **Pool-Kandidat** pro Slot; die **konkret geplante Auswahl** gehört zur **Instanz** (geplante Einheit), nicht zwingend zum Bibliotheksexemplar.
|
||||||
|
|
||||||
|
### 4.3 Integration in geplante Einheiten
|
||||||
|
|
||||||
|
Heute: `training_unit_section_items` mit `item_type` in (`exercise`, `note`).
|
||||||
|
|
||||||
|
**Erweiterungsoptionen (Entscheidung offen):**
|
||||||
|
|
||||||
|
1. **Expansion beim Einfügen:** Modul wird in Items „aufgeklappt“; optional `source_module_id` an Items für Herkunft (Lineage-Light).
|
||||||
|
2. **Block-Item:** neuer `item_type` `module_reference` oder `combination` mit ID und eingebetteter Bearbeitungssemantik (komplexer, aber „Modul als Einheit“ editierbar).
|
||||||
|
|
||||||
|
Empfehlung zur Abstimmung: MVP oft mit **Expansion** + optionaler Markierung; später Block-Knoten.
|
||||||
|
|
||||||
|
**Rahmenprogramm:** Blueprint-`training_units` pro Slot nutzen dieselbe Sektions-/Item-Struktur — Module müssen **dort** ebenfalls einfügbar sein, wenn Rahmen und konkrete Planung konsistent bleiben sollen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. API (Skizze)
|
||||||
|
|
||||||
|
Verbindliche Pfade und Payloads folgen nach Freigabe dieses Dokuments.
|
||||||
|
|
||||||
|
| Richtung | Beispielpfad / Funktion | Zweck |
|
||||||
|
|----------|-------------------------|--------|
|
||||||
|
| CRUD | `GET/POST/PUT/DELETE …/training-modules` | Bibliothek Trainingsmodule |
|
||||||
|
| Anwendung | `POST …/training-units/{id}/apply-module` | Modulinhalt in Sektion kopieren (tiefe Kopie) |
|
||||||
|
| Übungen | Erweiterung `GET/POST/PUT …/exercises` oder Unterressource `…/exercises/{id}/combination` | Kombinationsübung inkl. Slots |
|
||||||
|
| optional | `POST …/training-units/from-module` | Neue Einheit aus Modul (falls produktrelevant) |
|
||||||
|
|
||||||
|
**AuthZ:** analog andere Bibliotheks- und Planungsobjekte; Abgleich mit `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` und Endpoint-Audit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Frontend
|
||||||
|
|
||||||
|
- **Bibliothek:** Verwaltung Trainingsmodule (Liste, Editor, Sortierung, Vorschau).
|
||||||
|
- **Übungsbereich:** Editor für Kombinationsübungen (Slots, Pools, Methodenprofil/Archetyp).
|
||||||
|
- **Planungs-UI:** Aktion „Modul einfügen“, Ziel-Sektion und Position; Hinweis **Kopie** und Editierbarkeit pro Termin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Coaching- / Assistenzmodus (Durchlauf)
|
||||||
|
|
||||||
|
### 7.1 Phasenmodell (konzeptionell)
|
||||||
|
|
||||||
|
- **Briefing / Erklärung:** insbesondere für `circuit_all_parallel` und Varianten mit `explain_all_before_start`
|
||||||
|
- **Arbeitsphase(n):** timer- und stationsgetrieben
|
||||||
|
- **Übergänge:** Pausen, Wechsel, Rundenzähler
|
||||||
|
|
||||||
|
### 7.2 Persistenz während Durchführung
|
||||||
|
|
||||||
|
**Offen:** Ob ein **`training_session_run`** (Snapshot der aufgelösten Einheit zum Startzeitpunkt) für Nachvollziehbarkeit und Offline-Fähigkeit nötig ist.
|
||||||
|
|
||||||
|
### 7.3 Ausbaustufen
|
||||||
|
|
||||||
|
1. Read-only **Durchführungsansicht** (Archetyp + Zeiten, keine komplexe State Machine)
|
||||||
|
2. **Aktiver Modus** mit State Machine und Archetyp-spezifischer UI
|
||||||
|
3. Optional: Offline/PWA-Verhalten
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Umsetzungsphasen (Vorschlag)
|
||||||
|
|
||||||
|
| Phase | Inhalt |
|
||||||
|
|-------|--------|
|
||||||
|
| **A** | Dieses Dokument verbindlich machen; Archetypen und Parameter final; Governance-Regeln |
|
||||||
|
| **B** | Typ 2: `training_modules` + API + „Modul in Einheit einfügen“ (Expansion) |
|
||||||
|
| **C** | Typ 1: Kombinationsübung im Katalog + Slots/Pools + Methodenprofil |
|
||||||
|
| **D** | Einbindung in Rahmen-Slot-Blueprints (Editor-Flow) |
|
||||||
|
| **E** | Coaching-Modus gemäß Archetyp |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Offene Entscheidungen (Checkliste)
|
||||||
|
|
||||||
|
- [ ] Modul-Einfügung: nur **Expansion** vs. **Block-Knoten** vs. beides
|
||||||
|
- [ ] Normalisierung vs. JSON für **Methodenprofil-Parameter**
|
||||||
|
- [ ] Globale vs. vereinsbezogene vs. private **Trainingsmodule** (Governance-Matrix)
|
||||||
|
- [ ] Pflichtbinding: muss jede Kombinationsübung einen **Default-Archetyp** aus `training_methods` erben dürfen?
|
||||||
|
- [ ] Coaching: Mindestumfang MVP (nur Ansicht vs. interaktive Timer)
|
||||||
|
- [ ] Verweise in `DOMAIN_MODEL.md` und `DATABASE_SCHEMA.md` nach Implementierung pflegen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Changelog
|
||||||
|
|
||||||
|
| Datum | Änderung |
|
||||||
|
|-------|----------|
|
||||||
|
| 2026-05-12 | Erstversion (Entwurf) angelegt |
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Endpoint-Audit: Mandanten & Governance
|
||||||
|
|
||||||
|
Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||||
|
|
||||||
|
| Router / Bereich | Beispiel-Endpunkt | tenant-relevant | `Depends(get_tenant_context)` / Kontext | Governance geprüft (Liste+Detail) | Notizen |
|
||||||
|
|------------------|-------------------|-----------------|----------------------------------------|-------------------------------------|---------|
|
||||||
|
| profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht |
|
||||||
|
| profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin |
|
||||||
|
| profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft |
|
||||||
|
| clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth |
|
||||||
|
| club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | |
|
||||||
|
| club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | |
|
||||||
|
| exercises | `PATCH /api/exercises/bulk-metadata` | ja | `get_tenant_context` | ja | Liste: UI-Mehrfachwahl; bis 500 IDs; nur Ersteller oder Plattform-Admin |
|
||||||
|
| exercises | `GET .../media/{mid}/file` | ja | `get_tenant_context_flexible` | ja (wie Übung lesen) | Datei oder `?ssetoken`; kein anonymes `/media/` ohne ALLOW_PUBLIC_MEDIA_STATIC |
|
||||||
|
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
|
||||||
|
| exercise_progression_graphs | `/api/exercise-progression-graphs*` | ja | `get_tenant_context` | Liste wie Bibliothek; Schreiben Ersteller/Plattform-Admin | Kanten: Lesen wenn Graph lesbar |
|
||||||
|
| training_planning | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Vorlagen-Liste wie Übungen; POST Vorlage Default club_id |
|
||||||
|
| dashboard | `GET /api/dashboard/kpis` | ja | `get_tenant_context` | wie `GET /api/exercises` + `GET /api/training-units` | Aggregat für Dashboard-Kurzüberblick (ein Roundtrip) |
|
||||||
|
| training_modules | `/api/training-modules*` | ja | `get_tenant_context` | ja | Bibliotheks-Module wie Vorlagen/Rahmen; POST Default `club_id` bei `visibility=club` |
|
||||||
|
| training_framework_programs | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Liste + POST Default club_id |
|
||||||
|
| admin_users | `GET /api/admin/users` | Plattform | `require_auth` | Admin-Rolle | EXEMPT `check_access_layer_hints.py` |
|
||||||
|
| platform_media_storage | `GET/PUT /api/admin/platform-media-storage` | Plattform | `require_auth` | GET: `is_platform_admin`; PUT: nur `superadmin` | Relativer Pfad unter `MEDIA_ROOT`; keine Secrets; EXEMPT wie admin_users |
|
||||||
|
| media_assets | `POST /api/media-assets/{id}/lifecycle` | ja | `get_tenant_context` | ja | u. a. `trash_soft` mit Trainer-nur-privat-Eigentum; `purge` nur **Superadmin**; Superadmin: `superadmin_force_lifecycle`, `superadmin_hard_delete` |
|
||||||
|
| media_assets | `GET /api/media-assets` | ja | `get_tenant_context` | ja | optional `lifecycle`; Standard `active`; Liste inkl. `copyright_notice`; Papierkorb-Ansicht nur sichtbare Mandanten-Assets |
|
||||||
|
| media_assets | `POST /api/media-assets/bulk-lifecycle` | ja | `get_tenant_context` | ja | Mehrfach-Lifecycle; gleiche Regeln wie Einzel-POST |
|
||||||
|
| media_assets | `POST /api/media-assets/bulk-patch` | ja | `get_tenant_context` | ja | Copyright / Bezeichner / Sichtbarkeit für viele IDs; gemischte Fehler in `failed[]` |
|
||||||
|
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
|
||||||
|
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
|
||||||
|
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
|
||||||
|
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
|
||||||
|
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
|
||||||
|
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
|
||||||
|
| maturity_models | Admin-Matrix | nein (global) | `require_auth` | Admin für Schreiben; `GET …/{id}` nur Portal-Admin | EXEMPT |
|
||||||
|
| matrix_stack_bundle | Export/Import Bundles | Plattform/Test | `require_auth` | Admin | EXEMPT |
|
||||||
|
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
|
||||||
|
|
||||||
|
**Legende:** Router auf der EXEMPT-Liste des Scripts sind globale oder Auth-only-Pfade; sobald ein Router Vereinsdaten oder Bibliotheks-Sichtbarkeit erhält, EXEMPT entfernen und `get_tenant_context` einführen.
|
||||||
|
|
||||||
|
**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-13 — `GET /api/dashboard/kpis` (Kurzüberblick-Aggregat).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Changelog (Fortführung)
|
||||||
|
|
||||||
|
- **2026-05-13:** Dashboard-KPI-Endpunkt dokumentiert.
|
||||||
|
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||||
|
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Hinweis `GET /training-units`
|
||||||
|
|
||||||
|
Kein impliziter Filter nach `effective_club_id` (Multi-Verein-Kalender); bei Bedarf `club_id` Query setzen.
|
||||||
@@ -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)
|
# 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,125 @@
|
|||||||
|
# Parallele Trainingsstreams — Ist-Analyse und risikoarmer Umsetzungsplan
|
||||||
|
|
||||||
|
**Status:** Stufe A (Analyse/Plan, ohne produktive Umsetzung in jener Session)
|
||||||
|
**Stand:** 2026-05-14
|
||||||
|
**Verbindliche fachliche Basis:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||||
|
|
||||||
|
Dieses Dokument **persistiert** die strukturierte Prüfung der realen Codebasis (`training_planning.py`, `training_framework_programs.py`, `training_unit_sections`/`items`, Frontend Planung/Run/Coach) und den empfohlenen Implementierungspfad.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Zusammenfassung
|
||||||
|
|
||||||
|
- Plan-Inhalt pro Einheit ist heute **eine flache Liste** `training_unit_sections` mit **`UNIQUE (training_unit_id, order_index)`** (Migration 031) und `training_unit_section_items`; zentral: **`_fetch_sections`**, **`_replace_unit_sections`**, **`_hydrate_training_unit_payload`** in `backend/routers/training_planning.py`.
|
||||||
|
- Parallele Phasen/Streams **passen** zu den Produktregeln (ein Kalendertermin, N Streams, je Miniplan), sind im Schema aber **nicht** abbildbar ohne Erweiterung und **ohne Auflösung** des globalen `order_index`-Modells.
|
||||||
|
- **Empfehlung:** **Normalisierte** Tabellen `training_unit_phases`, `training_unit_parallel_streams`, erweiterte `training_unit_sections` mit FK auf Phase bzw. Stream, **partielle Unique-Indizes** statt `UNIQUE (training_unit_id, order_index)` für alle Sektionen.
|
||||||
|
- **Blocker im Code:** u. a. `POST /api/training-units/{id}/apply-training-module` mit **`section_order_index` global pro Einheit** (`_resolve_training_unit_section_id`).
|
||||||
|
- **Nicht persistiert an anderer Stelle:** Erste Fassung existierte nur als Chat-Antwort; dieses File ist die **kanonische** Arbeitskopie im Repo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Ist-Analyse (kurz)
|
||||||
|
|
||||||
|
### Datenbank
|
||||||
|
|
||||||
|
- `training_unit_sections`: u. a. `training_unit_id`, `order_index`, `UNIQUE (training_unit_id, order_index)`.
|
||||||
|
- `training_unit_section_items`: Übung/Notiz, `planning_method_profile` (Kombi), `source_training_module_id`.
|
||||||
|
|
||||||
|
### Backend (`training_planning.py`)
|
||||||
|
|
||||||
|
- `_replace_unit_sections`: DELETE aller Sektionen der Einheit + INSERT (vollständiger Ersetzungsbaum).
|
||||||
|
- `_sections_clone_payload` + `_copy_blueprint_into_scheduled_unit`: tiefe Kopie für `from-framework-slot`.
|
||||||
|
- `_flatten_exercises_from_sections`: flaches `exercises` am Unit-Payload.
|
||||||
|
- `apply_training_module_to_training_unit`: Sektion per **`section_order_index`** global.
|
||||||
|
|
||||||
|
### Rahmen (`training_framework_programs.py`)
|
||||||
|
|
||||||
|
- Blueprint-`training_units` pro Slot; gleiche `_replace_unit_sections`-Semantik.
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
|
||||||
|
- Planung: `TrainingPlanningPageRoot.jsx`, `TrainingUnitSectionsEditor`, `buildSectionsPayload` / `normalizeUnitToForm`.
|
||||||
|
- Run: `TrainingUnitRunPage.jsx` — Fortschritt `sessionStorage` Key `sj_training_run_checked_${unitId}`.
|
||||||
|
- Coach: `TrainingCoachPage.jsx` — `flattenPlanTimeline` (linearer Ablauf).
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
- Kaum Abdeckung für Plan-Inhalt; vorhanden u. a. `test_training_unit_assignments.py` (Merge Co-Trainer, ohne DB), `test_training_units_list_keyset.py` (Keyset-Validierung).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Technische Optionen und Empfehlung
|
||||||
|
|
||||||
|
| Option | Kurz |
|
||||||
|
|--------|------|
|
||||||
|
| A JSONB nur auf `training_units` | Niedriges DDL-Risiko, hohes Drift-/Wartungsrisiko — **nicht empfohlen** |
|
||||||
|
| B Normalisiert Phasen/Streams | **Empfohlen** — eine Wahrheit, saubere Kopie, Rahmen kompatibel |
|
||||||
|
| C Nur UI-Konvention ohne DB | Widerspricht Produkt — **abgelehnt** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Migrations- und Kompatibilitätsstrategie
|
||||||
|
|
||||||
|
- Default **`whole_group`‑Phase** für alle bestehenden Einheiten; alle bisherigen Sektionen erhalten `phase_id`.
|
||||||
|
- Unique-Regel: **pro Phase** bzw. **pro Stream** `order_index` eindeutig (partielle Unique-Indizes).
|
||||||
|
- API optional: zusätzlich abgeleitetes flaches `sections` für Übergang — Entscheidung je nach Consumer (praktisch nur dieses Frontend).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. API- / Frontend-Hotspots
|
||||||
|
|
||||||
|
- `GET`/`PUT` `/api/training-units/{id}`: verschachtelte `phases` / `streams` / `sections` / `items`.
|
||||||
|
- `POST .../apply-training-module`: Kontext **Phase/Stream + Sektionsindex im Träger**.
|
||||||
|
- Run/Coach: stream-spezifischer Fortschritt; `flattenPlanTimeline` phase-aware oder pro Stream.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Implementierungspakete (Überblick)
|
||||||
|
|
||||||
|
0. Spike DDL + Contract-Doku
|
||||||
|
1. **Erledigt (2026-05-14):** Migration **063** + `training_planning`: Phasen/Streams-Schema, Backfill whole_group, `GET` mit `phases`, Legacy-`sections`-PUT unverändert (eine whole_group-Phase).
|
||||||
|
2. PUT mit echten Parallelphasen / Streams, `apply-training-module` mit Stream-Kontext, `from-framework-slot`-Kopie
|
||||||
|
3. Planung UI
|
||||||
|
4. Run + Coach
|
||||||
|
5. Co-Trainer pro Stream
|
||||||
|
6. MVP+ (Duplizieren, Verschieben, „nur meine Spur“)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Risiken
|
||||||
|
|
||||||
|
- Migration Unique-Constraint / bestehende Daten.
|
||||||
|
- Regression Run/Coach / Dashboard-Joins (meist unkritisch, solange `training_unit_id` auf Sektionen bleibt).
|
||||||
|
- Rahmen-Blueprints: gleiche Struktur wie Kalender-Einheiten anstreben (oder bewusst zweite Phase nur Kalender).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Offene Produkt-/Technikfragen
|
||||||
|
|
||||||
|
- Rahmen-Blueprint parallel im MVP oder erst nach Kalender-Einheit?
|
||||||
|
- Semantik `exercises`-Flatlist bei Parallelität.
|
||||||
|
- Merge-Regel `assistant_trainer_profile_ids` Kopf vs. Stream-Zuweisungen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Verweise
|
||||||
|
|
||||||
|
- Fachkonzept: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||||
|
- Technische Spec (Entwurf): `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||||
|
- Domänenüberblick: `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||||
|
- `./PARALLEL_TRAINING_STREAMS_PREREQ_PROMPT.md` — **Prompt** für Folgesession (Performance/Wartung/Vorbereitung)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Vorbereitende Arbeiten (Session 2026-05-13)
|
||||||
|
|
||||||
|
Ohne produktives Parallel-Feature, nur Risikoabbau und Transparenz:
|
||||||
|
|
||||||
|
- **`training_planning.py`:** Lesepfad `_fetch_sections` in SQL-Konstanten + `_fetch_section_items_for_section` / `_hydrate_section_item_combination_slots` strukturiert; `_replace_unit_sections` delegiert an `_insert_one_replacement_section`; `_hydrate_training_unit_payload` dokumentiert.
|
||||||
|
- **Tests:** `tests/test_training_planning_sections_pure.py` (flatten, ohne DB); `tests/test_training_planning_sections_integration.py` (Roundtrip replace↔fetch bei `TRAINING_PLANNING_INTEGRATION=1`).
|
||||||
|
- **Frontend:** Kurzkommentare an Planung (`TrainingPlanningPageRoot`, `buildSectionsPayload`), Run, Coach, `flattenPlanTimeline` — Anbindungspunkte für spätere Phase/Stream-Logik.
|
||||||
|
- **DOMAIN_MODEL:** UNIQUE-Hinweis und „keine Migration ohne Freigabe“.
|
||||||
|
|
||||||
|
**Empfohlene nächste Schritte:** Pakete **0** (DDL/Contract festzurren) und **1** (Schema + Migration + hydrate/replace laut Plan Abschnitt 4–6) in einer dedizierten Feature-Session; danach Paket **2** (PUT/Module/Clone).
|
||||||
|
|
||||||
|
---
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Prompt: Vorbereitungs- / Vorarbeit-Session (Performance & Wartung) für „Parallele Trainingsstreams“
|
||||||
|
|
||||||
|
**Kontext:** Du arbeitest in **Shinkan Jinkendo** (`c:\Dev\shinkan-jinkendo`). Das Feature **Parallele Trainingsstreams / Breakout** ist **inhaltlich** spezifiziert; eine **Ist-Analyse und ein risikoarmer Umsetzungsplan** liegen **persistiert** in:
|
||||||
|
|
||||||
|
- `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`
|
||||||
|
- Fachlich: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||||
|
- Technik-Entwurf: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||||
|
|
||||||
|
**Deine Rolle:** Du hast bereits **Refaktorierungs- und Wartungsaufgaben** mit Fokus **Performance, Lesbarkeit und Testbarkeit** durchgeführt. In **dieser** Session geht es **nicht** darum, das komplette Parallel-Feature zu bauen, sondern um **Vorarbeiten („Prerequisites“)**, die die geplante Komplexitätsauflösung **sicherer und billiger** machen.
|
||||||
|
|
||||||
|
## Ziele
|
||||||
|
|
||||||
|
1. **Lesepfad Planung vereinheitlichen:** `backend/routers/training_planning.py` ist zentral für `_fetch_sections`, `_replace_unit_sections`, `_hydrate_training_unit_payload`, Klonen, Blueprint-Kopie, `apply-training-module`. Prüfe, ob klar abgegrenzte Hilfsfunktionen (ohne Verhaltensänderung) die **nächste** große Änderung erleichtern — **keine** Feature-Logik für Phasen/Streams hinzufügen, nur Struktur/Tests/Docs wenn nötig.
|
||||||
|
|
||||||
|
2. **Test-Lücken schließen (minimal, hoher Nutzen):** Heute fehlen **DB/API-Tests** für kritische Pfade (`_replace_unit_sections` Roundtrip, `from-framework-slot` Struktur-Kopie, optional `apply-training-module`). Ergänze **kleine, deterministische** Tests (pytest mit DB, falls im Projekt üblich), ohne riesige Fixtures.
|
||||||
|
|
||||||
|
3. **Frontend-Schneidstellen markieren:** kurze Kommentare oder ein **Working-Doc-Update**, wo `TrainingPlanningPageRoot`, `buildSectionsPayload`, `TrainingUnitRunPage`, `TrainingCoachPage` + `trainingPlanUtils.flattenPlanTimeline` später angebunden werden — **kein** großes UI-Rewrite.
|
||||||
|
|
||||||
|
4. **Migrations-Sicherheit:** Dokumentiere in **einem Absatz** im `ANALYSIS`-Dokument oder hier, welche **Unique-Constraints** (`training_unit_sections`: `UNIQUE (training_unit_id, order_index)`) die Parallelität blockieren — **ohne** sie schon zu ändern, außer es ist Teil einer **explizit** freigegebenen ersten Migration.
|
||||||
|
|
||||||
|
5. **Performance nur berührensensible Stellen:** Einzelabruf `GET /api/training-units/{id}` wird mit mehr JOINs kommen. Falls du **jetzt** N+1 oder redundante Arbeit in `_fetch_sections` siehst und das **risikoarm** verbesserbar ist, nur mit **Messpunkt/Messvorstellung** (kein unnötiger Micro-Optimismus).
|
||||||
|
|
||||||
|
## Leitplanken
|
||||||
|
|
||||||
|
- **Stabilität vor Geschwindigkeit:** Keine Änderung, die bestehende Einheiten, Rahmen-Blueprints oder Run-Modus bricht.
|
||||||
|
- **Keine pauschalen Refactors:** Nur Änderungen mit **klarem** Träger für das Parallel-Feature oder mit **Test-Regression-Schutz**.
|
||||||
|
- **Regeln:** `.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht wo relevant.
|
||||||
|
|
||||||
|
## Erwartete Ausgabe
|
||||||
|
|
||||||
|
1. Kurze **Liste erledigter Vorarbeiten** (Dateien, was warum).
|
||||||
|
2. **Empfohlene Reihenfolge** für die **nächste** Session, die Phasen/Streams **implementiert** (verweis auf `PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md` Pakete 0–2).
|
||||||
|
3. Falls nichts Sinnvolles ohne Feature-Branch riskiert werden kann: **explizit** „keine Code-Änderung“, nur Risiko-Notiz.
|
||||||
|
|
||||||
|
## Optionaler Startbefehl
|
||||||
|
|
||||||
|
```
|
||||||
|
Lies zuerst:
|
||||||
|
.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md
|
||||||
|
dann backend/routers/training_planning.py (Abschnitte um _fetch_sections, _replace_unit_sections).
|
||||||
|
```
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# Produktionsreife: Audit-Ergebnis & Umsetzungsplan (Stand 2026-05-07, Phase-3-Update)
|
||||||
|
|
||||||
|
**Zweck:** Einheitliche Referenz gegen **Drift** zwischen Sicherheits-/Betriebsanforderungen und Code.
|
||||||
|
**Bezug:** Zugriffsschicht `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`, Cursor-Regel `.cursor/rules/access-layer.mdc`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Teil A — Audit-Ergebnis (Kurzfassung)
|
||||||
|
|
||||||
|
### A.1 Kritisch / Hoch (behoben oder geplant)
|
||||||
|
|
||||||
|
| ID | Befund | Status (2026-05-07) |
|
||||||
|
|----|--------|----------------------|
|
||||||
|
| SEC-01 | `GET /api/profile` (Legacy): ohne Header wurde das **erste Profil der DB** geliefert → IDOR / Datenleck | **Behoben:** Profil immer aus Session |
|
||||||
|
| SEC-02 | OpenAPI `/docs`, `/redoc`, `/openapi.json` in Produktion exponiert | **Behoben:** bei `ENVIRONMENT=production` aus; Override `PUBLIC_OPENAPI=1` |
|
||||||
|
| SEC-03 | `/api/health/ready` mit Tabellendetails / Migrationszähler öffentlich | **Behoben:** in Prod nur kompakte Antwort; Detail via `HEALTH_READY_PUBLIC_DETAIL=1` |
|
||||||
|
| SEC-04 | Statische Auslieferung `/media` ohne Auth (Link-Leak) | **Behoben:** `GET /api/exercises/.../media/.../file` mit Governance + `ssetoken`; `/media` nur mit `ALLOW_PUBLIC_MEDIA_STATIC=1` |
|
||||||
|
| OPS-01 | PostgreSQL-Hostport in `docker-compose.yml` | **Behoben:** Bind `127.0.0.1:5434` (nur Host-Local) |
|
||||||
|
|
||||||
|
### A.2 Mittel / Konsistenz
|
||||||
|
|
||||||
|
| ID | Befund | Status |
|
||||||
|
|----|--------|--------|
|
||||||
|
| CON-01 | Frontend: direktes `fetch('/api/profiles')` ohne zentralen Client | **Behoben** (AdminCatalogsPage → `api.listProfiles`) |
|
||||||
|
| CON-02 | `ProfileContext.jsx` (unused): falsches Token-Feld / `session` | **Behoben** (`user` + `getCurrentProfile` / `listProfiles`) |
|
||||||
|
| MEM-01 | Vereinsmitgliederverzeichnis zeigt E-Mail an alle Mitglieder | **Behoben:** E-Mail nur Plattform-Admin / `can_manage_club_org` |
|
||||||
|
| MAT-01 | `GET /maturity-models/{id}` für jeden Auth-Nutzer | **Behoben:** nur Portal-Admin (UI nutzt ohnehin nur Admin-Panel) |
|
||||||
|
|
||||||
|
### A.3 Niedrig / Offen
|
||||||
|
|
||||||
|
| ID | Befund | Status |
|
||||||
|
|----|--------|--------|
|
||||||
|
| CON-03 | Sparten (`division`) vs. Zielbild ACCESS_LAYER | **Roadmap** — siehe Phase 3 unten (Stufe D); nicht in diesem Schritt implementiert |
|
||||||
|
| OPS-02 | CSP / restliche Browser-Härtung | **Behoben (Basis):** CSP auf SPA-Dokumente (nginx `location /`); API `X-Content-Type-Options: nosniff` (FastAPI-Middleware) |
|
||||||
|
| MISC-01 | `auth.py` Debug-`print` beim Import | **Behoben** (entfernt) |
|
||||||
|
| MISC-02 | `delete_profile`: DELETE auf Mitai-Tabellen schlägt fehl, wenn Tabelle fehlt | **Behoben:** nur löschen, wenn Tabelle existiert |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Teil B — Priorisierter Umsetzungsplan
|
||||||
|
|
||||||
|
### Phase 1 — Sofort (Beta-Blocker) ✅ umgesetzt in Repo-Stand
|
||||||
|
|
||||||
|
1. Legacy-Endpunkte `/api/profile` GET/PUT: **nur Session-`profile_id`**, kein „erstes Profil“-Fallback.
|
||||||
|
2. OpenAPI in Produktion deaktivieren; opt-in für Notfall-Debugging.
|
||||||
|
3. Readiness-Endpoint in Prod entschärfen; operatives Detail per Env.
|
||||||
|
4. Automatisierte **Security-Release-Tests** (`tests/test_security_release.py`) + Script `scripts/security_release_checks.py` in CI.
|
||||||
|
5. Profil-Löschung: optionale Tabellen nur bei Existenz.
|
||||||
|
6. Frontend: Admin-Kataloge Profilliste über `api.js`.
|
||||||
|
|
||||||
|
### Phase 2 — Kurzfristig (vor breitem Go-Live) ✅ Hauptpunkte umgesetzt (2026-05-07)
|
||||||
|
|
||||||
|
1. **Medien:** `GET /api/exercises/{id}/media/{mid}/file` — Auth (`X-Auth-Token` oder `?ssetoken=`), Zugriff wie GET Übung; statisches `/media` standardmäßig aus.
|
||||||
|
2. **Mitgliederverzeichnis:** E-Mail nur wenn Plattform-Admin oder `can_manage_club_org`.
|
||||||
|
3. **DB-Port:** Prod-Compose Postgres an `127.0.0.1` gebunden.
|
||||||
|
4. **`GET /api/maturity-models/{id}`:** nur Portal-Admin (Liste/resolve unverändert für Trainer).
|
||||||
|
|
||||||
|
### Phase 3 — Mittelfristig
|
||||||
|
|
||||||
|
1. **CSP & Header:** Content-Security-Policy für die SPA (nginx, `location /`); `X-Content-Type-Options: nosniff` auf allen FastAPI-Responses — ✅ umgesetzt.
|
||||||
|
2. **Audit-Pflege:** bei Tenant/Governance-Änderungen `ACCESS_LAYER_ENDPOINT_AUDIT.md` und dieses Dokument anpassen — fortlaufend (Hinweis im Endpoint-Audit).
|
||||||
|
3. **Division / Sparten (CON-03, Stufe D):** noch **nicht** code-seitig durchgesetzt. Nächste technische Schritte (für eigenes Epic):
|
||||||
|
- Ist-Zustand: `division_id` auf Objekten & `division_lead` in `can_plan_in_club` ohne strikte Objekt-Filter.
|
||||||
|
- Ziel: Lesen/Schreiben nur mit passender Sparten-Mitgliedschaft bzw. Rolle; einheitliche Filter in Listen (`training_groups`, Übungen, Planung).
|
||||||
|
- Tests: Zwei Nutzer, zwei Sparten, kein Cross-Lesen; Superadmin-Pfade getrennt.
|
||||||
|
- Spec: `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe D.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Teil C — CI / Qualitätssicherung
|
||||||
|
|
||||||
|
- **ACCESS_LAYER_STRICT:** `scripts/check_access_layer_hints.py` (unverändert Pflicht).
|
||||||
|
- **Security-Release:** `python scripts/security_release_checks.py` (pytest-Modul `test_security_release`).
|
||||||
|
- **Regression Profil:** `tests/test_profiles_read_access.py` (Legacy-Route).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Teil D — Umgebungsvariablen (Referenz)
|
||||||
|
|
||||||
|
| Variable | Bedeutung |
|
||||||
|
|----------|-----------|
|
||||||
|
| `ENVIRONMENT` | `production` / `prod` → OpenAPI aus, Health-Ready kompakt |
|
||||||
|
| `PUBLIC_OPENAPI` | `1` / `true` → OpenAPI trotz Prod einschalten (nur Debugging) |
|
||||||
|
| `HEALTH_READY_PUBLIC_DETAIL` | `1` / `true` → volle Ready-JSON inkl. Tabellenliste in Prod |
|
||||||
|
| `ALLOW_PUBLIC_MEDIA_STATIC` | `1` / `true` → öffentliches Mount von `/media/` (Notfall/Legacy; Standard: aus) |
|
||||||
|
| `CSP` (nginx) | Kein Env: Policy fest in `frontend/nginx.conf` (`location /`). API auf **anderer Host-URL** als SPA: `connect-src` in der Policy erweitern oder Build mit envsubst. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Pflege:** Nach jeder relevanten Änderung **Status-Spalte** und ggf. **Phase** aktualisieren; bei neuem Audit Datum im Titel anpassen oder Abschnitt „Changelog“ ergänzen.
|
||||||
|
|
||||||
|
### Changelog
|
||||||
|
|
||||||
|
- **2026-05-07:** Phase 2 Medien, Mitgliederverzeichnis E-Mail, maturity GET admin-only, Postgres localhost bind, Tests `test_exercise_media_download.py`.
|
||||||
|
- **Phase 3:** CSP (nginx SPA), API `X-Content-Type-Options` (FastAPI), Test `test_api_attachments_x_content_type_options_nosniff`; Division-Durchsetzung nur als Roadmap (CON-03).
|
||||||
@@ -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.
|
||||||
@@ -55,6 +55,23 @@ return {"error": "not found"}
|
|||||||
return {"message": "Fehler", "success": False}
|
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, 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:
|
||||||
|
|
||||||
|
1. Request-Kontext: `Depends(get_tenant_context)` (oder dokumentierte Ausnahme mit Kommentar `# ACCESS_LAYER exempt:` + Audit).
|
||||||
|
2. Lesen: gleiche Sichtbarkeitslogik wie vergleichbare Bibliotheks-/Planungsartefakte (`library_content_visibility_sql`, `exercise_visible_to_profile` / zentrale Helfer — nicht ad-hoc „alles aus der Tabelle“).
|
||||||
|
3. Schreiben: `assert_valid_governance_visibility` wo `visibility` / `club_id` gesetzt oder geändert wird.
|
||||||
|
4. Audit-Tabelle und bei Bedarf die EXEMPT-Liste im Script `backend/scripts/check_access_layer_hints.py` aktualisieren.
|
||||||
|
5. Optional vor Commit: `python backend/scripts/check_access_layer_hints.py` (mit `ACCESS_LAYER_STRICT=1` schlägt bei neuen Verstößen fehl).
|
||||||
|
|
||||||
|
Router ohne Vereinsbezug (z. B. globale Kataloge, Auth-Login) bleiben bewusst ohne `get_tenant_context`; sie stehen im Script auf der **EXEMPT**-Liste.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Versionskontrollsystem
|
## 2. Versionskontrollsystem
|
||||||
|
|||||||
@@ -4,17 +4,32 @@ Diese Regeln IMMER befolgen. Sie basieren auf Erfahrungen aus der Entwicklung.
|
|||||||
|
|
||||||
## Backend
|
## Backend
|
||||||
|
|
||||||
### 1. Auth auf jeden Endpoint
|
### 1. Auth und Mandantenkontext (Shinkan)
|
||||||
|
|
||||||
|
**Jeder geschützte Endpoint braucht Auth.** Sofern der Endpoint **Vereinsdaten**, **visibility/club_id** oder **mandanten-gefilterte Listen** betrifft, zusätzlich **`TenantContext`** — nicht nur `require_auth` allein.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Jeder neue Endpoint braucht Auth:
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
@router.get("/neuer-endpoint")
|
|
||||||
def neuer_endpoint(session: dict = Depends(require_auth)):
|
@router.get("/beispiel")
|
||||||
pid = session['profile_id']
|
def beispiel(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
club_ctx = tenant.effective_club_id # kann None sein (z. B. Plattform-Admin)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Profile-ID aus Session – nie aus Header
|
- **Bibliotheks-/Planungslisten:** Filter wie bestehende Module (`library_content_visibility_sql` oder gleiche Leseprüfung); keine vollständige Tabelle für normale Nutzer.
|
||||||
|
- **Schreiben:** `assert_valid_governance_visibility` aus `club_tenancy`, wenn `visibility` / `club_id` gesetzt werden.
|
||||||
|
- **Dokumentation:** Änderungen in `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` festhalten.
|
||||||
|
- **Ausnahmen** (z. B. reiner Login, globale Kataloge): Kommentar `# ACCESS_LAYER exempt: …` und ggf. Eintrag in `backend/scripts/check_access_layer_hints.py`.
|
||||||
|
|
||||||
|
Reine Plattform-Admin-Router (ohne Vereinskontext) können bei Bedarf weiter `Depends(require_auth)` nutzen — dann im Audit als „Plattform“ kennzeichnen.
|
||||||
|
|
||||||
|
### 2. Profile-ID aus TenantContext oder Session — nie aus freiem Header
|
||||||
|
|
||||||
```python
|
```python
|
||||||
pid = session['profile_id'] # ✅
|
pid = tenant.profile_id # ✅ bei Depends(get_tenant_context)
|
||||||
|
# oder session['profile_id'] nur wenn Endpoint ausdrücklich ohne TenantContext (Ausnahme dokumentieren)
|
||||||
# Nicht: request.headers.get('X-Profile-Id') ❌
|
# Nicht: request.headers.get('X-Profile-Id') ❌
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
|
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
|
||||||
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
|
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
|
||||||
3. Spez-Index: **`.claude/docs/README.md`**
|
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)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
description: Mandanten & Governance — TenantContext, Sichtbarkeit, keine Schnellpfade
|
||||||
|
globs: backend/routers/*.py
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Zugriffsschicht (Shinkan)
|
||||||
|
|
||||||
|
Vor neuen oder geänderten Endpoints in `backend/routers/` kurz prüfen:
|
||||||
|
|
||||||
|
1. **Pflichtlektüre** (bei inhaltsbezogenen APIs): `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` und `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`.
|
||||||
|
|
||||||
|
2. **Auth**: kein geschützter Endpoint ohne `Depends(require_auth)` bzw. eingebettet in `Depends(get_tenant_context)` (der holt die Session bereits).
|
||||||
|
|
||||||
|
3. **Verein / Sichtbarkeit** (`visibility`, `club_id`, Mitglieder-Inhalte):
|
||||||
|
`tenant: TenantContext = Depends(get_tenant_context)` verwenden; Profile-ID aus `tenant.profile_id`, Rolle aus `tenant.global_role`.
|
||||||
|
|
||||||
|
4. **Bibliothekslisten** (Übungen, Vorlagen, Rahmenprogramme, Progressionsgraphen, gleiche Semantik): Filter über `library_content_visibility_sql(...)` bzw. gleiche Leseregel wie bestehende Module — nicht „alle Zeilen aus SELECT“.
|
||||||
|
|
||||||
|
5. **Schreiben mit Governance**: bei `visibility`/`club_id`-Änderungen `assert_valid_governance_visibility`; bei `club` ohne `club_id` im Body → `tenant.effective_club_id` oder klare 400-Hinweise (wie bei Übungen).
|
||||||
|
|
||||||
|
6. **Ausnahmen** nur mit kurzem Kommentar im Code: `# ACCESS_LAYER exempt: …` und Eintrag im Audit oder in `backend/scripts/check_access_layer_hints.py` (EXEMPT-Liste).
|
||||||
|
|
||||||
|
7. **Nach Merge**: eine Zeile `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` anpassen, wenn sich Tenant oder Governance ändert.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ❌ Schnellpfad: nur Session, obwohl Vereinsdaten betroffen
|
||||||
|
@router.get("/foo")
|
||||||
|
def foo(session=Depends(require_auth)):
|
||||||
|
...
|
||||||
|
|
||||||
|
# ✅ Konsistent zu clubs/exercises/planning
|
||||||
|
@router.get("/foo")
|
||||||
|
def foo(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
...
|
||||||
|
```
|
||||||
+10
-1
@@ -12,6 +12,8 @@
|
|||||||
# APP_URL=https://shinkan.jinkendo.de
|
# APP_URL=https://shinkan.jinkendo.de
|
||||||
# ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
# ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
||||||
# ENVIRONMENT=production
|
# ENVIRONMENT=production
|
||||||
|
# SHINKAN_MEDIA_HOST=/shinkan-media
|
||||||
|
# MEDIA_ROOT=/app/media
|
||||||
|
|
||||||
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
|
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
|
||||||
# DB_NAME=shinkan_dev
|
# DB_NAME=shinkan_dev
|
||||||
@@ -20,6 +22,8 @@
|
|||||||
# APP_URL=https://dev.shinkan.jinkendo.de
|
# APP_URL=https://dev.shinkan.jinkendo.de
|
||||||
# ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098
|
# ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098
|
||||||
# ENVIRONMENT=development
|
# ENVIRONMENT=development
|
||||||
|
# SHINKAN_MEDIA_HOST=/shinkan-media/dev
|
||||||
|
# MEDIA_ROOT=/app/media
|
||||||
|
|
||||||
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
|
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
|
||||||
DB_HOST=postgres
|
DB_HOST=postgres
|
||||||
@@ -46,7 +50,12 @@ APP_URL=https://shinkan.jinkendo.de
|
|||||||
ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
||||||
ENVIRONMENT=production
|
ENVIRONMENT=production
|
||||||
|
|
||||||
MEDIA_DIR=/app/media
|
# 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
|
||||||
|
|
||||||
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
|
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
|
||||||
MEDIAWIKI_USER=Jinkendo
|
MEDIAWIKI_USER=Jinkendo
|
||||||
|
|||||||
+120
-1
@@ -3,11 +3,45 @@ name: Test Suite
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main, develop]
|
branches: [main, develop]
|
||||||
|
pull_request:
|
||||||
|
branches: [main, develop]
|
||||||
workflow_run:
|
workflow_run:
|
||||||
workflows: ["Deploy Development", "Deploy Production"]
|
workflows: ["Deploy Development", "Deploy Production"]
|
||||||
types: [completed]
|
types: [completed]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
||||||
|
pytest-backend:
|
||||||
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Backend pytest im deployten Container
|
||||||
|
run: |
|
||||||
|
EVENT_NAME="${{ github.event_name }}"
|
||||||
|
REF_NAME="${{ github.ref_name }}"
|
||||||
|
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||||
|
APP_DIR="/home/lars/docker/shinkan"
|
||||||
|
COMPOSE_FILE="docker-compose.yml"
|
||||||
|
|
||||||
|
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
||||||
|
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||||
|
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||||
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
|
fi
|
||||||
|
elif [ "$REF_NAME" = "develop" ]; then
|
||||||
|
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||||
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$APP_DIR"
|
||||||
|
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
||||||
|
pip install -r /app/requirements-dev.txt &&
|
||||||
|
cd /app &&
|
||||||
|
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
|
||||||
|
python scripts/security_release_checks.py &&
|
||||||
|
ACCESS_LAYER_INTEGRATION=1 TRAINING_PLANNING_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||||
|
"
|
||||||
|
|
||||||
lint-backend:
|
lint-backend:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -54,6 +88,90 @@ jobs:
|
|||||||
npm run build
|
npm run build
|
||||||
echo "✓ Frontend build OK"
|
echo "✓ Frontend build OK"
|
||||||
|
|
||||||
|
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
||||||
|
k6-health-baseline:
|
||||||
|
name: k6 /health Baseline
|
||||||
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||||
|
id: e2e
|
||||||
|
run: |
|
||||||
|
EVENT="${{ github.event_name }}"
|
||||||
|
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||||
|
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
||||||
|
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||||
|
echo "mode=prod" >> $GITHUB_OUTPUT
|
||||||
|
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
||||||
|
echo "→ k6 gegen Prod-Basis."
|
||||||
|
else
|
||||||
|
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||||
|
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||||
|
echo "→ k6 gegen Dev (${DEV_BASE})."
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Dev /health abwarten
|
||||||
|
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||||
|
run: |
|
||||||
|
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||||
|
echo "Warte auf $BASE/health …"
|
||||||
|
for i in $(seq 1 90); do
|
||||||
|
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||||
|
echo "Health OK (Versuch $i)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
||||||
|
curl -v "$BASE/health" || true
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Prod /health abwarten
|
||||||
|
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||||
|
run: |
|
||||||
|
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||||
|
echo "Warte auf $BASE/health …"
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||||
|
echo "Health OK (Versuch $i)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "Timeout: Prod /health nicht erreichbar"
|
||||||
|
curl -v "$BASE/health" || true
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Install k6
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
K6_VER="v0.55.0"
|
||||||
|
ARCH=$(uname -m)
|
||||||
|
case "$ARCH" in
|
||||||
|
x86_64) K6_ARCH=amd64 ;;
|
||||||
|
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||||
|
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
|
||||||
|
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||||
|
tar -xzf /tmp/k6.tgz -C /tmp
|
||||||
|
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||||
|
k6 version
|
||||||
|
|
||||||
|
- name: k6 Health-Baseline (parallele /health)
|
||||||
|
env:
|
||||||
|
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||||
|
k6 run scripts/load/k6-health-baseline.js
|
||||||
|
echo "✓ k6 Health-Baseline passed"
|
||||||
|
|
||||||
playwright-tests:
|
playwright-tests:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -172,7 +290,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload test screenshots
|
- name: Upload test screenshots
|
||||||
if: failure()
|
if: failure()
|
||||||
uses: actions/upload-artifact@v4
|
# v4 ist auf Gitea (GHES-kompatibles Actions-Backend) oft nicht verfügbar
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: playwright-screenshots
|
name: playwright-screenshots
|
||||||
path: screenshots/
|
path: screenshots/
|
||||||
|
|||||||
@@ -5,9 +5,17 @@
|
|||||||
> VOR jeder Implementierung lesen:
|
> VOR jeder Implementierung lesen:
|
||||||
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` |
|
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` |
|
||||||
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
|
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
|
||||||
|
> | Zugriffsschicht (Multi-Tenancy, Governance) | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
|
||||||
|
> | Endpoint-Audit (Tenant/Governance) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
|
||||||
|
> | Cursor-Regel Zugriffsschicht | `.cursor/rules/access-layer.mdc` |
|
||||||
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
|
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
|
||||||
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||||
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
||||||
|
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||||
|
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
|
||||||
|
> | Fachlicher Nutzerüberblick (Design/Product) | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||||
|
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
||||||
|
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
||||||
|
|
||||||
## Projekt-Übersicht
|
## Projekt-Übersicht
|
||||||
|
|
||||||
@@ -53,7 +61,7 @@ backend/
|
|||||||
└── routers/ # Router-Module
|
└── routers/ # Router-Module
|
||||||
auth · profiles · clubs · groups · skills · methods
|
auth · profiles · clubs · groups · skills · methods
|
||||||
exercises · exercise_progression_graphs · training_units · training_programs
|
exercises · exercise_progression_graphs · training_units · training_programs
|
||||||
planning · import_wiki · admin · membership
|
planning · import_wiki · admin · membership · media_assets
|
||||||
|
|
||||||
frontend/src/
|
frontend/src/
|
||||||
├── App.jsx # Root, Auth-Gates, Navigation
|
├── App.jsx # Root, Auth-Gates, Navigation
|
||||||
@@ -78,10 +86,11 @@ frontend/src/
|
|||||||
|
|
||||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
**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)
|
### 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-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`.
|
- 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`.
|
||||||
|
|
||||||
@@ -102,7 +111,7 @@ Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**
|
|||||||
- `exercises` - Übungen (Kernobjekt)
|
- `exercises` - Übungen (Kernobjekt)
|
||||||
- `exercise_variants` - Übungsvarianten
|
- `exercise_variants` - Übungsvarianten
|
||||||
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
||||||
- `exercise_media` - Medien (Bilder, Videos)
|
- `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:**
|
**Trainingsplanung / Rahmen:**
|
||||||
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
||||||
@@ -197,6 +206,10 @@ ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
|||||||
MEDIA_DIR=/app/media
|
MEDIA_DIR=/app/media
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Produktions-/Sicherheitsaudit (Drift vermeiden)
|
||||||
|
|
||||||
|
Aktuelle Befunde und Umsetzungsstände: `.claude/docs/working/PRODUCTION_READINESS_AUDIT_2026-05.md` (Fortlaufend pflegen.)
|
||||||
|
|
||||||
## Kritische Regeln für Claude Code
|
## Kritische Regeln für Claude Code
|
||||||
|
|
||||||
### Must-Do:
|
### Must-Do:
|
||||||
|
|||||||
@@ -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
|
- **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten
|
||||||
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
|
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
|
||||||
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
|
- **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
|
## Nicht in Shinkan
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ import bcrypt
|
|||||||
|
|
||||||
from db import get_db, get_cursor
|
from db import get_db, get_cursor
|
||||||
|
|
||||||
print("[AUTH.PY] Module loaded - require_auth_flexible will be defined")
|
|
||||||
|
|
||||||
|
|
||||||
def hash_pin(pin: str) -> str:
|
def hash_pin(pin: str) -> str:
|
||||||
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""
|
||||||
|
Vereins-Mandanten: Mitgliedschaften, aktiver Vereinskontext, einfache Berechtigungen.
|
||||||
|
|
||||||
|
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
|
||||||
|
"""
|
||||||
|
from typing import Any, Dict, List, Optional, Set
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
def is_platform_admin(role: Optional[str]) -> bool:
|
||||||
|
return (role or "").lower() in ("admin", "superadmin")
|
||||||
|
|
||||||
|
|
||||||
|
def is_superadmin(role: Optional[str]) -> bool:
|
||||||
|
return (role or "").lower() == "superadmin"
|
||||||
|
|
||||||
|
|
||||||
|
def club_ids_for_profile(cur, profile_id: int) -> Set[int]:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT club_id FROM club_members
|
||||||
|
WHERE profile_id = %s AND status = 'active'
|
||||||
|
""",
|
||||||
|
(profile_id,),
|
||||||
|
)
|
||||||
|
return {r["club_id"] for r in cur.fetchall()}
|
||||||
|
|
||||||
|
|
||||||
|
def assert_club_member(cur, profile_id: int, club_id: int) -> None:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members
|
||||||
|
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Mitgliedschaft in diesem Verein")
|
||||||
|
|
||||||
|
|
||||||
|
def has_club_role(cur, profile_id: int, club_id: int, *role_codes: str) -> bool:
|
||||||
|
if not role_codes:
|
||||||
|
return False
|
||||||
|
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 IN ({ph})
|
||||||
|
LIMIT 1
|
||||||
|
""".format(ph=",".join(["%s"] * len(role_codes))),
|
||||||
|
(profile_id, club_id, *role_codes),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def club_admin_shares_club_with_creator(
|
||||||
|
cur, club_admin_profile_id: int, creator_profile_id: int
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
True, wenn club_admin_profile_id in mindestens einem Verein die Rolle club_admin hat und
|
||||||
|
creator_profile_id dort ebenfalls aktives Mitglied ist (z. B. Löschen fremder privater Übungen).
|
||||||
|
"""
|
||||||
|
if club_admin_profile_id == creator_profile_id:
|
||||||
|
return False
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1
|
||||||
|
FROM club_members cm_admin
|
||||||
|
INNER JOIN club_member_roles r
|
||||||
|
ON r.club_member_id = cm_admin.id AND r.role_code = 'club_admin'
|
||||||
|
INNER JOIN club_members cm_creator
|
||||||
|
ON cm_creator.club_id = cm_admin.club_id
|
||||||
|
AND cm_creator.profile_id = %s
|
||||||
|
AND cm_creator.status = 'active'
|
||||||
|
WHERE cm_admin.profile_id = %s AND cm_admin.status = 'active'
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(creator_profile_id, club_admin_profile_id),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def can_manage_club_org(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
|
||||||
|
"""Sparten/Gruppen/Struktur: Vereinsadmin oder Plattform-Admin."""
|
||||||
|
if is_platform_admin(global_role):
|
||||||
|
return True
|
||||||
|
return has_club_role(cur, profile_id, club_id, "club_admin")
|
||||||
|
|
||||||
|
|
||||||
|
def can_plan_in_club(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
|
||||||
|
"""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(
|
||||||
|
cur, profile_id, club_id, "club_admin", "trainer", "content_editor", "division_lead"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def memberships_with_roles(cur, profile_id: int, active_only: bool = True) -> List[Dict[str, Any]]:
|
||||||
|
status_filter = "AND cm.status = 'active'" if active_only else ""
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT c.id, c.name, c.abbreviation, c.status,
|
||||||
|
cm.status AS membership_status,
|
||||||
|
COALESCE(
|
||||||
|
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||||
|
ARRAY[]::varchar[]
|
||||||
|
) AS roles
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN clubs c ON c.id = cm.club_id
|
||||||
|
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s {status_filter}
|
||||||
|
GROUP BY c.id, c.name, c.abbreviation, c.status, cm.status
|
||||||
|
ORDER BY c.name
|
||||||
|
""",
|
||||||
|
(profile_id,),
|
||||||
|
)
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
d = dict(row)
|
||||||
|
roles = d.get("roles") or []
|
||||||
|
if hasattr(roles, "tolist"):
|
||||||
|
roles = roles.tolist()
|
||||||
|
d["roles"] = list(roles)
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def club_ids_for_profile_with_roles(cur, profile_id: int, *role_codes: str) -> Set[int]:
|
||||||
|
"""Vereins-IDs, in denen das Profil mindestens eine der Rollen hat."""
|
||||||
|
if not role_codes:
|
||||||
|
return set()
|
||||||
|
ph = ",".join(["%s"] * len(role_codes))
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT DISTINCT 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 IN ({ph})
|
||||||
|
""",
|
||||||
|
(profile_id, *role_codes),
|
||||||
|
)
|
||||||
|
return {int(r["club_id"]) for r in cur.fetchall() if r.get("club_id") is not None}
|
||||||
|
|
||||||
|
|
||||||
|
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
|
||||||
|
|
||||||
|
|
||||||
|
def assert_valid_governance_visibility(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
role: Optional[str],
|
||||||
|
visibility: str,
|
||||||
|
club_id: Optional[int],
|
||||||
|
) -> None:
|
||||||
|
"""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_superadmin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Superadmins dürfen offizielle Inhalte setzen",
|
||||||
|
)
|
||||||
|
if visibility == "club":
|
||||||
|
if club_id is None:
|
||||||
|
raise HTTPException(status_code=400, detail="club_id ist bei visibility=club erforderlich")
|
||||||
|
if is_platform_admin(role):
|
||||||
|
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=400, detail="Verein nicht gefunden")
|
||||||
|
else:
|
||||||
|
assert_club_member(cur, profile_id, club_id)
|
||||||
|
|
||||||
|
|
||||||
|
def library_content_visible_to_profile(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
visibility: str,
|
||||||
|
content_club_id: Optional[int],
|
||||||
|
created_by: Optional[int],
|
||||||
|
global_role: Optional[str],
|
||||||
|
) -> bool:
|
||||||
|
"""Leserechte wie Übungen für alle Objekte mit visibility/club_id/created_by (Bibliothek & Co.)."""
|
||||||
|
return exercise_visible_to_profile(
|
||||||
|
cur, profile_id, visibility, content_club_id, created_by, global_role
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def exercise_visible_to_profile(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
visibility: str,
|
||||||
|
exercise_club_id: Optional[int],
|
||||||
|
created_by: Optional[int],
|
||||||
|
global_role: Optional[str],
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
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 created_by is not None and int(created_by) == pid:
|
||||||
|
return True
|
||||||
|
if vis == "private":
|
||||||
|
return plat
|
||||||
|
if vis != "club":
|
||||||
|
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"
|
||||||
+16
-16
@@ -32,13 +32,13 @@ def wait_for_postgres(max_retries=30):
|
|||||||
try:
|
try:
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
conn.close()
|
conn.close()
|
||||||
print("✓ PostgreSQL ready")
|
print("[OK] PostgreSQL ready")
|
||||||
return True
|
return True
|
||||||
except OperationalError:
|
except OperationalError:
|
||||||
print(f" Waiting for PostgreSQL... (attempt {i}/{max_retries})")
|
print(f" Waiting for PostgreSQL... (attempt {i}/{max_retries})")
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
print(f"✗ PostgreSQL not ready after {max_retries} attempts")
|
print(f"[FAIL] PostgreSQL not ready after {max_retries} attempts")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def check_table_exists(table_name="profiles"):
|
def check_table_exists(table_name="profiles"):
|
||||||
@@ -71,10 +71,10 @@ def load_schema(schema_file="/app/schema.sql"):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
print("✓ Schema loaded from schema.sql")
|
print("[OK] Schema loaded from schema.sql")
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"✗ Error loading schema: {e}")
|
print(f"[FAIL] Error loading schema: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_profile_count():
|
def get_profile_count():
|
||||||
@@ -146,10 +146,10 @@ def apply_migration(filepath, filename):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
print(f" ✓ Applied: {filename}")
|
print(f" [OK] Applied: {filename}")
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ✗ Failed to apply {filename}: {e}")
|
print(f" [FAIL] Failed to apply {filename}: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def run_migrations(migrations_dir="/app/migrations"):
|
def run_migrations(migrations_dir="/app/migrations"):
|
||||||
@@ -158,7 +158,7 @@ def run_migrations(migrations_dir="/app/migrations"):
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
if not os.path.exists(migrations_dir):
|
if not os.path.exists(migrations_dir):
|
||||||
print("✓ No migrations directory found")
|
print("[OK] No migrations directory found")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Ensure migration tracking table exists
|
# Ensure migration tracking table exists
|
||||||
@@ -174,7 +174,7 @@ def run_migrations(migrations_dir="/app/migrations"):
|
|||||||
migration_files = [f for f in all_files if migration_pattern.match(os.path.basename(f))]
|
migration_files = [f for f in all_files if migration_pattern.match(os.path.basename(f))]
|
||||||
|
|
||||||
if not migration_files:
|
if not migration_files:
|
||||||
print("✓ No migration files found")
|
print("[OK] No migration files found")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Apply pending migrations
|
# Apply pending migrations
|
||||||
@@ -185,7 +185,7 @@ def run_migrations(migrations_dir="/app/migrations"):
|
|||||||
pending.append((filepath, filename))
|
pending.append((filepath, filename))
|
||||||
|
|
||||||
if not pending:
|
if not pending:
|
||||||
print(f"✓ All {len(applied)} migrations already applied")
|
print(f"[OK] All {len(applied)} migrations already applied")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
print(f" Found {len(pending)} pending migration(s)...")
|
print(f" Found {len(pending)} pending migration(s)...")
|
||||||
@@ -211,12 +211,12 @@ if __name__ == "__main__":
|
|||||||
if not load_schema():
|
if not load_schema():
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
print("✓ Schema already exists")
|
print("[OK] Schema already exists")
|
||||||
|
|
||||||
# Run migrations
|
# Run migrations
|
||||||
print("\nRunning database migrations...")
|
print("\nRunning database migrations...")
|
||||||
if not run_migrations():
|
if not run_migrations():
|
||||||
print("✗ Migration failed")
|
print("[FAIL] Migration failed")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Check for migration
|
# Check for migration
|
||||||
@@ -232,14 +232,14 @@ if __name__ == "__main__":
|
|||||||
from migrate_to_postgres import main as migrate
|
from migrate_to_postgres import main as migrate
|
||||||
migrate()
|
migrate()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"✗ Migration failed: {e}")
|
print(f"[FAIL] Migration failed: {e}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
elif os.path.exists(sqlite_db) and profile_count > 0:
|
elif os.path.exists(sqlite_db) and profile_count > 0:
|
||||||
print(f"⚠ SQLite DB exists but PostgreSQL already has {profile_count} profiles")
|
print(f"[WARN] SQLite DB exists but PostgreSQL already has {profile_count} profiles")
|
||||||
print(" Skipping migration (already migrated)")
|
print(" Skipping migration (already migrated)")
|
||||||
elif not os.path.exists(sqlite_db):
|
elif not os.path.exists(sqlite_db):
|
||||||
print("✓ No SQLite database found (fresh install or already migrated)")
|
print("[OK] No SQLite database found (fresh install or already migrated)")
|
||||||
else:
|
else:
|
||||||
print("✓ No migration needed")
|
print("[OK] No migration needed")
|
||||||
|
|
||||||
print("\n✓ Database initialization complete")
|
print("\n[OK] Database initialization complete")
|
||||||
@@ -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),
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Hilfen für direkte Python-Aufrufe von FastAPI-Route-Handlern (ohne Request-Kontext)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def unwrap_query_default(value: Any) -> Any:
|
||||||
|
"""
|
||||||
|
Parameter mit Annotation ``= Query(default=…)`` sind im Funktionskörper ``fastapi.params.Query``-Instanzen,
|
||||||
|
solange FastAPI sie nicht durch echte Werte ersetzt hat (interne Aufrufe, Aggregat-Endpunkte).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from fastapi.params import Query
|
||||||
|
except ImportError:
|
||||||
|
return value
|
||||||
|
return value.default if isinstance(value, Query) else value
|
||||||
+71
-16
@@ -6,7 +6,7 @@ Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
@@ -18,32 +18,56 @@ from slowapi.errors import RateLimitExceeded
|
|||||||
|
|
||||||
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
|
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
|
||||||
|
|
||||||
|
|
||||||
|
def _is_production_environment() -> bool:
|
||||||
|
return os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod")
|
||||||
|
|
||||||
|
|
||||||
|
def _public_openapi_enabled() -> bool:
|
||||||
|
return os.getenv("PUBLIC_OPENAPI", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def _health_ready_public_detail_enabled() -> bool:
|
||||||
|
"""In Prod standardmäßig keine Tabellen-/Migrations-Details (Information Disclosure)."""
|
||||||
|
return os.getenv("HEALTH_READY_PUBLIC_DETAIL", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
# Run database migrations before API start — halbes Schema ist schlimmer als kein Start
|
# Run database migrations before API start — halbes Schema ist schlimmer als kein Start
|
||||||
|
# (run_migrations: pending *.sql in einer Transaktion pro Datei, Buchführung schema_migrations)
|
||||||
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
|
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
|
||||||
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
|
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
|
||||||
print("⚠ SKIP_DB_MIGRATE=1 — Migrationen wurden übersprungen (nur für Entwicklung ohne DB)")
|
print("[SKIP_DB_MIGRATE] Migrationen uebersprungen (nur fuer Entwicklung ohne DB)")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
import run_migrations
|
import run_migrations
|
||||||
|
|
||||||
rc = run_migrations.main()
|
rc = run_migrations.main()
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
print(f"✗ Datenbank-Migration fehlgeschlagen (Exit-Code {rc}). Start abgebrochen.")
|
print(f"[FAIL] Datenbank-Migration fehlgeschlagen (Exit-Code {rc}). Start abgebrochen.")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
print("✓ Database migrations completed")
|
print("[OK] Database migrations completed")
|
||||||
except SystemExit:
|
except SystemExit:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"✗ Migration-Laufzeitfehler: {e}")
|
print(f"[FAIL] Migration-Laufzeitfehler: {e}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
from routers.auth import limiter as auth_rate_limiter
|
from routers.auth import limiter as auth_rate_limiter
|
||||||
|
|
||||||
|
# OpenAPI: in Produktion standardmäßig aus (Schema nicht öffentlich). Notfall: PUBLIC_OPENAPI=1
|
||||||
|
_expose_docs = (not _is_production_environment()) or _public_openapi_enabled()
|
||||||
|
_openapi_url = "/openapi.json" if _expose_docs else None
|
||||||
|
_docs_url = "/docs" if _expose_docs else None
|
||||||
|
_redoc_url = "/redoc" if _expose_docs else None
|
||||||
|
|
||||||
# Initialize FastAPI app
|
# Initialize FastAPI app
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Shinkan Jinkendo API",
|
title="Shinkan Jinkendo API",
|
||||||
description="Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung",
|
description="Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung",
|
||||||
version=APP_VERSION
|
version=APP_VERSION,
|
||||||
|
openapi_url=_openapi_url,
|
||||||
|
docs_url=_docs_url,
|
||||||
|
redoc_url=_redoc_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
# SlowAPI: Rate Limits auf /api/auth/* (Decorator in routers/auth.py)
|
# SlowAPI: Rate Limits auf /api/auth/* (Decorator in routers/auth.py)
|
||||||
@@ -58,11 +82,17 @@ app.add_middleware(
|
|||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=ALLOWED_ORIGINS,
|
allow_origins=ALLOWED_ORIGINS,
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
||||||
allow_headers=["*"],
|
allow_headers=["Content-Type", "X-Auth-Token", "X-Active-Club-Id"],
|
||||||
)
|
)
|
||||||
|
|
||||||
# TODO: Initialize Database with migrations
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def add_api_security_headers(request: Request, call_next):
|
||||||
|
"""Konsistente Basis-Header auch für rein JSON-Responses (MIME-Sniffing)."""
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||||
|
return response
|
||||||
|
|
||||||
# Version Endpoint (public, no auth)
|
# Version Endpoint (public, no auth)
|
||||||
@app.get("/api/version")
|
@app.get("/api/version")
|
||||||
@@ -99,6 +129,8 @@ def health_ready():
|
|||||||
"skill_categories",
|
"skill_categories",
|
||||||
"maturity_models",
|
"maturity_models",
|
||||||
"sessions",
|
"sessions",
|
||||||
|
"club_members",
|
||||||
|
"club_member_roles",
|
||||||
)
|
)
|
||||||
tables: dict = {}
|
tables: dict = {}
|
||||||
err: Optional[str] = None
|
err: Optional[str] = None
|
||||||
@@ -130,7 +162,7 @@ def health_ready():
|
|||||||
migration_count = 0
|
migration_count = 0
|
||||||
|
|
||||||
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
|
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
|
||||||
return {
|
body = {
|
||||||
"status": "ready" if complete else "degraded",
|
"status": "ready" if complete else "degraded",
|
||||||
"database": err is None,
|
"database": err is None,
|
||||||
"detail": err,
|
"detail": err,
|
||||||
@@ -138,40 +170,63 @@ def health_ready():
|
|||||||
"tables": tables,
|
"tables": tables,
|
||||||
"schema_migrations_count": migration_count,
|
"schema_migrations_count": migration_count,
|
||||||
}
|
}
|
||||||
|
if _is_production_environment() and not _health_ready_public_detail_enabled():
|
||||||
|
return {
|
||||||
|
"status": body["status"],
|
||||||
|
"database": body["database"],
|
||||||
|
"schema_complete": body["schema_complete"],
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
# Root Endpoint
|
# Root Endpoint
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def read_root():
|
def read_root():
|
||||||
"""Root endpoint - API info"""
|
"""Root endpoint - API info"""
|
||||||
return {
|
out = {
|
||||||
"app": "Shinkan Jinkendo API",
|
"app": "Shinkan Jinkendo API",
|
||||||
"version": APP_VERSION,
|
"version": APP_VERSION,
|
||||||
"docs": "/docs",
|
"health": "/health",
|
||||||
"health": "/health"
|
|
||||||
}
|
}
|
||||||
|
if _expose_docs:
|
||||||
|
out["docs"] = "/docs"
|
||||||
|
return out
|
||||||
|
|
||||||
# Register routers
|
# Register routers
|
||||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
|
||||||
|
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(profiles.router)
|
app.include_router(profiles.router)
|
||||||
app.include_router(exercises.router)
|
app.include_router(exercises.router)
|
||||||
app.include_router(exercise_progression_graphs.router)
|
app.include_router(exercise_progression_graphs.router)
|
||||||
app.include_router(clubs.router)
|
app.include_router(clubs.router)
|
||||||
|
app.include_router(club_memberships.router)
|
||||||
|
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(skills.router)
|
||||||
app.include_router(training_planning.router)
|
app.include_router(training_planning.router)
|
||||||
|
app.include_router(dashboard.router)
|
||||||
|
app.include_router(training_modules.router)
|
||||||
app.include_router(training_framework_programs.router)
|
app.include_router(training_framework_programs.router)
|
||||||
app.include_router(catalogs.router)
|
app.include_router(catalogs.router)
|
||||||
app.include_router(maturity_models.router)
|
app.include_router(maturity_models.router)
|
||||||
app.include_router(matrix_stack_bundle.router)
|
app.include_router(matrix_stack_bundle.router)
|
||||||
app.include_router(import_wiki.router)
|
app.include_router(import_wiki.router)
|
||||||
app.include_router(import_wiki_admin.router)
|
app.include_router(import_wiki_admin.router)
|
||||||
|
app.include_router(legal_documents.router)
|
||||||
|
app.include_router(content_reports.router)
|
||||||
|
|
||||||
# Lokale Medien (Übungen-Uploads) unter MEDIA_ROOT, ausliefern unter /media/...
|
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||||
|
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
|
||||||
|
# Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/
|
||||||
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
||||||
Path(_media_dir).mkdir(parents=True, exist_ok=True)
|
Path(_media_dir).mkdir(parents=True, exist_ok=True)
|
||||||
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
|
if os.getenv("ALLOW_PUBLIC_MEDIA_STATIC", "").strip().lower() in ("1", "true", "yes"):
|
||||||
|
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
"""
|
||||||
|
Medien-Lebenszyklus (Papierkorb) — siehe MEDIA_ASSETS_AND_ARCHIVE_SPEC.md §5.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from club_tenancy import can_manage_club_org, is_platform_admin, is_superadmin
|
||||||
|
from db import r2d
|
||||||
|
from media_storage import get_effective_media_root, path_under_media_root
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
LC_ACTIVE = "active"
|
||||||
|
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")))
|
||||||
|
# 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 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
|
||||||
|
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 == "club":
|
||||||
|
cid = asset.get("club_id")
|
||||||
|
if cid is None:
|
||||||
|
raise HTTPException(status_code=403, detail="Ungültiges Vereins-Medium")
|
||||||
|
if can_manage_club_org(cur, profile_id, int(cid), role):
|
||||||
|
return
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Vereinsorganisation/Plattform-Admin")
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||||
|
|
||||||
|
|
||||||
|
def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
|
||||||
|
"""
|
||||||
|
Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads.
|
||||||
|
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
|
||||||
|
uid = asset.get("uploaded_by_profile_id")
|
||||||
|
cid = asset.get("club_id")
|
||||||
|
pid = int(tenant.profile_id)
|
||||||
|
if vis == "private":
|
||||||
|
if uid is not None and int(uid) == pid:
|
||||||
|
return
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur eigene private Medien dürfen in den Papierkorb",
|
||||||
|
)
|
||||||
|
if vis == "club":
|
||||||
|
if cid is not None and can_manage_club_org(cur, pid, int(cid), role_raw):
|
||||||
|
return
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen",
|
||||||
|
)
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||||
|
|
||||||
|
|
||||||
|
def assert_can_edit_media_asset_metadata(cur: Any, tenant: Any, asset: dict) -> None:
|
||||||
|
"""PATCH Metadaten / Sichtbarkeit — gleiche Stufen wie Lifecycle (ohne Papierkorb)."""
|
||||||
|
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
|
||||||
|
|
||||||
|
|
||||||
|
def superadmin_force_lifecycle_state(cur: Any, conn: Any, asset_id: int, target: str) -> dict:
|
||||||
|
"""Nur Superadmin: Zustand direkt setzen."""
|
||||||
|
if target not in (LC_ACTIVE, LC_TRASH_SOFT, LC_TRASH_HIDDEN):
|
||||||
|
raise HTTPException(status_code=400, detail="Ungültiger Ziel-Lifecycle")
|
||||||
|
if target == LC_ACTIVE:
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, updated_at = NOW(),
|
||||||
|
trash_soft_at = NULL, trash_hidden_at = NULL, purge_after_at = NULL
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id, lifecycle_state""",
|
||||||
|
(LC_ACTIVE, asset_id),
|
||||||
|
)
|
||||||
|
elif target == LC_TRASH_SOFT:
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, trash_soft_at = COALESCE(trash_soft_at, NOW()),
|
||||||
|
trash_hidden_at = NULL, purge_after_at = NULL, updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id, lifecycle_state, trash_soft_at""",
|
||||||
|
(LC_TRASH_SOFT, asset_id),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
pa = datetime.now(timezone.utc) + timedelta(days=HIDDEN_TO_PURGE_DAYS)
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, trash_hidden_at = NOW(),
|
||||||
|
purge_after_at = %s, updated_at = NOW(),
|
||||||
|
trash_soft_at = COALESCE(trash_soft_at, NOW())
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id, lifecycle_state, trash_hidden_at, purge_after_at""",
|
||||||
|
(LC_TRASH_HIDDEN, pa, asset_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||||
|
conn.commit()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
def superadmin_hard_delete_media_asset(cur: Any, conn: Any, asset_id: int) -> bool:
|
||||||
|
"""Nur Superadmin: Zeile + Datei unabhängig vom Lifecycle entfernen."""
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, storage_key FROM media_assets WHERE id = %s",
|
||||||
|
(asset_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
asset = r2d(row)
|
||||||
|
cur.execute("DELETE FROM exercise_media WHERE media_asset_id = %s", (asset_id,))
|
||||||
|
purge_asset_filesystem(cur, asset)
|
||||||
|
cur.execute("DELETE FROM media_assets WHERE id = %s", (asset_id,))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_media_asset_row(cur: Any, asset_id: int) -> Optional[dict]:
|
||||||
|
cur.execute(
|
||||||
|
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
|
||||||
|
storage_key, storage_backend, trash_soft_at, trash_hidden_at, purge_after_at
|
||||||
|
FROM media_assets WHERE id = %s""",
|
||||||
|
(asset_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return r2d(row) if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def purge_asset_filesystem(cur: Any, asset: dict) -> None:
|
||||||
|
sk = asset.get("storage_key")
|
||||||
|
if not sk:
|
||||||
|
return
|
||||||
|
root = get_effective_media_root(cur)
|
||||||
|
p = path_under_media_root(root, str(sk))
|
||||||
|
if p and p.is_file():
|
||||||
|
try:
|
||||||
|
p.unlink()
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning("Physische Medien-Löschung fehlgeschlagen: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
def purge_media_asset(cur: Any, conn: Any, asset_id: int) -> bool:
|
||||||
|
"""Löscht Verknüpfungen, Datei und DB-Zeile. Returns True wenn ausgeführt."""
|
||||||
|
cur.execute(
|
||||||
|
"""SELECT id, storage_key FROM media_assets
|
||||||
|
WHERE id = %s AND lifecycle_state = %s""",
|
||||||
|
(asset_id, LC_TRASH_HIDDEN),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
asset = r2d(row)
|
||||||
|
cur.execute("DELETE FROM exercise_media WHERE media_asset_id = %s", (asset_id,))
|
||||||
|
purge_asset_filesystem(cur, asset)
|
||||||
|
cur.execute("DELETE FROM media_assets WHERE id = %s", (asset_id,))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def transition_to_trash_soft(cur: Any, conn: Any, asset_id: int) -> dict:
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, trash_soft_at = NOW(), updated_at = NOW(),
|
||||||
|
trash_hidden_at = NULL, purge_after_at = NULL
|
||||||
|
WHERE id = %s AND lifecycle_state = %s
|
||||||
|
RETURNING id, lifecycle_state, trash_soft_at""",
|
||||||
|
(LC_TRASH_SOFT, asset_id, LC_ACTIVE),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=400, detail="Nur aktive Medien können in den Papierkorb")
|
||||||
|
conn.commit()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
def reactivate_media_asset_from_trash(cur: Any, conn: Any, asset_id: int) -> dict:
|
||||||
|
"""
|
||||||
|
Stufe 1 oder 2 → wieder aktiv (z. B. erneuter Upload derselben Datei / explizite Wiederherstellung).
|
||||||
|
"""
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, updated_at = NOW(),
|
||||||
|
trash_soft_at = NULL, trash_hidden_at = NULL, purge_after_at = NULL
|
||||||
|
WHERE id = %s AND lifecycle_state IN (%s, %s)
|
||||||
|
RETURNING id, lifecycle_state""",
|
||||||
|
(LC_ACTIVE, asset_id, LC_TRASH_SOFT, LC_TRASH_HIDDEN),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Nur Medien aus dem Papierkorb (Stufe 1 oder 2) können reaktiviert werden",
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
def transition_to_trash_hidden(cur: Any, conn: Any, asset_id: int, *, set_purge_after: Optional[datetime] = None) -> dict:
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
if set_purge_after is None:
|
||||||
|
set_purge_after = now + timedelta(days=HIDDEN_TO_PURGE_DAYS)
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, trash_hidden_at = NOW(), updated_at = NOW(),
|
||||||
|
purge_after_at = %s
|
||||||
|
WHERE id = %s AND lifecycle_state IN (%s, %s)
|
||||||
|
RETURNING id, lifecycle_state, trash_hidden_at, purge_after_at""",
|
||||||
|
(LC_TRASH_HIDDEN, set_purge_after, asset_id, LC_ACTIVE, LC_TRASH_SOFT),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Nur aktive oder Papierkorb-Stufe-1 Medien können ausgeblendet werden",
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
def transition_recover_from_hidden(cur: Any, conn: Any, asset_id: int) -> dict:
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET lifecycle_state = %s, updated_at = NOW(),
|
||||||
|
trash_hidden_at = NULL, purge_after_at = NULL
|
||||||
|
WHERE id = %s AND lifecycle_state = %s
|
||||||
|
RETURNING id, lifecycle_state, trash_soft_at""",
|
||||||
|
(LC_TRASH_SOFT, asset_id, LC_TRASH_HIDDEN),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=400, detail="Nur ausgeblendete Medien können zurückgestuft werden")
|
||||||
|
conn.commit()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
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(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
n_hidden = len(cur.fetchall())
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""SELECT id FROM media_assets
|
||||||
|
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()]
|
||||||
|
purged = 0
|
||||||
|
for aid in purge_ids:
|
||||||
|
if purge_media_asset(cur, conn, int(aid)):
|
||||||
|
purged += 1
|
||||||
|
|
||||||
|
return {"moved_to_hidden": n_hidden, "purged": purged}
|
||||||
@@ -0,0 +1,412 @@
|
|||||||
|
"""P-06: Zentrale Rechte-Policy fuer Medien-Uploads und Promotionen.
|
||||||
|
|
||||||
|
Konservative Erstannahmen (p06-v1-conservative):
|
||||||
|
- Alle Uploads (inkl. private) erfordern vollstaendige Erklaerung
|
||||||
|
- Personenfragen bei allen Sichtbarkeiten Pflicht zu beantworten
|
||||||
|
- Promotion zu hoeherem Niveau erfordert neue Erklaerung
|
||||||
|
- Altmedien ('legacy_unreviewed') duerfen nicht promoted werden
|
||||||
|
|
||||||
|
VORLAEUTIG: Juristische Validierung der Felder und Texte steht aus.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json as _json
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
DECLARATION_VERSION = "p06-v1-conservative"
|
||||||
|
|
||||||
|
# Sichtbarkeits-Hierarchie: private(1) < club(2) < official(3)
|
||||||
|
VISIBILITY_LEVELS: dict[str, int] = {
|
||||||
|
"private": 1,
|
||||||
|
"club": 2,
|
||||||
|
"official": 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def visibility_level(vis: str) -> int:
|
||||||
|
return VISIBILITY_LEVELS.get((vis or "").strip().lower(), 0)
|
||||||
|
|
||||||
|
|
||||||
|
def rights_covers_target(declared_for: Optional[str], target_vis: str) -> bool:
|
||||||
|
"""True wenn die vorhandene Erklaerung die Ziel-Sichtbarkeit abdeckt."""
|
||||||
|
if not declared_for:
|
||||||
|
return False
|
||||||
|
return visibility_level(declared_for) >= visibility_level(target_vis)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Validierung einer eingehenden Erklaerung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def validate_rights_declaration(decl: dict[str, Any], target_visibility: str) -> None:
|
||||||
|
"""Pruefen ob alle Pflichtfelder der konservativen Erstannahme vorliegen.
|
||||||
|
|
||||||
|
Wirft HTTPException 400 mit maschinenlesbarem code bei Verstoss.
|
||||||
|
Gilt fuer alle Sichtbarkeiten (private/club/official) identisch.
|
||||||
|
"""
|
||||||
|
# 1. rights_holder_confirmed ist immer Pflicht
|
||||||
|
if not decl.get("rights_holder_confirmed"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Bitte bestaetigen, dass du die erforderlichen Rechte an diesem Medium besitzt."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. contains_identifiable_persons muss explizit beantwortet sein
|
||||||
|
if decl.get("contains_identifiable_persons") is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": "Bitte angeben, ob erkennbare Personen abgebildet sind.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Wenn Personen vorhanden: Einwilligung Pflicht
|
||||||
|
if decl.get("contains_identifiable_persons") is True:
|
||||||
|
if not decl.get("person_consent_confirmed"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "PERSON_CONSENT_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Bitte bestaetigen, dass die Einwilligungen aller erkennbaren Personen vorliegen."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. contains_minors muss explizit beantwortet sein
|
||||||
|
if decl.get("contains_minors") is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": "Bitte angeben, ob Minderjaehrige abgebildet sind.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Wenn Minderjaehrige: Elterneinwilligung Pflicht
|
||||||
|
if decl.get("contains_minors") is True:
|
||||||
|
if not decl.get("parental_consent_confirmed"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "PARENTAL_CONSENT_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Bitte bestaetigen, dass die Einwilligungen der Sorgeberechtigten vorliegen."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. contains_music muss explizit beantwortet sein
|
||||||
|
if decl.get("contains_music") is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": "Bitte angeben, ob das Medium Musik enthaelt.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 7. Wenn Musik: Musikrechte Pflicht
|
||||||
|
if decl.get("contains_music") is True:
|
||||||
|
if not decl.get("music_rights_confirmed"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "MUSIC_RIGHTS_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Bitte bestaetigen, dass die erforderlichen Musikrechte vorliegen."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 8. contains_third_party_content muss explizit beantwortet sein
|
||||||
|
if decl.get("contains_third_party_content") is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": "Bitte angeben, ob fremde geschuetzte Inhalte (Logos, Grafiken etc.) enthalten sind.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 9. Wenn Fremdmaterial: Rechte Pflicht
|
||||||
|
if decl.get("contains_third_party_content") is True:
|
||||||
|
if not decl.get("third_party_rights_confirmed"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "THIRD_PARTY_RIGHTS_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Bitte bestaetigen, dass die Rechte an allen enthaltenen Fremdmaterialien vorliegen."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Pruefen ob vorhandene Erklaerung Zielsichtbarkeit abdeckt
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def check_rights_coverage(cur: Any, asset_id: int, target_visibility: str) -> str:
|
||||||
|
"""Status der Rechteabdeckung fuer ein Asset und eine Zielsichtbarkeit.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
'ok' - vorhandene Erklaerung reicht aus
|
||||||
|
'legacy' - Altmedium ohne Erklaerung (legacy_unreviewed)
|
||||||
|
'blocked' - durch Admin gesperrt
|
||||||
|
'no_declaration' - neues Medium ohne Erklaerung (sollte nicht vorkommen)
|
||||||
|
|
||||||
|
Hinweis: Eine P-06-Erklaerung beschreibt den Inhalt (Rechteinhaber, Personen, Musik etc.)
|
||||||
|
und ist sichtbarkeitsunabhaengig. rights_status='declared' gilt daher fuer alle
|
||||||
|
Sichtbarkeits-Stufen ohne Levelvergleich.
|
||||||
|
"""
|
||||||
|
cur.execute(
|
||||||
|
"SELECT rights_status FROM media_assets WHERE id = %s",
|
||||||
|
(asset_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return "no_declaration"
|
||||||
|
|
||||||
|
rs = (row[0] if not hasattr(row, "keys") else row["rights_status"] or "").strip().lower()
|
||||||
|
|
||||||
|
if rs == "blocked":
|
||||||
|
return "blocked"
|
||||||
|
if rs == "legacy_unreviewed":
|
||||||
|
return "legacy"
|
||||||
|
if rs == "declared":
|
||||||
|
return "ok"
|
||||||
|
return "no_declaration"
|
||||||
|
|
||||||
|
|
||||||
|
def assert_rights_for_promotion(cur: Any, asset_id: int, target_visibility: str) -> None:
|
||||||
|
"""Wirft HTTPException wenn das Asset keine gueltige Erklaerung fuer target_visibility hat."""
|
||||||
|
status = check_rights_coverage(cur, asset_id, target_visibility)
|
||||||
|
if status == "ok":
|
||||||
|
return
|
||||||
|
if status == "legacy":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "LEGACY_REDECLARATION_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Dieses Medium wurde vor Einfuehrung der Einwilligungspflicht hochgeladen. "
|
||||||
|
"Bitte eine Rechterklaerung nachreichen, bevor die Sichtbarkeit erhoeht wird."
|
||||||
|
),
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status == "blocked":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_BLOCKED",
|
||||||
|
"message": "Dieses Medium ist durch einen Administrator gesperrt.",
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
# no_declaration (neues Medium ohne Erklaerung)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_DECLARATION_REQUIRED",
|
||||||
|
"message": "Fuer dieses Medium liegt keine Rechterklaerung vor.",
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assert_rights_for_exercise_link(cur: Any, asset_id: int, exercise_visibility: str) -> None:
|
||||||
|
"""Pruefen ob das Asset in eine Uebung mit dieser Sichtbarkeit eingebunden werden darf."""
|
||||||
|
status = check_rights_coverage(cur, asset_id, exercise_visibility)
|
||||||
|
if status == "ok":
|
||||||
|
return
|
||||||
|
if status == "legacy" and exercise_visibility == "private":
|
||||||
|
# Altmedien duerfen in private Uebungen eingebunden bleiben (kein Upgrade-Risiko)
|
||||||
|
return
|
||||||
|
if status == "legacy":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "LEGACY_REDECLARATION_REQUIRED",
|
||||||
|
"message": (
|
||||||
|
"Das gewahlte Archiv-Medium hat noch keine Rechterklaerung nach neuem Standard. "
|
||||||
|
"Bitte zuerst eine Erklaerung fuer dieses Medium abgeben."
|
||||||
|
),
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status == "insufficient":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_SCOPE_INSUFFICIENT",
|
||||||
|
"message": (
|
||||||
|
f"Das Archiv-Medium hat keine Erklaerung fuer Sichtbarkeit '{exercise_visibility}'. "
|
||||||
|
"Bitte zuerst eine neue Erklaerung fuer dieses Medium abgeben."
|
||||||
|
),
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status == "blocked":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail={
|
||||||
|
"code": "RIGHTS_BLOCKED",
|
||||||
|
"message": "Dieses Medium ist gesperrt und kann nicht verwendet werden.",
|
||||||
|
"asset_id": asset_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Declaration-Log schreiben + Schnellfelder aktualisieren
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _clean_context(val: Any) -> Optional[str]:
|
||||||
|
"""Leere Strings → None, sonst auf 2000 Zeichen kuerzen."""
|
||||||
|
s = (val or "").strip()
|
||||||
|
return s[:2000] if s else None
|
||||||
|
|
||||||
|
|
||||||
|
def write_rights_declaration(
|
||||||
|
cur: Any,
|
||||||
|
asset_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
action_type: str,
|
||||||
|
target_visibility: str,
|
||||||
|
decl: dict[str, Any],
|
||||||
|
) -> int:
|
||||||
|
"""Schreibt einen neuen Eintrag in media_asset_rights_declarations (append-only).
|
||||||
|
|
||||||
|
Returns: id des neuen Eintrags
|
||||||
|
"""
|
||||||
|
cur.execute(
|
||||||
|
"""INSERT INTO media_asset_rights_declarations (
|
||||||
|
media_asset_id, declared_by_profile_id, action_type, target_visibility,
|
||||||
|
declaration_version,
|
||||||
|
rights_holder_confirmed,
|
||||||
|
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
|
||||||
|
contains_minors, parental_consent_confirmed, parental_consent_context,
|
||||||
|
contains_music, music_rights_confirmed, music_rights_context,
|
||||||
|
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id""",
|
||||||
|
(
|
||||||
|
asset_id,
|
||||||
|
profile_id,
|
||||||
|
action_type,
|
||||||
|
target_visibility,
|
||||||
|
DECLARATION_VERSION,
|
||||||
|
bool(decl.get("rights_holder_confirmed")),
|
||||||
|
decl.get("contains_identifiable_persons"),
|
||||||
|
decl.get("person_consent_confirmed"),
|
||||||
|
_clean_context(decl.get("person_consent_context")),
|
||||||
|
decl.get("contains_minors"),
|
||||||
|
decl.get("parental_consent_confirmed"),
|
||||||
|
_clean_context(decl.get("parental_consent_context")),
|
||||||
|
decl.get("contains_music"),
|
||||||
|
decl.get("music_rights_confirmed"),
|
||||||
|
_clean_context(decl.get("music_rights_context")),
|
||||||
|
decl.get("contains_third_party_content"),
|
||||||
|
decl.get("third_party_rights_confirmed"),
|
||||||
|
_clean_context(decl.get("third_party_rights_context")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if hasattr(row, "keys"):
|
||||||
|
return int(row["id"])
|
||||||
|
return int(row[0])
|
||||||
|
|
||||||
|
|
||||||
|
def write_audit_log_entry(
|
||||||
|
cur: Any,
|
||||||
|
asset_id: int,
|
||||||
|
acting_profile_id: Optional[int],
|
||||||
|
event_type: str,
|
||||||
|
old_values: dict,
|
||||||
|
new_values: dict,
|
||||||
|
) -> None:
|
||||||
|
"""Schreibt einen Eintrag in media_asset_audit_log (append-only)."""
|
||||||
|
cur.execute(
|
||||||
|
"""INSERT INTO media_asset_audit_log
|
||||||
|
(media_asset_id, acting_profile_id, event_type, old_values, new_values)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)""",
|
||||||
|
(
|
||||||
|
asset_id,
|
||||||
|
acting_profile_id,
|
||||||
|
event_type,
|
||||||
|
_json.dumps(old_values, default=str),
|
||||||
|
_json.dumps(new_values, default=str),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def write_rights_correction_declaration(
|
||||||
|
cur: Any,
|
||||||
|
asset_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
target_visibility: str,
|
||||||
|
decl: dict[str, Any],
|
||||||
|
correction_note: Optional[str],
|
||||||
|
) -> int:
|
||||||
|
"""Schreibt eine Korrektur-Deklaration (action_type='correction', append-only)."""
|
||||||
|
cur.execute(
|
||||||
|
"""INSERT INTO media_asset_rights_declarations (
|
||||||
|
media_asset_id, declared_by_profile_id, action_type, target_visibility,
|
||||||
|
declaration_version,
|
||||||
|
rights_holder_confirmed,
|
||||||
|
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
|
||||||
|
contains_minors, parental_consent_confirmed, parental_consent_context,
|
||||||
|
contains_music, music_rights_confirmed, music_rights_context,
|
||||||
|
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context,
|
||||||
|
correction_note
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id""",
|
||||||
|
(
|
||||||
|
asset_id,
|
||||||
|
profile_id,
|
||||||
|
"correction",
|
||||||
|
target_visibility,
|
||||||
|
DECLARATION_VERSION,
|
||||||
|
bool(decl.get("rights_holder_confirmed")),
|
||||||
|
decl.get("contains_identifiable_persons"),
|
||||||
|
decl.get("person_consent_confirmed"),
|
||||||
|
_clean_context(decl.get("person_consent_context")),
|
||||||
|
decl.get("contains_minors"),
|
||||||
|
decl.get("parental_consent_confirmed"),
|
||||||
|
_clean_context(decl.get("parental_consent_context")),
|
||||||
|
decl.get("contains_music"),
|
||||||
|
decl.get("music_rights_confirmed"),
|
||||||
|
_clean_context(decl.get("music_rights_context")),
|
||||||
|
decl.get("contains_third_party_content"),
|
||||||
|
decl.get("third_party_rights_confirmed"),
|
||||||
|
_clean_context(decl.get("third_party_rights_context")),
|
||||||
|
_clean_context(correction_note),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if hasattr(row, "keys"):
|
||||||
|
return int(row["id"])
|
||||||
|
return int(row[0])
|
||||||
|
|
||||||
|
|
||||||
|
def update_rights_quick_fields(cur: Any, asset_id: int, target_visibility: str) -> None:
|
||||||
|
"""Setzt die Schnellfelder in media_assets nach erfolgreicher Deklaration."""
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE media_assets
|
||||||
|
SET rights_status = 'declared',
|
||||||
|
rights_declared_for_visibility = %s,
|
||||||
|
rights_declared_at = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = %s""",
|
||||||
|
(target_visibility, asset_id),
|
||||||
|
)
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
"""Effektives Medien-Wurzelverzeichnis (MEDIA_ROOT + Superadmin-relativer Pfad). Siehe MEDIA_ASSETS_AND_ARCHIVE_SPEC.md §7.1."""
|
||||||
|
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")))
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_local_relative_root(raw: str) -> str:
|
||||||
|
s = (raw or "").strip().replace("\\", "/")
|
||||||
|
s = s.strip("/")
|
||||||
|
if not s:
|
||||||
|
return ""
|
||||||
|
if ".." in s.split("/"):
|
||||||
|
raise ValueError("Pfad darf nicht '..' enthalten")
|
||||||
|
if s.startswith("/"):
|
||||||
|
raise ValueError("Nur relativer Pfad erlaubt")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def get_effective_media_root(cur: Any) -> Path:
|
||||||
|
"""
|
||||||
|
MEDIA_ROOT aus ENV mit optionalem local_relative_root aus platform_media_storage (id=1).
|
||||||
|
"""
|
||||||
|
base = _default_media_root().resolve()
|
||||||
|
rel = ""
|
||||||
|
try:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT local_relative_root FROM platform_media_storage WHERE id = 1",
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is not None:
|
||||||
|
v = row["local_relative_root"] if isinstance(row, dict) else row[0]
|
||||||
|
rel = normalize_local_relative_root(str(v or ""))
|
||||||
|
except Exception:
|
||||||
|
rel = ""
|
||||||
|
if not rel:
|
||||||
|
return base
|
||||||
|
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("/")
|
||||||
|
if not key or ".." in key.split("/"):
|
||||||
|
return None
|
||||||
|
p = (media_root / key).resolve()
|
||||||
|
try:
|
||||||
|
p.relative_to(media_root.resolve())
|
||||||
|
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,119 @@
|
|||||||
|
-- Migration 039: Vereins-Mitgliedschaft, Rollen pro Verein, aktiver Vereinskontext (Multi-Tenancy Phase 1)
|
||||||
|
-- Erstellt: 2026-05-05
|
||||||
|
|
||||||
|
-- Mitgliedschaft Profil ↔ Verein
|
||||||
|
CREATE TABLE club_members (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
club_id INT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
UNIQUE(profile_id, club_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_club_members_profile ON club_members(profile_id);
|
||||||
|
CREATE INDEX idx_club_members_club ON club_members(club_id);
|
||||||
|
CREATE INDEX idx_club_members_status ON club_members(status);
|
||||||
|
|
||||||
|
-- Rollen pro Mitgliedschaft (role_code: club_admin, trainer, division_lead, content_editor)
|
||||||
|
CREATE TABLE club_member_roles (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
club_member_id INT NOT NULL REFERENCES club_members(id) ON DELETE CASCADE,
|
||||||
|
role_code VARCHAR(50) NOT NULL,
|
||||||
|
division_id INT REFERENCES divisions(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
UNIQUE (club_member_id, role_code)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_club_member_roles_member ON club_member_roles(club_member_id);
|
||||||
|
CREATE INDEX idx_club_member_roles_code ON club_member_roles(role_code);
|
||||||
|
|
||||||
|
-- Hauptverwalter:in (fachliche Referenz; Rechte über club_member_roles.club_admin)
|
||||||
|
ALTER TABLE clubs ADD COLUMN IF NOT EXISTS primary_admin_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_clubs_primary_admin ON clubs(primary_admin_profile_id);
|
||||||
|
|
||||||
|
-- Persistenz gewählter aktiver Verein (UI); Request-Header kann überschreiben
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS active_club_id INT REFERENCES clubs(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_profiles_active_club ON profiles(active_club_id);
|
||||||
|
|
||||||
|
-- ── Backfill: Trainer/Co-Trainer aus Trainingsgruppen → Mitgliedschaft + Rolle trainer
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
SELECT DISTINCT t.trainer_id, t.club_id, 'active'
|
||||||
|
FROM training_groups t
|
||||||
|
WHERE t.trainer_id IS NOT NULL
|
||||||
|
ON CONFLICT (profile_id, club_id) DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
SELECT DISTINCT elem::int, x.club_id, 'active'
|
||||||
|
FROM (
|
||||||
|
SELECT club_id, co_trainer_ids
|
||||||
|
FROM training_groups
|
||||||
|
WHERE CASE WHEN jsonb_typeof(co_trainer_ids) = 'array'
|
||||||
|
THEN jsonb_array_length(co_trainer_ids)
|
||||||
|
ELSE 0 END > 0
|
||||||
|
) x,
|
||||||
|
LATERAL jsonb_array_elements_text(x.co_trainer_ids) AS elem
|
||||||
|
ON CONFLICT (profile_id, club_id) DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
SELECT cm.id, 'trainer'
|
||||||
|
FROM club_members cm
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM club_member_roles r
|
||||||
|
WHERE r.club_member_id = cm.id AND r.role_code = 'trainer'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Pro Verein: kleinste trainer_id einer Gruppe als primärer Admin (Pilot / CURR-008-Analog)
|
||||||
|
UPDATE clubs c
|
||||||
|
SET primary_admin_profile_id = sub.pid
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT ON (club_id)
|
||||||
|
club_id,
|
||||||
|
trainer_id AS pid
|
||||||
|
FROM training_groups
|
||||||
|
WHERE trainer_id IS NOT NULL
|
||||||
|
ORDER BY club_id, id ASC
|
||||||
|
) sub
|
||||||
|
WHERE c.id = sub.club_id
|
||||||
|
AND c.primary_admin_profile_id IS NULL;
|
||||||
|
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
SELECT cm.id, 'club_admin'
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN clubs cl ON cl.id = cm.club_id AND cl.primary_admin_profile_id = cm.profile_id
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM club_member_roles r
|
||||||
|
WHERE r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Globale Admins: in jedem bestehenden Verein als club_admin spiegeln (volle Plattform-Sicht)
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
SELECT p.id, c.id, 'active'
|
||||||
|
FROM profiles p
|
||||||
|
CROSS JOIN clubs c
|
||||||
|
WHERE p.role IN ('admin', 'superadmin')
|
||||||
|
ON CONFLICT (profile_id, club_id) DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
SELECT cm.id, 'club_admin'
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN profiles p ON p.id = cm.profile_id AND p.role IN ('admin', 'superadmin')
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM club_member_roles r
|
||||||
|
WHERE r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Default aktiver Verein: einziger Verein des Nutzers
|
||||||
|
UPDATE profiles p
|
||||||
|
SET active_club_id = sub.only_club
|
||||||
|
FROM (
|
||||||
|
SELECT profile_id, MIN(club_id) AS only_club
|
||||||
|
FROM club_members
|
||||||
|
WHERE status = 'active'
|
||||||
|
GROUP BY profile_id
|
||||||
|
HAVING COUNT(DISTINCT club_id) = 1
|
||||||
|
) sub
|
||||||
|
WHERE p.id = sub.profile_id AND (p.active_club_id IS NULL);
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
-- Migration 040: Antrag auf Vereinsbeitritt (pending → accept/reject durch Vereins-/Plattform-Admin)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS club_membership_requests (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
club_id INT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending'
|
||||||
|
CHECK (status IN ('pending', 'accepted', 'rejected', 'withdrawn')),
|
||||||
|
message TEXT,
|
||||||
|
decided_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
decided_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_club_membership_requests_pending
|
||||||
|
ON club_membership_requests (profile_id, club_id)
|
||||||
|
WHERE status = 'pending';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_club_membership_requests_club_status
|
||||||
|
ON club_membership_requests (club_id, status);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_club_membership_requests_profile
|
||||||
|
ON club_membership_requests (profile_id);
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS club_membership_requests_update ON club_membership_requests;
|
||||||
|
CREATE TRIGGER club_membership_requests_update
|
||||||
|
BEFORE UPDATE ON club_membership_requests
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- Migration 041: Super-Admin für bestehende Installationen
|
||||||
|
-- Bisheriger Bootstrap (registration_role) setzte nur 'admin'. Viele Endpunkte
|
||||||
|
-- (z. B. Verein löschen, Super-Rolle vergeben) verlangen 'superadmin'.
|
||||||
|
-- Wenn noch kein Super-Admin existiert: den ältesten Nutzer mit role = admin hochstufen.
|
||||||
|
|
||||||
|
UPDATE profiles p
|
||||||
|
SET role = 'superadmin', updated_at = NOW()
|
||||||
|
FROM (
|
||||||
|
SELECT id
|
||||||
|
FROM profiles
|
||||||
|
WHERE lower(trim(COALESCE(role, ''))) = 'admin'
|
||||||
|
ORDER BY id ASC
|
||||||
|
LIMIT 1
|
||||||
|
) sub
|
||||||
|
WHERE p.id = sub.id
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM profiles
|
||||||
|
WHERE lower(trim(COALESCE(role, ''))) = 'superadmin'
|
||||||
|
);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Session-spezifische Co-Trainer: NULL = wie training_groups.co_trainer_ids; [] = explizit keine Co-Trainer
|
||||||
|
ALTER TABLE training_units
|
||||||
|
ADD COLUMN IF NOT EXISTS assistant_trainer_profile_ids JSONB;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN training_units.assistant_trainer_profile_ids IS
|
||||||
|
'Co-Trainer nur für diese Einheit; NULL vererbt training_groups.co_trainer_ids; leeres Array = keine Co-Trainer';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_units_assistant_trainers
|
||||||
|
ON training_units USING GIN (assistant_trainer_profile_ids);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- Gespeicherte Standard-Filter für die Übungsliste (pro Nutzer)
|
||||||
|
ALTER TABLE profiles
|
||||||
|
ADD COLUMN IF NOT EXISTS exercise_list_prefs JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- Rückschau / Nachbereitung: explizit abschließbar (Dashboard & Filter)
|
||||||
|
ALTER TABLE training_units
|
||||||
|
ADD COLUMN IF NOT EXISTS debrief_completed_at TIMESTAMPTZ NULL;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN training_units.debrief_completed_at IS
|
||||||
|
'Zeitpunkt, zu dem die Trainer-Rückschau (Nachbereitung) bewusst abgeschlossen wurde; NULL = offen';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_units_debrief_open
|
||||||
|
ON training_units (status, debrief_completed_at)
|
||||||
|
WHERE status = 'completed' AND debrief_completed_at IS NULL;
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
-- Migration 045: Zentrale media_assets, exercise_media.media_asset_id, platform_media_storage (Superadmin-Pfad).
|
||||||
|
-- Siehe .claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md
|
||||||
|
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE platform_media_storage (
|
||||||
|
id SMALLINT PRIMARY KEY DEFAULT 1,
|
||||||
|
CONSTRAINT platform_media_storage_singleton CHECK (id = 1),
|
||||||
|
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
|
||||||
|
local_relative_root VARCHAR(512) NOT NULL DEFAULT '',
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO platform_media_storage (id, storage_backend, local_relative_root)
|
||||||
|
VALUES (1, 'local', '')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
CREATE TABLE media_assets (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
mime_type VARCHAR(100),
|
||||||
|
byte_size INT,
|
||||||
|
sha256 CHAR(64) NOT NULL,
|
||||||
|
original_filename VARCHAR(300),
|
||||||
|
visibility VARCHAR(32) NOT NULL DEFAULT 'private',
|
||||||
|
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||||
|
uploaded_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
copyright_notice TEXT,
|
||||||
|
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
|
||||||
|
storage_key TEXT NOT NULL,
|
||||||
|
lifecycle_state VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||||
|
trash_soft_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
trash_hidden_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
purge_after_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_media_assets_club ON media_assets(club_id);
|
||||||
|
CREATE INDEX idx_media_assets_sha256 ON media_assets(sha256);
|
||||||
|
CREATE INDEX idx_media_assets_lifecycle ON media_assets(lifecycle_state);
|
||||||
|
CREATE UNIQUE INDEX ux_media_assets_storage_key ON media_assets(storage_key);
|
||||||
|
|
||||||
|
ALTER TABLE exercise_media
|
||||||
|
ADD COLUMN IF NOT EXISTS media_asset_id INT REFERENCES media_assets(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_media_asset ON exercise_media(media_asset_id);
|
||||||
|
|
||||||
|
-- Bestand: je distinct storage_key ein Asset; sha256 aus DB-Pfad (Migrations-Platzhalter, nicht Content-Hash)
|
||||||
|
INSERT INTO media_assets (
|
||||||
|
mime_type,
|
||||||
|
byte_size,
|
||||||
|
sha256,
|
||||||
|
original_filename,
|
||||||
|
visibility,
|
||||||
|
club_id,
|
||||||
|
uploaded_by_profile_id,
|
||||||
|
storage_backend,
|
||||||
|
storage_key,
|
||||||
|
copyright_notice,
|
||||||
|
lifecycle_state,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
s.mime_type,
|
||||||
|
s.byte_size,
|
||||||
|
s.sha256,
|
||||||
|
s.original_filename,
|
||||||
|
s.visibility,
|
||||||
|
s.club_id,
|
||||||
|
s.uploaded_by_profile_id,
|
||||||
|
'local',
|
||||||
|
s.storage_key,
|
||||||
|
NULL,
|
||||||
|
'active',
|
||||||
|
s.created_at,
|
||||||
|
NOW()
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT ON (storage_key)
|
||||||
|
em.mime_type,
|
||||||
|
em.file_size AS byte_size,
|
||||||
|
encode(digest(trim(em.file_path), 'sha256'), 'hex') AS sha256,
|
||||||
|
em.original_filename,
|
||||||
|
lower(trim(e.visibility)) AS visibility,
|
||||||
|
e.club_id,
|
||||||
|
e.created_by AS uploaded_by_profile_id,
|
||||||
|
regexp_replace(trim(em.file_path), '^/+media/+', '') AS storage_key,
|
||||||
|
em.created_at
|
||||||
|
FROM exercise_media em
|
||||||
|
JOIN exercises e ON e.id = em.exercise_id
|
||||||
|
WHERE em.file_path IS NOT NULL
|
||||||
|
AND trim(em.file_path) <> ''
|
||||||
|
AND em.embed_url IS NULL
|
||||||
|
ORDER BY regexp_replace(trim(em.file_path), '^/+media/+', ''), em.id
|
||||||
|
) s
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM media_assets ma WHERE ma.storage_key = s.storage_key);
|
||||||
|
|
||||||
|
UPDATE exercise_media em
|
||||||
|
SET media_asset_id = ma.id
|
||||||
|
FROM media_assets ma
|
||||||
|
WHERE em.media_asset_id IS NULL
|
||||||
|
AND em.file_path IS NOT NULL
|
||||||
|
AND trim(em.file_path) <> ''
|
||||||
|
AND em.embed_url IS NULL
|
||||||
|
AND ma.storage_key = regexp_replace(trim(em.file_path), '^/+media/+', '');
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Migration 046: Schlagwörter (tags) für media_assets — Suche & Filter in der Medienbibliothek.
|
||||||
|
--
|
||||||
|
-- Einordnung: läuft nach 045 (media_assets existiert). Idempotent:
|
||||||
|
-- • wird pro Umgebung höchstens einmal über schema_migrations ausgeführt;
|
||||||
|
-- • dieselben Statements sind bei Wiederholung harmlos (IF NOT EXISTS).
|
||||||
|
ALTER TABLE media_assets
|
||||||
|
ADD COLUMN IF NOT EXISTS tags TEXT[] NOT NULL DEFAULT '{}';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_media_assets_tags_gin ON media_assets USING GIN (tags);
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- Migration 047: Admin-konfigurierbare Rechtstexte
|
||||||
|
-- Tabellen: legal_documents (versioniert), legal_document_audit (Änderungslog)
|
||||||
|
-- document_type: impressum | privacy_policy | terms_of_use | media_policy
|
||||||
|
-- status: draft | published | archived
|
||||||
|
-- Partial unique index: nur genau ein published-Dokument pro document_type erlaubt.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS legal_documents (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
document_type VARCHAR(50) NOT NULL
|
||||||
|
CHECK (document_type IN ('impressum', 'privacy_policy', 'terms_of_use', 'media_policy')),
|
||||||
|
version INT NOT NULL DEFAULT 1,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
content_sections JSONB NOT NULL DEFAULT '[]',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'draft'
|
||||||
|
CHECK (status IN ('draft', 'published', 'archived')),
|
||||||
|
change_note TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
created_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
published_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
published_at TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Sicherstellt: pro document_type maximal ein published-Datensatz
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS legal_documents_unique_published
|
||||||
|
ON legal_documents (document_type)
|
||||||
|
WHERE status = 'published';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS legal_document_audit (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
legal_document_id INT NOT NULL REFERENCES legal_documents(id) ON DELETE CASCADE,
|
||||||
|
action VARCHAR(50) NOT NULL,
|
||||||
|
changed_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
change_note TEXT,
|
||||||
|
previous_status VARCHAR(20),
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
-- Migration 048: P-06 Upload-Einwilligungsdialog
|
||||||
|
-- Append-only Deklarations-Log + Schnellfelder in media_assets
|
||||||
|
-- Alle bestehenden Medien erhalten rights_status = 'legacy_unreviewed'
|
||||||
|
|
||||||
|
-- Deklarations-Log (append-only, wird nie geaendert oder geloescht)
|
||||||
|
CREATE TABLE IF NOT EXISTS media_asset_rights_declarations (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||||
|
declared_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
declared_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
-- Kontext der Erklaerung
|
||||||
|
action_type VARCHAR(50) NOT NULL
|
||||||
|
CHECK (action_type IN (
|
||||||
|
'upload', -- Erstupload
|
||||||
|
'promote_club', -- Promotion zu club
|
||||||
|
'promote_official', -- Promotion zu official
|
||||||
|
're_declaration', -- Freiwillige Nacherklaerung
|
||||||
|
'legacy_re_declaration' -- Altmedium: erste Erklaerung nachgereicht
|
||||||
|
)),
|
||||||
|
target_visibility VARCHAR(32) NOT NULL
|
||||||
|
CHECK (target_visibility IN ('private', 'club', 'official')),
|
||||||
|
-- Textversion der Erklaerung; 'p06-v1-conservative' = konservative Erstannahmen
|
||||||
|
-- VORLAEUTIG: Texte noch nicht juristisch geprueft
|
||||||
|
declaration_version VARCHAR(40) NOT NULL DEFAULT 'p06-v1-conservative',
|
||||||
|
|
||||||
|
-- Pflichtfeld (alle Sichtbarkeiten, alle Aktionen)
|
||||||
|
rights_holder_confirmed BOOLEAN NOT NULL,
|
||||||
|
|
||||||
|
-- Personen (konservative Annahme: immer abgefragt, auch bei 'private')
|
||||||
|
contains_identifiable_persons BOOLEAN,
|
||||||
|
person_consent_confirmed BOOLEAN, -- Pflicht wenn contains_identifiable_persons = true
|
||||||
|
|
||||||
|
-- Minderjaehrige
|
||||||
|
contains_minors BOOLEAN,
|
||||||
|
parental_consent_confirmed BOOLEAN, -- Pflicht wenn contains_minors = true
|
||||||
|
|
||||||
|
-- Drittmaterial
|
||||||
|
contains_music BOOLEAN,
|
||||||
|
music_rights_confirmed BOOLEAN, -- Pflicht wenn contains_music = true
|
||||||
|
contains_third_party_content BOOLEAN,
|
||||||
|
third_party_rights_confirmed BOOLEAN, -- Pflicht wenn contains_third_party_content = true
|
||||||
|
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_mard_asset
|
||||||
|
ON media_asset_rights_declarations (media_asset_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_mard_profile
|
||||||
|
ON media_asset_rights_declarations (declared_by_profile_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_mard_action_type
|
||||||
|
ON media_asset_rights_declarations (action_type);
|
||||||
|
|
||||||
|
-- Schnellfelder in media_assets (kein Ersatz fuer den Log, nur fuer effiziente Abfragen)
|
||||||
|
ALTER TABLE media_assets
|
||||||
|
ADD COLUMN IF NOT EXISTS rights_status VARCHAR(32)
|
||||||
|
NOT NULL DEFAULT 'legacy_unreviewed'
|
||||||
|
CHECK (rights_status IN ('legacy_unreviewed', 'declared', 'blocked')),
|
||||||
|
ADD COLUMN IF NOT EXISTS rights_declared_for_visibility VARCHAR(32)
|
||||||
|
CHECK (rights_declared_for_visibility IN ('private', 'club', 'official')),
|
||||||
|
ADD COLUMN IF NOT EXISTS rights_declared_at TIMESTAMPTZ;
|
||||||
|
|
||||||
|
-- Bestehende Medien: explicit legacy_unreviewed setzen (redundant zum DEFAULT, zur Klarheit)
|
||||||
|
UPDATE media_assets
|
||||||
|
SET rights_status = 'legacy_unreviewed'
|
||||||
|
WHERE rights_status = 'legacy_unreviewed'; -- no-op, setzt Default explizit
|
||||||
|
|
||||||
|
COMMENT ON TABLE media_asset_rights_declarations IS
|
||||||
|
'P-06: Append-only Erklaerungslog fuer Upload-Einwilligungen. '
|
||||||
|
'Eintraege werden nie geaendert. Juristische Validierung der Felder und Texte steht aus.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.rights_status IS
|
||||||
|
'P-06: legacy_unreviewed = Altbestand ohne P-06-Erklaerung; '
|
||||||
|
'declared = gueltige Erklaerung fuer rights_declared_for_visibility; '
|
||||||
|
'blocked = durch Admin gesperrt (P-11-Schnittstelle).';
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- Migration 049: P-06 Erweiterung – Einwilligungskontext-Felder und Copyright im Upload-Dialog
|
||||||
|
-- Optionale Freitextfelder fuer den Kontext der Einwilligung (z.B. "Schriftliche Einwilligung
|
||||||
|
-- vom 2026-05-01 liegt vor") sowie copyright_notice direkt beim Upload erfassbar.
|
||||||
|
|
||||||
|
ALTER TABLE media_asset_rights_declarations
|
||||||
|
ADD COLUMN IF NOT EXISTS person_consent_context TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS parental_consent_context TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS music_rights_context TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS third_party_rights_context TEXT;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_asset_rights_declarations.person_consent_context IS
|
||||||
|
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der abgebildeten Personen vor?';
|
||||||
|
COMMENT ON COLUMN media_asset_rights_declarations.parental_consent_context IS
|
||||||
|
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der Sorgeberechtigten vor?';
|
||||||
|
COMMENT ON COLUMN media_asset_rights_declarations.music_rights_context IS
|
||||||
|
'Optionaler Freitext: Welche Lizenz / GEMA-Regelung liegt fuer die Musik vor?';
|
||||||
|
COMMENT ON COLUMN media_asset_rights_declarations.third_party_rights_context IS
|
||||||
|
'Optionaler Freitext: Auf welcher Grundlage duerfen die enthaltenen Fremdinhalte verwendet werden?';
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
-- Migration 050: Medien-Volljournal – Audit-Log für alle Änderungen + Korrektur-Deklarationen
|
||||||
|
|
||||||
|
-- Vollständiger Audit-Log: Sichtbarkeitsänderungen, Copyright, Metadaten, Lifecycle
|
||||||
|
CREATE TABLE IF NOT EXISTS media_asset_audit_log (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
|
||||||
|
acting_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
event_type VARCHAR(50) NOT NULL
|
||||||
|
CHECK (event_type IN (
|
||||||
|
'visibility_change',
|
||||||
|
'copyright_change',
|
||||||
|
'metadata_change',
|
||||||
|
'lifecycle_change'
|
||||||
|
)),
|
||||||
|
old_values JSONB,
|
||||||
|
new_values JSONB
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_maal_asset ON media_asset_audit_log (media_asset_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_maal_asset_occurred ON media_asset_audit_log (media_asset_id, occurred_at);
|
||||||
|
|
||||||
|
COMMENT ON TABLE media_asset_audit_log IS
|
||||||
|
'Append-only Protokoll aller Aenderungen an Medien-Assets (Sichtbarkeit, Copyright, Metadaten, Lifecycle). '
|
||||||
|
'Wird nie aktualisiert oder geloescht (ausser ON DELETE CASCADE des Assets).';
|
||||||
|
|
||||||
|
-- Korrektur-Notiz für nachtraegliche Deklarations-Korrekturen
|
||||||
|
ALTER TABLE media_asset_rights_declarations
|
||||||
|
ADD COLUMN IF NOT EXISTS correction_note TEXT;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_asset_rights_declarations.correction_note IS
|
||||||
|
'Optionale Begruendung fuer action_type=correction: Warum wurde die Erklaerung korrigiert?';
|
||||||
|
|
||||||
|
-- ''correction'' action_type hinzufuegen (bestehende CHECK-Constraint ersetzen)
|
||||||
|
ALTER TABLE media_asset_rights_declarations
|
||||||
|
DROP CONSTRAINT IF EXISTS media_asset_rights_declarations_action_type_check;
|
||||||
|
|
||||||
|
ALTER TABLE media_asset_rights_declarations
|
||||||
|
ADD CONSTRAINT media_asset_rights_declarations_action_type_check
|
||||||
|
CHECK (action_type IN (
|
||||||
|
'upload',
|
||||||
|
'promote_club',
|
||||||
|
'promote_official',
|
||||||
|
're_declaration',
|
||||||
|
'legacy_re_declaration',
|
||||||
|
'correction'
|
||||||
|
));
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
-- Migration 051: P-11 Legal-Hold Lifecycle-Status
|
||||||
|
-- Sofortsperrung fuer rechtlich problematische Medien (Compliance-Paket P-11)
|
||||||
|
--
|
||||||
|
-- Architekturentscheidung:
|
||||||
|
-- rights_status='blocked' bleibt als Spiegel-Schnellstatus (P-06-Kompatibilitaet).
|
||||||
|
-- Primaere Wahrheit: legal_hold_active + dedizierte Metadaten-Felder in media_assets.
|
||||||
|
-- Dies ermoeglicht klare Trennung: P-06 Deklarationsstatus / P-11 Legal Hold / P-03 Lifecycle.
|
||||||
|
-- P-13 kann spaeter denselben set_legal_hold-Service nutzen.
|
||||||
|
|
||||||
|
ALTER TABLE media_assets
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_active BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_reason_code VARCHAR(50)
|
||||||
|
CHECK (legal_hold_reason_code IN (
|
||||||
|
'rights_dispute',
|
||||||
|
'consent_withdrawn',
|
||||||
|
'privacy_complaint',
|
||||||
|
'copyright_complaint',
|
||||||
|
'youth_protection',
|
||||||
|
'illegal_content',
|
||||||
|
'other'
|
||||||
|
)),
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_reason_note TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_set_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_set_at TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_released_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_released_at TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS legal_hold_release_note TEXT;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_active IS
|
||||||
|
'P-11: TRUE = Medium unter Legal Hold; sofortige Sperrung fuer alle normalen Nutzerpfade. '
|
||||||
|
'Retention-Job darf dieses Medium nicht purgen. '
|
||||||
|
'rights_status wird bei Aktivierung auf ''blocked'' gespiegelt.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_reason_code IS
|
||||||
|
'P-11: Kategorie des Legal Holds. Pflicht beim Setzen.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_reason_note IS
|
||||||
|
'P-11: Freitext-Begruendung fuer den Legal Hold.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_set_by_profile_id IS
|
||||||
|
'P-11: Profil das den Legal Hold gesetzt hat (Superadmin).';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_set_at IS
|
||||||
|
'P-11: Zeitpunkt der Legal-Hold-Aktivierung.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_released_by_profile_id IS
|
||||||
|
'P-11: Profil das den Legal Hold aufgehoben hat.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_released_at IS
|
||||||
|
'P-11: Zeitpunkt der Legal-Hold-Freigabe.';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN media_assets.legal_hold_release_note IS
|
||||||
|
'P-11: Begruendung fuer die Aufhebung des Legal Holds.';
|
||||||
|
|
||||||
|
-- Index fuer Admin-Liste aktiver Legal Holds
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_media_assets_legal_hold_active
|
||||||
|
ON media_assets (legal_hold_active)
|
||||||
|
WHERE legal_hold_active = TRUE;
|
||||||
|
|
||||||
|
-- Neue event_types fuer media_asset_audit_log
|
||||||
|
ALTER TABLE media_asset_audit_log
|
||||||
|
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
|
||||||
|
|
||||||
|
ALTER TABLE media_asset_audit_log
|
||||||
|
ADD CONSTRAINT media_asset_audit_log_event_type_check
|
||||||
|
CHECK (event_type IN (
|
||||||
|
'visibility_change',
|
||||||
|
'copyright_change',
|
||||||
|
'metadata_change',
|
||||||
|
'lifecycle_change',
|
||||||
|
'legal_hold_set',
|
||||||
|
'legal_hold_released'
|
||||||
|
));
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
-- P-13: Content-Melde-Backend
|
||||||
|
-- Meldungen rechtswidriger Inhalte (DSA-konformes Meldeverfahren, KRIT-03)
|
||||||
|
--
|
||||||
|
-- Architektur: Diese Tabelle traegt alle fachlichen Report-Daten.
|
||||||
|
-- Die bestehende Admin-Inbox (InboxPage.jsx, GET /api/me/inbox/join-requests)
|
||||||
|
-- wird um einen zweiten Abschnitt erweitert, der Content-Reports anzeigt.
|
||||||
|
-- Keine separate Admin-Queue, keine generische inbox_items-Tabelle.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS content_reports (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
|
||||||
|
-- Ziel der Meldung (erweiterbar auf weitere Typen)
|
||||||
|
target_type VARCHAR(20) NOT NULL DEFAULT 'media_asset'
|
||||||
|
CHECK (target_type IN ('media_asset', 'exercise')),
|
||||||
|
target_id INTEGER NOT NULL,
|
||||||
|
|
||||||
|
-- Meldungsinhalt
|
||||||
|
report_reason VARCHAR(50) NOT NULL
|
||||||
|
CHECK (report_reason IN (
|
||||||
|
'copyright',
|
||||||
|
'image_rights',
|
||||||
|
'privacy',
|
||||||
|
'minors',
|
||||||
|
'illegal_content',
|
||||||
|
'youth_protection',
|
||||||
|
'offensive_content',
|
||||||
|
'other'
|
||||||
|
)),
|
||||||
|
report_description TEXT NOT NULL,
|
||||||
|
|
||||||
|
-- Meldende Person (Name + E-Mail Pflicht; Profil optional bei eingeloggten Nutzern)
|
||||||
|
reporter_name VARCHAR(200) NOT NULL,
|
||||||
|
reporter_email VARCHAR(200) NOT NULL,
|
||||||
|
reporter_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
|
||||||
|
-- Gutglaubenserklärung (Pflicht)
|
||||||
|
good_faith_confirmed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
|
||||||
|
-- Automatische Priorisierung (high fuer minors/youth_protection/illegal_content)
|
||||||
|
priority VARCHAR(20) NOT NULL DEFAULT 'normal'
|
||||||
|
CHECK (priority IN ('high', 'normal')),
|
||||||
|
|
||||||
|
-- Workflow-Status
|
||||||
|
status VARCHAR(30) NOT NULL DEFAULT 'submitted'
|
||||||
|
CHECK (status IN (
|
||||||
|
'submitted',
|
||||||
|
'under_review',
|
||||||
|
'resolved_no_action',
|
||||||
|
'resolved_legal_hold',
|
||||||
|
'rejected_invalid'
|
||||||
|
)),
|
||||||
|
|
||||||
|
-- Bearbeitung
|
||||||
|
assigned_to_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
reviewed_by_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
reviewed_at TIMESTAMP,
|
||||||
|
resolution_note TEXT,
|
||||||
|
|
||||||
|
-- Zeitstempel
|
||||||
|
submitted_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Indices fuer Admin-Liste
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_content_reports_status_created
|
||||||
|
ON content_reports (status, created_at DESC);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_content_reports_target
|
||||||
|
ON content_reports (target_type, target_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_content_reports_priority
|
||||||
|
ON content_reports (priority, status, created_at DESC);
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- Migration 053: Audit-Log event_type-Constraint korrigieren + 'content_report_filed' hinzufuegen
|
||||||
|
--
|
||||||
|
-- Hintergrund: Die Tabelle media_asset_audit_log wurde per CREATE TABLE IF NOT EXISTS angelegt.
|
||||||
|
-- Da die Tabelle bereits existierte, wurde die CHECK-Constraint aus Migration 050 nie angewendet.
|
||||||
|
-- In der DB existieren Zeilen mit legal_hold_set und legal_hold_released (aus P-11).
|
||||||
|
-- Diese Migration setzt die Constraint erstmalig mit allen gueltigen Werten.
|
||||||
|
|
||||||
|
ALTER TABLE media_asset_audit_log
|
||||||
|
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
|
||||||
|
|
||||||
|
ALTER TABLE media_asset_audit_log
|
||||||
|
ADD CONSTRAINT media_asset_audit_log_event_type_check
|
||||||
|
CHECK (event_type IN (
|
||||||
|
'visibility_change',
|
||||||
|
'copyright_change',
|
||||||
|
'metadata_change',
|
||||||
|
'lifecycle_change',
|
||||||
|
'legal_hold_set',
|
||||||
|
'legal_hold_released',
|
||||||
|
'content_report_filed'
|
||||||
|
));
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
-- Migration 054: Trainingsmodule (Bibliothek / Planung) — Phase 1 MVP
|
||||||
|
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS training_modules (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||||
|
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||||
|
title VARCHAR(200) NOT NULL,
|
||||||
|
summary TEXT,
|
||||||
|
goal TEXT,
|
||||||
|
recommended_duration_min INT,
|
||||||
|
target_group_notes TEXT,
|
||||||
|
deployment_context_notes TEXT,
|
||||||
|
primary_method_id INT REFERENCES training_methods(id) ON DELETE SET NULL,
|
||||||
|
visibility VARCHAR(50) NOT NULL DEFAULT 'club'
|
||||||
|
CHECK (visibility IN ('private', 'club', 'official')),
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_modules_club ON training_modules(club_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_modules_creator ON training_modules(created_by);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_modules_visibility ON training_modules(visibility);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_modules_method ON training_modules(primary_method_id)
|
||||||
|
WHERE primary_method_id IS NOT NULL;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS training_modules_update ON training_modules;
|
||||||
|
CREATE TRIGGER training_modules_update
|
||||||
|
BEFORE UPDATE ON training_modules
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS training_module_items (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
module_id INT NOT NULL REFERENCES training_modules(id) ON DELETE CASCADE,
|
||||||
|
order_index INT NOT NULL,
|
||||||
|
item_type VARCHAR(20) NOT NULL CHECK (item_type IN ('exercise', 'note')),
|
||||||
|
exercise_id INT REFERENCES exercises(id) ON DELETE SET NULL,
|
||||||
|
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
|
||||||
|
planned_duration_min INT,
|
||||||
|
notes TEXT,
|
||||||
|
note_body TEXT,
|
||||||
|
UNIQUE (module_id, order_index),
|
||||||
|
CHECK (
|
||||||
|
(item_type = 'exercise' AND exercise_id IS NOT NULL AND note_body IS NULL)
|
||||||
|
OR
|
||||||
|
(item_type = 'note' AND exercise_id IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_module_items_module ON training_module_items(module_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_module_items_exercise ON training_module_items(exercise_id)
|
||||||
|
WHERE exercise_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- Herkunft bei Übernahme aus Modul-Bibliothek (Kopie, keine Live-Verknüpfung)
|
||||||
|
ALTER TABLE training_unit_section_items
|
||||||
|
ADD COLUMN IF NOT EXISTS source_training_module_id INT REFERENCES training_modules(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_unit_section_items_source_module
|
||||||
|
ON training_unit_section_items(source_training_module_id)
|
||||||
|
WHERE source_training_module_id IS NOT NULL;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- Persönliche Planungs-UI-Präferenzen (JSONB, selbst vom Nutzer setzbar)
|
||||||
|
ALTER TABLE profiles
|
||||||
|
ADD COLUMN IF NOT EXISTS training_planning_prefs JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- Migration 056: Kombinationsübungen (Phase 2 MVP) — Slots + Pool-Kandidaten
|
||||||
|
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md §6
|
||||||
|
|
||||||
|
ALTER TABLE exercises
|
||||||
|
ADD COLUMN IF NOT EXISTS exercise_kind VARCHAR(20) NOT NULL DEFAULT 'simple'
|
||||||
|
CHECK (exercise_kind IN ('simple', 'combination')),
|
||||||
|
ADD COLUMN IF NOT EXISTS method_archetype VARCHAR(80),
|
||||||
|
ADD COLUMN IF NOT EXISTS method_profile JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_exercise_kind ON exercises(exercise_kind);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_method_archetype ON exercises(method_archetype)
|
||||||
|
WHERE method_archetype IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS combination_exercise_slots (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||||
|
slot_index INT NOT NULL,
|
||||||
|
title VARCHAR(200),
|
||||||
|
UNIQUE (exercise_id, slot_index)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_combination_exercise_slots_exercise ON combination_exercise_slots(exercise_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS combination_slot_candidates (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
slot_id INT NOT NULL REFERENCES combination_exercise_slots(id) ON DELETE CASCADE,
|
||||||
|
candidate_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
UNIQUE (slot_id, candidate_exercise_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_slot ON combination_slot_candidates(slot_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_exercise ON combination_slot_candidates(candidate_exercise_id);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- 057: Terminspezifisches Ablaufprofil fuer Kombinationsuebungen in der Planung
|
||||||
|
-- NULL = method_profile vom Katalog (exercises) verwenden; sonst dieser JSONB-Stand gilt fuer diese Platzierung.
|
||||||
|
|
||||||
|
ALTER TABLE training_unit_section_items
|
||||||
|
ADD COLUMN IF NOT EXISTS planning_method_profile JSONB NULL;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN training_unit_section_items.planning_method_profile IS
|
||||||
|
'Snapshots des Ablaufprofils fuer diese Einheit/Zeile; NULL = exercises.method_profile.';
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Unterstützung für GET /api/exercises: ORDER BY e.updated_at DESC
|
||||||
|
-- und häufiger Pfad created_by_me (= e.created_by = Profil) mit derselben Sortierung.
|
||||||
|
-- Hinweis: idx_exercises_created_at (014) betrifft created_at, nicht updated_at.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_updated_at_desc ON exercises (updated_at DESC);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_created_by_updated_at_desc ON exercises (created_by, updated_at DESC);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- GET /api/training-units: Liste nutzt immer tu.framework_slot_id IS NULL (keine Rahmen-Blueprints)
|
||||||
|
-- und sortiert nach planned_date, planned_time_start (ASC/DESC mit NULLS LAST).
|
||||||
|
-- Teilindex verkleinert die Menge und unterstützt die Sortierung.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_units_scheduled_order
|
||||||
|
ON training_units (planned_date DESC, planned_time_start DESC NULLS LAST)
|
||||||
|
WHERE framework_slot_id IS NULL;
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- Migration 060: Übungslisten bei großem Bestand (Ziel: Tausende Übungen, viele Filterkombinationen).
|
||||||
|
-- Ergänzt 058 (globale Sortierung / created_by): kleinere Partial-Indizes für häufige
|
||||||
|
-- Sichtbarkeits-Pfade der Bibliothek sowie Junction-Indizes für die List-Subqueries
|
||||||
|
-- (primary_focus_name / JSON-Aggregate mit is_primary).
|
||||||
|
--
|
||||||
|
-- Bereits vorhanden und sinnvoll: UNIQUE(exercise_id, …) auf den M:N-Tabellen für EXISTS-Joins;
|
||||||
|
-- GIN auf exercises.search_vector (014); idx_exercises_exercise_kind (056).
|
||||||
|
|
||||||
|
-- Official: OR-Zweig der Bibliothek — kompakter als Full-Table-Scan bei BitmapOr mit anderen Partial-Indizes
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_list_official_updated
|
||||||
|
ON exercises (updated_at DESC)
|
||||||
|
WHERE visibility = 'official'
|
||||||
|
AND COALESCE(status, '') <> 'archived';
|
||||||
|
|
||||||
|
-- Club: häufig club_id + Sortierung nach updated_at (Mandanten-Bibliothek)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_list_club_updated
|
||||||
|
ON exercises (club_id, updated_at DESC)
|
||||||
|
WHERE visibility = 'club'
|
||||||
|
AND club_id IS NOT NULL
|
||||||
|
AND COALESCE(status, '') <> 'archived';
|
||||||
|
|
||||||
|
-- List-SELECT: Subqueries / json_agg sortieren zuerst nach is_primary (siehe exercises.py)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_exercise_primary
|
||||||
|
ON exercise_focus_areas (exercise_id, is_primary DESC NULLS LAST, focus_area_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_style_directions_exercise_primary
|
||||||
|
ON exercise_style_directions (exercise_id, is_primary DESC NULLS LAST, style_direction_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_training_types_exercise_primary
|
||||||
|
ON exercise_training_types (exercise_id, is_primary DESC NULLS LAST, training_type_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_exercise_primary
|
||||||
|
ON exercise_target_groups (exercise_id, is_primary DESC NULLS LAST, target_group_id);
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- GET /api/training-units: Keyset über (planned_date, planned_time_start NULLS LAST per Sort, id)
|
||||||
|
-- Ersetzt den reinen Datum/Uhrzeit-Teilindex 059 durch zwei Richtungen mit Tie-Break id.
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS idx_training_units_scheduled_order;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_desc
|
||||||
|
ON training_units (
|
||||||
|
planned_date DESC,
|
||||||
|
(planned_time_start IS NULL) ASC,
|
||||||
|
planned_time_start DESC NULLS LAST,
|
||||||
|
id DESC
|
||||||
|
)
|
||||||
|
WHERE framework_slot_id IS NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_asc
|
||||||
|
ON training_units (
|
||||||
|
planned_date ASC,
|
||||||
|
(planned_time_start IS NULL) ASC,
|
||||||
|
planned_time_start ASC NULLS LAST,
|
||||||
|
id ASC
|
||||||
|
)
|
||||||
|
WHERE framework_slot_id IS NULL;
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
-- list_exercises mit skill_min_level / skill_max_level: EXISTS auf exercise_skills mit numerischem Stufen-Rang.
|
||||||
|
-- Ausdruck muss mit backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL (Alias „es“) übereinstimmen.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercise_skills_exercise_level_rank
|
||||||
|
ON exercise_skills (
|
||||||
|
exercise_id,
|
||||||
|
(CASE COALESCE(
|
||||||
|
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||||
|
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||||
|
)
|
||||||
|
WHEN 'basis' THEN 1
|
||||||
|
WHEN 'grundlagen' THEN 2
|
||||||
|
WHEN 'aufbau' THEN 3
|
||||||
|
WHEN 'fortgeschritten' THEN 4
|
||||||
|
WHEN 'optimierung' THEN 5
|
||||||
|
WHEN 'einsteiger' THEN 1
|
||||||
|
WHEN 'experte' THEN 5
|
||||||
|
WHEN '1' THEN 1
|
||||||
|
WHEN '2' THEN 2
|
||||||
|
WHEN '3' THEN 3
|
||||||
|
WHEN '4' THEN 4
|
||||||
|
WHEN '5' THEN 5
|
||||||
|
ELSE NULL END)
|
||||||
|
)
|
||||||
|
WHERE (CASE COALESCE(
|
||||||
|
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||||
|
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||||
|
)
|
||||||
|
WHEN 'basis' THEN 1
|
||||||
|
WHEN 'grundlagen' THEN 2
|
||||||
|
WHEN 'aufbau' THEN 3
|
||||||
|
WHEN 'fortgeschritten' THEN 4
|
||||||
|
WHEN 'optimierung' THEN 5
|
||||||
|
WHEN 'einsteiger' THEN 1
|
||||||
|
WHEN 'experte' THEN 5
|
||||||
|
WHEN '1' THEN 1
|
||||||
|
WHEN '2' THEN 2
|
||||||
|
WHEN '3' THEN 3
|
||||||
|
WHEN '4' THEN 4
|
||||||
|
WHEN '5' THEN 5
|
||||||
|
ELSE NULL END) IS NOT NULL;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
-- Migration 063: Phasen und parallele Streams pro Trainingseinheit (Grundlage Breakout).
|
||||||
|
-- Bestehende Sektionen werden einer Default-whole_group-Phase zugeordnet.
|
||||||
|
-- UNIQUE (training_unit_id, order_index) auf Sektionen entfällt zugunsten
|
||||||
|
-- eindeutiger order_index je Phase bzw. je parallel_stream.
|
||||||
|
|
||||||
|
-- ── Phasen ───────────────────────────────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS training_unit_phases (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
training_unit_id INT NOT NULL REFERENCES training_units(id) ON DELETE CASCADE,
|
||||||
|
order_index INT NOT NULL,
|
||||||
|
phase_kind VARCHAR(20) NOT NULL CHECK (phase_kind IN ('whole_group', 'parallel')),
|
||||||
|
title VARCHAR(200),
|
||||||
|
guidance_notes TEXT,
|
||||||
|
UNIQUE (training_unit_id, order_index)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_unit_phases_unit ON training_unit_phases(training_unit_id);
|
||||||
|
|
||||||
|
-- ── Streams innerhalb einer Parallelphase ──────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS training_unit_parallel_streams (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
phase_id INT NOT NULL REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||||
|
order_index INT NOT NULL,
|
||||||
|
title VARCHAR(200),
|
||||||
|
notes TEXT,
|
||||||
|
assigned_trainer_profile_ids JSONB,
|
||||||
|
UNIQUE (phase_id, order_index)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_unit_parallel_streams_phase
|
||||||
|
ON training_unit_parallel_streams(phase_id);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN training_unit_parallel_streams.assigned_trainer_profile_ids IS
|
||||||
|
'Optionale Co-Trainer-IDs (JSON-Array von Profil-IDs) für diese Teilstrecke; MVP+';
|
||||||
|
|
||||||
|
-- ── Sektionen: Zuordnung zu Phase (gemeinsam) oder Stream (parallel) ─────
|
||||||
|
ALTER TABLE training_unit_sections
|
||||||
|
ADD COLUMN IF NOT EXISTS phase_id INT REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||||
|
ADD COLUMN IF NOT EXISTS parallel_stream_id INT REFERENCES training_unit_parallel_streams(id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
-- Backfill: je Einheit mit Sektionen eine whole_group-Phase, alle Sektionen dorthin
|
||||||
|
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title)
|
||||||
|
SELECT tu.id, 0, 'whole_group', NULL
|
||||||
|
FROM training_units tu
|
||||||
|
WHERE EXISTS (SELECT 1 FROM training_unit_sections s WHERE s.training_unit_id = tu.id)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM training_unit_phases p
|
||||||
|
WHERE p.training_unit_id = tu.id AND p.order_index = 0 AND p.phase_kind = 'whole_group'
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE training_unit_sections tus
|
||||||
|
SET phase_id = p.id
|
||||||
|
FROM training_unit_phases p
|
||||||
|
WHERE tus.phase_id IS NULL
|
||||||
|
AND p.training_unit_id = tus.training_unit_id
|
||||||
|
AND p.order_index = 0
|
||||||
|
AND p.phase_kind = 'whole_group';
|
||||||
|
|
||||||
|
-- Alte globale Reihenfolge-Eindeutigkeit pro Einheit entfernen
|
||||||
|
ALTER TABLE training_unit_sections
|
||||||
|
DROP CONSTRAINT IF EXISTS training_unit_sections_training_unit_id_order_index_key;
|
||||||
|
|
||||||
|
-- Genau eine Zielspalte gesetzt: gemeinsame Phase ODER paralleler Stream
|
||||||
|
ALTER TABLE training_unit_sections
|
||||||
|
DROP CONSTRAINT IF EXISTS training_unit_sections_phase_or_stream_chk;
|
||||||
|
|
||||||
|
ALTER TABLE training_unit_sections
|
||||||
|
ADD CONSTRAINT training_unit_sections_phase_or_stream_chk CHECK (
|
||||||
|
(phase_id IS NOT NULL AND parallel_stream_id IS NULL)
|
||||||
|
OR (phase_id IS NULL AND parallel_stream_id IS NOT NULL)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_phase_order
|
||||||
|
ON training_unit_sections (phase_id, order_index)
|
||||||
|
WHERE phase_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_stream_order
|
||||||
|
ON training_unit_sections (parallel_stream_id, order_index)
|
||||||
|
WHERE parallel_stream_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_phase
|
||||||
|
ON training_unit_sections(phase_id) WHERE phase_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_parallel_stream
|
||||||
|
ON training_unit_sections(parallel_stream_id) WHERE parallel_stream_id IS NOT NULL;
|
||||||
+21
-4
@@ -4,7 +4,7 @@ Pydantic Models for Shinkan Jinkendo API
|
|||||||
Request/Response schemas for all endpoints
|
Request/Response schemas for all endpoints
|
||||||
"""
|
"""
|
||||||
from pydantic import BaseModel, EmailStr, Field
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
from typing import Optional, List
|
from typing import Optional, List, Dict, Any
|
||||||
from datetime import date, time, datetime
|
from datetime import date, time, datetime
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
@@ -19,21 +19,38 @@ class RegisterRequest(BaseModel):
|
|||||||
email: EmailStr
|
email: EmailStr
|
||||||
password: str
|
password: str
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
|
requested_club_id: Optional[int] = Field(default=None, ge=1)
|
||||||
|
|
||||||
class PasswordResetRequest(BaseModel):
|
class PasswordResetRequest(BaseModel):
|
||||||
email: str
|
email: str
|
||||||
|
|
||||||
class PasswordResetConfirm(BaseModel):
|
class PasswordResetConfirm(BaseModel):
|
||||||
token: str
|
token: str
|
||||||
new_password: str
|
new_password: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
class ProfileCreate(BaseModel):
|
class ProfileCreate(BaseModel):
|
||||||
name: str
|
"""Nur für POST /api/profiles (Plattform-Admin): neues Nutzerprofil ohne Self-Registration."""
|
||||||
email: Optional[str] = None
|
|
||||||
|
name: str = Field(min_length=2, max_length=200)
|
||||||
|
email: EmailStr
|
||||||
|
|
||||||
class ProfileUpdate(BaseModel):
|
class ProfileUpdate(BaseModel):
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
email: Optional[str] = None
|
email: Optional[str] = None
|
||||||
|
active_club_id: Optional[int] = None
|
||||||
|
role: Optional[str] = Field(
|
||||||
|
default=None,
|
||||||
|
description="Portal-Rolle: user, trainer, admin, superadmin (nur Plattform-Admin)",
|
||||||
|
)
|
||||||
|
tier: Optional[str] = Field(default=None, max_length=50)
|
||||||
|
exercise_list_prefs: Optional[Dict[str, Any]] = Field(
|
||||||
|
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):
|
class ProfileResponse(BaseModel):
|
||||||
id: int
|
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)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
|
pythonpath = .
|
||||||
|
python_files = test_*.py
|
||||||
|
python_functions = test_*
|
||||||
|
addopts = -q --tb=short
|
||||||
|
markers =
|
||||||
|
smoke: Schnelle Kern-Regression.
|
||||||
|
integration: PostgreSQL-Integration (z. B. ACCESS_LAYER_INTEGRATION=1, TRAINING_PLANNING_INTEGRATION=1).
|
||||||
|
slow: Lange/schwere Tests; in CI wie Mitai-Jinkendo ausgeschlossen (Auswahl: not slow).
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Entwicklung / CI — zusätzlich zu backend/requirements.txt installieren:
|
||||||
|
# pip install -r backend/requirements.txt -r backend/requirements-dev.txt
|
||||||
|
pytest>=8.0,<9
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""
|
||||||
|
Plattform-Admin: Übersicht aller Nutzer inkl. Vereinsmitgliedschaften (ohne Passwort-Hashes).
|
||||||
|
"""
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from club_tenancy import is_platform_admin, memberships_with_roles
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin", tags=["admin_users"])
|
||||||
|
|
||||||
|
_SAFE_PROFILE_COLS = """
|
||||||
|
id, name, email, role, tier, email_verified, active_club_id,
|
||||||
|
created_at, updated_at, auth_type
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/users")
|
||||||
|
def list_platform_users(session: dict = Depends(require_auth)):
|
||||||
|
"""Alle Profile mit Vereinen/Rollen — nur Portal-Admin (admin oder superadmin)."""
|
||||||
|
role = (session.get("role") or "").lower()
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Portal-Administratoren")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT {_SAFE_PROFILE_COLS.strip()}
|
||||||
|
FROM profiles
|
||||||
|
ORDER BY COALESCE(lower(trim(email)), ''), id
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
rows: List[Dict[str, Any]] = []
|
||||||
|
for r in cur.fetchall():
|
||||||
|
d = r2d(r)
|
||||||
|
d["clubs"] = memberships_with_roles(cur, int(d["id"]), active_only=False)
|
||||||
|
rows.append(d)
|
||||||
|
return rows
|
||||||
+48
-30
@@ -20,13 +20,18 @@ from slowapi.util import get_remote_address
|
|||||||
from db import get_db, get_cursor
|
from db import get_db, get_cursor
|
||||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
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"])
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/login")
|
@router.post("/login")
|
||||||
@limiter.limit("5/minute")
|
@limiter.limit("30/minute")
|
||||||
async def login(req: LoginRequest, request: Request):
|
async def login(req: LoginRequest, request: Request):
|
||||||
"""Login with email + password."""
|
"""Login with email + password."""
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
@@ -78,8 +83,8 @@ def get_me(session: dict=Depends(require_auth)):
|
|||||||
"""Get current user info."""
|
"""Get current user info."""
|
||||||
pid = session['profile_id']
|
pid = session['profile_id']
|
||||||
# Import here to avoid circular dependency
|
# Import here to avoid circular dependency
|
||||||
from routers.profiles import get_profile
|
from routers.profiles import profile_document
|
||||||
return get_profile(pid, session)
|
return profile_document(pid)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status")
|
@router.get("/status")
|
||||||
@@ -93,8 +98,8 @@ def change_pin(req: dict, session: dict=Depends(require_auth)):
|
|||||||
"""Change PIN/password for current user."""
|
"""Change PIN/password for current user."""
|
||||||
pid = session['profile_id']
|
pid = session['profile_id']
|
||||||
new_pin = req.get('pin', '')
|
new_pin = req.get('pin', '')
|
||||||
if len(new_pin) < 4:
|
if len(new_pin) < 8:
|
||||||
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
|
raise HTTPException(400, "Passwort muss mind. 8 Zeichen haben")
|
||||||
|
|
||||||
new_hash = hash_pin(new_pin)
|
new_hash = hash_pin(new_pin)
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
@@ -116,28 +121,14 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
|
|||||||
if not prof:
|
if not prof:
|
||||||
# Don't reveal if email exists
|
# Don't reveal if email exists
|
||||||
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
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
|
reset_body = password_reset_email_body(
|
||||||
token = secrets.token_urlsafe(32)
|
recipient_name=prof.get("name"),
|
||||||
expires = datetime.now() + timedelta(hours=1)
|
token=raw_token,
|
||||||
|
intro="Du hast einen Passwort-Reset angefordert.",
|
||||||
# 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
|
|
||||||
"""
|
|
||||||
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
||||||
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
||||||
|
|
||||||
@@ -187,9 +178,10 @@ def verification_link(token: str) -> str:
|
|||||||
|
|
||||||
def registration_role(cur, email_lower: str) -> str:
|
def registration_role(cur, email_lower: str) -> str:
|
||||||
"""
|
"""
|
||||||
bootstrap: erste Registrierung in leerer DB → admin,
|
bootstrap: erste Registrierung in leerer DB → superadmin,
|
||||||
oder E-Mail ∈ ADMIN_BOOTSTRAP_EMAILS (kommasepariert, Groß/Klein egal).
|
oder E-Mail ∈ ADMIN_BOOTSTRAP_EMAILS (kommasepariert, Groß/Klein egal).
|
||||||
|
|
||||||
|
superadmin deckt alle Portal-Rechte ab (inkl. löschen / andere Super-Admins).
|
||||||
Um alle Self-Regs als Trainer zu haben: AUTO_ADMIN_FIRST_USER=false und keine ADMIN_BOOTSTRAP_EMAILS.
|
Um alle Self-Regs als Trainer zu haben: AUTO_ADMIN_FIRST_USER=false und keine ADMIN_BOOTSTRAP_EMAILS.
|
||||||
"""
|
"""
|
||||||
bootstrap = {
|
bootstrap = {
|
||||||
@@ -198,7 +190,7 @@ def registration_role(cur, email_lower: str) -> str:
|
|||||||
if x.strip()
|
if x.strip()
|
||||||
}
|
}
|
||||||
if email_lower in bootstrap:
|
if email_lower in bootstrap:
|
||||||
return "admin"
|
return "superadmin"
|
||||||
if os.getenv("AUTO_ADMIN_FIRST_USER", "true").strip().lower() not in ("1", "true", "yes"):
|
if os.getenv("AUTO_ADMIN_FIRST_USER", "true").strip().lower() not in ("1", "true", "yes"):
|
||||||
return "trainer"
|
return "trainer"
|
||||||
cur.execute("SELECT COUNT(*) AS n FROM profiles")
|
cur.execute("SELECT COUNT(*) AS n FROM profiles")
|
||||||
@@ -207,7 +199,7 @@ def registration_role(cur, email_lower: str) -> str:
|
|||||||
n = int(row["n"]) if row is not None else 0
|
n = int(row["n"]) if row is not None else 0
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
n = 0
|
n = 0
|
||||||
return "admin" if n == 0 else "trainer"
|
return "superadmin" if n == 0 else "trainer"
|
||||||
|
|
||||||
|
|
||||||
# ── Helper: Send Email ────────────────────────────────────────────────────────
|
# ── Helper: Send Email ────────────────────────────────────────────────────────
|
||||||
@@ -289,7 +281,7 @@ async def register(req: RegisterRequest, request: Request):
|
|||||||
verification_token = secrets.token_urlsafe(32)
|
verification_token = secrets.token_urlsafe(32)
|
||||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||||
|
|
||||||
# Rolle: erster Nutzer oder ADMIN_BOOTSTRAP_EMAILS → admin
|
# Rolle: erster Nutzer oder ADMIN_BOOTSTRAP_EMAILS → superadmin
|
||||||
role = registration_role(cur, email)
|
role = registration_role(cur, email)
|
||||||
|
|
||||||
# Create profile (inactive until verified) — profiles.id ist SERIAL (INT), keine String-IDs einfügen.
|
# Create profile (inactive until verified) — profiles.id ist SERIAL (INT), keine String-IDs einfügen.
|
||||||
@@ -302,7 +294,33 @@ async def register(req: RegisterRequest, request: Request):
|
|||||||
email_verified, verification_token, verification_expires,
|
email_verified, verification_token, verification_expires,
|
||||||
trial_ends_at, created_at
|
trial_ends_at, created_at
|
||||||
) VALUES (%s, %s, %s, 'email', %s, 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
|
) VALUES (%s, %s, %s, 'email', %s, 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
|
||||||
|
RETURNING id
|
||||||
""", (name, email, pin_hash, role, verification_token, verification_expires, trial_ends))
|
""", (name, email, pin_hash, role, verification_token, verification_expires, trial_ends))
|
||||||
|
new_profile_id = cur.fetchone()["id"]
|
||||||
|
|
||||||
|
req_club = req.requested_club_id
|
||||||
|
if req_club is not None:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM clubs WHERE id = %s AND status = 'active'",
|
||||||
|
(int(req_club),),
|
||||||
|
)
|
||||||
|
if cur.fetchone():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM club_membership_requests
|
||||||
|
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(new_profile_id, int(req_club)),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
|
||||||
|
VALUES (%s, %s, 'pending', NULL)
|
||||||
|
""",
|
||||||
|
(new_profile_id, int(req_club)),
|
||||||
|
)
|
||||||
|
|
||||||
verify_url = verification_link(verification_token)
|
verify_url = verification_link(verification_token)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,347 @@
|
|||||||
|
"""
|
||||||
|
Anträge auf Vereinsbeitritt: Nutzer stellt Antrag, Vereins-/Plattform-Admin nimmt an oder lehnt ab.
|
||||||
|
"""
|
||||||
|
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, is_platform_admin
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["club_join_requests"])
|
||||||
|
|
||||||
|
_ALLOWED_MEMBER_ROLES = frozenset({"club_admin", "trainer", "division_lead", "content_editor"})
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_roles(raw: List[str]) -> List[str]:
|
||||||
|
out: List[str] = []
|
||||||
|
seen = set()
|
||||||
|
for r in raw:
|
||||||
|
if not isinstance(r, str):
|
||||||
|
raise HTTPException(status_code=400, detail="Rollen müssen Strings sein")
|
||||||
|
code = r.strip().lower()
|
||||||
|
if not code or code not in _ALLOWED_MEMBER_ROLES:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unbekannte Rolle: {code}")
|
||||||
|
if code not in seen:
|
||||||
|
seen.add(code)
|
||||||
|
out.append(code)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _club_active(cur, club_id: int) -> bool:
|
||||||
|
cur.execute("SELECT 1 FROM clubs WHERE id = %s AND status = 'active'", (club_id,))
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_manage_club(cur, tenant: TenantContext, club_id: int) -> None:
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
if not can_manage_club_org(cur, pid, club_id, role):
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für Mitglieder-Verwaltung in diesem Verein")
|
||||||
|
|
||||||
|
|
||||||
|
def _is_active_member(cur, profile_id: int, club_id: int) -> bool:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members
|
||||||
|
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _upsert_active_member_with_roles(cur, club_id: int, profile_id: int, roles: List[str]) -> None:
|
||||||
|
roles_n = _normalize_roles(roles)
|
||||||
|
if not roles_n:
|
||||||
|
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
VALUES (%s, %s, 'active')
|
||||||
|
ON CONFLICT (profile_id, club_id)
|
||||||
|
DO UPDATE SET status = 'active', updated_at = NOW()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
cm_id = cur.fetchone()["id"]
|
||||||
|
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
|
||||||
|
for rc in roles_n:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (club_member_id, role_code) DO NOTHING
|
||||||
|
""",
|
||||||
|
(cm_id, rc),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class JoinRequestCreate(BaseModel):
|
||||||
|
club_id: int = Field(..., ge=1)
|
||||||
|
message: Optional[str] = Field(None, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
class JoinRequestAccept(BaseModel):
|
||||||
|
roles: List[str] = Field(default_factory=lambda: ["trainer"])
|
||||||
|
|
||||||
|
|
||||||
|
def _response_one(cur, req_id: int, viewer_profile_id: int) -> Dict[str, Any]:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT r.*, c.name AS club_name, c.abbreviation AS club_abbreviation
|
||||||
|
FROM club_membership_requests r
|
||||||
|
INNER JOIN clubs c ON c.id = r.club_id
|
||||||
|
WHERE r.id = %s AND r.profile_id = %s
|
||||||
|
""",
|
||||||
|
(req_id, viewer_profile_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Antrag nicht gefunden")
|
||||||
|
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
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT r.*, c.name AS club_name, c.abbreviation AS club_abbreviation
|
||||||
|
FROM club_membership_requests r
|
||||||
|
INNER JOIN clubs c ON c.id = r.club_id
|
||||||
|
WHERE r.profile_id = %s
|
||||||
|
ORDER BY r.created_at DESC
|
||||||
|
LIMIT 100
|
||||||
|
""",
|
||||||
|
(pid,),
|
||||||
|
)
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/me/club-join-requests", status_code=201)
|
||||||
|
def create_my_join_request(body: JoinRequestCreate, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""Antrag stellen (nicht möglich wenn bereits aktives Mitglied)."""
|
||||||
|
pid = tenant.profile_id
|
||||||
|
msg = (body.message or "").strip() or None
|
||||||
|
cid = body.club_id
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_active(cur, cid):
|
||||||
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden oder nicht aktiv")
|
||||||
|
|
||||||
|
if _is_active_member(cur, pid, cid):
|
||||||
|
raise HTTPException(status_code=400, detail="Du bist bereits Mitglied in diesem Verein")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM club_membership_requests
|
||||||
|
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(pid, cid),
|
||||||
|
)
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(status_code=409, detail="Für diesen Verein liegt bereits ein offener Antrag vor")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
|
||||||
|
VALUES (%s, %s, 'pending', %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(pid, cid, msg),
|
||||||
|
)
|
||||||
|
rid = cur.fetchone()["id"]
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return _response_one(cur, rid, pid)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/me/club-join-requests/{request_id}")
|
||||||
|
def withdraw_my_join_request(request_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
pid = tenant.profile_id
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE club_membership_requests
|
||||||
|
SET status = 'withdrawn', updated_at = NOW()
|
||||||
|
WHERE id = %s AND profile_id = %s AND status = 'pending'
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(request_id, pid),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Offener Antrag nicht gefunden")
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clubs/{club_id}/join-requests")
|
||||||
|
def list_club_join_requests(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""Offene Anträge für einen Verein (Vereins-/Plattform-Admin)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
_assert_manage_club(cur, tenant, club_id)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT r.*, p.email AS applicant_email, p.name AS applicant_name
|
||||||
|
FROM club_membership_requests r
|
||||||
|
INNER JOIN profiles p ON p.id = r.profile_id
|
||||||
|
WHERE r.club_id = %s AND r.status = 'pending'
|
||||||
|
ORDER BY r.created_at ASC
|
||||||
|
""",
|
||||||
|
(club_id,),
|
||||||
|
)
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/clubs/{club_id}/join-requests/{request_id}/accept")
|
||||||
|
def accept_club_join_request(
|
||||||
|
club_id: int,
|
||||||
|
request_id: int,
|
||||||
|
body: JoinRequestAccept,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
admin_pid = tenant.profile_id
|
||||||
|
roles = _normalize_roles(body.roles)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
_assert_manage_club(cur, tenant, club_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, profile_id, status FROM club_membership_requests
|
||||||
|
WHERE id = %s AND club_id = %s
|
||||||
|
""",
|
||||||
|
(request_id, club_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Antrag nicht gefunden")
|
||||||
|
if row["status"] != "pending":
|
||||||
|
raise HTTPException(status_code=400, detail="Antrag ist nicht mehr offen")
|
||||||
|
|
||||||
|
applicant_id = row["profile_id"]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE club_membership_requests
|
||||||
|
SET status = 'accepted',
|
||||||
|
decided_by_profile_id = %s,
|
||||||
|
decided_at = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = %s AND club_id = %s AND status = 'pending'
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(admin_pid, request_id, club_id),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=409, detail="Antrag konnte nicht angenommen werden")
|
||||||
|
|
||||||
|
_upsert_active_member_with_roles(cur, club_id, applicant_id, roles)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "profile_id": applicant_id, "club_id": club_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/clubs/{club_id}/join-requests/{request_id}/reject")
|
||||||
|
def reject_club_join_request(club_id: int, request_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
admin_pid = tenant.profile_id
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
_assert_manage_club(cur, tenant, club_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE club_membership_requests
|
||||||
|
SET status = 'rejected',
|
||||||
|
decided_by_profile_id = %s,
|
||||||
|
decided_at = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = %s AND club_id = %s AND status = 'pending'
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(admin_pid, request_id, club_id),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Offener Antrag nicht gefunden")
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
"""
|
||||||
|
Vereins-Mitgliedschaften und Rollen (ohne UI nutzbar für Admin/Automatisierung).
|
||||||
|
|
||||||
|
Berechtigung: Plattform-Admin (admin/superadmin) oder Vereinsadmin (club_admin) im Zielverein.
|
||||||
|
"""
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from club_tenancy import can_manage_club_org
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["club_memberships"])
|
||||||
|
|
||||||
|
_ALLOWED_ROLES = frozenset({"club_admin", "trainer", "division_lead", "content_editor"})
|
||||||
|
_ALLOWED_STATUS = frozenset({"active", "inactive"})
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_roles(raw: List[str]) -> List[str]:
|
||||||
|
out: List[str] = []
|
||||||
|
seen = set()
|
||||||
|
for r in raw:
|
||||||
|
if not isinstance(r, str):
|
||||||
|
raise HTTPException(status_code=400, detail="Rollen müssen Strings sein")
|
||||||
|
code = r.strip().lower()
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
if code not in _ALLOWED_ROLES:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Unbekannte Rolle: {code}. Erlaubt: {', '.join(sorted(_ALLOWED_ROLES))}",
|
||||||
|
)
|
||||||
|
if code not in seen:
|
||||||
|
seen.add(code)
|
||||||
|
out.append(code)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_manage(cur, tenant: TenantContext, club_id: int) -> None:
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
if not can_manage_club_org(cur, pid, club_id, role):
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung zur Mitglieder-Verwaltung in diesem Verein")
|
||||||
|
|
||||||
|
|
||||||
|
def _club_exists(cur, club_id: int) -> bool:
|
||||||
|
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
|
class ClubMemberPatch(BaseModel):
|
||||||
|
roles: Optional[List[str]] = None
|
||||||
|
status: Optional[str] = Field(None, description="active oder inactive")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clubs/{club_id}/members")
|
||||||
|
def list_club_members(
|
||||||
|
club_id: int,
|
||||||
|
include_inactive: bool = Query(False),
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Alle Mitglieder eines Vereins mit Rollen (nur Vereins-/Plattform-Admin)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_exists(cur, club_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||||
|
_assert_manage(cur, tenant, club_id)
|
||||||
|
|
||||||
|
status_clause = "" if include_inactive else "AND cm.status = 'active'"
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
||||||
|
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[]
|
||||||
|
) AS roles
|
||||||
|
FROM club_members cm
|
||||||
|
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, p.email_verified, p.role
|
||||||
|
ORDER BY p.name NULLS LAST, p.email
|
||||||
|
""",
|
||||||
|
(club_id,),
|
||||||
|
)
|
||||||
|
rows = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
d = r2d(row)
|
||||||
|
roles = d.get("roles") or []
|
||||||
|
if hasattr(roles, "tolist"):
|
||||||
|
roles = roles.tolist()
|
||||||
|
d["roles"] = list(roles)
|
||||||
|
rows.append(d)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/clubs/{club_id}/members", status_code=201)
|
||||||
|
def upsert_club_member(
|
||||||
|
club_id: int,
|
||||||
|
body: ClubMemberUpsert,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Mitglied anlegen oder aktivieren; Rollen werden vollständig ersetzt."""
|
||||||
|
roles = _normalize_roles(body.roles)
|
||||||
|
if not roles:
|
||||||
|
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_exists(cur, club_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||||
|
_assert_manage(cur, tenant, club_id)
|
||||||
|
|
||||||
|
cur.execute("SELECT id FROM profiles WHERE id = %s", (body.profile_id,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
VALUES (%s, %s, 'active')
|
||||||
|
ON CONFLICT (profile_id, club_id)
|
||||||
|
DO UPDATE SET status = 'active', updated_at = NOW()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(body.profile_id, club_id),
|
||||||
|
)
|
||||||
|
cm_id = cur.fetchone()["id"]
|
||||||
|
|
||||||
|
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
|
||||||
|
for rc in roles:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (club_member_id, role_code) DO NOTHING
|
||||||
|
""",
|
||||||
|
(cm_id, rc),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return _one_member(cur, club_id, body.profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
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, 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[]
|
||||||
|
) AS roles
|
||||||
|
FROM club_members cm
|
||||||
|
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, p.email_verified, p.role
|
||||||
|
""",
|
||||||
|
(club_id, profile_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
|
||||||
|
d = r2d(row)
|
||||||
|
roles = d.get("roles") or []
|
||||||
|
if hasattr(roles, "tolist"):
|
||||||
|
roles = roles.tolist()
|
||||||
|
d["roles"] = list(roles)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/clubs/{club_id}/members/{profile_id}")
|
||||||
|
def get_club_member(
|
||||||
|
club_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_exists(cur, club_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||||
|
_assert_manage(cur, tenant, club_id)
|
||||||
|
return _one_member(cur, club_id, profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/clubs/{club_id}/members/{profile_id}")
|
||||||
|
def update_club_member(
|
||||||
|
club_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
body: ClubMemberPatch,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Rollen ersetzen und/oder Status setzen."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_exists(cur, club_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||||
|
_assert_manage(cur, tenant, club_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM club_members WHERE club_id = %s AND profile_id = %s",
|
||||||
|
(club_id, profile_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
|
||||||
|
cm_id = row["id"]
|
||||||
|
|
||||||
|
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:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
|
||||||
|
(new_status, cm_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
if body.roles is not None:
|
||||||
|
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
|
||||||
|
for rc in new_roles:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (club_member_id, role_code) DO NOTHING
|
||||||
|
""",
|
||||||
|
(cm_id, rc),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
return _one_member(cur, club_id, profile_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/clubs/{club_id}/members/{profile_id}")
|
||||||
|
def delete_club_member(
|
||||||
|
club_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Mitgliedschaft löschen (Rollen per CASCADE)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _club_exists(cur, club_id):
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
+426
-177
@@ -3,37 +3,101 @@ Club & Organization Management Endpoints for Shinkan Jinkendo
|
|||||||
|
|
||||||
Handles CRUD operations for clubs, divisions, and training groups.
|
Handles CRUD operations for clubs, divisions, and training groups.
|
||||||
"""
|
"""
|
||||||
from typing import Optional
|
from typing import Any, List, Optional
|
||||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||||
|
from psycopg2.extras import Json
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from auth import require_auth
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
from club_tenancy import (
|
||||||
|
assert_club_member,
|
||||||
|
can_manage_club_org,
|
||||||
|
can_plan_in_club,
|
||||||
|
club_ids_for_profile,
|
||||||
|
is_platform_admin,
|
||||||
|
)
|
||||||
|
|
||||||
router = APIRouter(prefix="/api", tags=["clubs"])
|
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 ────────────────────────────────────────────────────────
|
# ── List Clubs ────────────────────────────────────────────────────────
|
||||||
@router.get("/clubs")
|
@router.get("/clubs")
|
||||||
def list_clubs(
|
def list_clubs(
|
||||||
status: Optional[str] = Query(default=None),
|
status: Optional[str] = Query(default=None),
|
||||||
session=Depends(require_auth)
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
List all clubs (public for authenticated users).
|
Vereine: für normale Nutzer nur Mitgliedschaft-Vereine; Plattform-Admins sehen alle.
|
||||||
|
|
||||||
Filters:
|
|
||||||
- status: active, inactive
|
|
||||||
"""
|
"""
|
||||||
|
role = tenant.global_role
|
||||||
|
profile_id = tenant.profile_id
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
query = "SELECT * FROM clubs"
|
query = "SELECT * FROM clubs"
|
||||||
params = []
|
params: List[Any] = []
|
||||||
|
conds = []
|
||||||
|
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
cids = club_ids_for_profile(cur, profile_id)
|
||||||
|
if not cids:
|
||||||
|
return []
|
||||||
|
conds.append("id IN (" + ",".join(["%s"] * len(cids)) + ")")
|
||||||
|
params.extend(sorted(cids))
|
||||||
|
|
||||||
if status:
|
if status:
|
||||||
query += " WHERE status = %s"
|
conds.append("status = %s")
|
||||||
params.append(status)
|
params.append(status)
|
||||||
|
|
||||||
|
if conds:
|
||||||
|
query += " WHERE " + " AND ".join(conds)
|
||||||
|
|
||||||
query += " ORDER BY name"
|
query += " ORDER BY name"
|
||||||
|
|
||||||
cur.execute(query, params)
|
cur.execute(query, params)
|
||||||
@@ -41,12 +105,64 @@ def list_clubs(
|
|||||||
return [r2d(r) for r in rows]
|
return [r2d(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
# ── Get Club ──────────────────────────────────────────────────────────
|
# ── Öffentliches Vereinsverzeichnis (Registrierung / Antrag ohne Mitgliedschaft) ──
|
||||||
@router.get("/clubs/{club_id}")
|
@router.get("/clubs/public-directory")
|
||||||
def get_club(club_id: int, session=Depends(require_auth)):
|
def public_club_directory():
|
||||||
"""Get club by ID with divisions and groups."""
|
"""Aktive Vereine zur Auswahl bei Registrierung oder Beitrittsantrag (nur id, name, Kürzel)."""
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, name, abbreviation
|
||||||
|
FROM clubs
|
||||||
|
WHERE status = 'active'
|
||||||
|
ORDER BY name
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
# ── Aktive Mitglieder für Trainer-/Co-Trainer-Auswahl (Vereinsmitglied) ──
|
||||||
|
@router.get("/clubs/{club_id}/members/directory")
|
||||||
|
def club_members_directory(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""id + name für alle aktiven Mitglieder; E-Mail nur für Plattform-Admin oder Vereinsadmin (Org-Verwaltung)."""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
assert_club_member(cur, profile_id, club_id)
|
||||||
|
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(404, "Verein nicht gefunden")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id, p.name, p.email
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||||
|
WHERE cm.club_id = %s AND cm.status = 'active'
|
||||||
|
ORDER BY COALESCE(p.name, ''), p.email
|
||||||
|
""",
|
||||||
|
(club_id,),
|
||||||
|
)
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
show_email = is_platform_admin(role) or can_manage_club_org(cur, profile_id, club_id, role)
|
||||||
|
if not show_email:
|
||||||
|
for d in rows:
|
||||||
|
d["email"] = None
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
# ── Get Club ──────────────────────────────────────────────────────────
|
||||||
|
@router.get("/clubs/{club_id}")
|
||||||
|
def get_club(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""Get club by ID with divisions and groups – nur Mitglied oder Plattform-Admin."""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
assert_club_member(cur, profile_id, club_id)
|
||||||
|
|
||||||
# Get club
|
# Get club
|
||||||
cur.execute("SELECT * FROM clubs WHERE id = %s", (club_id,))
|
cur.execute("SELECT * FROM clubs WHERE id = %s", (club_id,))
|
||||||
@@ -58,66 +174,108 @@ def get_club(club_id: int, session=Depends(require_auth)):
|
|||||||
club = r2d(club)
|
club = r2d(club)
|
||||||
|
|
||||||
# Get divisions
|
# Get divisions
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
SELECT * FROM divisions
|
SELECT * FROM divisions
|
||||||
WHERE club_id = %s
|
WHERE club_id = %s
|
||||||
ORDER BY name
|
ORDER BY name
|
||||||
""", (club_id,))
|
""",
|
||||||
club['divisions'] = [r2d(r) for r in cur.fetchall()]
|
(club_id,),
|
||||||
|
)
|
||||||
|
club["divisions"] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
# Get training groups
|
# Get training groups
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
SELECT g.*,
|
SELECT g.*,
|
||||||
p.name as trainer_name
|
p.name as trainer_name
|
||||||
FROM training_groups g
|
FROM training_groups g
|
||||||
LEFT JOIN profiles p ON g.trainer_id = p.id
|
LEFT JOIN profiles p ON g.trainer_id = p.id
|
||||||
WHERE g.club_id = %s
|
WHERE g.club_id = %s
|
||||||
ORDER BY g.weekday, g.time_start
|
ORDER BY g.weekday, g.time_start
|
||||||
""", (club_id,))
|
""",
|
||||||
club['training_groups'] = [r2d(r) for r in cur.fetchall()]
|
(club_id,),
|
||||||
|
)
|
||||||
|
club["training_groups"] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
return club
|
return club
|
||||||
|
|
||||||
|
|
||||||
# ── Create Club ───────────────────────────────────────────────────────
|
# ── Create Club ───────────────────────────────────────────────────────
|
||||||
@router.post("/clubs")
|
@router.post("/clubs")
|
||||||
def create_club(data: dict, session=Depends(require_auth)):
|
def create_club(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Create new club (Admin oder Trainer — MVP ohne separates Vereins-Onboarding)."""
|
"""Neuen Verein anlegen – nur Plattform-Admin; Pflicht: primary_admin_profile_id (Hauptverwalter:in)."""
|
||||||
role = session.get('role')
|
role = tenant.global_role
|
||||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
if not is_platform_admin(role):
|
||||||
raise HTTPException(403, "Keine Berechtigung, Vereine anzulegen")
|
raise HTTPException(403, "Nur Plattform-Administratoren dürfen neue Vereine anlegen")
|
||||||
|
|
||||||
name = data.get('name')
|
name = data.get("name")
|
||||||
|
primary_admin_profile_id = data.get("primary_admin_profile_id")
|
||||||
if not name:
|
if not name:
|
||||||
raise HTTPException(400, "Name ist Pflichtfeld")
|
raise HTTPException(400, "Name ist Pflichtfeld")
|
||||||
|
if not primary_admin_profile_id:
|
||||||
|
raise HTTPException(400, "primary_admin_profile_id ist Pflichtfeld (Hauptverwalter:in)")
|
||||||
|
|
||||||
|
try:
|
||||||
|
aid = int(primary_admin_profile_id)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(400, "primary_admin_profile_id ungültig")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id FROM profiles WHERE id = %s", (aid,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(404, "Profil für Hauptverwalter nicht gefunden")
|
||||||
|
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
INSERT INTO clubs (name, abbreviation, description, status)
|
"""
|
||||||
VALUES (%s, %s, %s, %s)
|
INSERT INTO clubs (name, abbreviation, description, status, primary_admin_profile_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""", (
|
""",
|
||||||
|
(
|
||||||
name,
|
name,
|
||||||
data.get('abbreviation'),
|
data.get("abbreviation"),
|
||||||
data.get('description'),
|
data.get("description"),
|
||||||
data.get('status', 'active')
|
data.get("status", "active"),
|
||||||
))
|
aid,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
club_id = cur.fetchone()["id"]
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_members (profile_id, club_id, status)
|
||||||
|
VALUES (%s, %s, 'active')
|
||||||
|
ON CONFLICT (profile_id, club_id)
|
||||||
|
DO UPDATE SET status = 'active', updated_at = NOW()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(aid, club_id),
|
||||||
|
)
|
||||||
|
cm_id = cur.fetchone()["id"]
|
||||||
|
for rc in ("club_admin", "trainer"):
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (club_member_id, role_code) DO NOTHING
|
||||||
|
""",
|
||||||
|
(cm_id, rc),
|
||||||
|
)
|
||||||
|
|
||||||
club_id = cur.fetchone()['id']
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_club(club_id, session)
|
return get_club(club_id, tenant)
|
||||||
|
|
||||||
|
|
||||||
# ── Update Club ───────────────────────────────────────────────────────
|
# ── Update Club ───────────────────────────────────────────────────────
|
||||||
@router.put("/clubs/{club_id}")
|
@router.put("/clubs/{club_id}")
|
||||||
def update_club(club_id: int, data: dict, session=Depends(require_auth)):
|
def update_club(club_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Update club (admin only)."""
|
"""Verein bearbeiten – Plattform-Admin oder Vereinsadmin."""
|
||||||
role = session.get('role')
|
profile_id = tenant.profile_id
|
||||||
if role not in ['admin', 'superadmin']:
|
role = tenant.global_role
|
||||||
raise HTTPException(403, "Nur Admins dürfen Vereine bearbeiten")
|
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
@@ -127,33 +285,46 @@ def update_club(club_id: int, data: dict, session=Depends(require_auth)):
|
|||||||
if not cur.fetchone():
|
if not cur.fetchone():
|
||||||
raise HTTPException(404, "Verein nicht gefunden")
|
raise HTTPException(404, "Verein nicht gefunden")
|
||||||
|
|
||||||
|
if not can_manage_club_org(cur, profile_id, club_id, role):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
|
||||||
|
|
||||||
|
# Nur Plattform-Admin darf primary_admin_profile_id ändern
|
||||||
|
if "primary_admin_profile_id" in data and data["primary_admin_profile_id"] is not None:
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(403, "Nur Plattform-Admins dürfen den Hauptverwalter ändern")
|
||||||
|
|
||||||
# Update
|
# Update
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
UPDATE clubs SET
|
UPDATE clubs SET
|
||||||
name = %s,
|
name = COALESCE(%s, name),
|
||||||
abbreviation = %s,
|
abbreviation = COALESCE(%s, abbreviation),
|
||||||
description = %s,
|
description = COALESCE(%s, description),
|
||||||
status = %s,
|
status = COALESCE(%s, status),
|
||||||
|
primary_admin_profile_id = COALESCE(%s, primary_admin_profile_id),
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
""", (
|
""",
|
||||||
data.get('name'),
|
(
|
||||||
data.get('abbreviation'),
|
data.get("name"),
|
||||||
data.get('description'),
|
data.get("abbreviation"),
|
||||||
data.get('status'),
|
data.get("description"),
|
||||||
club_id
|
data.get("status"),
|
||||||
))
|
data.get("primary_admin_profile_id"),
|
||||||
|
club_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_club(club_id, session)
|
return get_club(club_id, tenant)
|
||||||
|
|
||||||
|
|
||||||
# ── Delete Club ───────────────────────────────────────────────────────
|
# ── Delete Club ───────────────────────────────────────────────────────
|
||||||
@router.delete("/clubs/{club_id}")
|
@router.delete("/clubs/{club_id}")
|
||||||
def delete_club(club_id: int, session=Depends(require_auth)):
|
def delete_club(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Delete club (superadmin only)."""
|
"""Delete club (superadmin only)."""
|
||||||
role = session.get('role')
|
role = tenant.global_role
|
||||||
if role != 'superadmin':
|
if role != 'superadmin':
|
||||||
raise HTTPException(403, "Nur Superadmins dürfen Vereine löschen")
|
raise HTTPException(403, "Nur Superadmins dürfen Vereine löschen")
|
||||||
|
|
||||||
@@ -176,22 +347,41 @@ def delete_club(club_id: int, session=Depends(require_auth)):
|
|||||||
@router.get("/divisions")
|
@router.get("/divisions")
|
||||||
def list_divisions(
|
def list_divisions(
|
||||||
club_id: Optional[int] = Query(default=None),
|
club_id: Optional[int] = Query(default=None),
|
||||||
session=Depends(require_auth)
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
"""List divisions (optional filter by club)."""
|
"""Sparten – ohne Admin-Rechte nur in eigenen Vereinen sichtbar."""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
mine = club_ids_for_profile(cur, profile_id)
|
||||||
|
if not is_platform_admin(role) and not mine:
|
||||||
|
return []
|
||||||
|
|
||||||
query = """
|
query = """
|
||||||
SELECT d.*, c.name as club_name
|
SELECT d.*, c.name as club_name
|
||||||
FROM divisions d
|
FROM divisions d
|
||||||
LEFT JOIN clubs c ON d.club_id = c.id
|
LEFT JOIN clubs c ON d.club_id = c.id
|
||||||
"""
|
"""
|
||||||
|
where = []
|
||||||
params = []
|
params = []
|
||||||
|
|
||||||
if club_id:
|
if club_id is not None:
|
||||||
query += " WHERE d.club_id = %s"
|
where.append("d.club_id = %s")
|
||||||
params.append(club_id)
|
params.append(club_id)
|
||||||
|
if not is_platform_admin(role) and club_id not in mine:
|
||||||
|
return []
|
||||||
|
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
where.append(
|
||||||
|
"d.club_id IN (" + ",".join(["%s"] * len(mine)) + ")"
|
||||||
|
)
|
||||||
|
params.extend(sorted(mine))
|
||||||
|
|
||||||
|
if where:
|
||||||
|
query += " WHERE " + " AND ".join(where)
|
||||||
|
|
||||||
query += " ORDER BY d.name"
|
query += " ORDER BY d.name"
|
||||||
|
|
||||||
@@ -202,14 +392,13 @@ def list_divisions(
|
|||||||
|
|
||||||
# ── Create Division ───────────────────────────────────────────────────
|
# ── Create Division ───────────────────────────────────────────────────
|
||||||
@router.post("/divisions")
|
@router.post("/divisions")
|
||||||
def create_division(data: dict, session=Depends(require_auth)):
|
def create_division(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Create new division (admin only)."""
|
"""Create new division – Vereinsadmin / Plattform-Admin."""
|
||||||
role = session.get('role')
|
profile_id = tenant.profile_id
|
||||||
if role not in ['admin', 'superadmin']:
|
role = tenant.global_role
|
||||||
raise HTTPException(403, "Nur Admins dürfen Sparten erstellen")
|
|
||||||
|
|
||||||
club_id = data.get('club_id')
|
club_id = data.get("club_id")
|
||||||
name = data.get('name')
|
name = data.get("name")
|
||||||
|
|
||||||
if not club_id or not name:
|
if not club_id or not name:
|
||||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||||
@@ -217,93 +406,109 @@ def create_division(data: dict, session=Depends(require_auth)):
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
if not can_manage_club_org(cur, profile_id, int(club_id), role):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung, Sparten in diesem Verein anzulegen")
|
||||||
|
|
||||||
# Check club exists
|
# Check club exists
|
||||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||||
if not cur.fetchone():
|
if not cur.fetchone():
|
||||||
raise HTTPException(404, "Verein nicht gefunden")
|
raise HTTPException(404, "Verein nicht gefunden")
|
||||||
|
|
||||||
# Insert
|
# Insert
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
INSERT INTO divisions (club_id, name, focus_area)
|
INSERT INTO divisions (club_id, name, focus_area)
|
||||||
VALUES (%s, %s, %s)
|
VALUES (%s, %s, %s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""", (
|
""",
|
||||||
|
(
|
||||||
club_id,
|
club_id,
|
||||||
name,
|
name,
|
||||||
data.get('focus_area')
|
data.get("focus_area"),
|
||||||
))
|
),
|
||||||
|
)
|
||||||
|
|
||||||
division_id = cur.fetchone()['id']
|
division_id = cur.fetchone()["id"]
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
# Return created division
|
# Return created division
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
SELECT d.*, c.name as club_name
|
SELECT d.*, c.name as club_name
|
||||||
FROM divisions d
|
FROM divisions d
|
||||||
LEFT JOIN clubs c ON d.club_id = c.id
|
LEFT JOIN clubs c ON d.club_id = c.id
|
||||||
WHERE d.id = %s
|
WHERE d.id = %s
|
||||||
""", (division_id,))
|
""",
|
||||||
|
(division_id,),
|
||||||
|
)
|
||||||
return r2d(cur.fetchone())
|
return r2d(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
# ── Update Division ───────────────────────────────────────────────────
|
# ── Update Division ───────────────────────────────────────────────────
|
||||||
@router.put("/divisions/{division_id}")
|
@router.put("/divisions/{division_id}")
|
||||||
def update_division(division_id: int, data: dict, session=Depends(require_auth)):
|
def update_division(division_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Update division (admin only)."""
|
"""Update division – Vereinsadmin / Plattform-Admin."""
|
||||||
role = session.get('role')
|
profile_id = tenant.profile_id
|
||||||
if role not in ['admin', 'superadmin']:
|
role = tenant.global_role
|
||||||
raise HTTPException(403, "Nur Admins dürfen Sparten bearbeiten")
|
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Check existence
|
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
div = cur.fetchone()
|
||||||
if not cur.fetchone():
|
if not div:
|
||||||
raise HTTPException(404, "Sparte nicht gefunden")
|
raise HTTPException(404, "Sparte nicht gefunden")
|
||||||
|
|
||||||
# Update
|
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
|
||||||
cur.execute("""
|
raise HTTPException(403, "Keine Berechtigung")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
UPDATE divisions SET
|
UPDATE divisions SET
|
||||||
name = %s,
|
name = %s,
|
||||||
focus_area = %s,
|
focus_area = %s,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
""", (
|
""",
|
||||||
data.get('name'),
|
(
|
||||||
data.get('focus_area'),
|
data.get("name"),
|
||||||
division_id
|
data.get("focus_area"),
|
||||||
))
|
division_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
# Return updated division
|
cur.execute(
|
||||||
cur.execute("""
|
"""
|
||||||
SELECT d.*, c.name as club_name
|
SELECT d.*, c.name as club_name
|
||||||
FROM divisions d
|
FROM divisions d
|
||||||
LEFT JOIN clubs c ON d.club_id = c.id
|
LEFT JOIN clubs c ON d.club_id = c.id
|
||||||
WHERE d.id = %s
|
WHERE d.id = %s
|
||||||
""", (division_id,))
|
""",
|
||||||
|
(division_id,),
|
||||||
|
)
|
||||||
return r2d(cur.fetchone())
|
return r2d(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
# ── Delete Division ───────────────────────────────────────────────────
|
# ── Delete Division ───────────────────────────────────────────────────
|
||||||
@router.delete("/divisions/{division_id}")
|
@router.delete("/divisions/{division_id}")
|
||||||
def delete_division(division_id: int, session=Depends(require_auth)):
|
def delete_division(division_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Delete division (admin only)."""
|
"""Delete division – Vereinsadmin / Plattform-Admin."""
|
||||||
role = session.get('role')
|
profile_id = tenant.profile_id
|
||||||
if role not in ['admin', 'superadmin']:
|
role = tenant.global_role
|
||||||
raise HTTPException(403, "Nur Admins dürfen Sparten löschen")
|
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Check existence
|
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
div = cur.fetchone()
|
||||||
if not cur.fetchone():
|
if not div:
|
||||||
raise HTTPException(404, "Sparte nicht gefunden")
|
raise HTTPException(404, "Sparte nicht gefunden")
|
||||||
|
|
||||||
# Delete
|
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung")
|
||||||
|
|
||||||
cur.execute("DELETE FROM divisions WHERE id = %s", (division_id,))
|
cur.execute("DELETE FROM divisions WHERE id = %s", (division_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
@@ -316,19 +521,21 @@ def list_training_groups(
|
|||||||
club_id: Optional[int] = Query(default=None),
|
club_id: Optional[int] = Query(default=None),
|
||||||
division_id: Optional[int] = Query(default=None),
|
division_id: Optional[int] = Query(default=None),
|
||||||
status: Optional[str] = Query(default=None),
|
status: Optional[str] = Query(default=None),
|
||||||
session=Depends(require_auth)
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
List training groups with optional filters.
|
Trainingsgruppen – ohne Plattform-Admin nur in eigenen Vereinen.
|
||||||
|
|
||||||
Filters:
|
|
||||||
- club_id: Filter by club
|
|
||||||
- division_id: Filter by division
|
|
||||||
- status: active, inactive
|
|
||||||
"""
|
"""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
mine = club_ids_for_profile(cur, profile_id)
|
||||||
|
if not is_platform_admin(role) and not mine:
|
||||||
|
return []
|
||||||
|
|
||||||
query = """
|
query = """
|
||||||
SELECT g.*,
|
SELECT g.*,
|
||||||
c.name as club_name,
|
c.name as club_name,
|
||||||
@@ -343,11 +550,13 @@ def list_training_groups(
|
|||||||
where = []
|
where = []
|
||||||
params = []
|
params = []
|
||||||
|
|
||||||
if club_id:
|
if club_id is not None:
|
||||||
where.append("g.club_id = %s")
|
where.append("g.club_id = %s")
|
||||||
params.append(club_id)
|
params.append(club_id)
|
||||||
|
if not is_platform_admin(role) and club_id not in mine:
|
||||||
|
return []
|
||||||
|
|
||||||
if division_id:
|
if division_id is not None:
|
||||||
where.append("g.division_id = %s")
|
where.append("g.division_id = %s")
|
||||||
params.append(division_id)
|
params.append(division_id)
|
||||||
|
|
||||||
@@ -355,6 +564,10 @@ def list_training_groups(
|
|||||||
where.append("g.status = %s")
|
where.append("g.status = %s")
|
||||||
params.append(status)
|
params.append(status)
|
||||||
|
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
where.append("g.club_id IN (" + ",".join(["%s"] * len(mine)) + ")")
|
||||||
|
params.extend(sorted(mine))
|
||||||
|
|
||||||
if where:
|
if where:
|
||||||
query += " WHERE " + " AND ".join(where)
|
query += " WHERE " + " AND ".join(where)
|
||||||
|
|
||||||
@@ -367,12 +580,15 @@ def list_training_groups(
|
|||||||
|
|
||||||
# ── Get Training Group ────────────────────────────────────────────────
|
# ── Get Training Group ────────────────────────────────────────────────
|
||||||
@router.get("/groups/{group_id}")
|
@router.get("/groups/{group_id}")
|
||||||
def get_training_group(group_id: int, session=Depends(require_auth)):
|
def get_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Get training group by ID."""
|
"""Trainingsgruppe – nur mit Vereinszugriff."""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
SELECT g.*,
|
SELECT g.*,
|
||||||
c.name as club_name,
|
c.name as club_name,
|
||||||
d.name as division_name,
|
d.name as division_name,
|
||||||
@@ -382,45 +598,61 @@ def get_training_group(group_id: int, session=Depends(require_auth)):
|
|||||||
LEFT JOIN divisions d ON g.division_id = d.id
|
LEFT JOIN divisions d ON g.division_id = d.id
|
||||||
LEFT JOIN profiles p ON g.trainer_id = p.id
|
LEFT JOIN profiles p ON g.trainer_id = p.id
|
||||||
WHERE g.id = %s
|
WHERE g.id = %s
|
||||||
""", (group_id,))
|
""",
|
||||||
|
(group_id,),
|
||||||
|
)
|
||||||
|
|
||||||
group = cur.fetchone()
|
group = cur.fetchone()
|
||||||
|
|
||||||
if not group:
|
if not group:
|
||||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||||
|
|
||||||
|
cid = group["club_id"]
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
assert_club_member(cur, profile_id, cid)
|
||||||
|
|
||||||
return r2d(group)
|
return r2d(group)
|
||||||
|
|
||||||
|
|
||||||
# ── Create Training Group ─────────────────────────────────────────────
|
# ── Create Training Group ─────────────────────────────────────────────
|
||||||
@router.post("/groups")
|
@router.post("/groups")
|
||||||
def create_training_group(data: dict, session=Depends(require_auth)):
|
def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Create new training group (admin, trainer oder normaler Nutzer mit Vereinsbezug)."""
|
"""Trainingsgruppe anlegen – Mitglied mit Planungs-/Admin-Rolle im Verein."""
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get('role')
|
role = tenant.global_role
|
||||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
if role not in ("admin", "superadmin", "trainer", "user"):
|
||||||
raise HTTPException(403, "Keine Berechtigung, Trainingsgruppen anzulegen")
|
raise HTTPException(403, "Keine Berechtigung, Trainingsgruppen anzulegen")
|
||||||
|
|
||||||
club_id = data.get('club_id')
|
club_id = data.get("club_id")
|
||||||
name = data.get('name')
|
name = data.get("name")
|
||||||
|
|
||||||
if not club_id or not name:
|
if not club_id or not name:
|
||||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||||
|
|
||||||
trainer_id = data.get('trainer_id')
|
raw_tid = data.get("trainer_id")
|
||||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
if role in ("trainer", "user"):
|
||||||
trainer_id = profile_id
|
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:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
if not can_plan_in_club(cur, profile_id, int(club_id), role):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
|
||||||
|
|
||||||
# Check club exists
|
# Check club exists
|
||||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||||
if not cur.fetchone():
|
if not cur.fetchone():
|
||||||
raise HTTPException(404, "Verein nicht gefunden")
|
raise HTTPException(404, "Verein nicht gefunden")
|
||||||
|
|
||||||
# Insert
|
# Insert
|
||||||
cur.execute("""
|
cur.execute(
|
||||||
|
"""
|
||||||
INSERT INTO training_groups (
|
INSERT INTO training_groups (
|
||||||
club_id, division_id, name, focus, level, age_group,
|
club_id, division_id, name, focus, level, age_group,
|
||||||
weekday, time_start, time_end, location,
|
weekday, time_start, time_end, location,
|
||||||
@@ -428,52 +660,66 @@ def create_training_group(data: dict, session=Depends(require_auth)):
|
|||||||
) VALUES (
|
) VALUES (
|
||||||
%s, %s, %s, %s, %s, %s,
|
%s, %s, %s, %s, %s, %s,
|
||||||
%s, %s, %s, %s,
|
%s, %s, %s, %s,
|
||||||
%s, %s, %s
|
%s, %s::jsonb, %s
|
||||||
) RETURNING id
|
) RETURNING id
|
||||||
""", (
|
""",
|
||||||
club_id,
|
(
|
||||||
data.get('division_id'),
|
int(club_id),
|
||||||
|
division_id,
|
||||||
name,
|
name,
|
||||||
data.get('focus'),
|
_blank_to_none(data.get("focus")),
|
||||||
data.get('level'),
|
_blank_to_none(data.get("level")),
|
||||||
data.get('age_group'),
|
_blank_to_none(data.get("age_group")),
|
||||||
data.get('weekday'),
|
_blank_to_none(data.get("weekday")),
|
||||||
data.get('time_start'),
|
_blank_to_none(data.get("time_start")),
|
||||||
data.get('time_end'),
|
_blank_to_none(data.get("time_end")),
|
||||||
data.get('location'),
|
_blank_to_none(data.get("location")),
|
||||||
trainer_id,
|
trainer_id,
|
||||||
data.get('co_trainer_ids'),
|
co_json,
|
||||||
data.get('status', 'active')
|
data.get("status") or "active",
|
||||||
))
|
),
|
||||||
|
)
|
||||||
|
|
||||||
group_id = cur.fetchone()['id']
|
group_id = cur.fetchone()["id"]
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_training_group(group_id, session)
|
return get_training_group(group_id, tenant)
|
||||||
|
|
||||||
|
|
||||||
# ── Update Training Group ─────────────────────────────────────────────
|
# ── Update Training Group ─────────────────────────────────────────────
|
||||||
@router.put("/groups/{group_id}")
|
@router.put("/groups/{group_id}")
|
||||||
def update_training_group(group_id: int, data: dict, session=Depends(require_auth)):
|
def update_training_group(group_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Update training group (admin or assigned trainer)."""
|
"""Update training group – Vereinsadmin, Plattform-Admin oder zugewiesene Trainer."""
|
||||||
profile_id = session['profile_id']
|
profile_id = tenant.profile_id
|
||||||
role = session.get('role')
|
role = tenant.global_role
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Check existence and ownership
|
cur.execute(
|
||||||
cur.execute("SELECT trainer_id FROM training_groups WHERE id = %s", (group_id,))
|
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
|
||||||
|
(group_id,),
|
||||||
|
)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||||
|
|
||||||
# Only admin or assigned trainer can update
|
co_trainers = row["co_trainer_ids"] or []
|
||||||
if role not in ['admin', 'superadmin'] and row['trainer_id'] != profile_id:
|
club_id = row["club_id"]
|
||||||
|
|
||||||
|
allowed = role in ("admin", "superadmin")
|
||||||
|
if not allowed:
|
||||||
|
allowed = can_manage_club_org(cur, profile_id, club_id, role)
|
||||||
|
if not allowed:
|
||||||
|
allowed = row["trainer_id"] == profile_id or profile_id in co_trainers
|
||||||
|
|
||||||
|
if not allowed:
|
||||||
raise HTTPException(403, "Keine Berechtigung")
|
raise HTTPException(403, "Keine Berechtigung")
|
||||||
|
|
||||||
# Update
|
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||||
cur.execute("""
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
UPDATE training_groups SET
|
UPDATE training_groups SET
|
||||||
name = %s,
|
name = %s,
|
||||||
division_id = %s,
|
division_id = %s,
|
||||||
@@ -485,48 +731,51 @@ def update_training_group(group_id: int, data: dict, session=Depends(require_aut
|
|||||||
time_end = %s,
|
time_end = %s,
|
||||||
location = %s,
|
location = %s,
|
||||||
trainer_id = %s,
|
trainer_id = %s,
|
||||||
co_trainer_ids = %s,
|
co_trainer_ids = %s::jsonb,
|
||||||
status = %s,
|
status = %s,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
""", (
|
""",
|
||||||
data.get('name'),
|
(
|
||||||
data.get('division_id'),
|
data.get("name"),
|
||||||
data.get('focus'),
|
_optional_int(data.get("division_id")),
|
||||||
data.get('level'),
|
_blank_to_none(data.get("focus")),
|
||||||
data.get('age_group'),
|
_blank_to_none(data.get("level")),
|
||||||
data.get('weekday'),
|
_blank_to_none(data.get("age_group")),
|
||||||
data.get('time_start'),
|
_blank_to_none(data.get("weekday")),
|
||||||
data.get('time_end'),
|
_blank_to_none(data.get("time_start")),
|
||||||
data.get('location'),
|
_blank_to_none(data.get("time_end")),
|
||||||
data.get('trainer_id'),
|
_blank_to_none(data.get("location")),
|
||||||
data.get('co_trainer_ids'),
|
_optional_int(data.get("trainer_id")),
|
||||||
data.get('status'),
|
co_json,
|
||||||
group_id
|
data.get("status") or "active",
|
||||||
))
|
group_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_training_group(group_id, session)
|
return get_training_group(group_id, tenant)
|
||||||
|
|
||||||
|
|
||||||
# ── Delete Training Group ─────────────────────────────────────────────
|
# ── Delete Training Group ─────────────────────────────────────────────
|
||||||
@router.delete("/groups/{group_id}")
|
@router.delete("/groups/{group_id}")
|
||||||
def delete_training_group(group_id: int, session=Depends(require_auth)):
|
def delete_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
"""Delete training group (admin only)."""
|
"""Delete training group – Vereinsadmin oder Plattform-Admin."""
|
||||||
role = session.get('role')
|
profile_id = tenant.profile_id
|
||||||
if role not in ['admin', 'superadmin']:
|
role = tenant.global_role
|
||||||
raise HTTPException(403, "Nur Admins dürfen Gruppen löschen")
|
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Check existence
|
cur.execute("SELECT id, club_id FROM training_groups WHERE id = %s", (group_id,))
|
||||||
cur.execute("SELECT id FROM training_groups WHERE id = %s", (group_id,))
|
row = cur.fetchone()
|
||||||
if not cur.fetchone():
|
if not row:
|
||||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||||
|
|
||||||
# Delete
|
if not can_manage_club_org(cur, profile_id, row["club_id"], role):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung")
|
||||||
|
|
||||||
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,931 @@
|
|||||||
|
"""
|
||||||
|
P-13: Content-Melde-Backend
|
||||||
|
|
||||||
|
Meldeverfahren fuer moeglicherweise rechtswidrige Inhalte (DSA-Grundlage, KRIT-03).
|
||||||
|
|
||||||
|
Architektur:
|
||||||
|
- Fachliche Daten in 'content_reports' Tabelle (Migration 052)
|
||||||
|
- Integration in bestehende Admin-Inbox (GET /api/me/inbox/content-reports)
|
||||||
|
- Keine separate Admin-Queue; die InboxPage.jsx zeigt beide Vorgangstypen
|
||||||
|
- P-11-Anschluss: Superadmin kann aus Meldung heraus Legal Hold setzen
|
||||||
|
|
||||||
|
Berechtigungen:
|
||||||
|
- Meldung einreichen: optional Auth (ohne Auth nur fuer official-Medien erlaubt)
|
||||||
|
- Liste/Detail: Plattform-Admin (alle Meldungen) oder Club-Admin (nur eigene Vereinsmedien)
|
||||||
|
- Status-Bearbeitung: Plattform-Admin
|
||||||
|
- Legal Hold aus Meldung: ausschliesslich Superadmin
|
||||||
|
|
||||||
|
E-Mail-Benachrichtigungen:
|
||||||
|
- Nach Eingang: Bestaetigung an Melder
|
||||||
|
- Nach Eingang: Benachrichtigung aller Plattform-Admins (best-effort, kein Fehler wenn SMTP fehlt)
|
||||||
|
|
||||||
|
Audit-Log (Migration 053):
|
||||||
|
- Bei media_asset-Meldungen: Eintrag in media_asset_audit_log (event_type='content_report_filed')
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
|
from club_tenancy import is_platform_admin, is_superadmin
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from media_legal_hold import (
|
||||||
|
LEGAL_HOLD_REASON_CODES,
|
||||||
|
assert_superadmin_for_legal_hold,
|
||||||
|
set_legal_hold,
|
||||||
|
)
|
||||||
|
from media_rights import write_audit_log_entry
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["content_reports"])
|
||||||
|
|
||||||
|
# Erlaubte Meldungsgruende
|
||||||
|
REPORT_REASONS = frozenset({
|
||||||
|
"copyright",
|
||||||
|
"image_rights",
|
||||||
|
"privacy",
|
||||||
|
"minors",
|
||||||
|
"illegal_content",
|
||||||
|
"youth_protection",
|
||||||
|
"offensive_content",
|
||||||
|
"other",
|
||||||
|
})
|
||||||
|
|
||||||
|
REASON_LABELS_DE = {
|
||||||
|
"copyright": "Urheberrecht",
|
||||||
|
"image_rights": "Bildrechte",
|
||||||
|
"privacy": "Datenschutz / Persönlichkeitsrecht",
|
||||||
|
"minors": "Minderjährige",
|
||||||
|
"illegal_content": "Rechtswidriger Inhalt",
|
||||||
|
"youth_protection": "Jugendschutz",
|
||||||
|
"offensive_content": "Beleidigender Inhalt",
|
||||||
|
"other": "Sonstiges",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gruende mit hoher Prioritaet (illegal, Minderjaehrigenschutz)
|
||||||
|
HIGH_PRIORITY_REASONS = frozenset({
|
||||||
|
"minors",
|
||||||
|
"illegal_content",
|
||||||
|
"youth_protection",
|
||||||
|
})
|
||||||
|
|
||||||
|
# Mapping: report_reason -> legal_hold reason_code
|
||||||
|
_REASON_TO_HOLD_CODE = {
|
||||||
|
"copyright": "copyright_complaint",
|
||||||
|
"image_rights": "rights_dispute",
|
||||||
|
"privacy": "privacy_complaint",
|
||||||
|
"minors": "youth_protection",
|
||||||
|
"illegal_content": "illegal_content",
|
||||||
|
"youth_protection": "youth_protection",
|
||||||
|
"offensive_content": "illegal_content",
|
||||||
|
"other": "other",
|
||||||
|
}
|
||||||
|
|
||||||
|
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Pydantic-Modelle ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class ContentReportCreate(BaseModel):
|
||||||
|
target_type: str = Field(default="media_asset")
|
||||||
|
target_id: int = Field(..., ge=1)
|
||||||
|
report_reason: str
|
||||||
|
report_description: str = Field(..., min_length=10, max_length=8000)
|
||||||
|
reporter_name: str = Field(..., min_length=1, max_length=200)
|
||||||
|
reporter_email: str = Field(..., min_length=5, max_length=200)
|
||||||
|
good_faith_confirmed: bool
|
||||||
|
|
||||||
|
@field_validator("target_type")
|
||||||
|
@classmethod
|
||||||
|
def validate_target_type(cls, v: str) -> str:
|
||||||
|
if v not in ("media_asset", "exercise"):
|
||||||
|
raise ValueError("target_type muss 'media_asset' oder 'exercise' sein")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator("report_reason")
|
||||||
|
@classmethod
|
||||||
|
def validate_reason(cls, v: str) -> str:
|
||||||
|
if v not in REPORT_REASONS:
|
||||||
|
raise ValueError(f"Ungueltiger report_reason. Erlaubt: {sorted(REPORT_REASONS)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator("reporter_email")
|
||||||
|
@classmethod
|
||||||
|
def validate_email(cls, v: str) -> str:
|
||||||
|
if not _EMAIL_RE.match(v.strip()):
|
||||||
|
raise ValueError("Ungueltige E-Mail-Adresse")
|
||||||
|
return v.strip().lower()
|
||||||
|
|
||||||
|
@field_validator("reporter_name")
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: str) -> str:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("Name darf nicht leer sein")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class ContentReportPatch(BaseModel):
|
||||||
|
status: Optional[str] = None
|
||||||
|
resolution_note: Optional[str] = Field(None, max_length=4000)
|
||||||
|
assigned_to_profile_id: Optional[int] = None
|
||||||
|
|
||||||
|
@field_validator("status")
|
||||||
|
@classmethod
|
||||||
|
def validate_status(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is None:
|
||||||
|
return v
|
||||||
|
allowed = {"submitted", "under_review", "resolved_no_action",
|
||||||
|
"resolved_legal_hold", "rejected_invalid"}
|
||||||
|
if v not in allowed:
|
||||||
|
raise ValueError(f"Ungueltiger status. Erlaubt: {sorted(allowed)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class ContentReportLegalHoldBody(BaseModel):
|
||||||
|
reason_note: str = Field(..., min_length=5, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Hilfsfunktionen ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _assert_can_manage_report(cur, role: Optional[str], pid: int, report: dict) -> None:
|
||||||
|
"""Platform-Admins: jede Meldung. Club-Admin: nur Meldungen zu Medien ihres Vereins."""
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
if report.get("target_type") != "media_asset":
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Plattform-Admins können Meldungen zu Übungen bearbeiten")
|
||||||
|
cur.execute("SELECT club_id FROM media_assets WHERE id = %s", (int(report["target_id"]),))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||||
|
club_id = r2d(row).get("club_id")
|
||||||
|
if not club_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein Zugriff – Medium ohne Vereinszugehörigkeit")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members cm
|
||||||
|
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||||
|
AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||||
|
""",
|
||||||
|
(pid, club_id),
|
||||||
|
)
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein Zugriff auf diese Meldung")
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_can_set_legal_hold_from_report(cur, role: Optional[str], pid: int, asset_id: int) -> None:
|
||||||
|
"""Superadmin: immer. Club-Admin: nur für Vereinsmedien mit visibility != 'official'."""
|
||||||
|
if is_superadmin(role):
|
||||||
|
return
|
||||||
|
cur.execute("SELECT club_id, visibility FROM media_assets WHERE id = %s", (asset_id,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||||
|
asset = r2d(row)
|
||||||
|
if asset.get("visibility") == "official":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Legal Hold auf offiziellen Medien erfordert Superadmin-Rechte",
|
||||||
|
)
|
||||||
|
club_id = asset.get("club_id")
|
||||||
|
if not club_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Legal Hold erfordert Superadmin-Rechte für Medien ohne Vereinszugehörigkeit")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members cm
|
||||||
|
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||||
|
AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||||
|
""",
|
||||||
|
(pid, club_id),
|
||||||
|
)
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein Zugriff – Superadmin oder Vereinsadmin des Vereins erforderlich")
|
||||||
|
|
||||||
|
|
||||||
|
def _is_media_asset_visible_anonymous(cur, asset_id: int) -> bool:
|
||||||
|
"""True wenn das Medium als 'official' und aktiv gilt (fuer anonyme Meldung zugaenglich)."""
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM media_assets
|
||||||
|
WHERE id = %s
|
||||||
|
AND visibility = 'official'
|
||||||
|
AND lifecycle_state = 'active'
|
||||||
|
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)
|
||||||
|
""",
|
||||||
|
(asset_id,),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _is_media_asset_visible_to_profile(cur, asset_id: int, profile_id: int, global_role: Optional[str]) -> bool:
|
||||||
|
"""Prueft ob ein eingeloggter Nutzer das Medium sehen darf."""
|
||||||
|
if is_platform_admin(global_role):
|
||||||
|
cur.execute("SELECT 1 FROM media_assets WHERE id = %s", (asset_id,))
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT ma.id, ma.visibility, ma.club_id, ma.uploaded_by_profile_id
|
||||||
|
FROM media_assets ma
|
||||||
|
WHERE ma.id = %s
|
||||||
|
AND ma.lifecycle_state = 'active'
|
||||||
|
AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL)
|
||||||
|
""",
|
||||||
|
(asset_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
asset = r2d(row)
|
||||||
|
visibility = asset.get("visibility")
|
||||||
|
if visibility == "official":
|
||||||
|
return True
|
||||||
|
if visibility == "club":
|
||||||
|
club_id = asset.get("club_id")
|
||||||
|
if not club_id:
|
||||||
|
return False
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members
|
||||||
|
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||||
|
""",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
if visibility == "private":
|
||||||
|
if asset.get("uploaded_by_profile_id") == profile_id:
|
||||||
|
return True
|
||||||
|
club_id = asset.get("club_id")
|
||||||
|
if club_id:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT 1 FROM club_members cm
|
||||||
|
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s AND cm.club_id = %s AND cm.status = 'active'
|
||||||
|
AND r.role_code = 'club_admin'
|
||||||
|
""",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _is_exercise_visible_to_profile(cur, exercise_id: int, profile_id: Optional[int], global_role: Optional[str]) -> bool:
|
||||||
|
"""Vereinfachte Sichtbarkeitspruefung fuer Uebungen (fuer Meldungen)."""
|
||||||
|
if profile_id and is_platform_admin(global_role):
|
||||||
|
cur.execute("SELECT 1 FROM exercises WHERE id = %s AND status != 'deleted'", (exercise_id,))
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
if profile_id is None:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT 1 FROM exercises WHERE id = %s AND visibility = 'official' AND status = 'active'",
|
||||||
|
(exercise_id,),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT e.visibility, e.club_id, e.created_by_profile_id
|
||||||
|
FROM exercises e WHERE e.id = %s AND e.status != 'deleted'
|
||||||
|
""",
|
||||||
|
(exercise_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
ex = r2d(row)
|
||||||
|
if ex.get("visibility") == "official":
|
||||||
|
return True
|
||||||
|
if ex.get("visibility") == "club":
|
||||||
|
club_id = ex.get("club_id")
|
||||||
|
if not club_id:
|
||||||
|
return False
|
||||||
|
cur.execute(
|
||||||
|
"SELECT 1 FROM club_members WHERE profile_id = %s AND club_id = %s AND status = 'active'",
|
||||||
|
(profile_id, club_id),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
if ex.get("visibility") == "private":
|
||||||
|
return ex.get("created_by_profile_id") == profile_id
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_optional_auth(cur, x_auth_token: Optional[str]) -> tuple[Optional[int], Optional[str]]:
|
||||||
|
"""Gibt (profile_id, global_role) zurueck wenn Token gueltig, sonst (None, None)."""
|
||||||
|
if not x_auth_token:
|
||||||
|
return None, None
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT p.id AS profile_id, p.role
|
||||||
|
FROM sessions s
|
||||||
|
INNER JOIN profiles p ON p.id = s.profile_id
|
||||||
|
WHERE s.token = %s
|
||||||
|
AND (s.expires_at IS NULL OR s.expires_at > NOW())
|
||||||
|
""",
|
||||||
|
(x_auth_token,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None, None
|
||||||
|
d = r2d(row)
|
||||||
|
return d.get("profile_id"), d.get("role")
|
||||||
|
|
||||||
|
|
||||||
|
def _get_platform_admin_emails(cur) -> list[str]:
|
||||||
|
"""Gibt E-Mail-Adressen aller aktiven Plattform-Admins zurueck."""
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT email FROM profiles
|
||||||
|
WHERE role IN ('admin', 'superadmin')
|
||||||
|
AND email IS NOT NULL AND email <> ''
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return [r2d(row)["email"] for row in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def _send_email(to: str, subject: str, body: str) -> None:
|
||||||
|
"""SMTP-Versand (best-effort, ignoriert Fehler und nicht konfiguriertes SMTP)."""
|
||||||
|
try:
|
||||||
|
import smtplib, ssl
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
|
||||||
|
smtp_host = (os.getenv("SMTP_HOST") or "").strip()
|
||||||
|
smtp_user = (os.getenv("SMTP_USER") or "").strip()
|
||||||
|
smtp_pass = os.getenv("SMTP_PASS") or ""
|
||||||
|
if not smtp_host or not smtp_user or not smtp_pass:
|
||||||
|
return
|
||||||
|
smtp_port = int(os.getenv("SMTP_PORT") or "587")
|
||||||
|
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
|
||||||
|
force_ssl = (os.getenv("SMTP_SSL", "").strip().lower() in ("1", "true", "yes")) or smtp_port == 465
|
||||||
|
use_tls = os.getenv("SMTP_STARTTLS", "true").strip().lower() not in ("0", "false", "no")
|
||||||
|
|
||||||
|
msg = MIMEText(body, "plain", "utf-8")
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg["From"] = smtp_from
|
||||||
|
msg["To"] = to
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
if force_ssl:
|
||||||
|
with smtplib.SMTP_SSL(smtp_host, smtp_port, context=ctx, timeout=30) as srv:
|
||||||
|
srv.login(smtp_user, smtp_pass)
|
||||||
|
srv.send_message(msg)
|
||||||
|
else:
|
||||||
|
with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as srv:
|
||||||
|
srv.ehlo()
|
||||||
|
if use_tls:
|
||||||
|
srv.starttls(context=ctx)
|
||||||
|
srv.ehlo()
|
||||||
|
srv.login(smtp_user, smtp_pass)
|
||||||
|
srv.send_message(msg)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[SMTP content_reports] Fehler: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
def _notify_report_submitted(
|
||||||
|
*,
|
||||||
|
report_id: int,
|
||||||
|
reporter_name: str,
|
||||||
|
reporter_email: str,
|
||||||
|
reason: str,
|
||||||
|
priority: str,
|
||||||
|
target_type: str,
|
||||||
|
target_id: int,
|
||||||
|
target_label: str,
|
||||||
|
admin_emails: list[str],
|
||||||
|
) -> None:
|
||||||
|
"""Sendet Bestaetigungs-Mail an Melder + Benachrichtigung an alle Plattform-Admins (best-effort)."""
|
||||||
|
app_url = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||||
|
reason_label = REASON_LABELS_DE.get(reason, reason)
|
||||||
|
prio_label = "DRINGEND" if priority == "high" else "normal"
|
||||||
|
|
||||||
|
# Bestaetigungs-Mail an Melder
|
||||||
|
confirmation_body = (
|
||||||
|
f"Hallo {reporter_name},\n\n"
|
||||||
|
f"Ihre Meldung (#{report_id}) wurde entgegengenommen.\n\n"
|
||||||
|
f"Meldegrund: {reason_label}\n"
|
||||||
|
f"Gemeldeter Inhalt: {target_label}\n\n"
|
||||||
|
f"Ein Administrator wird Ihre Meldung zeitnah prüfen. Sie müssen nichts weiter tun.\n\n"
|
||||||
|
f"Shinkan Jinkendo\n"
|
||||||
|
f"{app_url}"
|
||||||
|
)
|
||||||
|
_send_email(reporter_email, f"Meldung #{report_id} eingegangen – Shinkan Jinkendo", confirmation_body)
|
||||||
|
|
||||||
|
# Admin-Benachrichtigung
|
||||||
|
admin_body = (
|
||||||
|
f"Neue Inhaltsmeldung #{report_id} [{prio_label}]\n\n"
|
||||||
|
f"Meldegrund: {reason_label}\n"
|
||||||
|
f"Gemeldeter Inhalt: {target_label}\n"
|
||||||
|
f"Gemeldet von: {reporter_name} <{reporter_email}>\n\n"
|
||||||
|
f"Posteingang öffnen: {app_url}/inbox\n"
|
||||||
|
)
|
||||||
|
subject = f"Inhaltsmeldung #{report_id} [{prio_label}] – Shinkan Jinkendo"
|
||||||
|
for email in admin_emails:
|
||||||
|
_send_email(email, subject, admin_body)
|
||||||
|
|
||||||
|
|
||||||
|
def _report_row_to_dict(row) -> dict:
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Endpoints ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@router.post("/content-reports", status_code=201)
|
||||||
|
def submit_content_report(
|
||||||
|
body: ContentReportCreate,
|
||||||
|
x_auth_token: Optional[str] = Header(default=None),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Meldung einreichen (optionale Authentifizierung).
|
||||||
|
|
||||||
|
- Ohne Login: nur fuer 'official'-Medien erlaubt (öffentlich erreichbare Inhalte)
|
||||||
|
- Mit Login: fuer alle Inhalte, die der Nutzer laut Sichtbarkeitslogik sehen darf
|
||||||
|
- Gutglaubenserklärung (good_faith_confirmed=true) ist Pflicht
|
||||||
|
- Journaleintrag im Medien-Audit-Log (wenn target_type=media_asset)
|
||||||
|
- E-Mail-Bestaetigung an Melder + Benachrichtigung an Plattform-Admins (best-effort)
|
||||||
|
"""
|
||||||
|
if not body.good_faith_confirmed:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
|
||||||
|
)
|
||||||
|
|
||||||
|
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
|
||||||
|
|
||||||
|
report_id: int
|
||||||
|
admin_emails: list[str] = []
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Optionale Auth aufloesen
|
||||||
|
profile_id, global_role = _resolve_optional_auth(cur, x_auth_token)
|
||||||
|
|
||||||
|
# Sichtbarkeit pruefen
|
||||||
|
if body.target_type == "media_asset":
|
||||||
|
if profile_id:
|
||||||
|
visible = _is_media_asset_visible_to_profile(cur, body.target_id, profile_id, global_role)
|
||||||
|
else:
|
||||||
|
visible = _is_media_asset_visible_anonymous(cur, body.target_id)
|
||||||
|
if not visible:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="Das gemeldete Medium existiert nicht oder ist nicht zugänglich.",
|
||||||
|
)
|
||||||
|
elif body.target_type == "exercise":
|
||||||
|
visible = _is_exercise_visible_to_profile(cur, body.target_id, profile_id, global_role)
|
||||||
|
if not visible:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="Die gemeldete Übung existiert nicht oder ist nicht zugänglich.",
|
||||||
|
)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO content_reports (
|
||||||
|
target_type, target_id, report_reason, report_description,
|
||||||
|
reporter_name, reporter_email, reporter_profile_id,
|
||||||
|
good_faith_confirmed, priority, status,
|
||||||
|
submitted_at, created_at, updated_at
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'submitted', NOW(), NOW(), NOW())
|
||||||
|
RETURNING id, status, priority, submitted_at
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
body.target_type,
|
||||||
|
body.target_id,
|
||||||
|
body.report_reason,
|
||||||
|
body.report_description.strip(),
|
||||||
|
body.reporter_name,
|
||||||
|
body.reporter_email,
|
||||||
|
profile_id,
|
||||||
|
body.good_faith_confirmed,
|
||||||
|
priority,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
result = r2d(row)
|
||||||
|
report_id = int(result["id"])
|
||||||
|
|
||||||
|
# Dateinamen / Zielbezeichnung fuer E-Mail abfragen
|
||||||
|
target_label_for_email = f"{'Medium' if body.target_type == 'media_asset' else 'Übung'} #{body.target_id}"
|
||||||
|
if body.target_type == "media_asset":
|
||||||
|
cur.execute("SELECT original_filename FROM media_assets WHERE id = %s", (body.target_id,))
|
||||||
|
fn_row = cur.fetchone()
|
||||||
|
if fn_row:
|
||||||
|
fn = r2d(fn_row).get("original_filename") or ""
|
||||||
|
if fn:
|
||||||
|
target_label_for_email = f"{fn} (Medium #{body.target_id})"
|
||||||
|
|
||||||
|
elif body.target_type == "exercise":
|
||||||
|
cur.execute("SELECT title FROM exercises WHERE id = %s", (body.target_id,))
|
||||||
|
ex_row = cur.fetchone()
|
||||||
|
if ex_row:
|
||||||
|
ex_name = r2d(ex_row).get("title") or ""
|
||||||
|
if ex_name:
|
||||||
|
target_label_for_email = f"{ex_name} (Übung #{body.target_id})"
|
||||||
|
|
||||||
|
# Audit-Log-Eintrag (nur fuer media_asset-Meldungen)
|
||||||
|
if body.target_type == "media_asset":
|
||||||
|
write_audit_log_entry(
|
||||||
|
cur,
|
||||||
|
body.target_id,
|
||||||
|
profile_id,
|
||||||
|
"content_report_filed",
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
"content_report_id": report_id,
|
||||||
|
"report_reason": REASON_LABELS_DE.get(body.report_reason, body.report_reason),
|
||||||
|
"priority": "hoch" if priority == "high" else "normal",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Admin-E-Mails vor Commit abfragen (Verbindung noch offen)
|
||||||
|
admin_emails = _get_platform_admin_emails(cur)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# E-Mails nach Commit senden (best-effort, kein Rollback-Risiko)
|
||||||
|
_notify_report_submitted(
|
||||||
|
report_id=report_id,
|
||||||
|
reporter_name=body.reporter_name,
|
||||||
|
reporter_email=body.reporter_email,
|
||||||
|
reason=body.report_reason,
|
||||||
|
priority=priority,
|
||||||
|
target_type=body.target_type,
|
||||||
|
target_id=body.target_id,
|
||||||
|
target_label=target_label_for_email,
|
||||||
|
admin_emails=admin_emails,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": report_id,
|
||||||
|
"status": result["status"],
|
||||||
|
"priority": result["priority"],
|
||||||
|
"submitted_at": str(result["submitted_at"]),
|
||||||
|
"message": "Ihre Meldung wurde entgegengenommen. Ein Administrator wird sie prüfen.",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me/inbox/content-reports")
|
||||||
|
def list_inbox_content_reports(
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Meldungen fuer die Inbox.
|
||||||
|
- Plattform-Admins (admin/superadmin): alle Meldungen
|
||||||
|
- Club-Admins: nur Meldungen ueber Medien ihres Vereins
|
||||||
|
"""
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
|
is_padmin = is_platform_admin(role)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
if is_padmin:
|
||||||
|
# Plattform-Admin: alle Meldungen
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
cr.id,
|
||||||
|
cr.target_type,
|
||||||
|
cr.target_id,
|
||||||
|
cr.report_reason,
|
||||||
|
cr.report_description,
|
||||||
|
cr.reporter_name,
|
||||||
|
cr.reporter_email,
|
||||||
|
cr.reporter_profile_id,
|
||||||
|
cr.priority,
|
||||||
|
cr.status,
|
||||||
|
cr.assigned_to_profile_id,
|
||||||
|
cr.reviewed_by_profile_id,
|
||||||
|
cr.reviewed_at,
|
||||||
|
cr.resolution_note,
|
||||||
|
cr.submitted_at,
|
||||||
|
cr.created_at,
|
||||||
|
cr.updated_at,
|
||||||
|
ma.original_filename AS target_filename,
|
||||||
|
ma.visibility AS target_visibility,
|
||||||
|
ma.mime_type AS target_mime_type,
|
||||||
|
ma.legal_hold_active AS target_legal_hold_active,
|
||||||
|
ex.title AS target_exercise_name,
|
||||||
|
rev.name AS reviewed_by_name,
|
||||||
|
asgn.name AS assigned_to_name
|
||||||
|
FROM content_reports cr
|
||||||
|
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||||
|
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||||
|
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||||
|
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN cr.status = 'submitted' THEN 0
|
||||||
|
WHEN cr.status = 'under_review' THEN 1
|
||||||
|
ELSE 2 END ASC,
|
||||||
|
cr.priority DESC,
|
||||||
|
cr.created_at ASC
|
||||||
|
LIMIT 500
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Club-Admin: Meldungen ueber Medien der eigenen Vereine
|
||||||
|
# Zuerst pruefen ob ueberhaupt Club-Admin-Rolle vorhanden
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS cnt
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||||
|
""",
|
||||||
|
(pid,),
|
||||||
|
)
|
||||||
|
cnt_row = r2d(cur.fetchone())
|
||||||
|
if int(cnt_row.get("cnt", 0)) == 0:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein Zugriff auf Inhaltsmeldungen")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
cr.id,
|
||||||
|
cr.target_type,
|
||||||
|
cr.target_id,
|
||||||
|
cr.report_reason,
|
||||||
|
cr.report_description,
|
||||||
|
cr.reporter_name,
|
||||||
|
cr.reporter_email,
|
||||||
|
cr.reporter_profile_id,
|
||||||
|
cr.priority,
|
||||||
|
cr.status,
|
||||||
|
cr.assigned_to_profile_id,
|
||||||
|
cr.reviewed_by_profile_id,
|
||||||
|
cr.reviewed_at,
|
||||||
|
cr.resolution_note,
|
||||||
|
cr.submitted_at,
|
||||||
|
cr.created_at,
|
||||||
|
cr.updated_at,
|
||||||
|
ma.original_filename AS target_filename,
|
||||||
|
ma.visibility AS target_visibility,
|
||||||
|
ma.mime_type AS target_mime_type,
|
||||||
|
ma.legal_hold_active AS target_legal_hold_active,
|
||||||
|
ex.title AS target_exercise_name,
|
||||||
|
rev.name AS reviewed_by_name,
|
||||||
|
asgn.name AS assigned_to_name
|
||||||
|
FROM content_reports cr
|
||||||
|
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||||
|
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||||
|
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||||
|
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||||
|
WHERE cr.target_type = 'media_asset'
|
||||||
|
AND ma.club_id IN (
|
||||||
|
SELECT cm.club_id
|
||||||
|
FROM club_members cm
|
||||||
|
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
|
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
|
||||||
|
)
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN cr.status = 'submitted' THEN 0
|
||||||
|
WHEN cr.status = 'under_review' THEN 1
|
||||||
|
ELSE 2 END ASC,
|
||||||
|
cr.priority DESC,
|
||||||
|
cr.created_at ASC
|
||||||
|
LIMIT 200
|
||||||
|
""",
|
||||||
|
(pid,),
|
||||||
|
)
|
||||||
|
|
||||||
|
return [_report_row_to_dict(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/content-reports/{report_id}")
|
||||||
|
def get_content_report(
|
||||||
|
report_id: int,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Detail-Ansicht einer Meldung fuer Plattform-Admins und zustaendige Club-Admins."""
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
cr.*,
|
||||||
|
ma.original_filename AS target_filename,
|
||||||
|
ma.visibility AS target_visibility,
|
||||||
|
ma.mime_type AS target_mime_type,
|
||||||
|
ma.legal_hold_active AS target_legal_hold_active,
|
||||||
|
ma.legal_hold_reason_code AS target_legal_hold_reason_code,
|
||||||
|
ex.title AS target_exercise_name,
|
||||||
|
ex.visibility AS target_exercise_visibility,
|
||||||
|
rev.name AS reviewed_by_name,
|
||||||
|
asgn.name AS assigned_to_name,
|
||||||
|
rep.name AS reporter_profile_name
|
||||||
|
FROM content_reports cr
|
||||||
|
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
|
||||||
|
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
|
||||||
|
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
|
||||||
|
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
|
||||||
|
LEFT JOIN profiles rep ON rep.id = cr.reporter_profile_id
|
||||||
|
WHERE cr.id = %s
|
||||||
|
""",
|
||||||
|
(report_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||||
|
report_dict = _report_row_to_dict(row)
|
||||||
|
_assert_can_manage_report(cur, role, pid, report_dict)
|
||||||
|
return report_dict
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/content-reports/{report_id}")
|
||||||
|
def patch_content_report(
|
||||||
|
report_id: int,
|
||||||
|
body: ContentReportPatch,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Status und Bearbeitungsnotiz einer Meldung aktualisieren.
|
||||||
|
Abschluss ohne Massnahme (resolved_no_action, rejected_invalid) erfordert resolution_note.
|
||||||
|
Plattform-Admins: jede Meldung. Club-Admins: nur Meldungen zu Medien ihres Vereins.
|
||||||
|
"""
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
|
if body.status in ("resolved_no_action", "rejected_invalid") and not (body.resolution_note or "").strip():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Bei Abschluss ohne Massnahme ist eine Begründung (resolution_note) Pflicht.",
|
||||||
|
)
|
||||||
|
|
||||||
|
STATUS_LABELS_DE = {
|
||||||
|
"submitted": "Eingegangen",
|
||||||
|
"under_review": "In Bearbeitung",
|
||||||
|
"resolved_no_action": "Abgeschlossen (kein Handlungsbedarf)",
|
||||||
|
"resolved_legal_hold": "Abgeschlossen (Legal Hold)",
|
||||||
|
"rejected_invalid": "Abgewiesen (ungültig)",
|
||||||
|
}
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, status, resolution_note, target_type, target_id FROM content_reports WHERE id = %s",
|
||||||
|
(report_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||||
|
old_report = r2d(row)
|
||||||
|
_assert_can_manage_report(cur, role, pid, old_report)
|
||||||
|
old_status = old_report["status"]
|
||||||
|
old_note = (old_report.get("resolution_note") or "").strip()
|
||||||
|
|
||||||
|
updates = ["updated_at = NOW()"]
|
||||||
|
params = []
|
||||||
|
|
||||||
|
if body.status is not None:
|
||||||
|
updates.append("status = %s")
|
||||||
|
params.append(body.status)
|
||||||
|
if body.status in ("resolved_no_action", "resolved_legal_hold", "rejected_invalid"):
|
||||||
|
updates.append("reviewed_by_profile_id = %s")
|
||||||
|
updates.append("reviewed_at = NOW()")
|
||||||
|
params.append(pid)
|
||||||
|
elif body.status == "submitted":
|
||||||
|
# Wieder öffnen: Prüferfelder zurücksetzen
|
||||||
|
updates.append("reviewed_by_profile_id = NULL")
|
||||||
|
updates.append("reviewed_at = NULL")
|
||||||
|
|
||||||
|
if body.resolution_note is not None:
|
||||||
|
updates.append("resolution_note = %s")
|
||||||
|
params.append(body.resolution_note.strip() or None)
|
||||||
|
|
||||||
|
if body.assigned_to_profile_id is not None:
|
||||||
|
updates.append("assigned_to_profile_id = %s")
|
||||||
|
params.append(body.assigned_to_profile_id)
|
||||||
|
|
||||||
|
if len(updates) == 1:
|
||||||
|
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren angegeben")
|
||||||
|
|
||||||
|
params.append(report_id)
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE content_reports SET {', '.join(updates)} WHERE id = %s RETURNING id, status",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
updated = r2d(cur.fetchone())
|
||||||
|
new_status = updated["status"]
|
||||||
|
|
||||||
|
is_media = old_report["target_type"] == "media_asset"
|
||||||
|
if is_media:
|
||||||
|
new_note = (body.resolution_note or "").strip() if body.resolution_note is not None else old_note
|
||||||
|
|
||||||
|
# Audit-Log: Statuswechsel
|
||||||
|
if body.status is not None and old_status != new_status:
|
||||||
|
write_audit_log_entry(
|
||||||
|
cur,
|
||||||
|
int(old_report["target_id"]),
|
||||||
|
pid,
|
||||||
|
"content_report_filed",
|
||||||
|
{"status": STATUS_LABELS_DE.get(old_status, old_status)},
|
||||||
|
{
|
||||||
|
"content_report_id": report_id,
|
||||||
|
"status": STATUS_LABELS_DE.get(new_status, new_status),
|
||||||
|
**({"begründung": new_note} if new_note else {}),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
# Audit-Log: reine Notizänderung (ohne Statuswechsel)
|
||||||
|
elif body.resolution_note is not None and new_note != old_note:
|
||||||
|
write_audit_log_entry(
|
||||||
|
cur,
|
||||||
|
int(old_report["target_id"]),
|
||||||
|
pid,
|
||||||
|
"content_report_filed",
|
||||||
|
{"content_report_id": report_id, "begründung": old_note or None},
|
||||||
|
{"content_report_id": report_id, "begründung": new_note or None},
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "id": updated["id"], "status": updated["status"]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/content-reports/{report_id}/legal-hold")
|
||||||
|
def set_legal_hold_from_report(
|
||||||
|
report_id: int,
|
||||||
|
body: ContentReportLegalHoldBody,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Legal Hold (P-11) aus einer Meldung heraus setzen.
|
||||||
|
Superadmin: immer. Club-Admin: nur fuer Vereinsmedien (visibility != 'official').
|
||||||
|
Nur fuer Meldungen mit target_type='media_asset'.
|
||||||
|
|
||||||
|
Der Reason-Code wird automatisch aus dem report_reason der Meldung abgeleitet.
|
||||||
|
Nach dem Setzen wird der Report-Status auf 'resolved_legal_hold' gesetzt.
|
||||||
|
"""
|
||||||
|
pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
|
||||||
|
# Plattform-Admin ohne Superadmin hat keine Legal-Hold-Rechte (fruehzeitig ablehnen)
|
||||||
|
if is_platform_admin(role) and not is_superadmin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Legal Hold erfordert Superadmin oder Vereinsadmin-Rechte",
|
||||||
|
)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, target_type, target_id, report_reason, status FROM content_reports WHERE id = %s",
|
||||||
|
(report_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
|
||||||
|
report = r2d(row)
|
||||||
|
|
||||||
|
if report["target_type"] != "media_asset":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Legal Hold ist nur fuer Meldungen mit target_type='media_asset' verfügbar.",
|
||||||
|
)
|
||||||
|
|
||||||
|
asset_id = int(report["target_id"])
|
||||||
|
_assert_can_set_legal_hold_from_report(cur, role, pid, asset_id)
|
||||||
|
reason_code = _REASON_TO_HOLD_CODE.get(report["report_reason"], "other")
|
||||||
|
|
||||||
|
# P-11-Service aufrufen
|
||||||
|
set_legal_hold(
|
||||||
|
cur=cur,
|
||||||
|
conn=conn,
|
||||||
|
asset_id=asset_id,
|
||||||
|
acting_profile_id=pid,
|
||||||
|
reason_code=reason_code,
|
||||||
|
reason_note=f"[P-13 Meldung #{report_id}] {body.reason_note.strip()}",
|
||||||
|
)
|
||||||
|
|
||||||
|
# set_legal_hold committed bereits — neue Transaktion fuer Report-Update
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE content_reports
|
||||||
|
SET status = 'resolved_legal_hold',
|
||||||
|
reviewed_by_profile_id = %s,
|
||||||
|
reviewed_at = NOW(),
|
||||||
|
resolution_note = %s,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id, status
|
||||||
|
""",
|
||||||
|
(pid, f"Legal Hold gesetzt auf Asset #{asset_id} (reason_code: {reason_code})", report_id),
|
||||||
|
)
|
||||||
|
updated = r2d(cur.fetchone())
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"report_id": updated["id"],
|
||||||
|
"report_status": updated["status"],
|
||||||
|
"asset_id": asset_id,
|
||||||
|
"legal_hold_reason_code": reason_code,
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""
|
||||||
|
Dashboard: zusammengefasste Kennzahlen (ein Roundtrip statt mehrerer Listen).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
from routers.exercises import list_exercises_like_get
|
||||||
|
from routers.training_planning import list_training_units
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["dashboard"])
|
||||||
|
|
||||||
|
|
||||||
|
def _slice_training_home_notes(planned_pool: List[Dict[str, Any]], max_notes: int = 5) -> List[Dict[str, Any]]:
|
||||||
|
out = []
|
||||||
|
for u in planned_pool:
|
||||||
|
tn = (u.get("trainer_notes") or "").strip()
|
||||||
|
n = (u.get("notes") or "").strip()
|
||||||
|
if tn or n:
|
||||||
|
out.append(u)
|
||||||
|
if len(out) >= max_notes:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dashboard/kpis")
|
||||||
|
def get_dashboard_kpis(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""
|
||||||
|
Kurzüberblick: Übungs-KPIs + YTD-Einheiten + Trainings-Home (nächste Termine, Vermerke, offene Rückschau)
|
||||||
|
in einem Roundtrip — gleiche Filter wie zuvor im Dashboard (mehrere Client-Calls).
|
||||||
|
"""
|
||||||
|
year = date.today().year
|
||||||
|
year_start = f"{year}-01-01"
|
||||||
|
year_end = f"{year}-12-31"
|
||||||
|
today = date.today().isoformat()
|
||||||
|
|
||||||
|
draft_list = list_exercises_like_get(
|
||||||
|
tenant, created_by_me=True, status="draft", limit=100
|
||||||
|
)
|
||||||
|
mine_list = list_exercises_like_get(
|
||||||
|
tenant, created_by_me=True, status=None, limit=100
|
||||||
|
)
|
||||||
|
ytd_completed = list_training_units(
|
||||||
|
group_id=None,
|
||||||
|
club_id=None,
|
||||||
|
start_date=year_start,
|
||||||
|
end_date=year_end,
|
||||||
|
status="completed",
|
||||||
|
assigned_to_me=True,
|
||||||
|
debrief_pending=False,
|
||||||
|
sort="desc",
|
||||||
|
limit=250,
|
||||||
|
tenant=tenant,
|
||||||
|
)
|
||||||
|
planned_pool = list_training_units(
|
||||||
|
group_id=None,
|
||||||
|
club_id=None,
|
||||||
|
start_date=today,
|
||||||
|
end_date=None,
|
||||||
|
status="planned",
|
||||||
|
assigned_to_me=True,
|
||||||
|
debrief_pending=False,
|
||||||
|
sort="asc",
|
||||||
|
limit=40,
|
||||||
|
tenant=tenant,
|
||||||
|
)
|
||||||
|
review_pending = list_training_units(
|
||||||
|
group_id=None,
|
||||||
|
club_id=None,
|
||||||
|
start_date=None,
|
||||||
|
end_date=None,
|
||||||
|
status=None,
|
||||||
|
assigned_to_me=True,
|
||||||
|
debrief_pending=True,
|
||||||
|
sort="desc",
|
||||||
|
limit=8,
|
||||||
|
tenant=tenant,
|
||||||
|
)
|
||||||
|
|
||||||
|
draft_preview = [
|
||||||
|
{"id": int(ex["id"]), "title": ex.get("title") or f"Übung #{ex['id']}"}
|
||||||
|
for ex in draft_list[:8]
|
||||||
|
]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"year": year,
|
||||||
|
"draft_count": len(draft_list),
|
||||||
|
"draft_capped": len(draft_list) >= 100,
|
||||||
|
"draft_preview": draft_preview,
|
||||||
|
"mine_count": len(mine_list),
|
||||||
|
"mine_capped": len(mine_list) >= 100,
|
||||||
|
"ytd_completed_count": len(ytd_completed),
|
||||||
|
"ytd_capped": len(ytd_completed) >= 250,
|
||||||
|
"training_home": {
|
||||||
|
"upcoming": planned_pool[:8],
|
||||||
|
"planned_with_notes": _slice_training_home_notes(planned_pool),
|
||||||
|
"review_pending": review_pending,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -9,8 +9,13 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
|||||||
from pydantic import BaseModel, Field, model_validator
|
from pydantic import BaseModel, Field, model_validator
|
||||||
from psycopg2 import IntegrityError
|
from psycopg2 import IntegrityError
|
||||||
|
|
||||||
from auth import require_auth
|
|
||||||
from db import get_db, get_cursor, r2d
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
from routers.training_planning import _has_planning_role
|
from routers.training_planning import _has_planning_role
|
||||||
|
|
||||||
@@ -82,7 +87,7 @@ _EDGE_SELECT = """
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _graph_access(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
def _graph_row(cur, graph_id: int) -> dict:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT * FROM exercise_progression_graphs WHERE id = %s",
|
"SELECT * FROM exercise_progression_graphs WHERE id = %s",
|
||||||
(graph_id,),
|
(graph_id,),
|
||||||
@@ -90,11 +95,40 @@ def _graph_access(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
|||||||
r = cur.fetchone()
|
r = cur.fetchone()
|
||||||
if not r:
|
if not r:
|
||||||
raise HTTPException(status_code=404, detail="Progressionsgraph nicht gefunden")
|
raise HTTPException(status_code=404, detail="Progressionsgraph nicht gefunden")
|
||||||
row = r2d(r)
|
return r2d(r)
|
||||||
if role in ("admin", "superadmin"):
|
|
||||||
return row
|
|
||||||
if row.get("created_by") != profile_id:
|
def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||||
|
vis = (row.get("visibility") or "private").strip().lower()
|
||||||
|
cid = row.get("club_id")
|
||||||
|
if cid is not None:
|
||||||
|
cid = int(cid)
|
||||||
|
cr = row.get("created_by")
|
||||||
|
if cr is not None:
|
||||||
|
cr = int(cr)
|
||||||
|
if not library_content_visible_to_profile(cur, profile_id, vis, cid, cr, role):
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
created_by = row.get("created_by")
|
||||||
|
if created_by is not None:
|
||||||
|
created_by = int(created_by)
|
||||||
|
if created_by != profile_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
||||||
|
|
||||||
|
|
||||||
|
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||||
|
row = _graph_row(cur, graph_id)
|
||||||
|
_assert_graph_readable(cur, row, profile_id, role)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _require_graph_write(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||||
|
row = _graph_row(cur, graph_id)
|
||||||
|
_assert_graph_writable(cur, row, profile_id, role)
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
@@ -167,30 +201,26 @@ def _insert_edge_row(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/exercise-progression-graphs")
|
@router.get("/exercise-progression-graphs")
|
||||||
def list_progression_graphs(session: dict = Depends(require_auth)):
|
def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
if role in ("admin", "superadmin"):
|
vis_sql, vis_params = library_content_visibility_sql(
|
||||||
cur.execute(
|
alias="g",
|
||||||
"""
|
profile_id=profile_id,
|
||||||
SELECT g.*,
|
role=role,
|
||||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
effective_club_id=tenant.effective_club_id,
|
||||||
FROM exercise_progression_graphs g
|
|
||||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
|
||||||
"""
|
|
||||||
)
|
)
|
||||||
else:
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
f"""
|
||||||
SELECT g.*,
|
SELECT g.*,
|
||||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||||
FROM exercise_progression_graphs g
|
FROM exercise_progression_graphs g
|
||||||
WHERE g.created_by = %s
|
WHERE ({vis_sql})
|
||||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||||
""",
|
""",
|
||||||
(profile_id,),
|
vis_params,
|
||||||
)
|
)
|
||||||
return [r2d(r) for r in cur.fetchall()]
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
@@ -199,13 +229,13 @@ def list_progression_graphs(session: dict = Depends(require_auth)):
|
|||||||
def get_progression_graph(
|
def get_progression_graph(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
include_edges: bool = Query(default=False),
|
include_edges: bool = Query(default=False),
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
row = _graph_access(cur, graph_id, profile_id, role)
|
row = _require_graph_read(cur, graph_id, profile_id, role)
|
||||||
if include_edges:
|
if include_edges:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
_EDGE_SELECT + " WHERE e.graph_id = %s ORDER BY e.id",
|
_EDGE_SELECT + " WHERE e.graph_id = %s ORDER BY e.id",
|
||||||
@@ -218,10 +248,10 @@ def get_progression_graph(
|
|||||||
@router.post("/exercise-progression-graphs", status_code=201)
|
@router.post("/exercise-progression-graphs", status_code=201)
|
||||||
def create_progression_graph(
|
def create_progression_graph(
|
||||||
body: ProgressionGraphCreate,
|
body: ProgressionGraphCreate,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
if not _has_planning_role(role):
|
if not _has_planning_role(role):
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Anlegen von Progressionsgraphen")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Anlegen von Progressionsgraphen")
|
||||||
|
|
||||||
@@ -229,55 +259,105 @@ def create_progression_graph(
|
|||||||
if not name:
|
if not name:
|
||||||
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
||||||
|
|
||||||
|
vis = (body.visibility or "private").strip().lower()
|
||||||
|
cid = body.club_id
|
||||||
|
if vis == "club":
|
||||||
|
if cid is None:
|
||||||
|
cid = tenant.effective_club_id
|
||||||
|
if cid is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
|
||||||
|
)
|
||||||
|
|
||||||
|
gov_club = cid if vis == "club" else None
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
assert_valid_governance_visibility(cur, profile_id, role, vis, gov_club)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO exercise_progression_graphs (name, description, visibility, club_id, created_by)
|
INSERT INTO exercise_progression_graphs (name, description, visibility, club_id, created_by)
|
||||||
VALUES (%s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(name, body.description, body.visibility, body.club_id, profile_id),
|
(name, body.description, vis, cid if vis == "club" else None, profile_id),
|
||||||
)
|
)
|
||||||
gid = cur.fetchone()["id"]
|
gid = cur.fetchone()["id"]
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_progression_graph(gid, include_edges=False, session=session)
|
return get_progression_graph(gid, include_edges=False, tenant=tenant)
|
||||||
|
|
||||||
|
|
||||||
@router.put("/exercise-progression-graphs/{graph_id}")
|
@router.put("/exercise-progression-graphs/{graph_id}")
|
||||||
def update_progression_graph(
|
def update_progression_graph(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
body: ProgressionGraphUpdate,
|
body: ProgressionGraphUpdate,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
data = body.model_dump(exclude_unset=True)
|
original = body.model_dump(exclude_unset=True)
|
||||||
if not data:
|
if not original:
|
||||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
row = _require_graph_write(cur, graph_id, profile_id, role)
|
||||||
|
|
||||||
|
ex_vis = (row.get("visibility") or "private").strip().lower()
|
||||||
|
ex_cid_raw = row.get("club_id")
|
||||||
|
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||||
|
|
||||||
|
next_vis = ex_vis
|
||||||
|
if "visibility" in original and original["visibility"] is not None:
|
||||||
|
v_raw = str(original["visibility"]).strip().lower()
|
||||||
|
if v_raw:
|
||||||
|
next_vis = v_raw
|
||||||
|
|
||||||
|
next_club = ex_cid
|
||||||
|
if "club_id" in original:
|
||||||
|
raw_c = original["club_id"]
|
||||||
|
if raw_c in (None, "", []):
|
||||||
|
next_club = None
|
||||||
|
else:
|
||||||
|
next_club = int(raw_c)
|
||||||
|
|
||||||
|
if next_vis == "club":
|
||||||
|
if next_club is None:
|
||||||
|
next_club = tenant.effective_club_id
|
||||||
|
if next_club is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
|
||||||
|
)
|
||||||
|
|
||||||
|
gov_club = next_club if next_vis == "club" else None
|
||||||
|
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
|
||||||
|
|
||||||
fields: List[str] = []
|
fields: List[str] = []
|
||||||
params: List[Any] = []
|
params: List[Any] = []
|
||||||
if "name" in data:
|
if "name" in original:
|
||||||
n = (data["name"] or "").strip()
|
n = (original["name"] or "").strip()
|
||||||
if not n:
|
if not n:
|
||||||
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
||||||
fields.append("name = %s")
|
fields.append("name = %s")
|
||||||
params.append(n)
|
params.append(n)
|
||||||
if "description" in data:
|
if "description" in original:
|
||||||
fields.append("description = %s")
|
fields.append("description = %s")
|
||||||
params.append(data["description"])
|
params.append(original["description"])
|
||||||
if "visibility" in data:
|
|
||||||
|
vis_changed = next_vis != ex_vis
|
||||||
|
if "visibility" in original or vis_changed:
|
||||||
fields.append("visibility = %s")
|
fields.append("visibility = %s")
|
||||||
params.append(data["visibility"])
|
params.append(next_vis)
|
||||||
if "club_id" in data:
|
|
||||||
|
if "club_id" in original or vis_changed:
|
||||||
fields.append("club_id = %s")
|
fields.append("club_id = %s")
|
||||||
params.append(data["club_id"])
|
params.append(next_club if next_vis == "club" else None)
|
||||||
|
|
||||||
|
if not fields:
|
||||||
|
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||||
|
|
||||||
fields.append("updated_at = NOW()")
|
fields.append("updated_at = NOW()")
|
||||||
params.append(graph_id)
|
params.append(graph_id)
|
||||||
@@ -287,16 +367,16 @@ def update_progression_graph(
|
|||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_progression_graph(graph_id, include_edges=False, session=session)
|
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/exercise-progression-graphs/{graph_id}")
|
@router.delete("/exercise-progression-graphs/{graph_id}")
|
||||||
def delete_progression_graph(graph_id: int, session: dict = Depends(require_auth)):
|
def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
@@ -307,13 +387,13 @@ def list_progression_edges(
|
|||||||
graph_id: int,
|
graph_id: int,
|
||||||
from_exercise_id: Optional[int] = Query(default=None),
|
from_exercise_id: Optional[int] = Query(default=None),
|
||||||
to_exercise_id: Optional[int] = Query(default=None),
|
to_exercise_id: Optional[int] = Query(default=None),
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_read(cur, graph_id, profile_id, role)
|
||||||
q = _EDGE_SELECT + " WHERE e.graph_id = %s"
|
q = _EDGE_SELECT + " WHERE e.graph_id = %s"
|
||||||
params: List[Any] = [graph_id]
|
params: List[Any] = [graph_id]
|
||||||
if from_exercise_id is not None:
|
if from_exercise_id is not None:
|
||||||
@@ -331,14 +411,14 @@ def list_progression_edges(
|
|||||||
def create_progression_edge(
|
def create_progression_edge(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
body: ProgressionEdgeCreate,
|
body: ProgressionEdgeCreate,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
||||||
fv = body.from_exercise_variant_id
|
fv = body.from_exercise_variant_id
|
||||||
tv = body.to_exercise_variant_id
|
tv = body.to_exercise_variant_id
|
||||||
@@ -372,11 +452,11 @@ def create_progression_edge(
|
|||||||
def create_progression_sequence(
|
def create_progression_sequence(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
body: ProgressionSequenceCreate,
|
body: ProgressionSequenceCreate,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
"""Legt n−1 Nachfolger-Kanten (next_exercise) für eine geordnete Schrittliste an."""
|
"""Legt n−1 Nachfolger-Kanten (next_exercise) für eine geordnete Schrittliste an."""
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
steps = body.steps
|
steps = body.steps
|
||||||
n_seg = len(steps) - 1
|
n_seg = len(steps) - 1
|
||||||
seg_notes = body.segment_notes
|
seg_notes = body.segment_notes
|
||||||
@@ -384,7 +464,7 @@ def create_progression_sequence(
|
|||||||
created: List[dict] = []
|
created: List[dict] = []
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
|
|
||||||
ex_ids = [s.exercise_id for s in steps]
|
ex_ids = [s.exercise_id for s in steps]
|
||||||
_assert_exercises_exist(cur, *ex_ids)
|
_assert_exercises_exist(cur, *ex_ids)
|
||||||
@@ -425,17 +505,17 @@ def update_progression_edge(
|
|||||||
graph_id: int,
|
graph_id: int,
|
||||||
edge_id: int,
|
edge_id: int,
|
||||||
body: ProgressionEdgeUpdate,
|
body: ProgressionEdgeUpdate,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
data = body.model_dump(exclude_unset=True)
|
data = body.model_dump(exclude_unset=True)
|
||||||
if not data:
|
if not data:
|
||||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT id FROM exercise_progression_edges WHERE id = %s AND graph_id = %s",
|
"SELECT id FROM exercise_progression_edges WHERE id = %s AND graph_id = %s",
|
||||||
(edge_id, graph_id),
|
(edge_id, graph_id),
|
||||||
@@ -459,13 +539,13 @@ def update_progression_edge(
|
|||||||
def delete_progression_edge(
|
def delete_progression_edge(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
edge_id: int,
|
edge_id: int,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
DELETE FROM exercise_progression_edges
|
DELETE FROM exercise_progression_edges
|
||||||
@@ -484,17 +564,17 @@ def delete_progression_edge(
|
|||||||
def delete_progression_edges_batch(
|
def delete_progression_edges_batch(
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
body: EdgeIdsBatch,
|
body: EdgeIdsBatch,
|
||||||
session: dict = Depends(require_auth),
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
):
|
):
|
||||||
"""Löscht mehrere Kanten (z. B. eine zusammenhängende Kette in einem Schritt)."""
|
"""Löscht mehrere Kanten (z. B. eine zusammenhängende Kette in einem Schritt)."""
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
ids = body.edge_ids
|
ids = body.edge_ids
|
||||||
clean_ids = list(dict.fromkeys(ids))
|
clean_ids = list(dict.fromkeys(ids))
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_graph_access(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
f"""
|
f"""
|
||||||
DELETE FROM exercise_progression_edges
|
DELETE FROM exercise_progression_edges
|
||||||
|
|||||||
+2351
-161
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]
|
||||||
@@ -3,7 +3,8 @@ Reifegradmodelle / Fähigkeitsmatrix (kontextbezogen)
|
|||||||
|
|
||||||
Kontext zu Fokusbereich, Stilrichtung, Zielgruppe: jeweils M:N (leer = gilt überall).
|
Kontext zu Fokusbereich, Stilrichtung, Zielgruppe: jeweils M:N (leer = gilt überall).
|
||||||
|
|
||||||
Lesen: alle authentifizierten Nutzer.
|
Lesen: Liste & resolve für alle authentifizierten Nutzer; GET eines Modells nach ID nur Portal-Admin (Admin-UI).
|
||||||
|
|
||||||
Schreiben: admin, superadmin.
|
Schreiben: admin, superadmin.
|
||||||
"""
|
"""
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
@@ -534,6 +535,7 @@ def list_maturity_models(
|
|||||||
|
|
||||||
@router.get("/maturity-models/{model_id}")
|
@router.get("/maturity-models/{model_id}")
|
||||||
def get_maturity_model(model_id: int, session: dict = Depends(require_auth)):
|
def get_maturity_model(model_id: int, session: dict = Depends(require_auth)):
|
||||||
|
_require_admin(session)
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
return _load_full_model(cur, model_id)
|
return _load_full_model(cur, model_id)
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,97 @@
|
|||||||
|
"""Superadmin: Speicherpfad-Konfiguration (§7.1 MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from club_tenancy import is_platform_admin
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from media_storage import _default_media_root, get_effective_media_root, normalize_local_relative_root
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin", tags=["admin", "media-storage"])
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformMediaStorageUpdate(BaseModel):
|
||||||
|
local_relative_root: str = Field(
|
||||||
|
"",
|
||||||
|
description="Relativer Unterordner unter MEDIA_ROOT (z. B. nas/videos). Leer = nur MEDIA_ROOT.",
|
||||||
|
max_length=512,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformMediaStorageOut(BaseModel):
|
||||||
|
storage_backend: str
|
||||||
|
local_relative_root: str
|
||||||
|
media_root_env: str
|
||||||
|
effective_media_root: str
|
||||||
|
|
||||||
|
|
||||||
|
def _require_superadmin(session: dict) -> None:
|
||||||
|
role = (session.get("role") or "").strip().lower()
|
||||||
|
if role != "superadmin":
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Superadmin")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/platform-media-storage", response_model=PlatformMediaStorageOut)
|
||||||
|
def get_platform_media_storage(session: dict = Depends(require_auth)):
|
||||||
|
"""Lesen: Plattform-Admin (admin/superadmin) – Hilfe für Betrieb."""
|
||||||
|
role = (session.get("role") or "").strip().lower()
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""SELECT storage_backend, local_relative_root
|
||||||
|
FROM platform_media_storage WHERE id = 1""",
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
backend, rel = "local", ""
|
||||||
|
else:
|
||||||
|
d = r2d(row)
|
||||||
|
backend = d.get("storage_backend") or "local"
|
||||||
|
rel = str(d.get("local_relative_root") or "")
|
||||||
|
eff = get_effective_media_root(cur)
|
||||||
|
return PlatformMediaStorageOut(
|
||||||
|
storage_backend=backend,
|
||||||
|
local_relative_root=rel,
|
||||||
|
media_root_env=str(_default_media_root().resolve()),
|
||||||
|
effective_media_root=str(eff),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/platform-media-storage", response_model=PlatformMediaStorageOut)
|
||||||
|
def put_platform_media_storage(
|
||||||
|
body: PlatformMediaStorageUpdate,
|
||||||
|
session: dict = Depends(require_auth),
|
||||||
|
):
|
||||||
|
"""Schreiben: nur superadmin."""
|
||||||
|
_require_superadmin(session)
|
||||||
|
profile_id = session["profile_id"]
|
||||||
|
try:
|
||||||
|
rel_norm = normalize_local_relative_root(body.local_relative_root)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""UPDATE platform_media_storage
|
||||||
|
SET local_relative_root = %s, updated_at = NOW(), updated_by_profile_id = %s
|
||||||
|
WHERE id = 1
|
||||||
|
RETURNING storage_backend, local_relative_root""",
|
||||||
|
(rel_norm, profile_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=500, detail="platform_media_storage fehlt")
|
||||||
|
d = r2d(row)
|
||||||
|
eff = get_effective_media_root(cur)
|
||||||
|
return PlatformMediaStorageOut(
|
||||||
|
storage_backend=str(d.get("storage_backend") or "local"),
|
||||||
|
local_relative_root=str(d.get("local_relative_root") or ""),
|
||||||
|
media_root_env=str(_default_media_root().resolve()),
|
||||||
|
effective_media_root=str(eff),
|
||||||
|
)
|
||||||
+354
-51
@@ -3,90 +3,281 @@ Profile Management Endpoints for Mitai Jinkendo
|
|||||||
|
|
||||||
Handles profile CRUD operations for both admin and current user.
|
Handles profile CRUD operations for both admin and current user.
|
||||||
"""
|
"""
|
||||||
import uuid
|
import secrets
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Header, Depends
|
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 db import get_db, get_cursor, r2d
|
||||||
from auth import require_auth
|
from auth import require_auth, hash_pin
|
||||||
|
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
|
from models import ProfileCreate, ProfileUpdate
|
||||||
|
|
||||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||||
|
|
||||||
|
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||||
|
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
||||||
|
|
||||||
# ── Helper ────────────────────────────────────────────────────────────────────
|
|
||||||
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
class ManagementPasswordResetBody(BaseModel):
|
||||||
"""Get profile_id - from header for legacy endpoints."""
|
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
|
||||||
if x_profile_id:
|
|
||||||
return x_profile_id
|
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
@field_validator("new_password", mode="before")
|
||||||
cur.execute("SELECT id FROM profiles ORDER BY created LIMIT 1")
|
@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()
|
row = cur.fetchone()
|
||||||
if row: return row['id']
|
return (row.get("r") or "user") if row else "user"
|
||||||
raise HTTPException(400, "Kein Profil gefunden")
|
|
||||||
|
|
||||||
|
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 ──────────────────────────────────────────────────────
|
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||||
@router.get("/profiles/me")
|
@router.get("/profiles/me")
|
||||||
def get_current_profile(session=Depends(require_auth)):
|
def get_current_profile(
|
||||||
"""Get current user's profile (for auth check on refresh)."""
|
session=Depends(require_auth),
|
||||||
profile_id = session['profile_id']
|
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||||
|
):
|
||||||
|
"""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:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (profile_id,))
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (profile_id,))
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, "Profil nicht gefunden")
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
return r2d(row)
|
data = r2d(row)
|
||||||
|
data.pop("pin_hash", None)
|
||||||
|
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
|
||||||
|
tenant = resolve_tenant_context(
|
||||||
|
cur,
|
||||||
|
profile_id=int(profile_id),
|
||||||
|
global_role=session.get("role") or "",
|
||||||
|
header_raw=x_active_club_id,
|
||||||
|
memberships=clubs,
|
||||||
|
stored_active_club_id=stored_ac,
|
||||||
|
invalid_header_policy="ignore",
|
||||||
|
)
|
||||||
|
data["effective_club_id"] = tenant.effective_club_id
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
# ── Admin Profile Management ──────────────────────────────────────────────────
|
# ── Admin Profile Management ──────────────────────────────────────────────────
|
||||||
@router.get("/profiles")
|
@router.get("/profiles")
|
||||||
def list_profiles(session=Depends(require_auth)):
|
def list_profiles(session=Depends(require_auth)):
|
||||||
"""List all profiles (admin)."""
|
"""Liste aller Profile (nur Plattform-Admin)."""
|
||||||
|
role = (session.get("role") or "").lower()
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Plattform-Administratoren dürfen alle Profile einsehen")
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("SELECT * FROM profiles ORDER BY created")
|
cur.execute("SELECT * FROM profiles ORDER BY created")
|
||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
return [r2d(r) for r in rows]
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
d = r2d(r)
|
||||||
|
d.pop("pin_hash", None)
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
@router.post("/profiles")
|
@router.post("/profiles")
|
||||||
def create_profile(p: ProfileCreate, session=Depends(require_auth)):
|
def create_profile(p: ProfileCreate, session=Depends(require_auth)):
|
||||||
"""Create new profile (admin)."""
|
"""
|
||||||
pid = str(uuid.uuid4())
|
Neues Profil anlegen — nur Plattform-Admin.
|
||||||
|
|
||||||
|
Nutzt gleiches Kernschema wie Registrierung (SERIAL id); PIN wird zufällig gesetzt — Nutzer
|
||||||
|
setzt das Passwort über „Passwort vergessen“ oder ein späteres Admin-Tool.
|
||||||
|
"""
|
||||||
|
role = session.get("role") or ""
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Plattform-Administratoren dürfen Profile anlegen",
|
||||||
|
)
|
||||||
|
|
||||||
|
email_norm = str(p.email).strip().lower()
|
||||||
|
name_s = (p.name or "").strip()
|
||||||
|
|
||||||
|
pin_hash = hash_pin(secrets.token_urlsafe(24))
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("""INSERT INTO profiles (id,name,avatar_color,sex,dob,height,goal_weight,goal_bf_pct,created,updated)
|
cur.execute(
|
||||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)""",
|
"SELECT id FROM profiles WHERE email IS NOT NULL AND lower(trim(email)) = %s",
|
||||||
(pid,p.name,p.avatar_color,p.sex,p.dob,p.height,p.goal_weight,p.goal_bf_pct))
|
(email_norm,),
|
||||||
with get_db() as conn:
|
)
|
||||||
cur = get_cursor(conn)
|
if cur.fetchone():
|
||||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
raise HTTPException(status_code=409, detail="E-Mail bereits registriert")
|
||||||
return r2d(cur.fetchone())
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profiles (
|
||||||
|
name, email, pin_hash, auth_type, role, tier,
|
||||||
|
email_verified, created_at, updated_at
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, 'email', 'user', 'free', TRUE,
|
||||||
|
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(name_s, email_norm, pin_hash),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
new_id = row["id"] if row else None
|
||||||
|
if new_id is None:
|
||||||
|
raise HTTPException(status_code=500, detail="Profil konnte nicht angelegt werden")
|
||||||
|
|
||||||
|
return profile_document(str(new_id))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/profiles/{pid}")
|
def profile_document(pid: str) -> dict:
|
||||||
def get_profile(pid: str, session=Depends(require_auth)):
|
"""Profil ohne PIN — für Routen und interne Aufrufe (z. B. /auth/me)."""
|
||||||
"""Get profile by ID."""
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row: raise HTTPException(404, "Profil nicht gefunden")
|
if not row:
|
||||||
return r2d(row)
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
|
d = r2d(row)
|
||||||
|
d.pop("pin_hash", None)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
@router.put("/profiles/{pid}")
|
@router.post("/profiles/{pid}/management-password-reset")
|
||||||
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
def management_password_reset(
|
||||||
"""Update profile — nur eigenes Profil oder Admin."""
|
pid: str,
|
||||||
sess_pid = session.get('profile_id')
|
body: ManagementPasswordResetBody,
|
||||||
role = (session.get('role') or '').lower()
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
if str(sess_pid) != str(pid) and role not in ('admin', 'superadmin'):
|
):
|
||||||
raise HTTPException(403, 'Keine Berechtigung für dieses Profil')
|
"""
|
||||||
|
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)."""
|
||||||
|
viewer = session["profile_id"]
|
||||||
|
role = session.get("role") or ""
|
||||||
|
if str(viewer) != str(pid) and not is_platform_admin(role):
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Profil")
|
||||||
|
return profile_document(pid)
|
||||||
|
def _run_profile_update(pid: str, p: ProfileUpdate, tenant: TenantContext) -> dict:
|
||||||
|
"""Gemeinsame PUT-Logik für /profiles/{id} und Legacy /profile."""
|
||||||
|
sess_pid = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
if str(sess_pid) != str(pid) and role not in ("admin", "superadmin"):
|
||||||
|
raise HTTPException(403, "Keine Berechtigung für dieses Profil")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
@@ -100,6 +291,51 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
|||||||
patch = p.model_dump(exclude_unset=True)
|
patch = p.model_dump(exclude_unset=True)
|
||||||
data = {}
|
data = {}
|
||||||
|
|
||||||
|
if "role" in patch or "tier" in patch:
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Portal-Admins dürfen Rolle oder Tier ändern",
|
||||||
|
)
|
||||||
|
|
||||||
|
if "role" in patch:
|
||||||
|
new_role = (patch["role"] or "").strip().lower()
|
||||||
|
if new_role not in _ALLOWED_PORTAL_ROLES:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Ungültige Portal-Rolle. Erlaubt: {', '.join(sorted(_ALLOWED_PORTAL_ROLES))}",
|
||||||
|
)
|
||||||
|
if new_role == "superadmin" and role != "superadmin":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Super-Admins dürfen die Rolle Super-Admin vergeben",
|
||||||
|
)
|
||||||
|
old_r = (rowd.get("role") or "user").strip().lower()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*)::int AS c FROM profiles
|
||||||
|
WHERE lower(trim(role)) IN ('admin','superadmin')
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
admin_cnt = int(cur.fetchone()["c"])
|
||||||
|
if old_r in ("admin", "superadmin") and new_role not in ("admin", "superadmin"):
|
||||||
|
if admin_cnt <= 1:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Der letzte Portal-Administrator kann nicht zurückgestuft werden",
|
||||||
|
)
|
||||||
|
data["role"] = new_role
|
||||||
|
del patch["role"]
|
||||||
|
|
||||||
|
if "tier" in patch:
|
||||||
|
tv = patch["tier"]
|
||||||
|
if tv is None:
|
||||||
|
data["tier"] = "free"
|
||||||
|
else:
|
||||||
|
ts = str(tv).strip()
|
||||||
|
data["tier"] = (ts or "free")[:50]
|
||||||
|
del patch["tier"]
|
||||||
|
|
||||||
if "email" in patch:
|
if "email" in patch:
|
||||||
ev = patch["email"]
|
ev = patch["email"]
|
||||||
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
|
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
|
||||||
@@ -127,34 +363,98 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
|||||||
data["verification_token"] = None
|
data["verification_token"] = None
|
||||||
data["verification_expires"] = None
|
data["verification_expires"] = None
|
||||||
|
|
||||||
|
if "active_club_id" in patch:
|
||||||
|
ac = patch["active_club_id"]
|
||||||
|
if ac is None:
|
||||||
|
data["active_club_id"] = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
cid = int(ac)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(400, "active_club_id ungültig")
|
||||||
|
assert_club_member(cur, int(pid), cid)
|
||||||
|
data["active_club_id"] = cid
|
||||||
|
|
||||||
|
if "exercise_list_prefs" in patch:
|
||||||
|
ep = patch.pop("exercise_list_prefs")
|
||||||
|
if ep is None:
|
||||||
|
data["exercise_list_prefs"] = Json({})
|
||||||
|
elif isinstance(ep, dict):
|
||||||
|
data["exercise_list_prefs"] = Json(ep)
|
||||||
|
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"}
|
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||||
for k, v in patch.items():
|
for k, v in patch.items():
|
||||||
if k == "email":
|
if k == "email":
|
||||||
continue
|
continue
|
||||||
|
if k == "active_club_id":
|
||||||
|
continue
|
||||||
if v is None and k in nullable_keys:
|
if v is None and k in nullable_keys:
|
||||||
data[k] = None
|
data[k] = None
|
||||||
elif v is not None:
|
elif v is not None:
|
||||||
data[k] = v
|
data[k] = v
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
return get_profile(pid, session)
|
return profile_document(pid)
|
||||||
|
|
||||||
data["updated_at"] = datetime.now()
|
data["updated_at"] = datetime.now()
|
||||||
cols = ", ".join(f"{k}=%s" for k in data)
|
cols = ", ".join(f"{k}=%s" for k in data)
|
||||||
vals = list(data.values()) + [pid]
|
vals = list(data.values()) + [pid]
|
||||||
cur.execute(f"UPDATE profiles SET {cols} WHERE id=%s", vals)
|
cur.execute(f"UPDATE profiles SET {cols} WHERE id=%s", vals)
|
||||||
return get_profile(pid, session)
|
return profile_document(pid)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}")
|
||||||
|
def update_profile(pid: str, p: ProfileUpdate, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""Update profile — nur eigenes Profil oder Admin; TenantContext validiert X-Active-Club-Id."""
|
||||||
|
return _run_profile_update(pid, p, tenant)
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/profiles/{pid}")
|
@router.delete("/profiles/{pid}")
|
||||||
def delete_profile(pid: str, session=Depends(require_auth)):
|
def delete_profile(pid: str, session=Depends(require_auth)):
|
||||||
"""Delete profile (admin)."""
|
"""Profil löschen — nur Plattform-Admin; letztes Profil wird geschützt."""
|
||||||
|
role = session.get("role") or ""
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Plattform-Administratoren dürfen Profile löschen",
|
||||||
|
)
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("SELECT COUNT(*) as count FROM profiles")
|
cur.execute("SELECT COUNT(*) as count FROM profiles")
|
||||||
count = cur.fetchone()['count']
|
count = cur.fetchone()['count']
|
||||||
if count <= 1: raise HTTPException(400, "Letztes Profil kann nicht gelöscht werden")
|
if count <= 1: raise HTTPException(400, "Letztes Profil kann nicht gelöscht werden")
|
||||||
for table in ['weight_log','circumference_log','caliper_log','nutrition_log','activity_log','ai_insights']:
|
# Mitai-Überbleibsel: nur löschen, wenn die Tabelle im Schema existiert (Shinkan-DB ohne diese Tabellen).
|
||||||
|
_optional_mitai_tables = (
|
||||||
|
"weight_log",
|
||||||
|
"circumference_log",
|
||||||
|
"caliper_log",
|
||||||
|
"nutrition_log",
|
||||||
|
"activity_log",
|
||||||
|
"ai_insights",
|
||||||
|
)
|
||||||
|
for table in _optional_mitai_tables:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public' AND table_name = %s
|
||||||
|
) AS t_exists
|
||||||
|
""",
|
||||||
|
(table,),
|
||||||
|
)
|
||||||
|
ex = cur.fetchone()
|
||||||
|
if ex and next(iter(ex.values())):
|
||||||
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
|
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
|
||||||
cur.execute("DELETE FROM profiles WHERE id=%s", (pid,))
|
cur.execute("DELETE FROM profiles WHERE id=%s", (pid,))
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
@@ -162,14 +462,17 @@ def delete_profile(pid: str, session=Depends(require_auth)):
|
|||||||
|
|
||||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||||
@router.get("/profile")
|
@router.get("/profile")
|
||||||
def get_active_profile(x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
def get_active_profile(session: dict = Depends(require_auth)):
|
||||||
"""Legacy endpoint – returns active profile."""
|
"""Legacy-Alias für das eingeloggte Profil — immer Session, kein X-Profile-Id (SECURITY: kein IDOR)."""
|
||||||
pid = get_pid(x_profile_id)
|
pid = str(session["profile_id"])
|
||||||
return get_profile(pid, session)
|
return profile_document(pid)
|
||||||
|
|
||||||
|
|
||||||
@router.put("/profile")
|
@router.put("/profile")
|
||||||
def update_active_profile(p: ProfileUpdate, x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
def update_active_profile(
|
||||||
"""Update current user's profile."""
|
p: ProfileUpdate,
|
||||||
pid = get_pid(x_profile_id)
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
return update_profile(pid, p, session)
|
):
|
||||||
|
"""Profil des eingeloggten Nutzers aktualisieren — dieselbe Quelle wie GET /profile."""
|
||||||
|
pid = str(tenant.profile_id)
|
||||||
|
return _run_profile_update(pid, p, tenant)
|
||||||
@@ -3,13 +3,17 @@ Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere
|
|||||||
|
|
||||||
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
||||||
nicht über group_id oder training_unit_id am Rahmen.
|
nicht über group_id oder training_unit_id am Rahmen.
|
||||||
AuthZ wie Planungs-Vorlagen: Admin sieht alle, sonst nur eigene Artefakte; Schreibzugriff mit Planungsrolle.
|
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
|
||||||
"""
|
"""
|
||||||
from typing import Any, Dict, List, Optional, Sequence
|
from typing import Any, Dict, List, Optional, Sequence
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
from auth import require_auth
|
from club_tenancy import (
|
||||||
|
assert_valid_governance_visibility,
|
||||||
|
is_platform_admin,
|
||||||
|
library_content_visible_to_profile,
|
||||||
|
)
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
|
|
||||||
from routers.training_planning import (
|
from routers.training_planning import (
|
||||||
@@ -21,23 +25,57 @@ from routers.training_planning import (
|
|||||||
_validate_variant_for_exercise,
|
_validate_variant_for_exercise,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||||
|
|
||||||
router = APIRouter(prefix="/api", tags=["training_framework_programs"])
|
router = APIRouter(prefix="/api", tags=["training_framework_programs"])
|
||||||
_VALID_VISIBILITY = frozenset({"private", "club", "official"})
|
_VALID_VISIBILITY = frozenset({"private", "club", "official"})
|
||||||
|
|
||||||
|
|
||||||
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
def _fetch_framework_row(cur, framework_id: int) -> Dict[str, Any]:
|
||||||
cur.execute("SELECT * FROM training_framework_programs WHERE id = %s", (framework_id,))
|
cur.execute("SELECT * FROM training_framework_programs WHERE id = %s", (framework_id,))
|
||||||
r = cur.fetchone()
|
r = cur.fetchone()
|
||||||
if not r:
|
if not r:
|
||||||
raise HTTPException(status_code=404, detail="Trainingsrahmen nicht gefunden")
|
raise HTTPException(status_code=404, detail="Trainingsrahmen nicht gefunden")
|
||||||
row = r2d(r)
|
return r2d(r)
|
||||||
if role in ("admin", "superadmin"):
|
|
||||||
return row
|
|
||||||
|
def _framework_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 "private",
|
||||||
|
row.get("club_id"),
|
||||||
|
row.get("created_by"),
|
||||||
|
role,
|
||||||
|
):
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
||||||
|
|
||||||
|
|
||||||
|
def _framework_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:
|
if row.get("created_by") != profile_id:
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
||||||
|
|
||||||
|
|
||||||
|
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||||
|
row = _fetch_framework_row(cur, framework_id)
|
||||||
|
_framework_assert_readable(cur, row, profile_id, role)
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _response_framework_detail(framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||||
|
"""Einzelabruf nach Schreiboperation (ohne FastAPI-Depends-Schleife)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
row = _framework_access(cur, framework_id, profile_id, role)
|
||||||
|
return _hydrate_framework(cur, row)
|
||||||
|
|
||||||
|
|
||||||
def _training_type_ids(cur, framework_id: int) -> List[int]:
|
def _training_type_ids(cur, framework_id: int) -> List[int]:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
@@ -279,9 +317,9 @@ def _insert_slots_and_blueprints(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/training-framework-programs")
|
@router.get("/training-framework-programs")
|
||||||
def list_training_framework_programs(session=Depends(require_auth)):
|
def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
profile_id = session["profile_id"]
|
profile_id = tenant.profile_id
|
||||||
role = session.get("role")
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
base_sel = """
|
base_sel = """
|
||||||
@@ -312,30 +350,36 @@ def list_training_framework_programs(session=Depends(require_auth)):
|
|||||||
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
||||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||||
"""
|
"""
|
||||||
if role in ("admin", "superadmin"):
|
vis_clause, vis_params = library_content_visibility_sql(
|
||||||
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
|
alias="fp",
|
||||||
else:
|
profile_id=profile_id,
|
||||||
|
role=role,
|
||||||
|
effective_club_id=tenant.effective_club_id,
|
||||||
|
)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
base_sel + " WHERE fp.created_by = %s ORDER BY fp.updated_at DESC NULLS LAST, fp.title",
|
base_sel
|
||||||
(profile_id,),
|
+ f""" WHERE ({vis_clause})
|
||||||
|
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
||||||
|
vis_params,
|
||||||
)
|
)
|
||||||
return [r2d(r) for r in cur.fetchall()]
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
@router.get("/training-framework-programs/{framework_id}")
|
@router.get("/training-framework-programs/{framework_id}")
|
||||||
def get_training_framework_program(framework_id: int, session=Depends(require_auth)):
|
def get_training_framework_program(
|
||||||
profile_id = session["profile_id"]
|
framework_id: int, tenant: TenantContext = Depends(get_tenant_context)
|
||||||
role = session.get("role")
|
):
|
||||||
with get_db() as conn:
|
profile_id = tenant.profile_id
|
||||||
cur = get_cursor(conn)
|
role = tenant.global_role
|
||||||
row = _framework_access(cur, framework_id, profile_id, role)
|
return _response_framework_detail(framework_id, profile_id, role)
|
||||||
return _hydrate_framework(cur, row)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/training-framework-programs")
|
@router.post("/training-framework-programs")
|
||||||
def create_training_framework_program(data: dict, session=Depends(require_auth)):
|
def create_training_framework_program(
|
||||||
profile_id = session["profile_id"]
|
data: dict, tenant: TenantContext = Depends(get_tenant_context)
|
||||||
role = session.get("role")
|
):
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
if not _has_planning_role(role):
|
if not _has_planning_role(role):
|
||||||
raise HTTPException(status_code=403, detail="Nur Planungsberechtigte dürfen Rahmenprogramme anlegen")
|
raise HTTPException(status_code=403, detail="Nur Planungsberechtigte dürfen Rahmenprogramme anlegen")
|
||||||
|
|
||||||
@@ -346,6 +390,11 @@ def create_training_framework_program(data: dict, session=Depends(require_auth))
|
|||||||
vis = data.get("visibility") or "private"
|
vis = data.get("visibility") or "private"
|
||||||
vis = _assert_visibility(vis)
|
vis = _assert_visibility(vis)
|
||||||
club_id = data.get("club_id")
|
club_id = data.get("club_id")
|
||||||
|
if club_id in ("", []):
|
||||||
|
club_id = None
|
||||||
|
if vis == "club" and club_id is None:
|
||||||
|
club_id = tenant.effective_club_id
|
||||||
|
|
||||||
goals_in = data.get("goals")
|
goals_in = data.get("goals")
|
||||||
slots_in = data.get("slots")
|
slots_in = data.get("slots")
|
||||||
if not isinstance(goals_in, list) or not goals_in:
|
if not isinstance(goals_in, list) or not goals_in:
|
||||||
@@ -358,6 +407,7 @@ def create_training_framework_program(data: dict, session=Depends(require_auth))
|
|||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
assert_valid_governance_visibility(cur, profile_id, role, vis, club_id)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO training_framework_programs (
|
INSERT INTO training_framework_programs (
|
||||||
@@ -387,19 +437,36 @@ def create_training_framework_program(data: dict, session=Depends(require_auth))
|
|||||||
_replace_target_groups(cur, fid, tg_ids)
|
_replace_target_groups(cur, fid, tg_ids)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_training_framework_program(fid, session)
|
return _response_framework_detail(fid, profile_id, role)
|
||||||
|
|
||||||
|
|
||||||
@router.put("/training-framework-programs/{framework_id}")
|
@router.put("/training-framework-programs/{framework_id}")
|
||||||
def update_training_framework_program(framework_id: int, data: dict, session=Depends(require_auth)):
|
def update_training_framework_program(
|
||||||
profile_id = session["profile_id"]
|
framework_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
|
||||||
role = session.get("role")
|
):
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
if not _has_planning_role(role):
|
if not _has_planning_role(role):
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_framework_access(cur, framework_id, profile_id, role)
|
row_prev = _fetch_framework_row(cur, framework_id)
|
||||||
|
_framework_assert_writable(cur, row_prev, profile_id, role)
|
||||||
|
|
||||||
|
merged_vis = row_prev.get("visibility") or "private"
|
||||||
|
merged_club = row_prev.get("club_id")
|
||||||
|
if "visibility" in data:
|
||||||
|
v_m = _assert_visibility(data.get("visibility"))
|
||||||
|
if v_m is None:
|
||||||
|
raise HTTPException(status_code=400, detail="visibility fehlt")
|
||||||
|
merged_vis = v_m
|
||||||
|
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)
|
||||||
|
|
||||||
header_fields = []
|
header_fields = []
|
||||||
header_params: List[Any] = []
|
header_params: List[Any] = []
|
||||||
@@ -422,14 +489,11 @@ def update_training_framework_program(framework_id: int, data: dict, session=Dep
|
|||||||
header_params.append(data.get("planned_period_end"))
|
header_params.append(data.get("planned_period_end"))
|
||||||
|
|
||||||
if "visibility" in data:
|
if "visibility" in data:
|
||||||
v = _assert_visibility(data.get("visibility"))
|
|
||||||
if v is None:
|
|
||||||
raise HTTPException(status_code=400, detail="visibility fehlt")
|
|
||||||
header_fields.append("visibility = %s")
|
header_fields.append("visibility = %s")
|
||||||
header_params.append(v)
|
header_params.append(merged_vis)
|
||||||
if "club_id" in data:
|
if "club_id" in data:
|
||||||
header_fields.append("club_id = %s")
|
header_fields.append("club_id = %s")
|
||||||
header_params.append(data.get("club_id"))
|
header_params.append(merged_club)
|
||||||
|
|
||||||
if "focus_area_id" in data:
|
if "focus_area_id" in data:
|
||||||
fidv = data.get("focus_area_id")
|
fidv = data.get("focus_area_id")
|
||||||
@@ -489,16 +553,19 @@ def update_training_framework_program(framework_id: int, data: dict, session=Dep
|
|||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_training_framework_program(framework_id, session)
|
return _response_framework_detail(framework_id, profile_id, role)
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/training-framework-programs/{framework_id}")
|
@router.delete("/training-framework-programs/{framework_id}")
|
||||||
def delete_training_framework_program(framework_id: int, session=Depends(require_auth)):
|
def delete_training_framework_program(
|
||||||
profile_id = session["profile_id"]
|
framework_id: int, tenant: TenantContext = Depends(get_tenant_context)
|
||||||
role = session.get("role")
|
):
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_framework_access(cur, framework_id, profile_id, role)
|
row_fw = _fetch_framework_row(cur, framework_id)
|
||||||
|
_framework_assert_writable(cur, row_fw, profile_id, role)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"DELETE FROM training_framework_programs WHERE id = %s",
|
"DELETE FROM training_framework_programs WHERE id = %s",
|
||||||
(framework_id,),
|
(framework_id,),
|
||||||
|
|||||||
@@ -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}
|
||||||
+1354
-184
File diff suppressed because it is too large.
Load diff
+23
-14
@@ -2,8 +2,17 @@
|
|||||||
"""
|
"""
|
||||||
Shinkan Jinkendo — Datenbank-Migrationen
|
Shinkan Jinkendo — Datenbank-Migrationen
|
||||||
|
|
||||||
**Idempotent** über `schema_migrations`: jede numerische Datei `migrations/*.sql` höchstens einmal
|
**Deployment:** Beim Start importiert `main.py` dieses Modul und ruft `main()` auf, bevor FastAPI
|
||||||
als „erfolgreich“ eingetragen; bei erneutem Start werden nur noch fehlende Dateien abgearbeitet.
|
die App lädt (`SKIP_DB_MIGRATE=1` nur für Tests oder ohne DB). Jeder Backend-Container-Start
|
||||||
|
wendet ausstehende Migrationen an — kein separater Deploy-Schritt nötig.
|
||||||
|
|
||||||
|
**Idempotent (Runner):** Über `schema_migrations` wird jede Datei `NNN_*.sql` höchstens einmal
|
||||||
|
als erfolgreich markiert; wiederholte Starts führen nur noch fehlende Dateien aus.
|
||||||
|
|
||||||
|
**Idempotent (SQL, empfohlen):** `IF NOT EXISTS`, `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`,
|
||||||
|
damit ein erneuter Lauf derselben Datei harmlos bleibt. Ohne diese Guards schützt nur der
|
||||||
|
`schema_migrations`-Eintrag; ältere Migrationen ohne IF NOT EXISTS können bei manuell gelöschtem
|
||||||
|
Eintrag und bestehenden Tabellen fehlschlagen.
|
||||||
|
|
||||||
**Reihenfolge:** Alle `NNN_*.sql` nach führender Zahl (001 vor 009 vor 010 …), bei gleicher Zahl
|
**Reihenfolge:** Alle `NNN_*.sql` nach führender Zahl (001 vor 009 vor 010 …), bei gleicher Zahl
|
||||||
alphabetisch nach Dateinamen — nicht bloß String-Sortierung (vermeidet z. B. `10_` vor `9_`).
|
alphabetisch nach Dateinamen — nicht bloß String-Sortierung (vermeidet z. B. `10_` vor `9_`).
|
||||||
@@ -49,14 +58,14 @@ def get_db_connection():
|
|||||||
password=p["password"],
|
password=p["password"],
|
||||||
)
|
)
|
||||||
conn.autocommit = False
|
conn.autocommit = False
|
||||||
print(f"✓ Connected to database: {p['dbname']}")
|
print(f"[OK] Connected to database: {p['dbname']}")
|
||||||
return conn
|
return conn
|
||||||
except psycopg2.OperationalError:
|
except psycopg2.OperationalError:
|
||||||
if i < max_retries - 1:
|
if i < max_retries - 1:
|
||||||
print(f"Waiting for database... ({i+1}/{max_retries})")
|
print(f"Waiting for database... ({i+1}/{max_retries})")
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
else:
|
else:
|
||||||
print(f"✗ Failed to connect to database after {max_retries} attempts")
|
print(f"[FAIL] Failed to connect to database after {max_retries} attempts")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
@@ -72,7 +81,7 @@ def init_migrations_table(conn):
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
print("✓ schema_migrations initialisiert")
|
print("[OK] schema_migrations initialisiert")
|
||||||
|
|
||||||
|
|
||||||
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
||||||
@@ -190,7 +199,7 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
|||||||
if shutil.which("psql"):
|
if shutil.which("psql"):
|
||||||
ok, diag = _run_file_with_psql(filepath)
|
ok, diag = _run_file_with_psql(filepath)
|
||||||
if not ok:
|
if not ok:
|
||||||
print(f" ✗ psql fehlgeschlagen:\n{diag or '(kein Output)'}")
|
print(f" [FAIL] psql fehlgeschlagen:\n{diag or '(kein Output)'}")
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
return False
|
return False
|
||||||
detail_suffix = "(psql -1)"
|
detail_suffix = "(psql -1)"
|
||||||
@@ -199,7 +208,7 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
|||||||
with open(filepath, "r", encoding="utf-8") as fh:
|
with open(filepath, "r", encoding="utf-8") as fh:
|
||||||
body = fh.read()
|
body = fh.read()
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
print(f" ✗ kann Datei nicht lesen: {e}")
|
print(f" [FAIL] kann Datei nicht lesen: {e}")
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -207,7 +216,7 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
|||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
if not statements:
|
if not statements:
|
||||||
print(
|
print(
|
||||||
f" ⚠ keine ausführbaren Statements (leer?) — "
|
f" [WARN] keine ausführbaren Statements (leer?) — "
|
||||||
f"Eintrag trotzdem: {migration_name}"
|
f"Eintrag trotzdem: {migration_name}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -217,12 +226,12 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
|||||||
|
|
||||||
_record_migration(conn, migration_name)
|
_record_migration(conn, migration_name)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
print(f" ✓ {migration_name} erfolgreich {detail_suffix}")
|
print(f" [OK] {migration_name} erfolgreich {detail_suffix}")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
print(f" ✗ {migration_name}: {e}")
|
print(f" [FAIL] {migration_name}: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
@@ -243,7 +252,7 @@ def main():
|
|||||||
pending = get_pending(conn, migrations_dir)
|
pending = get_pending(conn, migrations_dir)
|
||||||
|
|
||||||
if not pending:
|
if not pending:
|
||||||
print("✓ Keine ausstehenden Migrationen — Schema aktuell.")
|
print("[OK] Keine ausstehenden Migrationen — Schema aktuell.")
|
||||||
conn.close()
|
conn.close()
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@@ -262,17 +271,17 @@ def main():
|
|||||||
|
|
||||||
print("\n" + "=" * 60)
|
print("\n" + "=" * 60)
|
||||||
if failed:
|
if failed:
|
||||||
print(f"✗ Abbruch nach: {failed}")
|
print(f"[FAIL] Abbruch nach: {failed}")
|
||||||
print(" (Bereits erfolgreiche Dateien dieser Session sind committed.)")
|
print(" (Bereits erfolgreiche Dateien dieser Session sind committed.)")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
print(f"✓ {len(pending)} Migration(s) angewendet — Schema aktuell.")
|
print(f"[OK] {len(pending)} Migration(s) angewendet — Schema aktuell.")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"\n✗ Fehler: {e}")
|
print(f"\n[FAIL] Fehler: {e}")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Heuristik-Check: Router mit FastAPI-Routen und Auth sollten bei mandantenrelevanten APIs
|
||||||
|
get_tenant_context nutzen — siehe ACCESS_LAYER_AND_GOVERNANCE_PLAN.md.
|
||||||
|
|
||||||
|
Lauf aus Repo-Root:
|
||||||
|
python backend/scripts/check_access_layer_hints.py
|
||||||
|
|
||||||
|
Mit Fehler-Exit bei Verstößen (z. B. CI):
|
||||||
|
set ACCESS_LAYER_STRICT=1 # Windows: set ACCESS_LAYER_STRICT=1
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# Router, die bewusst keinen TenantContext verwenden (global / Auth-only / Admin-Tools).
|
||||||
|
# Neuen Eintrag nur mit kurzer Begründung im Commit/Audit ergänzen.
|
||||||
|
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",
|
||||||
|
"matrix_stack_bundle.py",
|
||||||
|
"import_wiki.py",
|
||||||
|
"import_wiki_admin.py",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
strict = os.environ.get("ACCESS_LAYER_STRICT", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
routers = root / "routers"
|
||||||
|
if not routers.is_dir():
|
||||||
|
print("check_access_layer_hints: routers/ nicht gefunden", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
issues: list[str] = []
|
||||||
|
for path in sorted(routers.glob("*.py")):
|
||||||
|
name = path.name
|
||||||
|
text = path.read_text(encoding="utf-8")
|
||||||
|
if "@router." not in text:
|
||||||
|
continue
|
||||||
|
if name in EXEMPT_ROUTERS:
|
||||||
|
continue
|
||||||
|
if "get_tenant_context" in text:
|
||||||
|
continue
|
||||||
|
if "require_auth" not in text:
|
||||||
|
continue
|
||||||
|
issues.append(
|
||||||
|
f" {path.relative_to(root.parent)}: Routen + require_auth, "
|
||||||
|
f"aber kein get_tenant_context — TenantContext ergänzen oder in EXEMPT_ROUTERS eintragen "
|
||||||
|
f"(mit Begründung / Audit)."
|
||||||
|
)
|
||||||
|
|
||||||
|
if not issues:
|
||||||
|
print("check_access_layer_hints: OK (keine auffälligen Router außerhalb EXEMPT).")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
print("check_access_layer_hints: mögliche ACCESS_LAYER-Abweichungen:\n", file=sys.stderr)
|
||||||
|
for line in issues:
|
||||||
|
print(line, file=sys.stderr)
|
||||||
|
print(
|
||||||
|
"\nHinweis: Heuristik — false positives möglich. "
|
||||||
|
"Bei echter Ausnahme Datei zu EXEMPT_ROUTERS hinzufügen.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1 if strict else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
|
||||||
|
|
||||||
|
Lauf z. B. täglich per Cron:
|
||||||
|
cd /path/to/backend && python scripts/media_retention_job.py
|
||||||
|
|
||||||
|
Umgebung wie Backend (DB_*), optional:
|
||||||
|
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
|
||||||
|
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 90)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Repo-Root: backend/scripts -> parents[1] == backend
|
||||||
|
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||||
|
if _ROOT not in sys.path:
|
||||||
|
sys.path.insert(0, _ROOT)
|
||||||
|
|
||||||
|
from db import get_db, get_cursor # noqa: E402
|
||||||
|
from media_lifecycle import run_retention_pass # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
summary = run_retention_pass(cur, conn)
|
||||||
|
print(summary)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
CI-Sicherheitschecks: schlanke pytest-Sammlung ohne Integrations-DB.
|
||||||
|
|
||||||
|
Repo-Root ist egal — arbeitet relativ zu diesem Script (backend/).
|
||||||
|
|
||||||
|
Usage (aus backend/):
|
||||||
|
python scripts/security_release_checks.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
test_file = root / "tests" / "test_security_release.py"
|
||||||
|
cmd = [
|
||||||
|
sys.executable,
|
||||||
|
"-m",
|
||||||
|
"pytest",
|
||||||
|
str(test_file),
|
||||||
|
"-v",
|
||||||
|
"--tb=short",
|
||||||
|
]
|
||||||
|
return subprocess.run(cmd, cwd=str(root)).returncode
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
"""
|
||||||
|
Request-weiter Mandanten-Kontext (ACCESS_LAYER_AND_GOVERNANCE_PLAN.md, Stufe B).
|
||||||
|
|
||||||
|
Zielt auf einheitliche Auflösung aus Session + Header X-Active-Club-Id + Profilfeld active_club_id.
|
||||||
|
Router können Depends(get_tenant_context) nutzen oder resolve_tenant_context mit bereits geladenen Mitgliedschaften (ein DB-Block).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, Header, HTTPException
|
||||||
|
|
||||||
|
from auth import require_auth, require_auth_flexible
|
||||||
|
from club_tenancy import is_platform_admin, memberships_with_roles
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
|
||||||
|
|
||||||
|
def _club_exists(cur, club_id: int) -> bool:
|
||||||
|
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
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:
|
||||||
|
return None
|
||||||
|
s = str(raw).strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
v = int(s)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail="X-Active-Club-Id ungültig")
|
||||||
|
if v < 1:
|
||||||
|
raise HTTPException(status_code=400, detail="X-Active-Club-Id ungültig")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def library_content_visibility_sql(
|
||||||
|
*,
|
||||||
|
alias: str,
|
||||||
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
|
effective_club_id: Optional[int],
|
||||||
|
) -> tuple[str, List[Any]]:
|
||||||
|
"""
|
||||||
|
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).
|
||||||
|
"""
|
||||||
|
plat = is_platform_admin(role)
|
||||||
|
parts: List[str] = [f"{alias}.visibility = 'official'"]
|
||||||
|
params: List[Any] = []
|
||||||
|
|
||||||
|
if plat:
|
||||||
|
parts.append(f"({alias}.visibility = 'private')")
|
||||||
|
else:
|
||||||
|
parts.append(f"({alias}.visibility = 'private' AND {alias}.created_by = %s)")
|
||||||
|
params.append(profile_id)
|
||||||
|
|
||||||
|
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'
|
||||||
|
AND {alias}.club_id IS NOT NULL
|
||||||
|
AND {alias}.club_id = %s
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM club_members cm
|
||||||
|
WHERE cm.profile_id = %s AND cm.club_id = {alias}.club_id AND cm.status = 'active'
|
||||||
|
)
|
||||||
|
)"""
|
||||||
|
)
|
||||||
|
params.extend([effective_club_id, profile_id])
|
||||||
|
|
||||||
|
return "(" + " OR ".join(parts) + ")", params
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TenantContext:
|
||||||
|
profile_id: int
|
||||||
|
global_role: str
|
||||||
|
# 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]]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_tenant_context(
|
||||||
|
cur,
|
||||||
|
*,
|
||||||
|
profile_id: int,
|
||||||
|
global_role: str,
|
||||||
|
header_raw: Optional[str],
|
||||||
|
memberships: Optional[List[Dict[str, Any]]] = None,
|
||||||
|
stored_active_club_id: Optional[int] = None,
|
||||||
|
invalid_header_policy: str = "reject",
|
||||||
|
) -> TenantContext:
|
||||||
|
"""
|
||||||
|
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 → 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).
|
||||||
|
"""
|
||||||
|
role_lc = (global_role or "").lower()
|
||||||
|
header_cid = parse_active_club_header(header_raw)
|
||||||
|
|
||||||
|
if memberships is None:
|
||||||
|
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 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(
|
||||||
|
profile_id=profile_id,
|
||||||
|
global_role=role_lc,
|
||||||
|
effective_club_id=effective,
|
||||||
|
club_ids=club_ids,
|
||||||
|
memberships=membership_rows,
|
||||||
|
)
|
||||||
|
|
||||||
|
chosen_header = header_cid
|
||||||
|
if chosen_header is not None and chosen_header not in club_ids:
|
||||||
|
if invalid_header_policy == "reject":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Keine Mitgliedschaft im gewählten Verein",
|
||||||
|
)
|
||||||
|
chosen_header = None
|
||||||
|
|
||||||
|
if chosen_header is not None:
|
||||||
|
effective = chosen_header
|
||||||
|
elif stored_active_club_id is not None and stored_active_club_id in club_ids:
|
||||||
|
effective = stored_active_club_id
|
||||||
|
elif len(club_ids) == 1:
|
||||||
|
effective = next(iter(club_ids))
|
||||||
|
elif len(club_ids) == 0:
|
||||||
|
effective = None
|
||||||
|
else:
|
||||||
|
effective = min(club_ids)
|
||||||
|
|
||||||
|
return TenantContext(
|
||||||
|
profile_id=profile_id,
|
||||||
|
global_role=role_lc,
|
||||||
|
effective_club_id=effective,
|
||||||
|
club_ids=club_ids,
|
||||||
|
memberships=membership_rows,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_tenant_context(
|
||||||
|
session: dict = Depends(require_auth),
|
||||||
|
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||||
|
) -> TenantContext:
|
||||||
|
"""FastAPI-Dependency: öffnet eine DB-Verbindung und liefert TenantContext."""
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
role = session.get("role") or ""
|
||||||
|
stored: Optional[int] = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT active_club_id FROM profiles WHERE id = %s", (pid,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is not None:
|
||||||
|
ac = row.get("active_club_id")
|
||||||
|
if ac is not None:
|
||||||
|
stored = int(ac)
|
||||||
|
return resolve_tenant_context(
|
||||||
|
cur,
|
||||||
|
profile_id=pid,
|
||||||
|
global_role=role,
|
||||||
|
header_raw=x_active_club_id,
|
||||||
|
memberships=None,
|
||||||
|
stored_active_club_id=stored,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_tenant_context_flexible(
|
||||||
|
session: dict = Depends(require_auth_flexible),
|
||||||
|
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||||
|
) -> TenantContext:
|
||||||
|
"""
|
||||||
|
Wie get_tenant_context, aber Auth per Header oder Query ?ssetoken (für <img>/<video> ohne Custom-Header).
|
||||||
|
"""
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
role = session.get("role") or ""
|
||||||
|
stored: Optional[int] = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT active_club_id FROM profiles WHERE id = %s", (pid,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is not None:
|
||||||
|
ac = row.get("active_club_id")
|
||||||
|
if ac is not None:
|
||||||
|
stored = int(ac)
|
||||||
|
return resolve_tenant_context(
|
||||||
|
cur,
|
||||||
|
profile_id=pid,
|
||||||
|
global_role=role,
|
||||||
|
header_raw=x_active_club_id,
|
||||||
|
memberships=None,
|
||||||
|
stored_active_club_id=stored,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def tenant_context_from_session_only(
|
||||||
|
cur,
|
||||||
|
session: dict,
|
||||||
|
header_raw: Optional[str],
|
||||||
|
*,
|
||||||
|
memberships: Optional[List[Dict[str, Any]]] = None,
|
||||||
|
stored_active_club_id: Optional[int] = None,
|
||||||
|
invalid_header_policy: str = "reject",
|
||||||
|
) -> TenantContext:
|
||||||
|
"""Variante ohne FastAPI (Tests / gemeinsamer Cursor mit anderen Queries)."""
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
role = session.get("role") or ""
|
||||||
|
return resolve_tenant_context(
|
||||||
|
cur,
|
||||||
|
profile_id=pid,
|
||||||
|
global_role=role,
|
||||||
|
header_raw=header_raw,
|
||||||
|
memberships=memberships,
|
||||||
|
stored_active_club_id=stored_active_club_id,
|
||||||
|
invalid_header_policy=invalid_header_policy,
|
||||||
|
)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""Unit tests ohne Datenbank für die Zugriffsschicht (Visibility-SQL, Header-Parsing)."""
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
|
||||||
|
|
||||||
|
|
||||||
|
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 "e.visibility = 'official'" in sql
|
||||||
|
assert "club_members" in sql
|
||||||
|
assert params == [1, 1]
|
||||||
|
|
||||||
|
|
||||||
|
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 "club_members" in sql
|
||||||
|
assert params == [2, 2]
|
||||||
|
|
||||||
|
|
||||||
|
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
|
||||||
|
sql, params = library_content_visibility_sql(
|
||||||
|
alias="g",
|
||||||
|
profile_id=42,
|
||||||
|
role="trainer",
|
||||||
|
effective_club_id=None,
|
||||||
|
)
|
||||||
|
assert "official" in sql
|
||||||
|
assert "private" in sql
|
||||||
|
assert "visibility = 'club'" not in sql
|
||||||
|
assert params == [42]
|
||||||
|
|
||||||
|
|
||||||
|
def test_library_visibility_sql_user_with_active_club_includes_club_branch():
|
||||||
|
sql, params = library_content_visibility_sql(
|
||||||
|
alias="t",
|
||||||
|
profile_id=7,
|
||||||
|
role="user",
|
||||||
|
effective_club_id=99,
|
||||||
|
)
|
||||||
|
assert "visibility = 'club'" in sql
|
||||||
|
assert "club_members" in sql
|
||||||
|
assert params[0] == 7 # private branch created_by
|
||||||
|
assert 99 in params
|
||||||
|
assert params.count(7) >= 2 # private + EXISTS membership
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_active_club_header_none_and_empty():
|
||||||
|
assert parse_active_club_header(None) is None
|
||||||
|
assert parse_active_club_header("") is None
|
||||||
|
assert parse_active_club_header(" ") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_active_club_header_valid():
|
||||||
|
assert parse_active_club_header("12") == 12
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_active_club_header_invalid():
|
||||||
|
with pytest.raises(HTTPException) as exc:
|
||||||
|
parse_active_club_header("not-int")
|
||||||
|
assert exc.value.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
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,323 @@
|
|||||||
|
"""
|
||||||
|
Cross-Tenant-Integrationstests (PostgreSQL).
|
||||||
|
|
||||||
|
Voraussetzungen:
|
||||||
|
- Migrierte Datenbank (wie lokaler Docker-Postgres).
|
||||||
|
- ACCESS_LAYER_INTEGRATION=1 oder true
|
||||||
|
- DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD passend setzen
|
||||||
|
(lokal z. B. DB_HOST=localhost DB_PORT=5434 bei docker-compose Port-Mapping).
|
||||||
|
|
||||||
|
Aufruf aus backend/:
|
||||||
|
set ACCESS_LAYER_INTEGRATION=1
|
||||||
|
pytest tests/test_access_layer_integration.py -v -m integration
|
||||||
|
|
||||||
|
main wird mit SKIP_DB_MIGRATE=1 importiert, damit beim Testlauf keine Migrationen erneut laufen.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
def _integration_enabled() -> bool:
|
||||||
|
return os.getenv("ACCESS_LAYER_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
pytestmark = [
|
||||||
|
pytest.mark.integration,
|
||||||
|
pytest.mark.skipif(
|
||||||
|
not _integration_enabled(),
|
||||||
|
reason="ACCESS_LAYER_INTEGRATION=1 setzen und PostgreSQL (DB_*) konfigurieren",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _db_ping() -> bool:
|
||||||
|
try:
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT 1 AS ok")
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row is not None and row.get("ok") == 1
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def integration_app():
|
||||||
|
"""FastAPI-App ohne erneuten Migrationslauf beim Import."""
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
from main import app
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def db_ready():
|
||||||
|
if not _db_ping():
|
||||||
|
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/… prüfen)")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CrossTenantFixture:
|
||||||
|
suffix: str
|
||||||
|
club_a_id: int
|
||||||
|
club_b_id: int
|
||||||
|
user_a_id: int
|
||||||
|
user_b_id: int
|
||||||
|
token_a: str
|
||||||
|
token_b: str
|
||||||
|
exercise_official_id: int
|
||||||
|
exercise_club_b_id: int
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cross_tenant(integration_app, db_ready) -> CrossTenantFixture:
|
||||||
|
from auth import hash_pin, make_token
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
|
||||||
|
suffix = uuid.uuid4().hex[:10]
|
||||||
|
email_a = f"access_layer_it_{suffix}_a@test.local"
|
||||||
|
email_b = f"access_layer_it_{suffix}_b@test.local"
|
||||||
|
name_a = f"Club A User {suffix}"
|
||||||
|
name_b = f"Club B User {suffix}"
|
||||||
|
club_a_name = f"access_layer_it_club_a_{suffix}"
|
||||||
|
club_b_name = f"access_layer_it_club_b_{suffix}"
|
||||||
|
token_a = f"it-token-a-{suffix}"
|
||||||
|
token_b = f"it-token-b-{suffix}"
|
||||||
|
|
||||||
|
pin_hash = hash_pin("integration-test-pin")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||||
|
(club_a_name, "ITA", "active"),
|
||||||
|
)
|
||||||
|
club_a_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||||
|
(club_b_name, "ITB", "active"),
|
||||||
|
)
|
||||||
|
club_b_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(email_a, pin_hash, name_a, "trainer", club_a_id),
|
||||||
|
)
|
||||||
|
user_a_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(email_b, pin_hash, name_b, "trainer", club_b_id),
|
||||||
|
)
|
||||||
|
user_b_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO club_members (profile_id, club_id, status) VALUES (%s, %s, %s)",
|
||||||
|
(user_a_id, club_a_id, "active"),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO club_members (profile_id, club_id, status) VALUES (%s, %s, %s)",
|
||||||
|
(user_b_id, club_b_id, "active"),
|
||||||
|
)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (profile_id, token, expires_at)
|
||||||
|
VALUES (%s, %s, NOW() + INTERVAL '2 days')
|
||||||
|
""",
|
||||||
|
(user_a_id, token_a),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (profile_id, token, expires_at)
|
||||||
|
VALUES (%s, %s, NOW() + INTERVAL '2 days')
|
||||||
|
""",
|
||||||
|
(user_b_id, token_b),
|
||||||
|
)
|
||||||
|
|
||||||
|
title_official = f"access_layer_it_official_{suffix}"
|
||||||
|
title_club_b = f"access_layer_it_club_b_only_{suffix}"
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO exercises
|
||||||
|
(title, summary, goal, execution, visibility, status, created_by, club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
title_official,
|
||||||
|
None,
|
||||||
|
"Goal",
|
||||||
|
"Execution",
|
||||||
|
"official",
|
||||||
|
"approved",
|
||||||
|
user_b_id,
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
exercise_official_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO exercises
|
||||||
|
(title, summary, goal, execution, visibility, status, created_by, club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
title_club_b,
|
||||||
|
None,
|
||||||
|
"Goal",
|
||||||
|
"Execution",
|
||||||
|
"club",
|
||||||
|
"approved",
|
||||||
|
user_b_id,
|
||||||
|
club_b_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
exercise_club_b_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
fx = CrossTenantFixture(
|
||||||
|
suffix=suffix,
|
||||||
|
club_a_id=club_a_id,
|
||||||
|
club_b_id=club_b_id,
|
||||||
|
user_a_id=user_a_id,
|
||||||
|
user_b_id=user_b_id,
|
||||||
|
token_a=token_a,
|
||||||
|
token_b=token_b,
|
||||||
|
exercise_official_id=exercise_official_id,
|
||||||
|
exercise_club_b_id=exercise_club_b_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield fx
|
||||||
|
finally:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM exercises WHERE id IN (%s, %s)",
|
||||||
|
(exercise_official_id, exercise_club_b_id),
|
||||||
|
)
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token IN (%s, %s)", (token_a, token_b))
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM club_members WHERE profile_id IN (%s, %s)",
|
||||||
|
(user_a_id, user_b_id),
|
||||||
|
)
|
||||||
|
cur.execute("DELETE FROM profiles WHERE id IN (%s, %s)", (user_a_id, user_b_id))
|
||||||
|
cur.execute("DELETE FROM clubs WHERE id IN (%s, %s)", (club_a_id, club_b_id))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_hides_foreign_club_exercise_same_active_header(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
"""Nutzer nur Verein A sieht keine Vereins-Übung von Verein B (aktiver Header = A)."""
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
"/api/exercises",
|
||||||
|
params={"search": f"access_layer_it_club_b_only_{cross_tenant.suffix}", "limit": 50},
|
||||||
|
headers={
|
||||||
|
"X-Auth-Token": cross_tenant.token_a,
|
||||||
|
"X-Active-Club-Id": str(cross_tenant.club_a_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
ids = [row["id"] for row in r.json()]
|
||||||
|
assert cross_tenant.exercise_club_b_id not in ids
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_shows_official_exercise_for_foreign_user(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
"""Offizielle Übung ist für alle authentifizierten Nutzer sichtbar."""
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
"/api/exercises",
|
||||||
|
params={"search": f"access_layer_it_official_{cross_tenant.suffix}", "limit": 50},
|
||||||
|
headers={
|
||||||
|
"X-Auth-Token": cross_tenant.token_a,
|
||||||
|
"X-Active-Club-Id": str(cross_tenant.club_a_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
ids = [row["id"] for row in r.json()]
|
||||||
|
assert cross_tenant.exercise_official_id in ids
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_forbidden_foreign_club_exercise(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
"""Detail: keine Mitgliedschaft im Übungs-Verein → 403."""
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
f"/api/exercises/{cross_tenant.exercise_club_b_id}",
|
||||||
|
headers={
|
||||||
|
"X-Auth-Token": cross_tenant.token_a,
|
||||||
|
"X-Active-Club-Id": str(cross_tenant.club_a_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_member_club_b_can_read_own_club_exercise(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
f"/api/exercises/{cross_tenant.exercise_club_b_id}",
|
||||||
|
headers={
|
||||||
|
"X-Auth-Token": cross_tenant.token_b,
|
||||||
|
"X-Active-Club-Id": str(cross_tenant.club_b_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.json()
|
||||||
|
assert body["id"] == cross_tenant.exercise_club_b_id
|
||||||
|
assert body["visibility"] == "club"
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_profile_forbidden_other_user_integration(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
"""GET /profiles/{id}: Fremdes Profil → 403 (PostgreSQL-Integration)."""
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
f"/api/profiles/{cross_tenant.user_b_id}",
|
||||||
|
headers={"X-Auth-Token": cross_tenant.token_a},
|
||||||
|
)
|
||||||
|
assert r.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_profile_ok_own_integration(
|
||||||
|
integration_app, cross_tenant: CrossTenantFixture
|
||||||
|
):
|
||||||
|
client = TestClient(integration_app)
|
||||||
|
r = client.get(
|
||||||
|
f"/api/profiles/{cross_tenant.user_a_id}",
|
||||||
|
headers={"X-Auth-Token": cross_tenant.token_a},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
body = r.json()
|
||||||
|
assert body["id"] == cross_tenant.user_a_id
|
||||||
|
assert "pin_hash" not in body
|
||||||
@@ -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,69 @@
|
|||||||
|
"""GET /api/dashboard/kpis: Auth + interne Aufruf-Hilfen."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import Query
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
|
||||||
|
from fastapi_param_unwrap import unwrap_query_default
|
||||||
|
from main import app
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client() -> TestClient:
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unwrap_query_default_for_direct_route_calls() -> None:
|
||||||
|
assert unwrap_query_default(Query(default=None)) is None
|
||||||
|
assert unwrap_query_default("2026-01-01") == "2026-01-01"
|
||||||
|
assert unwrap_query_default(7) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_kpis_unauthenticated_401(client: TestClient) -> None:
|
||||||
|
r = client.get("/api/dashboard/kpis")
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_tenant_for_kpis() -> TenantContext:
|
||||||
|
return TenantContext(
|
||||||
|
profile_id=42,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=7,
|
||||||
|
club_ids=frozenset({7}),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@patch("routers.dashboard.list_training_units")
|
||||||
|
@patch("routers.dashboard.list_exercises_like_get")
|
||||||
|
def test_dashboard_kpis_200_when_inner_lists_mocked(
|
||||||
|
mock_list_ex: object,
|
||||||
|
mock_list_tu: object,
|
||||||
|
client: TestClient,
|
||||||
|
) -> None:
|
||||||
|
mock_list_ex.return_value = []
|
||||||
|
mock_list_tu.return_value = []
|
||||||
|
app.dependency_overrides[get_tenant_context] = _fake_tenant_for_kpis
|
||||||
|
try:
|
||||||
|
r = client.get("/api/dashboard/kpis")
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
data = r.json()
|
||||||
|
assert "year" in data
|
||||||
|
assert data["draft_count"] == 0
|
||||||
|
assert data["mine_count"] == 0
|
||||||
|
assert data["ytd_completed_count"] == 0
|
||||||
|
th = data["training_home"]
|
||||||
|
assert th["upcoming"] == []
|
||||||
|
assert th["planned_with_notes"] == []
|
||||||
|
assert th["review_pending"] == []
|
||||||
|
assert mock_list_ex.call_count == 2
|
||||||
|
assert mock_list_tu.call_count == 3
|
||||||
|
finally:
|
||||||
|
app.dependency_overrides.clear()
|
||||||
@@ -0,0 +1,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,75 @@
|
|||||||
|
"""
|
||||||
|
Geschützte Übungs-Mediendatei: Auth + Governance (kein anonymes /media/).
|
||||||
|
"""
|
||||||
|
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 auth import require_auth_flexible
|
||||||
|
from main import app
|
||||||
|
from tenant_context import TenantContext, get_tenant_context_flexible
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client() -> TestClient:
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _clear_overrides():
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(require_auth_flexible, None)
|
||||||
|
app.dependency_overrides.pop(get_tenant_context_flexible, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_exercise_media_file_unauthenticated_401(client: TestClient) -> None:
|
||||||
|
r = client.get("/api/exercises/1/media/2/file")
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_exercise_media_file_forbidden_when_not_visible(client: TestClient) -> None:
|
||||||
|
app.dependency_overrides[get_tenant_context_flexible] = lambda: TenantContext(
|
||||||
|
profile_id=22,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=None,
|
||||||
|
club_ids=frozenset(),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
mock_cm = MagicMock()
|
||||||
|
mock_conn = MagicMock()
|
||||||
|
mock_cm.__enter__.return_value = mock_conn
|
||||||
|
mock_cm.__exit__.return_value = False
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.return_value = {
|
||||||
|
"id": 3,
|
||||||
|
"visibility": "private",
|
||||||
|
"club_id": None,
|
||||||
|
"created_by": 99,
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
), patch("routers.exercises.library_content_visible_to_profile", return_value=False):
|
||||||
|
r = client.get("/api/exercises/3/media/2/file", headers={"X-Auth-Token": "t"})
|
||||||
|
assert r.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_maturity_model_requires_admin(client: TestClient) -> None:
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
def _user() -> dict:
|
||||||
|
return {"profile_id": 1, "role": "trainer"}
|
||||||
|
|
||||||
|
app.dependency_overrides[require_auth] = _user
|
||||||
|
try:
|
||||||
|
r = client.get("/api/maturity-models/1", headers={"X-Auth-Token": "x"})
|
||||||
|
assert r.status_code == 403
|
||||||
|
finally:
|
||||||
|
app.dependency_overrides.pop(require_auth, None)
|
||||||
@@ -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,131 @@
|
|||||||
|
"""
|
||||||
|
DELETE /api/exercises/{id}: Mandanten-/Rollenlogik und Verwendungsblock (409).
|
||||||
|
|
||||||
|
TestClient mit Overrides für Auth und TenantContext; DB via get_db/get_cursor gemockt.
|
||||||
|
"""
|
||||||
|
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 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 _mock_db_cm(mock_cur: MagicMock):
|
||||||
|
mock_conn = MagicMock()
|
||||||
|
mock_cm = MagicMock()
|
||||||
|
mock_cm.__enter__.return_value = mock_conn
|
||||||
|
mock_cm.__exit__.return_value = False
|
||||||
|
return mock_cm
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_trainer_private_own_ok(client: TestClient) -> None:
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.side_effect = [
|
||||||
|
{"id": 7, "created_by": 42, "visibility": "private", "club_id": None},
|
||||||
|
{"block_items": 0, "section_items": 0, "prog_edges": 0},
|
||||||
|
]
|
||||||
|
mock_cm = _mock_db_cm(mock_cur)
|
||||||
|
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
|
||||||
|
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||||
|
profile_id=42,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=5,
|
||||||
|
club_ids=frozenset({5}),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
):
|
||||||
|
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json().get("ok") is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_trainer_club_exercise_forbidden_without_club_admin(client: TestClient) -> None:
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.side_effect = [
|
||||||
|
{"id": 7, "created_by": 42, "visibility": "club", "club_id": 5},
|
||||||
|
]
|
||||||
|
mock_cm = _mock_db_cm(mock_cur)
|
||||||
|
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
|
||||||
|
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||||
|
profile_id=42,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=5,
|
||||||
|
club_ids=frozenset({5}),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
), patch("routers.exercises.has_club_role", return_value=False):
|
||||||
|
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
|
||||||
|
assert r.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_usage_returns_409(client: TestClient) -> None:
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.side_effect = [
|
||||||
|
{"id": 7, "created_by": 42, "visibility": "private", "club_id": None},
|
||||||
|
{"block_items": 1, "section_items": 2, "prog_edges": 3},
|
||||||
|
]
|
||||||
|
mock_cm = _mock_db_cm(mock_cur)
|
||||||
|
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
|
||||||
|
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||||
|
profile_id=42,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=None,
|
||||||
|
club_ids=frozenset(),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
):
|
||||||
|
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
|
||||||
|
assert r.status_code == 409
|
||||||
|
detail = r.json().get("detail", "")
|
||||||
|
assert "Übungsblöcken" in detail or "Trainingsplänen" in detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_official_forbidden_non_platform_admin(client: TestClient) -> None:
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.side_effect = [
|
||||||
|
{"id": 99, "created_by": 1, "visibility": "official", "club_id": None},
|
||||||
|
]
|
||||||
|
mock_cm = _mock_db_cm(mock_cur)
|
||||||
|
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
|
||||||
|
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||||
|
profile_id=42,
|
||||||
|
global_role="trainer",
|
||||||
|
effective_club_id=None,
|
||||||
|
club_ids=frozenset(),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
):
|
||||||
|
r = client.delete("/api/exercises/99", headers={"X-Auth-Token": "dummy"})
|
||||||
|
assert r.status_code == 403
|
||||||
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user