Compare commits
158
Commits
bce235b9f6
..
V0.9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3134160003 | ||
|
|
01be9ffcd4 | ||
|
|
b19940c997 | ||
|
|
30c1c259d2 | ||
|
|
24c70c5ea0 | ||
|
|
624c19dcba | ||
|
|
f54372d7b5 | ||
|
|
c46f5f99be | ||
|
|
58a38702b9 | ||
|
|
dbc9057601 | ||
|
|
59fb8a5527 | ||
|
|
6136813f60 | ||
|
|
a7cecca36f | ||
|
|
d82b805ffa | ||
|
|
bab9b178a4 | ||
|
|
c8c40474d1 | ||
|
|
5cf775c920 | ||
|
|
337f29401b | ||
|
|
311a106d93 | ||
|
|
979e328cef | ||
|
|
cc51b0f08f | ||
|
|
f035b5bb0b | ||
|
|
f745e5d082 | ||
|
|
b6de1f15ea | ||
|
|
3ff47779e0 | ||
|
|
d3055f6f2f | ||
|
|
f354bd9f77 | ||
|
|
01636b5baf | ||
|
|
3e4fa0dc39 | ||
|
|
8d85649cf8 | ||
|
|
3f0d02edab | ||
|
|
4fb77d6927 | ||
|
|
b8842cf98e | ||
|
|
f8a7247ccc | ||
|
|
d758de3852 | ||
|
|
c1d1c2d7e0 | ||
|
|
bebcf5af73 | ||
|
|
5b13a0a526 | ||
|
|
c921f0dd8f | ||
|
|
ceef6f09e2 | ||
|
|
cc4e621f95 | ||
|
|
d213746bd2 | ||
|
|
f9e6e61244 | ||
|
|
696cb09bf4 | ||
|
|
4f64cb105b | ||
|
|
a8667f4757 | ||
|
|
084ac38c2e | ||
|
|
1bc7ea95fb | ||
|
|
33fedd5ec6 | ||
|
|
3d321857ec | ||
|
|
b8453f3f07 | ||
|
|
0a1816e38b | ||
|
|
95f5b0b2d7 | ||
|
|
88fb60e244 | ||
|
|
da368222e0 | ||
|
|
e2964a077d | ||
|
|
631ba1cb43 | ||
|
|
8ac723eafe | ||
|
|
ece08ec1a1 | ||
|
|
7284c577d7 | ||
|
|
161d520329 | ||
|
|
9365125969 | ||
|
|
b752883392 | ||
|
|
c2d9eac151 | ||
|
|
c8a08f8a94 | ||
|
|
18fa4de055 | ||
|
|
fe703ca414 | ||
|
|
f9d518fb78 | ||
|
|
c6a7d668c5 | ||
|
|
ff8fd78a31 | ||
|
|
40a3b4b8e6 | ||
|
|
3bf0af001a | ||
|
|
3210796139 | ||
|
|
d04ebee1f6 | ||
|
|
b9d27b59b0 | ||
|
|
518918a6e5 | ||
|
|
cfd40889ac | ||
|
|
585ee8c90d | ||
|
|
8eec145393 | ||
|
|
db8af53652 | ||
|
|
1e1fd80fb7 | ||
|
|
b9ef0395c1 | ||
|
|
5096eec16b | ||
|
|
68923b0364 | ||
|
|
657f73d2c5 | ||
|
|
8b86021293 | ||
|
|
35a3f6e18d | ||
|
|
18a58cb5a5 | ||
|
|
14884e6e55 | ||
|
|
2007f3f659 | ||
|
|
d4b9db9520 | ||
|
|
00b22a756f | ||
|
|
56ea36ea25 | ||
|
|
9dbd3cbd5f | ||
|
|
9e759a28c6 | ||
|
|
c778d21b26 | ||
|
|
0c1fbab0ef | ||
|
|
14745b347d | ||
|
|
35b14fe1a6 | ||
|
|
caab9f2863 | ||
|
|
f03330bf77 | ||
|
|
61e3b3a6b1 | ||
|
|
347af0c36e | ||
|
|
a7d68c0646 | ||
|
|
dc310b38eb | ||
|
|
e0ecfe927f | ||
|
|
abee6171df | ||
|
|
5aee9c52fc | ||
|
|
870a7611dc | ||
|
|
0181575962 | ||
|
|
c919e02441 | ||
|
|
4b6fd49940 | ||
|
|
413a096432 | ||
|
|
f48b573a63 | ||
|
|
b661d0edb2 | ||
|
|
9afcd762d0 | ||
|
|
0f08e8df58 | ||
|
|
7d476268b8 | ||
|
|
c7bf7dcd9d | ||
|
|
e69aca51f6 | ||
|
|
0c044249d9 | ||
|
|
a34dc19f5d | ||
|
|
0748990328 | ||
|
|
e69de82028 | ||
|
|
7e8421bfde | ||
|
|
1923feb5bb | ||
|
|
d774d60a15 | ||
|
|
6dcbc8c610 | ||
|
|
86192df508 | ||
|
|
4080088d42 | ||
|
|
2bfe67879f | ||
|
|
354216cb4f | ||
|
|
69adf1fde0 | ||
|
|
c4fbabd8f6 | ||
|
|
7e21b44604 | ||
|
|
b4495e39c1 | ||
|
|
8f32a6df29 | ||
|
|
0971f35402 | ||
|
|
8c9c97bedb | ||
|
|
83ee300192 | ||
|
|
b1af59b134 | ||
|
|
6c87989863 | ||
|
|
44f224e5d1 | ||
|
|
88fc9d9ba5 | ||
|
|
eade9af2fe | ||
|
|
17f0513821 | ||
|
|
8328e7e0d3 | ||
|
|
b054c642a3 | ||
|
|
f5895b6637 | ||
|
|
ae6c089366 | ||
|
|
1b7a0405e9 | ||
|
|
9227b98431 | ||
|
|
362eb4145f | ||
|
|
390b0ecb73 | ||
|
|
07b1cd8209 | ||
|
|
7e7adfab54 | ||
|
|
fe86d763ad | ||
|
|
f4a86f9726 |
No files matched your search
@@ -1,31 +1,37 @@
|
||||
# Shinkan Jinkendo - Projekt-Status
|
||||
|
||||
**Stand:** 2026-04-27
|
||||
**Version (Code):** 0.7.9 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260427030`
|
||||
**Stand:** 2026-05-08
|
||||
**Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||
**Branch:** develop
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Aktueller Meilenstein:** Übungsvarianten Ende-zu-Ende (API, DB 030, Planung, UI) sowie Listen-Suche ohne Full-Page-Reload ✅
|
||||
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge), plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop mit Auto-Scroll, Vorschau-/Rückweg-UX). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
|
||||
|
||||
**Letzte dokumentierte Änderungen (April 2026):**
|
||||
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||
|
||||
- ✅ Migration **030**: `training_unit_exercises.exercise_variant_id` (FK zu `exercise_variants`, ON DELETE SET NULL).
|
||||
- ✅ **GET `/api/exercises?include_variants=true`** für Trainingsplanung und Übersichten.
|
||||
- ✅ Varianten-**CRUD** + **Reorder**; Validierung in der Trainingsplanung (Variante gehört zur Übung).
|
||||
- ✅ **Übungsliste**: Filter-Chips, Modal, `listFetching` statt Full-Page-Spinner, `<datalist>`-Titel aus Treffern.
|
||||
- ✅ **Medien-Upload**: rollenbasierte Limits (Standard 50 MB, Admin bis 1024 MB, Env-Vars).
|
||||
- ✅ **RichTextEditor**: Selection-Restore, Listen-Styling im Editor.
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
|
||||
|
||||
**Referenz:** Ausführliche technische Liste → [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md)
|
||||
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
|
||||
|
||||
**Nächste Schritte (Auszug):**
|
||||
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).
|
||||
|
||||
1. Prod-Deployment der Migrationen **020–030** und Smoke-Tests.
|
||||
2. Optional: Server-Autocomplete für Suche; Progressions-Serien als Blöcke (siehe Feature-Doc).
|
||||
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||
|
||||
---
|
||||
|
||||
**Nächste Schritte (Auszug — Planung/Rahmen):**
|
||||
|
||||
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
||||
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
|
||||
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
|
||||
|
||||
---
|
||||
|
||||
@@ -42,6 +48,9 @@
|
||||
| 023 | Skills Complete Import (69 Skills) | ✅ | 🔲 |
|
||||
| 028–029 | exercise_media / skills Stufen | ✅ | 🔲 |
|
||||
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
|
||||
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
|
||||
| **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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -66,6 +75,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
- [x] CRUD (Create, Read, Update, Delete)
|
||||
- [x] M:N Beziehungen (Focus Areas, Styles, Target Groups, Skills)
|
||||
- [x] **Varianten** (CRUD, Reorder, Voraussetzung) + Anzeige im Detail
|
||||
- [x] **Progressionsgraph zwischen Übungen** (Bibliotheks-Container, Kanten, Sequenz-Bulk, Varianten-Knoten — Zwischenstand, siehe TRAINING_FRAMEWORK_SPEC §4)
|
||||
- [x] Medien (Upload/Embed, rollenabhängige Größenlimits)
|
||||
- [x] Suche & Filter (Multi-Filter, Chips, Fokus beim Suchen)
|
||||
- [x] Exercise Blocks (Bausteine)
|
||||
@@ -73,8 +83,10 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
**Trainingsplanung:**
|
||||
|
||||
- [x] Training Units / Einbinden von Übungen
|
||||
- [x] Training Units / strukturierter Ablauf (Sektionen + Items)
|
||||
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
|
||||
- [x] **Trainingsrahmenprogramm Bibliothek** (Ziele, Slots, Kontext) + **Slot‑Blueprints** in `training_units` (036–037)
|
||||
- [x] **Materialisierung** aus Rahmen‑Slot (`POST …/training-units/from-framework-slot`; UI‑Anbindung optional)
|
||||
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
|
||||
|
||||
**MediaWiki Import:**
|
||||
@@ -91,6 +103,11 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
### 🔲 In Arbeit / Backlog
|
||||
|
||||
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (0.8.42 ff.)
|
||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
|
||||
- [x] **Medien:** Medienbibliothek `/media` (Filter, Tags, Copyright, Bulk-Lifecycle/PATCH, Lesemodus für eingeschränkte Rollen bei `official`)
|
||||
- [x] **Medien:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
|
||||
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
|
||||
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
||||
- [ ] Responsive Design / Dark Mode / PWA
|
||||
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
||||
@@ -121,7 +138,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
### Dev
|
||||
|
||||
Branch `develop`; Migrations bis mindestens **030** 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
|
||||
|
||||
@@ -133,15 +150,17 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
| Dokument | Pfad | Stand | Status |
|
||||
|----------|------|-------|--------|
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-04-27 | ✅ Neu |
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-08 | ✅ Aktualisiert (§12 Medien inkl. Inline 0.8.60–0.8.64) |
|
||||
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
|
||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-04-27 | ✅ Aktualisiert (030) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-04-27 | ✅ Referenz |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (v1.3) |
|
||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-27 | ✅ Aktualisiert |
|
||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-07 | ✅ Abschnitt Medien-Archiv |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
||||
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Limits) |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-04-27 | ✅ Diese Datei |
|
||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
|
||||
|
||||
---
|
||||
|
||||
@@ -152,4 +171,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-04-27
|
||||
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo - Fachliches Domänenmodell
|
||||
|
||||
**Version:** 0.4.0
|
||||
**Stand:** 2026-04-27 (Migration 023: Skills Complete Import)
|
||||
**Version:** 0.4.4
|
||||
**Stand:** 2026-05-08 (Medien-Archiv **`media_assets`** / Bibliothek **`/media`** im Ist; **Inline-Medien** im Fließtext umgesetzt — `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11)
|
||||
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||
|
||||
---
|
||||
@@ -458,6 +458,32 @@ skill_level_definitions (
|
||||
|
||||
**Umsetzung (Trainingsplanung):** Ein Eintrag in `training_unit_exercises` kann optional eine konkrete Varianten-ID (`exercise_variant_id`, Migration 030) tragen; Bindung wird gegen die gewählte Übung validiert. Varianten werden über die Übungs-API verwaltet (`technical/EXERCISES_API_SPEC.md`).
|
||||
|
||||
### Progressionsgraph zwischen Übungen (Zwischenstand, CURR‑002 Stufe 1)
|
||||
|
||||
**Abgrenzung:** Zusätzlich zur Varianten-Reihe **innerhalb** einer Übung gibt es optional einen **Bibliotheks-Progressionsgraphen**: gerichtete Kanten zwischen **Übungen** (Knoten optional auf konkrete **Varianten** eingegrenzt). Gemeinsamer Kontainer pro Graph (`exercise_progression_graphs`); Kanten mit Typ z. B. Nachfolger oder Schwester.
|
||||
|
||||
**Rolle:** **unterstützend** für Planung und spätere Rahmenprogramme — keine Pflicht, jeden Trainingsablauf als Graph zu modellieren (**CURR‑013**).
|
||||
|
||||
**Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4.
|
||||
|
||||
### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009)
|
||||
|
||||
**Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**).
|
||||
|
||||
**Bibliothek only (036):** Kein Kopf‑`plan_mode`/keine Kopf‑`group_id`; Zuordnung zu Gruppe und Datum erfolgt nur über **kopierte** Kalender‑`training_units` (Instanz).
|
||||
|
||||
**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**).
|
||||
|
||||
---
|
||||
|
||||
## 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)
|
||||
|
||||
@@ -5,8 +5,10 @@ Ausführliche fachliche Inhalte:
|
||||
| Dokument | Inhalt |
|
||||
|----------|--------|
|
||||
| [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 (§11.2), **Medien-Archiv** (Abschnitt 2026-05) |
|
||||
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **geplante Inline-Medien §11** |
|
||||
| [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan |
|
||||
|
||||
**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) §12, Repo-Root **`docs/HANDOVER.md`**.
|
||||
|
||||
`CLAUDE.md` (Repo-Root) verweist hierher als Einstieg.
|
||||
@@ -0,0 +1,225 @@
|
||||
# Konzept: Trainingsplanung über Einheiten hinweg, Kurspläne, Governance, Assessments
|
||||
|
||||
**Status:** Arbeitspapier (lebend)
|
||||
**Stand:** 2026-05-05 (Rahmen‑Bibliothek **036**, Slot‑Blueprint **037** / API `from-framework-slot`; CURR‑002 Stufe 1 Graph unverändert 032–034)
|
||||
**Zweck:** Erkenntnisse und **getroffene Entscheidungen** festhalten, um Spec- und Implementierungsdrift zu vermeiden.
|
||||
**Kanons:** Bei Widersprüchen mit produktiven Specs zuerst diese Datei mit dem Team abstimmen; technische Details ergänzen später in `technical/`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Kurz-Zielbild (Problem)
|
||||
|
||||
- **Heute:** Planung denkt stark pro **einer** Trainingseinheit (Struktur + Übungen).
|
||||
- **Gewünscht:**
|
||||
- **Trainingsrahmenprogramm** (über **mehrere** Session-Slots): **mehrere** **Entwicklungsziele** über denselben Zeitraum sowie **Zuordnung von Übungen** zu Sessions; unterstützt **manuelle** Verteilung (ohne Pflicht-Progressionsgraph) und optional **persistente Progressionsbäume** (v. a. Verwalter) — siehe CURR‑010, CURR‑011, CURR‑013.
|
||||
- **Mehrwöchige / periodische Planung** (z. B. Monat) mit **Entwicklungszielen** und Verteilung aufbauender Elemente über **mehrere Einheiten** – auch **ohne** vollständiges „Kursprogramm“-Produkt.
|
||||
- **Standard-Kurs-/Stufenpläne** (zeitlos, mehrschrittig) als Basis für konkrete Durchführung; Instanzen **editierbar ohne** Änderung der Vorlage.
|
||||
- **Governance** einheitlich über Domänen (Übungen, Verein, Trainingspläne, Kurspläne …), ohne spätere Modellbrüche.
|
||||
- **Nachvollziehbarkeit:** real durchgeführte Einheiten an Pläne/Vorlagen zurückführen; **Feedback** zur Verbesserung von Standardplänen.
|
||||
- **Assessments** als Spezialfall eines Plans (Tests, z. B. Gürtel), später ggf. Teilnehmerbezug und Erwartungsniveau.
|
||||
|
||||
---
|
||||
|
||||
## 2. Geführte Konzepterstellung (Arbeitsschritte)
|
||||
|
||||
**Konzept-Arbeit:** Ziele klären → Optionen → **Entscheidung** in §5 → Glossar §4 pflegen.
|
||||
|
||||
### 2.a Umsetzungs-Reihenfolge „Rahmenprogramm“ (product / binding laut CURR-001–002)
|
||||
|
||||
| Stufe | Inhalt | Status |
|
||||
|--------|--------|--------|
|
||||
| **1** | **Progressionsbezüge** zwischen Übungen **persistent speicherbar** (Progressionsbaum / -graph zwischen Übungseinheiten, nicht nur UI) | ✅ **Zwischenstand im Produkt** (Migrationen 032–034, UI/API); UX für **parallele gleichwertige Alternativ‑Pakete** noch kein Erstklass‑Fall — siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4 |
|
||||
| **2** | **Planungs-/Rahmenmodus:** Übungen auf **mehrere** Session-Slots verteilen; **mehrere Ziele**; speicherbare Rahmen-Vorlage (CURR‑002 (2) i. V. m. **CURR‑010–013**) | **in Arbeit**: Bibliotheks‑Backend + Slot‑Blueprint + Kopie‑API (**037**); **UI Kalender**/Bulk folgt (**CURR‑012**) |
|
||||
| **3** | **Konkrete Einheit:** aus Rahmen-/Verteilungsplan **Vorschläge** beim Ausarbeiten laden; Bezug zur Idee **„Warenkorb“** bei der Übungsplanung | folgt nach 2 |
|
||||
|
||||
### 2.b Übrige Konzept-Schritte (noch durchzuarbeiten)
|
||||
|
||||
| Schritt | Thema | Status |
|
||||
|--------|--------|--------|
|
||||
| **A** | Scope & Reihenfolge relativ zu Kursprogramm, Backlog-Themen | ✅ siehe §5 CURR-001–004 |
|
||||
| **B** | **Governance-Muster** (einheitliche Sichtbarkeit; Bibliothek vs. Instanz) | ✅ Leitplan §2.c; Entscheidungen §5 CURR-005–007 |
|
||||
| **C** | **Rahmenprogramm** — §2.d (**C1–C4** ✅ · **C5** Leitplan) | ✅ Kern i. V. m. **CURR‑009–013** |
|
||||
| **D** | **Kurs-/Stufenprogramm:** nach Rahmenprogramm; plantechnisch ähnlich | 📌 zeitlich nachgelagert (CURR-003) |
|
||||
| **E** | **Lineage & Feedback** (Einheit ↔ Vorlage/Rahmen; Issues zur Nachbesserung) | ➕ **teilweise:** `training_units.origin_framework_slot_id`; vollständiges Konzept/UX offen |
|
||||
| **F** | **Assessments** | 📌 Backlog (CURR-003) |
|
||||
| **G** | **Progressions-Automatik** (KI, komplexe Vorschläge) | 📌 Backlog (CURR-003) |
|
||||
|
||||
**Aktueller Fokus:** **Kalender-/Planungs‑UI** an **`POST /api/training-units/from-framework-slot`** und Visibility für geteilte Rahmen; weiteres Lineage (**Schritt E**) ergänzend zu **`origin_framework_slot_id`**.
|
||||
|
||||
---
|
||||
|
||||
### 2.c Schritt B – Governance-Muster (Leitplan)
|
||||
|
||||
#### B.1 Ziel
|
||||
|
||||
Ein **wiedererkennbares Muster** für alle **Bibliotheksobjekte** (Übung, Trainingsplan-Vorlage, Übungsblock, künftig Rahmen-/Kurs-Vorlage, Progressions-Paket …), damit **CURR-004** (spätere Rechte nach Rolle/Zugehörigkeit) **ohne Modellbruch** nachrüstbar ist.
|
||||
|
||||
#### B.2 Ist-Stand im Produkt (kurz, Stand Code-Review)
|
||||
|
||||
| Objekt | Relevante Felder / Muster |
|
||||
|--------|---------------------------|
|
||||
| `exercises`, `exercise_blocks` | `visibility` ∈ `private` \| `club` \| `official`, `club_id`, `created_by` — **Referenzmuster** |
|
||||
| `training_plan_templates` | `club_id`, `created_by`, **`visibility`** seit **035** (Backfill **`club`**); Referenz‑Muster an Übung angleichen (**CURR‑007** erledigt für dieses Feld) |
|
||||
| `training_framework_programs` | `visibility`, `club_id`, `created_by`; Kontext `focus_area_id`, `style_direction_id`; keine Kopf‑`group_id`; Slot‑Inhalt über **Blueprint‑`training_units`** (**036–037**) |
|
||||
| `training_units` | `group_id`, `created_by`, `plan_template_id` — **Instanz** oder **Blueprint** (`framework_slot_id`); Lineage‑Light **`origin_framework_slot_id`** |
|
||||
|
||||
#### B.3 Prinzipien (binding mit §5)
|
||||
|
||||
1. **Bibliothek vs. Instanz**
|
||||
- **Bibliothek:** zeitlose Objekte (Übung, Vorlage, Rahmen-Template, Graph-Definition …). Tragen **Sichtbarkeits-Metadaten** nach gemeinsamem Muster.
|
||||
- **Instanz:** z. B. `training_unit` am Termin; **inhaltliche** Bearbeitung **entkoppelt** von der Vorlage (**Kopie** der Struktur, nicht „Live-Link“ zur Überschreibung der Vorlage).
|
||||
- Zugriff auf Instanzen: primär über **Trainingsgruppe / Rolle** (Trainer, Co-Trainer); **nicht** zwingend über `visibility` der Vorlage dublett führen in Phase 1.
|
||||
|
||||
2. **Einheitlicher Governance-Kern für neue & nachzuziehende Bibliothekstypen**
|
||||
- Minimal: **`visibility`** (gleiche Semantik wie bei Übungen), **`club_id`** (optional, NULL = nicht vereinsgebunden / global nutzbar je nach Policy), **`created_by`**.
|
||||
- **Sparte (`division`):** optional später **`division_id`** oder M:N — **nicht** im MVP-Kern erzwingen, damit keine parallele „Rights-Welt“ pro Objekttyp entsteht.
|
||||
|
||||
3. **Policy vs. Speicherung**
|
||||
- DB-Felder beschreiben **„wem gehört es / welche Lesestufe“** intentionell; **durchsetzende** Filter in API/UI folgen schrittweise (CURR-004).
|
||||
- Vermeiden: Objekttypen mit völlig anderen Spaltennamen für dieselbe Idee (`owner` vs `created_by` ohne Konvention).
|
||||
|
||||
4. **Herkunft / Lineage (nur Metadaten)**
|
||||
- Wo sinnvoll: `plan_template_id`, später `framework_program_template_id`, optional `forked_from_*` für **Nachvollziehbarkeit** ohne Kopplung für Writes.
|
||||
- Detail Arbeitspaket **Schritt E**; nicht mit Governance-Kern vermischen.
|
||||
|
||||
5. **Progressionsgraph**
|
||||
- Als eigener Bibliotheks-**Kontainer** oder als **Annotion** an Übung(en): gleicher Governance-Kern; **Ausnahmen** nicht vorwegnahmen ohne technische Spec (§6 offene Fragen).
|
||||
|
||||
#### B.4 Bewusste Nicht-Ziele in diesem Schritt
|
||||
|
||||
- Keine endgültige **Matrix** „Welche Rolle sieht welches `official`“.
|
||||
- Keine Pflicht-Anbindung Sportler/Lehrender außerhalb bestehender Gruppenmitgliedschaft.
|
||||
|
||||
---
|
||||
|
||||
### 2.d Schritt C – Trainingsrahmenprogramm (Ausarbeitung · Status **Kern geklärt**)
|
||||
|
||||
#### Checkliste — Abgleich Produktfeedback 2026‑04‑29
|
||||
|
||||
| Check | Ergebnis | Verweis |
|
||||
|-------|----------|---------|
|
||||
| **C1** | ✅ **Eigene Rahmen-Entität** (C1a) — nicht die Einheitenvorlage überladen | **CURR‑009** |
|
||||
| **C2** | ✅ Slots erlauben **beliebige Übungen** über Trainings-/Slots zu verteilen; **persistenter Progressionsgraph** ist **unterstützend**, **Pflicht‑Pflege** im Graph gilt **nicht** (Admin‑Aufwand; v. a. global) | **CURR‑010**, **CURR‑013** |
|
||||
| **C3** | ✅ Über denselben Planungszeitraum **mehrere** gleichzeitige **Entwicklungsziele** (nicht nur ein Sammelfeld) | **CURR‑011** |
|
||||
| **C4** | ✅ **Zwei Nutzungsbilder**, kein „entweder C4a oder C4b global“ — siehe Ausführungen unten zu **Konkret** vs. **Bibliothek** | **CURR‑012** |
|
||||
| **C5** | ✅ `training_plan_template` bleibt **eine‑Einheit‑Mikrovorlage**; Rahmen adressiert **n** Sessions; pro Slot weiterhin möglich: **optional** `training_plan_template_id` (Technical Spec entscheidet MVP‑Pflicht) | Glossar |
|
||||
|
||||
---
|
||||
|
||||
#### C4 verständlich: **„Materialisierung“** = zwei echte Situationen
|
||||
|
||||
| Nutzungsbild | Kontext | Gruppe / Datum | Typische Persistenz‑Schicht |
|
||||
|--------------|---------|----------------|----------------------------|
|
||||
| **A – Kurzfrist‑ / Basisplanung („nächste Wochen“)** | Konkret für **eine Trainingsgruppe** geplant | **Immer:** Gruppe + Termin(e) wie heute beim Training | Existierende oder neu angelegte **`training_units`**; Rahmen fungiert als **Planhilfe**/Vorlage **über mehrere dieser Einheiten** |
|
||||
| **B – Kursprogramm-/Lehrplan‑Bibliothek** | Übergeordnete **Struktur** ohne laufenden Kurs | **In der Bibliotheksvorlage selbst oft:** keine Gruppe/Zeit | Rahmen-/Kurs‑Vorlage **zeit‑ und gruppenlos** gespeichert; **Übertrag** (`Instanziierung`) erst bei „wir machen einen Kurs daraus“: dann Wahl **Gruppe + Zeitraum** → Anlegen oder Befüllen von **`training_units`** |
|
||||
|
||||
**Klartext zur früheren Frage „C4a vs. C4b“:** Bei **Modus A** passen **automatisches Anlegen n Einheiten** (früheres C4a) **oder** Zuordnung zu **bereits geplanten** Einheiten (C4b) — je nach Produkt/UI. Bei **Modus B** existieren erst bei der Übernahme überhaupt Gruppe/Zeiten; die Bibliotheksvorlage bleibt **neutral**.
|
||||
|
||||
**Stand Code 036–037:** Am Rahmenkopf gibt es **keine** **`plan_mode`/`group_id`** mehr — die Bibliothek ist immer „Modus B“; konkrete Gruppe/Zeit entstehen **nur** in **`training_units`** (Kalender‑Zeilen oder Übernahme‑API **`from-framework-slot`**).
|
||||
|
||||
---
|
||||
|
||||
#### C2 (Klärung fürs Team)
|
||||
|
||||
„**C2**“ im Entwurf bezog sich auf „**wie** weiß ich pro Slot welche Übungen (nur Progression oder auch Mikro‑Vorlage)?“ — **aktueller Beschluss:**
|
||||
Pro Slot: **Zuordnung von Übung(en)** als **Teil des vollständigen Ablaufs** (wie geplante Einheit: **Sektionen und Items**, **037**) ist **tragend**; **Progressionsgraph** liefert **Vorschläge / Pakete**, wenn Admins sie pflegen — **Trainer** können **ohne** Graph planen.
|
||||
|
||||
---
|
||||
|
||||
#### C1/Erinnerung Checkbox (historisch)
|
||||
|
||||
- **`[x] C1a`** eigene Rahmen‑Entität bestätigt (Chat 2026‑04‑29).
|
||||
|
||||
---
|
||||
|
||||
*Konkretisierung technischer Felder (ein Objekt zwei Modi vs. zwei Typen) → **Technical Spec**; keine neuen Contradicts zu CURR‑001 ohne expliziten Beschluss.*
|
||||
|
||||
---
|
||||
|
||||
## 3. Richtungen aus Diskussion (nicht-binding, wenn nicht in §5)
|
||||
|
||||
| Thema | Richtung |
|
||||
|--------|----------|
|
||||
| Assessments als Plantyp | **Spezielle Form eines Trainingsplans**; Test-Übungen; später **Sportlerbezug**/Erwartungsniveau (Gürtel) — aktuell **Backlog**, siehe CURR-003. |
|
||||
| Bibliothek vs. Durchführung | Konkrete Pläne/Einheiten editierbar **ohne** Änderung am Standard-/Rahmen-Template (**Kopien / Instanzen**). |
|
||||
|
||||
*Scope-Reihenfolge und Governance-Startpunkt sind ab 2026-04-29 in §5 festgehalten (CURR-001 bis CURR-004).*
|
||||
|
||||
---
|
||||
|
||||
## 4. Glossar (wird ergänzt)
|
||||
|
||||
| Begriff | Bedeutung (vorläufig) |
|
||||
|---------|------------------------|
|
||||
| **Bibliotheksobjekt** | Zeitlose Vorlage (Übung, Trainingsplan-Vorlage, Kursrahmen, später Assessment-Vorlage …) |
|
||||
| **Governance-Kern** | Einheitliches Minimalset an Metadaten für Bibliotheksobjekte: v. a. `visibility`, `club_id`, `created_by` (siehe §2.c) |
|
||||
| **Instanz (Training)** | `training_unit` o. Ä.; Zugriff über Gruppe/Rolle; Inhalt als **Kopie** aus Vorlagen, nicht schreibend an Vorlage gekoppelt |
|
||||
| **Trainingsrahmenprogramm** | Über **mehrere Session-Slots**: **mehrere gleichzeitige Entwicklungsziele** und **Zuordnung von Übungen** zu Slots/Einheiten; **manuelle** Zuordnung + optional **Progression** (**CURR‑010**, **CURR‑011**, **CURR‑013**) |
|
||||
| **Progressionsbaum / -graph** | Optionale gerichtete Beziehungen **zwischen Übungen** zur **Unterstützung** beim Planen (**CURR‑010** — **kein Pflicht‑Pflegeschritt für jede Zuordnung**); v. a. für globale Pflege |
|
||||
| **Rahmen-Vorlage** („Framework“) | Bibliothekskontainer mit **ordered Slots**, **zeitlos möglich** (Modus B) oder im Konkretkontext an Gruppe geknüpfte Planung (**CURR‑012**); eigene Entität (**CURR‑009**) |
|
||||
| **Slot** | Position in der Reihenfolge eines Rahmens; trägt **Übungszuweisungen** („Stückliste“), optional Hinweise/Text; Datum optional bis Materialisierung |
|
||||
| **Materialisierung / Instanziierung** | Überführung aus (ggf. zeit‑/gruppenloser) **Rahmen-Bibliothek** in konkrete **`training_units`** mit Gruppe/Zeitraum — **CURR‑012 Modus B**. Modus A bleibt nahe bestehender Einheiten-Planung |
|
||||
| **Konkret-Planung (Modus A)** | Mehr‑Wochen für **bekannte** Trainingsgruppe + Terminen — **`training_units`** |
|
||||
| **Bibliotheks-Rahmen (Modus B)** | Strukturierte Vorlage ohne Gruppe/Uhrzeit („Kursprogramm“‑Wurzel bis zum Import in einen Kurs) |
|
||||
| **Kursprogramm** | Wie Curriculum-/Stufen-Standard; **planerisch nachgelagert** an Rahmenprogramm (CURR-003) |
|
||||
|
||||
---
|
||||
|
||||
## 5. Entscheidungsprotokoll (binding)
|
||||
|
||||
| ID | Datum | Entscheidung | Begründung / Kontext |
|
||||
|----|--------|---------------|---------------------|
|
||||
| **CURR-013** | 2026-04-29 | Präzisierung zu **CURR‑002 (1)+(2)**: **Persistenter Progressionsgraph** ist **unterstützend**, **nicht** die alleinige Quelle für Slot‑geplante Übungen. Der Planungsmodus **muss beliebige Übungen** auf Slots verteilen **ohne** Pflicht zur Graph‑Pflege im Alltag. Reichhaltiges Pflegen von Progressionsbezügen v. a. durch **globale Verwalter** erwünscht, nicht verpflichtend pro Übungszuordnung. | Chat C2 |
|
||||
| **CURR-012** | 2026-04-29 | **Zwei Nutzungsbilder:** **Modus A (Konkret)** — Mehr‑Wochenplan für **bekannte Trainingsgruppe + Termine** → bestehende/neue **`training_units`**; Rahmen als Planhilfe über mehrere Einheiten. **Modus B (Bibliothek)** — **Kurs-/Stufen‑Struktur ohne** Gruppe/Uhrzeit bis zur **Übernahme**; dann Zuordnung von Gruppe+Zeitraum und **Instanziierung** in **`training_units`**. Bulk‑Anlegen (**C4a**) und Verknüpfen existierender (**C4b**) sind **Modus‑A‑Alternativen**. | Chat C4 |
|
||||
| **CURR-011** | 2026-04-29 | **Mehrere parallele Entwicklungsziele** im selben Planungszeitraum → Datenmodell: **Zielliste mit ≥1 Einträgen** auf Rahmen‑Ebene (Details Technical Spec). **Nicht** nur ein einziges Sammelziel‑Feld. | Chat C3 |
|
||||
| **CURR-010** | 2026-04-29 | **Slot‑Inhalt:** tragend **direkte Zuordnung beliebiger Übungen** („Stückliste“); Option **Graph** für Vorschläge/Anreicherung. **`training_plan_template_id` pro Slot** weiterhin **optional** (MVP offen). | Chat C2 |
|
||||
| **CURR-009** | 2026-04-29 | **C1a:** **Neue eigene Bibliotheks‑Entität** für Mehr‑Slot‑Rahmen (**Framework**/`training_framework_*`-Arbeitscode); **`training_plan_template`** bleibt **eine Einheit**‑Mikrovorlage (**C5**). | Chat C1 |
|
||||
| **CURR-008** | 2026-04-29 | **Migration / Backfill (Early-Installation):** Migrationen betreffen aktuell nur **frühe Systeme ohne weitere Nutzer**. Vereins‑Zuordnung für Bestands-/Default‑Zeilen erfolgt beim Backfill mit dem **Standard‑Verein der Installation** (konkret: Club‑ID bzw. Konvention im Migrate‑Skript dokumentieren — z. B. erster Verein oder `DEFAULT_CLUB_ID` in Env). **`visibility`**-Default beim Hinzufügen der Spalte: **`club`**, wenn fachlich alles diesem Vereinskontext zugeordnet wird; anderenfalls bei Multi‑Tenant eigene Migrate‑Anweisung. | Nutzerfestlegung; pragmatisches Backfill ohne Mehr‑Mandanten‑Heuristik; §6 entsprechend vereinfacht. |
|
||||
| **CURR-007** | 2026-04-29 | **`training_plan_templates`** weichen aktuell vom Übungs-Muster ab (**kein** `visibility`). **Festlegung:** Bei der nächsten sinnvollen Migration auf den **gemeinsamen Governance-Kern** angleichen (**`visibility`** zusätzlich zu `club_id` / `created_by`), Semantik **analog zu Übungen** im Vereinskontext; von dieser Linie nur abweichen, wenn ausdrücklich anders dokumentiert. | Bekannte Schulden bis Migration vermeiden; neue Objekttypen sollen CURR-005 folgen; Zuordnung/Backfill **CURR‑008**. |
|
||||
| **CURR-006** | 2026-04-29 | **Instanz-Ebene (`training_unit` u. Ä.):** In der Rahmenprogramm-Phase **keine** neue parallele `visibility`-Schicht auf der Einheit; **Zugriff** über **`group_id`** und bestehende Trainer-/Mitgliedschaftslogik. **Lineage** zu Vorlagen/Rahmen nur als **optionale Metadaten-FKs** (`plan_template_id`, spätere Erweiterungen), ohne dass Schreiben in der Einheit die Vorlage ändert. | CURR-004-kompatibel: API-Policy später ergänzbar ohne Instanz-Umbau. |
|
||||
| **CURR-005** | 2026-04-29 | **Governance-Kern für Bibliotheksobjekte** (Übung, neue/alte Vorlagen, künftig Rahmen-/Kurs-/Progressions-Container): **`visibility`** im Sinne von `exercises` (`private` \| `club` \| `official`), **`club_id`** optional (NULL wenn nicht vereinsspezifisch), **`created_by`**. Sparte später optional **`division_id`** oder Verknüpfungstabelle — **nicht** Blocker für ersten Progressions-/Rahmen-Entwurf. | Einheitliche Semantik; Altabweichungen gezielt nachziehen (CURR-007). |
|
||||
| **CURR-004** | 2026-04-29 | **Sichtbarkeit:** Aktuell **globale Nutzungs-/Planungssicht** für alle; Architektur und Datenmodell aber **von Anfang an** so gestalten, dass **spätere** Einschränkungen nach Rollen und Zugehörigkeiten (Verein, Gruppe, Sparte …) ohne Bruch eingeführt werden können. | Vorbereitung einheitlicher Governance; siehe CURR-005/006 für Konkretisierung. |
|
||||
| **CURR-003** | 2026-04-29 | **Nachgelagert / explizites Backlog (nicht Phase Rahmenprogramm):** **Kursprogramm** kommt nach dem Rahmenprogramm (planerisch ähnlich); **Assessments**, **Sportlerakte**, **KI-Optimierungen** ebenfalls zurückgestellt bis Rahmenkern steht. | Priorität liegt auf Persistenz Progression → Multi-Einheiten-Planung → Einheitenvorschläge. |
|
||||
| **CURR-002** | 2026-04-29 | **Umsetzungsreihenfolge Rahmenprogramm:** **(1)** Progressionsbezüge **zwischen Übungen** müssen als **persistierter Graph/Baum** modellierbar sein. **(2)** **Planungsmodus**, der **Übungen** (u. a. aus Progression, **auch manuell**, **CURR‑010**) **auf mehrere Trainingseinheiten verteilt**, **mehrere Ziele** (**CURR‑011**) enthält und als **speicherbares Rahmen‑Template** dient. **(3)** **Warenkorb**-Idee beim Ausarbeiten einer **einzelnen** Einheit. | Reihenfolge vom Datenkern zur UX; Zuordnung/Graph **CURR‑013** |
|
||||
| **CURR-001** | 2026-04-29 | Vor dem separaten Produkt **„Kursprogramm“** wird das **„Trainingsrahmenprogramm“** (Ziele + Progression über mehrere Einheiten) angegangen — **nicht** umgekehrt. | Kursprogramm baut auf derselben Planungslogik auf; erst gemeinsamen Kern liefern. |
|
||||
|
||||
*Format:* Neue Zeile **oben** einfügen (neueste zuerst).
|
||||
|
||||
---
|
||||
|
||||
## 6. Offene Fragen (Backlog)
|
||||
|
||||
- **Minimal-UI** Rahmenprogramm vs. bestehende Kalender/Liste `training_units`?
|
||||
- ~~Governance Migrate Default~~ → **CURR‑008**
|
||||
- ~~Slots / C4 generisch~~ → **CURR‑012** (Modi A/B)
|
||||
- ~~Relation zwei Vorlagenfamilien~~ → **CURR‑009** (**Rahmen** neu, **Einheit** bleibt `training_plan_template`)
|
||||
- **Technical:** ~~gleiche DB‑Entität mit `plan_mode` (**A \| B**) vs. **konsequente Teilung** zweier Objekttypen?~~ → **Festgelegt:** eine Entität **`training_framework_programs`** + **`plan_mode`**; siehe **`technical/TRAINING_FRAMEWORK_SPEC.md` §2.0**.
|
||||
- **Progressionsgraph:** Kantentypen (nächste Übung vs. **Variante** vs. Level innerhalb gleicher Übung); optional **Skills**-Anbindung
|
||||
|
||||
---
|
||||
|
||||
## 7. Produkt-Backlog (explizit, nicht aktuelle Phase)
|
||||
|
||||
Siehe **CURR-003:** Kurs-/Stufenprogramm (nach Rahmenkern), Assessments (Plantyp/Testübungen/Sportler), Sportlerakte, KI-/optimierungsunterstützte Planung.
|
||||
|
||||
---
|
||||
|
||||
## 8. Nächste Aktion (für dich / Team)
|
||||
|
||||
1. ~~**Schritt C**~~ · siehe §2.d · **CURR‑009 bis CURR‑013**
|
||||
2. ~~Progressionsgraph Stufe 1~~ ✅ siehe **`technical/TRAINING_FRAMEWORK_SPEC.md`** §3–§4 · **Jetzt:** **`TRAINING_FRAMEWORK_SPEC.md`** §2 (Checkliste) mit **DDL-/API-Abschnitt Rahmen** ergänzen (**CURR‑002 (2)**); Modus A/B siehe Funktionskonzept §6
|
||||
3. **Migrate** weiter **CURR‑007 / CURR‑008** (ideal parallel oder vor erster Rahmen‑Migration mit neuem Bibliothekstyp)
|
||||
4. Konzeptpaket optional **Schritt E** Lineage vor Implementierung Großrelease
|
||||
|
||||
---
|
||||
|
||||
## 9. Changelog dieser Datei
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|-----------|
|
||||
| 2026-04-30 | §8 Punkt 2 angepasst (Graph ✅; nächster Fokus Rahmen‑Spec **CURR‑002 (2)**). |
|
||||
| 2026-04-28 | Technische Ausarbeitung gebündelt: neue Datei **`technical/TRAINING_FRAMEWORK_SPEC.md`** (Stub); Verweis §8. |
|
||||
| 2026-04-29 | **CURR‑009–013**, **CURR‑002** präzisiert; Glossar Modi A/B Slot; §2.d C geklärt; §6‑Backlog gekürzt. |
|
||||
| 2026-04-29 | CURR‑008 (Migration Standard‑Verein); **§2.d Schritt C** Checkpoints C1–C5; Glossar/§6 angepasst. |
|
||||
| 2026-04-29 | CURR-001–004; Umsetzungsreihenfolge §2.a; Glossar Rahmenprogramm/Progressionsgraph; Scope-Backlog. |
|
||||
| 2026-04-28 | Erstanlage aus Konzept-Arbeitsphase Chat; Schritttabelle und Protokollstruktur. |
|
||||
@@ -1,9 +1,9 @@
|
||||
# Gelieferte Features & technische Basis (April 2026)
|
||||
# Gelieferte Features & technische Basis (Q2 2026)
|
||||
|
||||
**Stand:** 2026-04-27
|
||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.7.9**, **DB_SCHEMA_VERSION 20260427030**
|
||||
**Stand:** 2026-05-08
|
||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.64**, **DB_SCHEMA_VERSION** siehe dort
|
||||
|
||||
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. 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/`.
|
||||
|
||||
---
|
||||
|
||||
@@ -11,20 +11,32 @@ Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren**
|
||||
|
||||
| Migration | Inhalt |
|
||||
|-----------|--------|
|
||||
| **032–034** | **Progressionsgraph Übung→Übung:** Container `exercise_progression_graphs`, Kanten `exercise_progression_edges`; **`notes`** (033); optionale Varianten-Endpunkte + Constraints (034) |
|
||||
| **028** | `exercise_media` erweitert (Embed/Metadaten), `exercise_skills` Level-Felder (VARCHAR); Medien-API |
|
||||
| **029** | Kanonische Fähigkeitsstufen (basis–optimierung), `model_levels`-Namen |
|
||||
| **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL |
|
||||
| **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** |
|
||||
| **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` |
|
||||
| **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Backend – Übungen (`routers/exercises.py`)
|
||||
## 2. Backend – Progressionsgraphen (`routers/exercise_progression_graphs.py`)
|
||||
|
||||
### 2.1 Liste & Suche
|
||||
- REST unter **`/api/exercise-progression-graphs`** inkl. Kanten-CRUD, **`POST …/edges/sequence`** (Reihe auf einmal), **`POST …/edges/delete-batch`**.
|
||||
- AuthZ wie Trainingsvorlagen: Admin/Superadmin oder Graph‑Ersteller; Anlegen mit Trainings-/Planungsrolle (`_has_planning_role`).
|
||||
- Listenresponses mit Übungstiteln und Variantennamen (JOIN).
|
||||
|
||||
---
|
||||
|
||||
## 3. Backend – Übungen (`routers/exercises.py`)
|
||||
|
||||
### 3.1 Liste & Suche
|
||||
|
||||
- `GET /api/exercises` mit Filtern u. a.: Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeiten, **Skill-Stufe min/max**, `visibility_any`, `status_any`, `search`, **`ai_search`** (Platzhalter, derzeit gleiche Volltextlogik wie `search`).
|
||||
- Optional: **`include_variants=true`** — liefert pro Übung ein kompaktes **`variants`**-JSON (id, variant_name, sequence_order) für Planung/UI.
|
||||
|
||||
### 2.2 Übungsvarianten (CRUD)
|
||||
### 3.2 Übungsvarianten (CRUD)
|
||||
|
||||
Implementiert gemäß **`EXERCISES_API_SPEC.md`** (Varianten-Abschnitt):
|
||||
|
||||
@@ -35,7 +47,7 @@ Implementiert gemäß **`EXERCISES_API_SPEC.md`** (Varianten-Abschnitt):
|
||||
|
||||
Sortierung der Varianten im Detail: **`sequence_order`**, dann **`progression_level`**, dann **`id`**.
|
||||
|
||||
### 2.3 Medien-Upload – Größenlimits
|
||||
### 3.3 Medien-Upload – Größenlimits
|
||||
|
||||
- Standard: **50 MB** pro Datei (`EXERCISE_MEDIA_MAX_UPLOAD_MB`, Default 50).
|
||||
- **`admin`** / **`superadmin`**: **1024 MB** Default (`EXERCISE_MEDIA_ADMIN_MAX_UPLOAD_MB`), nie unter dem Nutzer-Limit (in MB verglichen).
|
||||
@@ -44,16 +56,18 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
|
||||
---
|
||||
|
||||
## 3. Backend – Trainingsplanung (`routers/training_planning.py`)
|
||||
## 4. Backend – Trainingsplanung (`routers/training_planning.py`)
|
||||
|
||||
- `training_unit_exercises`: Schreiben/Lesen von **`exercise_variant_id`**.
|
||||
- Validierung: Variante muss zur gewählten **`exercise_id`** gehören.
|
||||
- JOIN liefert u. a. **`exercise_variant_name`** beim Lesen einer Einheit.
|
||||
- Strukturierte Einheiten: **`training_unit_sections`** + **`training_unit_section_items`** (Migration **031**) — Hauptpfad beim Lesen/Schreiben von Einheiten.
|
||||
- **`training_unit_exercises`:** Legacy-/Nebenpfad; weiterhin **`exercise_variant_id`** (Migration **030**) mit Validierung gegen die gewählte **`exercise_id`**; JOINs liefern u. a. **`exercise_variant_name`**.
|
||||
- **Blueprint‑Zeilen (`framework_slot_id` gesetzt):** **`GET /api/training-units`** listet diese **nicht**; **`PUT`** mit eingeschränkten Regeln (**kein** `plan_template_id` / kein Reset aus Vorlage über diesen Kopf wie bei Kalender‑Einheit).
|
||||
- Übernahme aus Rahmen: **`POST /api/training-units/from-framework-slot`** ({ `framework_slot_id`, `group_id`, `planned_date` }) — tiefe Kopie inkl. Sektionen/Items; **`origin_framework_slot_id`** setzt Lineage‑Light.
|
||||
|
||||
---
|
||||
|
||||
## 4. Frontend – Übungsliste (`ExercisesListPage.jsx`)
|
||||
## 5. Frontend – Übungsliste (`ExercisesListPage.jsx`)
|
||||
|
||||
- Tabs **Liste** · **Progressionsgraphen** (`ExerciseProgressionGraphPanel`): Graphen anlegen/bearbeiten, Kanten inkl. Sequenz-Bulk und Tabellenansicht.
|
||||
- **Filter-Modal** (Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeit + Stufen von/bis, Sichtbarkeit, Status).
|
||||
- **Filter-Chips** unter der Suchleiste; Klick entfernt einen Filter; Badge am Filter-Button = Anzahl Chips.
|
||||
- **Kein Vollbild-Spinner** bei jeder Suche: nur noch **`listFetching`** — Suchfelder bleiben im DOM (**Fokus/Cursor** bleiben erhalten); Liste zeigt optional „Aktualisiere Treffer…“.
|
||||
@@ -62,29 +76,30 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
|
||||
---
|
||||
|
||||
## 5. 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.
|
||||
- **Medien** wie zuvor (Formularteil).
|
||||
- **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
|
||||
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
|
||||
|
||||
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
|
||||
|
||||
---
|
||||
|
||||
## 6. Frontend – Übung Detail (`ExerciseDetailPage.jsx`)
|
||||
## 7. Frontend – Übung Detail (`ExerciseDetailPage.jsx`)
|
||||
|
||||
- Varianten-Abschnitt mit **Meta** (Dauer, Schwierigkeit, Material, Progressionsstufe) wo vorhanden.
|
||||
|
||||
---
|
||||
|
||||
## 7. Frontend – Trainingsplanung (`TrainingPlanningPage.jsx`)
|
||||
## 8. Frontend – Trainingsplanung (`TrainingPlanningPage.jsx`)
|
||||
|
||||
- `listExercises({ include_variants: true })`.
|
||||
- Pro Zeile: Übung + **Variante** (optional), Dauer, Reihenfolge.
|
||||
|
||||
---
|
||||
|
||||
## 8. Rich-Text (`RichTextEditor.jsx` + CSS)
|
||||
## 9. Rich-Text (`RichTextEditor.jsx` + CSS)
|
||||
|
||||
- **Selection Save/Restore** vor Toolbar-Klicks (`insertUnorderedList` / `insertOrderedList` zuverlässiger bei Mehrzeilen-Markierung).
|
||||
- **`styleWithCSS` false** vor Formatbefehlen.
|
||||
@@ -92,26 +107,67 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
|
||||
---
|
||||
|
||||
## 9. Admin – Matrix / Reifegrad (Kontext)
|
||||
## 10. Admin – Matrix / Reifegrad (Kontext)
|
||||
|
||||
- Bereits dokumentiert in **`CHANGELOG`** / Module **`maturity_models`**: Matrix-Stack-Bundle Export/Import, Kontext-Bindings — siehe `version.py` und Admin-UI-Pfade.
|
||||
|
||||
---
|
||||
|
||||
## 10. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
## 11. Trainingsrahmen: Bibliothek + Slot‑Blueprint (DB **036–037**)
|
||||
|
||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
||||
- **036:** `training_framework_programs` nur Bibliothek — `focus_area_id`, `style_direction_id`, M:N `training_framework_program_training_types` / `_target_groups`; Entfall `plan_mode`, `group_id`; Slot‑Verknüpfungen zu Kalender‑Einheiten geleert.
|
||||
- **037:** Pro Slot genau eine **`training_units`**‑Zeile mit **`framework_slot_id`**; Ablauf über **`training_unit_sections`** / **`training_unit_section_items`** (wie Planung); Legacy **`training_framework_slot_exercises`** Datenmigration + **`DROP` TABLE**; geplante Kopien können **`origin_framework_slot_id`** tragen.
|
||||
- **Router `training_framework_programs.py`:** CRUD **`/api/training-framework-programs`**, Slots im Speichern mit neuen Blueprint‑`training_units`, Hydration **`sections`/`exercises`/`blueprint_training_unit_id`**; siehe **`TRAINING_FRAMEWORK_SPEC.md`** §2.3.
|
||||
- **Frontend:** **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** (`api.js`).
|
||||
- **Doku:** **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2; **`technical/DATABASE_SCHEMA.md`**; **`functional/DOMAIN_MODEL.md`** (Trainingsrahmen‑Abschnitt).
|
||||
|
||||
---
|
||||
|
||||
## 11. Verweise
|
||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
||||
|
||||
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
||||
|
||||
### 12.1 Datenbank & Router
|
||||
|
||||
- **`media_assets`**, **`platform_media_storage`**, **`exercise_media.media_asset_id`** (Dedupe `sha256` + Sichtbarkeit + `club_id` je nach Policy).
|
||||
- Router **`media_assets.py`**: Listen, PATCH, Lifecycle, Dateiauslieferung, Bulk; Integration in **`exercises.py`** (Upload, `from-asset`, Promotion/Copyright-Regeln bei `official` / Vereinsübungen).
|
||||
|
||||
### 12.2 Funktional (Ist)
|
||||
|
||||
- Zentrale **Medienbibliothek** Frontend **`/media`**: Filter (Lifecycle, Medientyp, Verein für Admins), Suche, Tags, Copyright bearbeiten (rollengerecht), Kacheln/Liste, Nutzungs-Hinweise (Übungen/Planung wo implementiert).
|
||||
- **Papierkorb** mehrstufig (`trash_soft` / `trash_hidden`), Recovery, Superadmin-Purge; strukturierte Fehlercodes bei Governance (u. a. Übung **`CLUB_MEDIA_*`**).
|
||||
- **Speicher:** Pfadkonvention **`library/{vereinssegment}/…`** mit Medienkind-Unterordnern; Umzug bei Sichtbarkeits-/Vereinsänderung; effektives Wurzelverzeichnis `MEDIA_ROOT` + Superadmin-`local_relative_root`.
|
||||
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
|
||||
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
|
||||
|
||||
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
|
||||
|
||||
- Platzhalter-Syntax: `{{exerciseMedia:id}}` (normalisiert auf `data-shinkan-exercise-media`), Validierung gegen `exercise_media` der aktuellen Übung.
|
||||
- Zentraler Anzeigepfad über `ExerciseRichTextBlock` inkl. Sanitize und Lifecycle-Hinweisen.
|
||||
- RTE-Workflow: Modal „Medien im Text“ (Mediathek + Upload), separates „Embed im Text“-Modal, Größenwahl (`small|medium|full`) und sprechende Platzhalter-Captions.
|
||||
- Bearbeiten: kompakte Medien-Kacheln + Drag&Drop in Textfelder; Auto-Scroll beim Drag aktiv.
|
||||
- UX-Schutz: Warnung bei Wechsel „Ansehen“ mit ungespeicherten Änderungen; Detailseite bietet Rückweg zur Bearbeitung.
|
||||
|
||||
---
|
||||
|
||||
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
|
||||
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
||||
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
|
||||
|
||||
---
|
||||
|
||||
## 14. Verweise
|
||||
|
||||
| Thema | Dokument |
|
||||
|--------|----------|
|
||||
| Rahmenprogramm / Progressionsgraph | `technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
||||
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||
| Upload formal | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| 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)
|
||||
|
||||
**Version:** 0.4.0
|
||||
**Stand:** 2026-04-27
|
||||
**Aktuell deployed:** Migration 023 (Skills Complete Import)
|
||||
**Version:** 0.5.3
|
||||
**Stand:** 2026-05-07
|
||||
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints) und für Medien-Archiv bis **045+** (`media_assets`, …) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`) und **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
---
|
||||
|
||||
@@ -40,8 +40,14 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
|
||||
| 021 | 2026-04-27 | ~~Import Skills from Matrix~~ (DEPRECATED) | ⚠️ Faulty |
|
||||
| **022** | **2026-04-27** | **Skills Schema Complete (BREAKING)** | ✅ Deployed |
|
||||
| **023** | **2026-04-27** | **Skills Complete Import (69 Skills)** | ✅ Deployed |
|
||||
|
||||
---
|
||||
| 024–031 | *versch.* | Reifegradmodelle, Medien, Planvorlagen/Sektionen u. a. — siehe `backend/migrations/` | ✅ je Umgebung |
|
||||
| **032** | **2026-04-30** | **Progressionsgraph Übung→Übung:** `exercise_progression_graphs`, `exercise_progression_edges` | ✅ |
|
||||
| **033** | **2026-04-30** | **`exercise_progression_edges.notes`** | ✅ |
|
||||
| **034** | **2026-04-30** | **Kanten-Endpunkte optional `exercise_variants`; UNIQUE/CHECK** | ✅ |
|
||||
| **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ |
|
||||
| **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ |
|
||||
| **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ |
|
||||
| **040–046** | **2026-05** | **Mitgliedschaft/Anträge, Übungs-Governance-Erweiterungen, `media_assets`, `platform_media_storage`, `exercise_media.media_asset_id`, Tags/GIN u. a.** — exakte Nummern: `backend/migrations/`; fachliche Norm Medien: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** | ✅ je Umgebung |
|
||||
|
||||
## Migration 022: Skills Schema Complete (BREAKING CHANGE)
|
||||
|
||||
@@ -260,22 +266,81 @@ exercise_skills (
|
||||
UNIQUE (exercise_id, skill_id) -- Migration 020
|
||||
)
|
||||
|
||||
-- Varianten & Medien
|
||||
-- Varianten & Medien (028+ Embed/Datei; 045+ optional media_asset_id → media_assets)
|
||||
exercise_variants (id, exercise_id, name, description, ...)
|
||||
exercise_media (id, exercise_id, type, url, title, description, ...)
|
||||
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
||||
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
||||
platform_media_storage (id, local_relative_root, …)
|
||||
```
|
||||
|
||||
### Training Planning
|
||||
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||
|
||||
Kopf ohne Gruppenbindung (`training_framework_programs`), Ziele, Slots. Slot‑spezifischer Ablauf liegt nach **037** nicht mehr in eigener Übungstabelle, sondern in **`training_units`** mit **`framework_slot_id`** — siehe nächster Abschnitt.
|
||||
|
||||
```sql
|
||||
training_units (id, group_id, date, title, description, ...)
|
||||
training_unit_exercises (
|
||||
training_unit_id, exercise_id, sort_order,
|
||||
exercise_variant_id -- FK exercise_variants(id) ON DELETE SET NULL (Migration 030)
|
||||
training_framework_programs (… focus_area_id, style_direction_id, visibility, club_id, created_by …)
|
||||
training_framework_goals (framework_program_id, sort_order, title, notes)
|
||||
training_framework_slots (framework_program_id, sort_order, title, notes, training_unit_id -- ungenutzt)
|
||||
training_framework_program_training_types (framework_program_id, training_type_id)
|
||||
training_framework_program_target_groups (framework_program_id, target_group_id)
|
||||
```
|
||||
|
||||
### Training Planning & Rahmen‑Blueprint (Migrationen 006, 031, **037**)
|
||||
|
||||
Geplante Einheit und **Rahmen‑Slot‑Blueprint** teilen sich **`training_units`** und den strukturierten Ablauf über **Sektionen** (031). Blueprint‑Zeilen haben **`framework_slot_id`** gesetzt (genau eine Zeile pro Slot); Kalender‑Zeilen haben **`framework_slot_id IS NULL`** und **`group_id` / `planned_date`** gesetzt. Kopien aus dem Rahmen können **`origin_framework_slot_id`** setzen.
|
||||
|
||||
```sql
|
||||
training_units (
|
||||
id,
|
||||
group_id INT NULL REFERENCES training_groups(id), -- Pflicht für Kalender‑Zeilen (CHECK)
|
||||
planned_date DATE NULL, -- Pflicht für Kalender‑Zeilen (CHECK)
|
||||
planned_time_start, planned_time_end, planned_focus,
|
||||
actual_date, actual_time_start, actual_time_end, attendance_count,
|
||||
status, notes, trainer_notes,
|
||||
created_by, plan_template_id REFERENCES training_plan_templates(id),
|
||||
framework_slot_id INT NULL REFERENCES training_framework_slots(id) ON DELETE CASCADE,
|
||||
origin_framework_slot_id INT NULL REFERENCES training_framework_slots(id) ON DELETE SET NULL,
|
||||
…
|
||||
)
|
||||
training_unit_sections (
|
||||
training_unit_id, order_index, title, guidance_notes,
|
||||
source_template_section_id REFERENCES training_plan_template_sections(id)
|
||||
)
|
||||
training_unit_section_items (
|
||||
section_id, order_index, item_type CHECK ('exercise'|'note'),
|
||||
exercise_id, exercise_variant_id, planned_duration_min, actual_duration_min,
|
||||
notes, modifications, note_body
|
||||
)
|
||||
```
|
||||
|
||||
**Legacy (Migration 006, für ältere Codepfade noch referenzierbar):** `training_unit_exercises`; produktiver Standardablauf liegt in **Sections/Items**.
|
||||
|
||||
**Trainingsvorlagen (031):** `training_plan_templates`, `training_plan_template_sections`.
|
||||
|
||||
```sql
|
||||
exercise_blocks (id, name, description, created_by, club_id, ...) -- Migration 017
|
||||
```
|
||||
|
||||
### Progressionsgraph Übung → Übung (Migrationen 032–034)
|
||||
|
||||
Separater gerichteter Graph **zwischen** Übungen (nicht zu verwechseln mit Varianten-Reihen **innerhalb** einer Übung, Migration 014). Detail-DDL und REST siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §3.
|
||||
|
||||
```sql
|
||||
exercise_progression_graphs (
|
||||
id, name, description, visibility, club_id, created_by,
|
||||
created_at, updated_at
|
||||
)
|
||||
exercise_progression_edges (
|
||||
id, graph_id,
|
||||
from_exercise_id, to_exercise_id,
|
||||
from_exercise_variant_id, -- nullable (Migration 034)
|
||||
to_exercise_variant_id,
|
||||
edge_type, -- z. B. next_exercise, sibling
|
||||
notes, -- Migration 033
|
||||
created_at
|
||||
)
|
||||
```
|
||||
|
||||
### MediaWiki Import (Migration 018)
|
||||
|
||||
```sql
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# Exercises API Specification
|
||||
|
||||
**Version:** 1.3
|
||||
**Datum:** 2026-04-27
|
||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits siehe Code)
|
||||
**Version:** 1.5
|
||||
**Datum:** 2026-05-08
|
||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
|
||||
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
||||
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
||||
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||
@@ -60,6 +62,20 @@ Development: https://dev.shinkan.jinkendo.de/api
|
||||
| PUT | `/exercise-blocks/{id}/items/{item_id}` | Update item |
|
||||
| DELETE | `/exercise-blocks/{id}/items/{item_id}` | Remove item |
|
||||
| PUT | `/exercise-blocks/{id}/items/reorder` | Reorder items (DnD) |
|
||||
| **Progressionsgraphen** (Übung→Übung) |
|
||||
| GET | `/exercise-progression-graphs` | Liste Graphen |
|
||||
| GET | `/exercise-progression-graphs/{id}` | Detail; Query `include_edges` |
|
||||
| POST | `/exercise-progression-graphs` | Graph anlegen |
|
||||
| PUT | `/exercise-progression-graphs/{id}` | Metadaten |
|
||||
| DELETE | `/exercise-progression-graphs/{id}` | Graph + Kanten |
|
||||
| GET | `/exercise-progression-graphs/{id}/edges` | Kantenliste |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges` | Einzelkante |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges/sequence` | Reihe (`steps`) in einer Transaktion |
|
||||
| PUT | `/exercise-progression-graphs/{id}/edges/{edge_id}` | z. B. Notiz |
|
||||
| DELETE | `/exercise-progression-graphs/{id}/edges/{edge_id}` | Kante löschen |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges/delete-batch` | `{ edge_ids }` |
|
||||
|
||||
Vollständige Pfadtabelle, Auth und Feldgrenzen: **`TRAINING_FRAMEWORK_SPEC.md`** §3.
|
||||
|
||||
---
|
||||
|
||||
@@ -320,7 +336,8 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
|
||||
### `PUT /exercises/{id}`
|
||||
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Inline-Hinweis:** Rich-Text-Felder (`summary`, `goal`, `execution`, `preparation`, `trainer_notes` sowie `execution_changes` bei Varianten) unterstützen Platzhalter `{{exerciseMedia:id}}`, die serverseitig auf kanonisches Span-Markup normalisiert werden. Beim erstmaligen Anlegen ohne vorhandene `exercise_media` wird dies mit 400 abgelehnt.
|
||||
|
||||
**Response:** `200 OK` (full exercise object)
|
||||
|
||||
@@ -444,7 +461,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
- `media_type` (enum, required) - `image | video | document | sketch`
|
||||
- `title` (string, optional)
|
||||
- `description` (string, optional)
|
||||
- `context` (enum, optional) - `ablauf | detail | trainer_hint`
|
||||
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
|
||||
|
||||
**Entweder `file` ODER `embed_url` (nicht beides).**
|
||||
|
||||
@@ -490,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
{
|
||||
"title": "Neuer Titel",
|
||||
"description": "Neue Beschreibung",
|
||||
"is_primary": true,
|
||||
"context": "detail"
|
||||
"is_primary": true
|
||||
}
|
||||
```
|
||||
|
||||
`context` bleibt backendseitig kompatibel, wird in aktuellen Bearbeitungsflüssen jedoch nicht mehr aktiv zur UI-Zuordnung verwendet (Inline-Platzhalter priorisiert).
|
||||
|
||||
**Response:** `200 OK` (media object)
|
||||
|
||||
---
|
||||
@@ -878,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
- File size: max 50MB
|
||||
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
||||
- Embed platforms: `youtube, instagram, vimeo`
|
||||
- Inline-Rich-Text: `{{exerciseMedia:id}}` bzw. `data-shinkan-exercise-media="<id>"`; optional `data-shinkan-exercise-media-size="small|medium|full"` für Layout.
|
||||
|
||||
### Exercise Block
|
||||
- `name`: 3-200 chars
|
||||
@@ -932,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0
|
||||
**Letzte Änderung:** 2026-04-24
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Version:** 1.5
|
||||
**Letzte Änderung:** 2026-05-08
|
||||
**Status:** Living Spec
|
||||
@@ -1,9 +1,10 @@
|
||||
# Exercise System Architecture
|
||||
|
||||
**Version:** 1.0
|
||||
**Datum:** 2026-04-24
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-04-30
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.1:** Progressionsgraph **zwischen** Übungen (Migration 032–034); Verweis `TRAINING_FRAMEWORK_SPEC.md`
|
||||
|
||||
---
|
||||
|
||||
@@ -54,6 +55,10 @@ Exercise Block ──── (N) Block Items ──── (1) Exercise
|
||||
└── is_placeholder (for templates)
|
||||
```
|
||||
|
||||
### 1.1b Progressionsgraph zwischen Übungen (nicht „Serie“)
|
||||
|
||||
**Abgrenzung:** Separates Konzept von der **Varianten-Serie** (§1.1): hier geht es um **gerichtete Kanten zwischen verschiedenen Übungen** (optional mit Varianten als Knoten-Endpunkten), gruppiert in Bibliotheks-Containern (`exercise_progression_graphs`). Schema, REST, Produktgrenzen und Backlog (parallele Alternativ-Pakete): **`TRAINING_FRAMEWORK_SPEC.md`** §3–§4.
|
||||
|
||||
---
|
||||
|
||||
### 1.2 Medien-Strategie
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
**Basis:** Migrationen 001-013 (bereits deployed)
|
||||
|
||||
**Progressionsgraph zwischen Übungen:** Migrationen **032–034** — nicht Bestandteil dieses „Exercise Catalog“-Schemas-Dokuments; siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3 und **`DATABASE_SCHEMA.md`** (Migrationshistorie).
|
||||
|
||||
---
|
||||
|
||||
## 2. Migration 014: Variant Progression + Search
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# Frontend Routing & Navigation Specification
|
||||
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-04-27
|
||||
**Version:** 1.2
|
||||
**Datum:** 2026-04-30
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.2:** Übersicht **Übungen**: Tabs Liste \| Progressionsgraphen auf `/exercises`; Progressions-Editor ohne neue Routen (Panel + Formularblock unter `/exercises/:id/edit`)
|
||||
**Änderungen v1.1:** Übungsvarianten-Bearbeitung nur unter `/exercises/:id/edit` (keine VariantFormPage-Routen)
|
||||
|
||||
---
|
||||
@@ -13,10 +14,10 @@
|
||||
### 1.1 Route-Übersicht
|
||||
|
||||
```
|
||||
/exercises → ExercisesListPage (Grid + Filter + Chips)
|
||||
/exercises → ExercisesListPage — Tabs: **Liste** \| **Progressionsgraphen** (`ExerciseProgressionGraphPanel`)
|
||||
/exercises/new → ExerciseFormPage (Create)
|
||||
/exercises/{id} → ExerciseDetailPage (Accordion-Layout)
|
||||
/exercises/{id}/edit → ExerciseFormPage (Edit inkl. Varianten-Editor inline)
|
||||
/exercises/{id}/edit → ExerciseFormPage (Edit inkl. Varianten-Editor inline + Block Progressionsgraph)
|
||||
|
||||
/exercise-blocks → ExerciseBlocksListPage (Meine Blocks)
|
||||
/exercise-blocks/new → ExerciseBlockFormPage (Create)
|
||||
@@ -672,7 +673,7 @@ function App() {
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.1
|
||||
**Letzte Änderung:** 2026-04-24
|
||||
**Status:** REVIEWED - Pending Implementation
|
||||
**Review-Änderungen:** Exercise Blocks Routes + Navigation hinzugefügt
|
||||
**Version:** 1.2
|
||||
**Letzte Änderung:** 2026-04-30
|
||||
**Status:** REVIEWED - Pending Implementation
|
||||
**Review-Änderungen:** Progressionsgraphen-UI (Tabs, Formularblock); Exercise Blocks Routes + Navigation (früher)
|
||||
@@ -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
|
||||
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-04-27
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
|
||||
**Version:** 1.2
|
||||
**Datum:** 2026-05-07
|
||||
**Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
|
||||
|
||||
> **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:**
|
||||
> Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung).
|
||||
> 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,193 @@
|
||||
# Trainingsrahmenprogramm — Technische Spezifikation
|
||||
|
||||
**Status:** Rahmen‑Bibliothek + Slot‑Blueprint dokumentiert · **Stand:** 2026-05-05 (Migration **036–037**)
|
||||
**Bindendes Fachkonzept / Entscheide:** `.claude/docs/functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR‑001 bis CURR‑013)
|
||||
|
||||
**Relevant für nächsten Schritt:** CURR‑002 **(2)** Trainingsplanung / Rahmen über mehrere Einheiten — der hier dokumentierte **Progressionsgraph Stufe 1** ist bewusst **unterstützend**, keine Pflicht für Slot-Zuordnungen (**CURR‑013**).
|
||||
|
||||
---
|
||||
|
||||
## 1. Abgrenzung zu anderen Dokumenten
|
||||
|
||||
| Dokument | Rolle · warum **nicht** hier hineinmischen |
|
||||
|----------|--------------------------------------------|
|
||||
| `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_API_SPEC.md` | **Übungskatalog** inkl. Varianten-Progression **innerhalb einer Übung** (Migration 014). Kanten **zwischen** Übungen siehe **§3**. |
|
||||
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
|
||||
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
|
||||
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
|
||||
|
||||
**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).
|
||||
|
||||
---
|
||||
|
||||
## 2. Rahmenprogramm (CURR‑002 Stufe 2) — Checkliste & technische Ausarbeitung
|
||||
|
||||
### 2.0 Technische Entscheidung: nur Bibliothek + Slot‑Blueprint = `training_units`
|
||||
|
||||
**Fachlich:** Das Rahmenprogramm ist eine **wiederverwendbare Bibliotheksvorlage** ohne Bindung an eine Trainingsgruppe oder einen Kalendertermin (**Migration 036** entfernte `plan_mode`, `group_id` am Kopf sowie die Nutzung von `training_framework_slots.training_unit_id` für „konkrete“ Kopplung).
|
||||
|
||||
**Slot‑Inhalt (Migration 037):** Pro `training_framework_slot` existiert genau eine **Blueprint‑Zeile** in `training_units` mit **`framework_slot_id`** (partieller **UNIQUE**-Index); der Ablauf entspricht **derselben** Struktur wie geplante Einheiten über **`training_unit_sections`** und **`training_unit_section_items`** (Übungen, Notizen, Varianten wie in der Planung). Die frühere Tabelle **`training_framework_slot_exercises`** wird nach Datenübernahme **`DROP`**pt.
|
||||
|
||||
**Geplante Einheit aus Rahmen:** **`POST /api/training-units/from-framework-slot`** kopiert diese Blueprint‑Unit (**tiefe Kopie**) mit **`group_id` + `planned_date`**; **`origin_framework_slot_id`** hält die Herkunft (Lineage‑Light). **`GET /api/training-units`** blendet Einheiten mit **`framework_slot_id IS NOT NULL`** aus (Kalender/API‑Liste ohne Rahmen‑Blueprints).
|
||||
|
||||
**CHECK‑Constraint auf `training_units`:** Zeile ist entweder **Blueprint** (`framework_slot_id` gesetzt, `group_id`/`planned_date` NULL, kein `origin_framework_slot_id`) oder **Kalender‑Einheit** (`framework_slot_id` NULL, `group_id` und `planned_date` gesetzt; `origin_framework_slot_id` optional).
|
||||
|
||||
**Konsequenz Konzept CURR‑012 („concrete/library“):** Persistiert wird **ein** Kopf ohne Modus-Spalte: Immer Bibliotheks‑Rolle; Konkretisierung nur über Planung/API‑Kopie. Historische DDL mit `plan_mode` siehe **`035`**/`036` in dieser Datei (**§5 Changelog**) und `backend/migrations/`.
|
||||
|
||||
### 2.1 Checkliste (Abhak-Stand)
|
||||
|
||||
- [x] **Entität(en):** `training_framework_programs` (**CURR‑009**); `training_plan_templates` unverändert **eine‑Einheit‑Mikrovorlage** (**C5**).
|
||||
- [x] **Bibliothek only (036):** Kopf ohne `plan_mode`/`group_id`; Kontextfilter **`focus_area_id`**, **`style_direction_id`**; M:N **`training_framework_program_training_types`**, **`training_framework_program_target_groups`**.
|
||||
- [x] **Zielliste:** `training_framework_goals`, API **≥ 1** Ziel (**CURR‑011**).
|
||||
- [x] **Slots:** `training_framework_slots` mit **`sort_order`**, optional **Titel/Notizen**; **Ablauf** über zugehörige **Blueprint‑`training_units`** + Sektionen/Items (**037**), nicht mehr `training_framework_slot_exercises`.
|
||||
- [x] **Progressionsgraph:** Stufe 1 (**§3–§4**); **kein Pflichtbezug** pro Slot (**CURR‑013**).
|
||||
- [x] **Kein Live‑Write** von Kalendereinheiten zurück in die Vorlage (**CURR‑006**); Konkretisierung = **Kopie** (siehe **§2.4**).
|
||||
- [x] **Instanziierung (MVP):** `POST /api/training-units/from-framework-slot` — weiterer Ausbau: Bulk, Kalender‑UI‑Flow, **`training_plan_template_id` pro Slot** weiterhin optional/deferred (**CURR‑010**).
|
||||
- [x] **Governance:** `visibility`, `club_id`, **`training_plan_templates.visibility`** (**035**) — (**CURR‑005–008**).
|
||||
- [x] **REST Rahmenprogramm:** `/api/training-framework-programs` (**§2.3**); Planung (**§2.4**).
|
||||
|
||||
### 2.2 DDL‑Überblick (Migrationen **035** → **036** → **037**)
|
||||
|
||||
Auszug aktueller Zustand nach **036/037** (Details: `backend/migrations/035_training_framework_programs.sql`, `036_framework_program_context_only_library.sql`, `037_training_framework_blueprint_units.sql`):
|
||||
|
||||
```sql
|
||||
-- Kopf (ohne Modus-Spalten nach 036)
|
||||
training_framework_programs (
|
||||
id, title NOT NULL, description,
|
||||
planned_period_start, planned_period_end NULL,
|
||||
visibility NOT NULL, club_id, created_by,
|
||||
focus_area_id, style_direction_id NULL REFERENCES …,
|
||||
… timestamps
|
||||
)
|
||||
|
||||
training_framework_goals (
|
||||
id, framework_program_id FK CASCADE, sort_order UNIQUE per framework,
|
||||
title, notes
|
||||
)
|
||||
|
||||
training_framework_slots (
|
||||
id, framework_program_id FK CASCADE, sort_order UNIQUE per framework,
|
||||
title, notes,
|
||||
training_unit_id FK … (Spalte technisch noch vorhanden; fachlich ungenutzt, per 036 geleert)
|
||||
)
|
||||
|
||||
-- Blueprint: eigene Einheit wie in der Planung (031)
|
||||
training_units.framework_slot_id -- UNIQUE (partial index), FK → slots ON DELETE CASCADE
|
||||
training_units.origin_framework_slot_id -- optional auf Kopien aus dem Rahmen (SET NULL)
|
||||
-- CHECK chk_training_units_blueprint_vs_scheduled (Blueprint vs. Kalender‑Zeile)
|
||||
-- training_framework_slot_exercises → entfallen (037)
|
||||
```
|
||||
|
||||
**Löschkaskaden:** Rahmen löschen ⇒ Ziele + Slots; **Slot löschen** ⇒ zugehörige Blueprint‑`training_unit` per **`ON DELETE CASCADE`** auf `framework_slot_id`.
|
||||
|
||||
### 2.3 REST‑Überblick (`router` `training_framework_programs`)
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---------|------|--------|
|
||||
| GET | `/training-framework-programs` | Liste; Admin/Superadmin alle, sonst eigene (`created_by`); u. a. `goals_count`, `slots_count`, Kontext‑Counts |
|
||||
| GET | `/training-framework-programs/{id}` | Detail inkl. `goals[]`, `slots[]` mit je **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`** (letzteres aus Sektionen geflacht, kompatibel zum Editor) |
|
||||
| POST | `/training-framework-programs` | Neu; **Pflicht:** `title`, **`goals`** (≥ 1); optional `slots` (weiterhin **`exercises[]`** pro Slot möglich — Backend materialisiert Sektionen); Header: `focus_area_id`, `style_direction_id`, `training_type_ids`, `target_group_ids`, … |
|
||||
| PUT | `/training-framework-programs/{id}` | Header; volles Ersetzen von **`goals`** und/oder **`slots`** (neue Slots ⇒ neue Blueprint‑Units) |
|
||||
| DELETE | `/training-framework-programs/{id}` | Rahmen + Kinder |
|
||||
|
||||
**AuthZ:** wie zuvor — Planungsrolle zum Schreiben; Lesen/Schreiben/Löschen des Rahmens: Admin/Superadmin oder Ersteller.
|
||||
|
||||
**Payload‑Hinweise (JSON), Slots:**
|
||||
|
||||
- Weiterhin: `exercises: [{ exercise_id, exercise_variant_id?, order_index? }]` (wird intern in eine Sektion übernommen).
|
||||
- Erweitert möglich: `sections` wie bei **`PUT /api/training-units/{id}`** (voller Ablauf mit Notizen/Items).
|
||||
|
||||
### 2.4 Planung / Kalender (`router` `training_planning.py`, Auszug)
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---------|------|--------|
|
||||
| GET | `/training-units` | Nur **Kalender‑Einheiten** (`framework_slot_id IS NULL`) |
|
||||
| GET/PUT | `/training-units/{id}` | Blueprint lesen/bearbeiten: möglich mit Rahmen‑Auth; spezielle Regeln im **PUT** (kein Template‑Reset, kein `plan_template_id` am Blueprint) |
|
||||
| DELETE | `/training-units/{id}` | Blueprint **nicht** über diesen Pfad löschen (Fehlerhinweis); Slot entfernen über Rahmen‑**PUT** |
|
||||
| POST | `/training-units/from-framework-slot` | Body: `framework_slot_id`, `group_id`, `planned_date` — tiefe Kopie + **`origin_framework_slot_id`** |
|
||||
|
||||
**Frontend:** `createTrainingUnitFromFrameworkSlot` in `frontend/src/utils/api.js`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Progressionsgraph Übung → Übung (implementierter Stand)
|
||||
|
||||
### 3.1 Abgrenzung
|
||||
|
||||
- **Zwischen Übungen:** gerichtete Kanten auf Ebene **`exercises`** mit optionalen Endpunkten auf konkreten **`exercise_variants`** (Knoten = „Übung“ oder „Übung · Variante“). Migrationen **032–034**.
|
||||
- **Innerhalb einer Übung:** Reihenfolge / Progressionsmetadaten der Varianten unverändert über **`exercise_variants`** (Migration **014**) — nicht duplizieren.
|
||||
|
||||
AuthZ analog **`training_plan_templates`**: Graph nur für **Admin/Superadmin** oder **Ersteller** (`created_by`); Anlegen neuer Graphen mit **`_has_planning_role`**.
|
||||
|
||||
### 3.2 Migrationen & Schema (Kurz)
|
||||
|
||||
| Mig. | Inhalt |
|
||||
|------|--------|
|
||||
| **032** | `exercise_progression_graphs` (Name, Beschreibung, **`visibility`**, **`club_id`**, **`created_by`**); `exercise_progression_edges` (`graph_id`, von/nach Übung, `edge_type` VARCHAR Default `next_exercise`). FK CASCADE zu Graph und Übungen. |
|
||||
| **033** | `exercise_progression_edges.notes` (freier Text / „Entwicklungsziel“ pro Kante). |
|
||||
| **034** | `from_exercise_variant_id`, `to_exercise_variant_id` (nullable, FK `exercise_variants`, CASCADE). CHECK: gleiche Übung nur mit **zwei verschiedenen Varianten**. UNIQUE-Index über Graph + Endpunkte inkl. `COALESCE(variant_id,0)` + `edge_type`. |
|
||||
|
||||
Kantentypen in Produktnutzung: **`next_exercise`** (Nachfolger), **`sibling`** (Schwester / gleiche „Entwicklungslage“, semantisch oft Paar — weiterhin eine gerichtete Kante in DB).
|
||||
|
||||
Listenqueries liefern Join‑Felder **`from_exercise_title`**, **`to_exercise_title`**, **`from_variant_name`**, **`to_variant_name`**.
|
||||
|
||||
### 3.3 REST (`/api`, Router `exercise_progression_graphs.py`)
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---------|------|--------|
|
||||
| GET | `/exercise-progression-graphs` | Liste (+ `edges_count`); Admin sieht alle, sonst nur eigene. |
|
||||
| GET | `/exercise-progression-graphs/{id}` | Detail; `?include_edges=true` |
|
||||
| POST | `/exercise-progression-graphs` | Graph anlegen |
|
||||
| PUT | `/exercise-progression-graphs/{id}` | Metadaten |
|
||||
| DELETE | `/exercise-progression-graphs/{id}` | Graph + Kanten |
|
||||
| GET | `/exercise-progression-graphs/{id}/edges` | Kanten; Query optional `from_exercise_id`, `to_exercise_id` |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges` | Einzelkante; Duplikat/Constraint → **409** |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges/sequence` | **Bulk:** `{ steps: [{ exercise_id, variant_id? }, …], segment_notes?: [...] }` — nur **`next_exercise`**, Transaktion alle oder keine Zeile |
|
||||
| PUT | `/exercise-progression-graphs/{id}/edges/{edge_id}` | z. B. **`notes`** |
|
||||
| DELETE | `/exercise-progression-graphs/{id}/edges/{edge_id}` | eine Kante |
|
||||
| POST | `/exercise-progression-graphs/{id}/edges/delete-batch` | `{ edge_ids: [...] }` — z. B. gesamte sichtbare „Reihe“ löschen |
|
||||
|
||||
### 3.4 Frontend (Stand Code)
|
||||
|
||||
- **`ExercisesListPage`:** Tabs **Liste** · **Progressionsgraphen** → **`ExerciseProgressionGraphPanel`**.
|
||||
- **`ExerciseFormPage`** (nur Edit): eingeklappter Block **Progressionsgraph** mit Kontext „diese Übung“ + Filter „nur betroffene Kanten“.
|
||||
- Panel‑Funktionen: **Sequenz‑Editor** (mehrere Schritte → ein Bulk‑Speichern), zusammengefasste **Reihen‑Lesart** für `next_exercise`, eigene Liste für **Schwestern**, Einzelkantenbereich, Tab **Alle Kanten (Tabelle)**.
|
||||
- API‑Client: `frontend/src/utils/api.js` (`createExerciseProgressionSequence`, `deleteExerciseProgressionEdgesBatch`, …).
|
||||
|
||||
---
|
||||
|
||||
## 4. Zwischenstand für Produkt / Trainingsplanung (bewusste Grenzen)
|
||||
|
||||
**Freigabe:** Der beschriebene Stand unterstützt **Rahmen‑Bibliothek mit vollem Ablauf pro Slot** (wie Planung) und **Kopie in die Gruppenplanung**; der **Progressionsgraph** bleibt **unterstützend** (**CURR‑013**). Offen: Kalender‑UI‑Flow, Bulk‑Instanziierung, erweiterte Lineage/Feedback (**Konzept Schritt E**).
|
||||
|
||||
**Was gut nutzbar ist**
|
||||
|
||||
- Lineare **Reihen** mehrerer Übungen (bzw. Varianten‑Knoten) über **Sequenz‑API** bzw. Sequenz‑UI.
|
||||
- **Nachfolger‑Lesart** als zusammenhängende Kette in der Übersicht.
|
||||
- **Schwester‑Kanten** als eigene Liste (Alternative gleicher „Stufe“ zwischen zwei Knoten).
|
||||
- **Einzelkanten** für Sonderfälle und Verzweigungen.
|
||||
|
||||
**Was noch nicht „ein Knopf“ ist (bekannt)**
|
||||
|
||||
- **Parallele gleichwertige Alternativen** („Paket B bestehend aus mehreren Übungen als echte Alternative zu Paket A“) sind **nicht** als erste‑Klass‑UX modelliert: mehrere Nachfolger aus einem Knoten sind technisch möglich (mehrere `next_exercise`‑Kanten), aber **keine** dedizierte Gruppe „Alternativ‑Set“. Pflege kann mehrzeilig und koplastisch wirken.
|
||||
- **Visualisierung echter Bäume** (Join‑Points, mehrere ausgehende Pfeile in einem Bild) ist nur eingeschränkt über Reihen‑Zusammenfassung + Tabelle abbildbar.
|
||||
|
||||
**Nächste sinnvolle Ausbaustufen** (Backlog Graph‑UX, nicht Blocker Planung)
|
||||
|
||||
- Semantik **`alternative_group_id`** oder **Hyperkanten** (ein UX‑Schritt legt mehrere Kanten mit gemeinsamer Gruppe an).
|
||||
- Komfort beim Pflegen **symmetrischer Schwestern** (ein Klick für zwei Richtungen / Dedupe).
|
||||
- Karten-/Baum‑Layout statt nur Zeilen.
|
||||
|
||||
Details weiterhin Diskussionsgrundlage in `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` §6 (Kantentypen).
|
||||
|
||||
---
|
||||
|
||||
## 5. Changelog (Dokument)
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-05 | **037 / API:** Nur Bibliothek + **Blueprint** pro Slot über `training_units` + Sektionen/Items; `training_framework_slot_exercises` entfernt; `POST …/training-units/from-framework-slot`; Planungsliste ohne Blueprints. **036** dokumentiert am Kopf (Kontext, M:N, kein plan_mode/group_id). **§2** vollständig ersetzt. |
|
||||
| 2026-05-05 | **CURR‑002 (2):** §2 Rahmenprogramm — Entscheid **eine Tabelle + `plan_mode`**, DDL‑Skizze, REST‑Überblick; Migration **035**; `training_plan_templates.visibility`. *(Historisch — Modus-Spalten durch **036** ersetzt.)* |
|
||||
| 2026-04-30 | **Zwischen-Doku:** §3 auf Migrationen 032–034 + API **sequence/delete-batch** + Frontend erweitert; **§4** Produktfreigabe vs. Lücken (parallele Alternativen); Changelog §5. |
|
||||
| 2026-04-30 | §3: erste Fassung Migration 032 + REST‑Basis (CURR‑002 (1)). |
|
||||
| 2026-04-28 | Erstanlage Stub mit Checkliste. |
|
||||
@@ -0,0 +1,52 @@
|
||||
# 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 |
|
||||
| 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-07 — Upload-Dedupe Papierkorb 409 + `reactivate`; DELETE …/media nur Verknüpfung.
|
||||
|
||||
---
|
||||
|
||||
### Changelog (Fortführung)
|
||||
|
||||
- **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.
|
||||
@@ -1,11 +1,14 @@
|
||||
# Session Handover (Verweis)
|
||||
|
||||
**Dieses Dokument ist veraltet.** Der aktuelle Entwicklungsstand und die Handover-Basis stehen hier:
|
||||
**Aktuelle Handover-Basis (Stand Implementierung + Medien):**
|
||||
|
||||
👉 **`docs/HANDOVER.md`** (Projektroot: `c:\Dev\shinkan-jinkendo\docs\HANDOVER.md`)
|
||||
👉 **`docs/HANDOVER.md`** (Projektroot)
|
||||
|
||||
Dort: Fähigkeits-/Reifegrad-Stand (Bindings, Resolve, Export/Import, Matrix-Stack), Verweise auf `.claude/docs` für Anforderungen, und **nächste Priorität Übungen (UI/CRUD/Medien)**.
|
||||
Dort: **Medien-Archiv/Medienbibliothek (Ist)**, **geplante Inline-Medienverlinkung (§11 Spec)**, Reifegrad/Matrix, Rahmenprogramm, nächste sinnvolle Arbeitspakete für neue Sessions.
|
||||
|
||||
**Projektstatus-Kachel:** `.claude/docs/PROJECT_STATUS.md`
|
||||
**Medien Single Source of Truth:** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
|
||||
---
|
||||
|
||||
*Historischer Inhalt aus April 2026 wurde durch `docs/HANDOVER.md` ersetzt.*
|
||||
*Die historische „Übungen Lücke“-Fassung (2026-04) ist überholt; Medien-UI und Archiv sind seit 0.8.41+ weitgehend umgesetzt — Details `docs/HANDOVER.md` §4.*
|
||||
@@ -0,0 +1,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).
|
||||
@@ -55,6 +55,23 @@ return {"error": "not found"}
|
||||
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
|
||||
|
||||
@@ -4,17 +4,32 @@ Diese Regeln IMMER befolgen. Sie basieren auf Erfahrungen aus der Entwicklung.
|
||||
|
||||
## 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
|
||||
# Jeder neue Endpoint braucht Auth:
|
||||
@router.get("/neuer-endpoint")
|
||||
def neuer_endpoint(session: dict = Depends(require_auth)):
|
||||
pid = session['profile_id']
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
@router.get("/beispiel")
|
||||
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
|
||||
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') ❌
|
||||
```
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
|
||||
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
|
||||
3. Spez-Index: **`.claude/docs/README.md`**
|
||||
4. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
4. **Session-Handover (aktuelle Prioritäten, Medien-Ist):** **`docs/HANDOVER.md`**
|
||||
5. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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)):
|
||||
...
|
||||
```
|
||||
+33
-17
@@ -1,49 +1,65 @@
|
||||
# === Deploy (.env auf dem Host) ============================================
|
||||
# Kopiere diese Datei nach `.env` im SELBEN Verzeichnis wie `docker-compose.yml` (Pi: ~/docker/shinkan).
|
||||
# Docker Compose liest `.env` beim Start — dadurch wird z. B. SMTP_HOST=${SMTP_HOST} gefüllt.
|
||||
# Ist die Datei weg/leer oder steht SMTP_PASS nicht darin → im Container keine SMTP-Daten ([SMTP] nicht konfiguriert).
|
||||
# === .env neben der Jeweiligen docker-compose.*.yml kopieren ====================
|
||||
# Docker Compose ersetzt ${VARIABLE} beim Start.
|
||||
#
|
||||
# Pro Umgebung eigene Datei (z. B. ~/docker/shinkan/.env für Prod,
|
||||
# ~/docker/shinkan-dev/.env für Dev) — dieselben SCHLÜSSEL, unterschiedliche Werte.
|
||||
# Kein separates DEV_APP_URL vs APP_URL: immer APP_URL, ALLOWED_ORIGINS, DB_*, …
|
||||
|
||||
# Database
|
||||
# ─── Typische Werte PROD (docker-compose.yml) ─────────────────────────────────
|
||||
# DB_NAME=shinkan
|
||||
# DB_USER=shinkan_user
|
||||
# DB_PASSWORD=…
|
||||
# APP_URL=https://shinkan.jinkendo.de
|
||||
# ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
||||
# ENVIRONMENT=production
|
||||
# SHINKAN_MEDIA_HOST=/shinkan-media
|
||||
# MEDIA_ROOT=/app/media
|
||||
|
||||
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
|
||||
# DB_NAME=shinkan_dev
|
||||
# DB_USER=shinkan_dev
|
||||
# DB_PASSWORD=dev_password
|
||||
# APP_URL=https://dev.shinkan.jinkendo.de
|
||||
# ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098
|
||||
# ENVIRONMENT=development
|
||||
# SHINKAN_MEDIA_HOST=/shinkan-media/dev
|
||||
# MEDIA_ROOT=/app/media
|
||||
|
||||
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
|
||||
DB_HOST=postgres
|
||||
DB_PORT=5432
|
||||
DB_NAME=shinkan
|
||||
DB_USER=shinkan_user
|
||||
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
||||
|
||||
# OpenRouter (KI - optional)
|
||||
OPENROUTER_API_KEY=your_api_key_here
|
||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
||||
|
||||
# SMTP (E-Mail)
|
||||
SMTP_HOST=smtp.example.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=noreply@jinkendo.de
|
||||
SMTP_PASS=your_smtp_password
|
||||
SMTP_FROM=noreply@jinkendo.de
|
||||
# Port 465 oft SSL; dann z. B. SMTP_SSL=true und SMTP_STARTTLS=false
|
||||
SMTP_SSL=
|
||||
SMTP_STARTTLS=
|
||||
|
||||
# Bootstrap: erste Registrierung (leere Nutzerliste) erhält Rolle admin; oder feste Admin-Mails:
|
||||
AUTO_ADMIN_FIRST_USER=true
|
||||
ADMIN_BOOTSTRAP_EMAILS=
|
||||
|
||||
# App
|
||||
APP_URL=https://shinkan.jinkendo.de
|
||||
# Kommasepariert (ohne Leerzeichen um die Kommas ist am sichersten). Für Dev mehrere Origins nötig (HTTPS + LAN).
|
||||
ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
||||
ENVIRONMENT=production
|
||||
|
||||
# Nur docker-compose.dev-env.yml (optional): DEV_APP_URL, DEV_ALLOWED_ORIGINS
|
||||
# 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
|
||||
|
||||
# Media Storage
|
||||
MEDIA_DIR=/app/media
|
||||
|
||||
# MediaWiki Import (Semantic MediaWiki)
|
||||
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
|
||||
MEDIAWIKI_USER=Jinkendo
|
||||
MEDIAWIKI_PASSWORD=CHANGE_ME
|
||||
# Kategorienamen im Wiki (echte Namen von karatetrainer.net)
|
||||
MEDIAWIKI_CATEGORY_EXERCISES=Übungen
|
||||
MEDIAWIKI_CATEGORY_SKILLS=Fähigkeitsbeschreibung
|
||||
MEDIAWIKI_CATEGORY_METHODS=Methodenbeschreibung
|
||||
|
||||
+116
-24
@@ -3,11 +3,45 @@ name: Test Suite
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop]
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
workflow_run:
|
||||
workflows: ["Deploy Development", "Deploy Production"]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
# Wie Mitai-Jinkendo: pytest im laufenden backend-Container (Python aus Image, gleiche DB wie Deploy).
|
||||
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 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
"
|
||||
|
||||
lint-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
@@ -57,6 +91,11 @@ jobs:
|
||||
playwright-tests:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
|
||||
# Dev: Tests gegen bereits deployte URL (HTTPS, Reverse-Proxy). Prod: gleicher Ablauf.
|
||||
env:
|
||||
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
|
||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
@@ -66,33 +105,69 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Start dev stack for E2E
|
||||
env:
|
||||
DEV_ALLOWED_ORIGINS: http://127.0.0.1:3098,http://localhost:3098,http://host.docker.internal:3098,https://dev.shinkan.jinkendo.de
|
||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||
id: e2e
|
||||
run: |
|
||||
docker compose -f docker-compose.dev-env.yml up -d --build
|
||||
echo "Warte auf Frontend + API (/health) …"
|
||||
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 "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
|
||||
else
|
||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
|
||||
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 http://127.0.0.1:3098/health >/dev/null 2>&1; then
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Timeout: /health nicht erreichbar"
|
||||
curl -v http://127.0.0.1:3098/health || true
|
||||
docker compose -f docker-compose.dev-env.yml logs --tail=120
|
||||
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Seed E2E test user (erste Registrierung in frischer DB)
|
||||
env:
|
||||
TEST_EMAIL: lars@stommer.com
|
||||
TEST_PASSWORD: 12345678
|
||||
- name: Prod /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||
run: |
|
||||
curl -sf -X POST "http://127.0.0.1:3098/api/auth/register" \
|
||||
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: Testnutzer registrieren (Dev, nur wenn möglich)
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
env:
|
||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
|
||||
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
|
||||
exit 0
|
||||
fi
|
||||
curl -sf -X POST "$BASE/api/auth/register" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"email\":\"${TEST_EMAIL}\",\"password\":\"${TEST_PASSWORD}\",\"name\":\"Playwright CI\"}" \
|
||||
|| echo "(Registrierung übersprungen — Nutzer existiert evtl. schon)"
|
||||
-d "{\"email\":\"${E2E_DEV_TEST_EMAIL}\",\"password\":\"${E2E_DEV_TEST_PASSWORD}\",\"name\":\"Playwright CI\"}" \
|
||||
|| echo "(Register evtl. schon erfolgt oder Limits — Login-Test gilt trotzdem.)"
|
||||
|
||||
- name: Install Playwright
|
||||
run: |
|
||||
@@ -101,21 +176,38 @@ jobs:
|
||||
|
||||
- name: Run Playwright tests
|
||||
env:
|
||||
PLAYWRIGHT_BASE_URL: http://127.0.0.1:3098
|
||||
TEST_EMAIL: lars@stommer.com
|
||||
TEST_PASSWORD: 12345678
|
||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||
run: |
|
||||
set -e
|
||||
MODE="${{ steps.e2e.outputs.mode }}"
|
||||
BASE_URL="${{ steps.e2e.outputs.base_url }}"
|
||||
export PLAYWRIGHT_BASE_URL="$BASE_URL"
|
||||
|
||||
if [ "$MODE" = "prod" ]; then
|
||||
export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
|
||||
export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
|
||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
||||
echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
|
||||
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
|
||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
||||
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
mkdir -p screenshots
|
||||
npx playwright test
|
||||
echo "✓ Playwright tests passed"
|
||||
|
||||
- name: Stop dev stack
|
||||
if: always()
|
||||
run: docker compose -f docker-compose.dev-env.yml down
|
||||
|
||||
- name: Upload test screenshots
|
||||
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:
|
||||
name: playwright-screenshots
|
||||
path: screenshots/
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
> VOR jeder Implementierung lesen:
|
||||
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.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` |
|
||||
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.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`** |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
@@ -52,8 +57,8 @@ backend/
|
||||
├── migrations/ # SQL-Migrationen (XXX_*.sql Pattern)
|
||||
└── routers/ # Router-Module
|
||||
auth · profiles · clubs · groups · skills · methods
|
||||
exercises · training_units · training_programs
|
||||
planning · import_wiki · admin · membership
|
||||
exercises · exercise_progression_graphs · training_units · training_programs
|
||||
planning · import_wiki · admin · membership · media_assets
|
||||
|
||||
frontend/src/
|
||||
├── App.jsx # Root, Auth-Gates, Navigation
|
||||
@@ -78,12 +83,13 @@ frontend/src/
|
||||
|
||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||
|
||||
Kurz (Stand 2026-04-27): App **0.7.9**, DB-Schema-Version **20260427030**; Kern-Features: Übungen mit Varianten, Medien, Trainingsplanung mit optionaler Variantenwahl.
|
||||
Kurz (Stand 2026-05-08): App **0.8.64**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll), Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (§11 umgesetzt).
|
||||
|
||||
### Log (Auszug)
|
||||
|
||||
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
|
||||
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
|
||||
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
|
||||
- 2026-04-21: Repository- und Initial-Setup (Historie; Details in Git).
|
||||
|
||||
## Domänenmodell (MVP Core)
|
||||
|
||||
@@ -102,14 +108,13 @@ Kurz (Stand 2026-04-27): App **0.7.9**, DB-Schema-Version **20260427030**; Kern-
|
||||
- `exercises` - Übungen (Kernobjekt)
|
||||
- `exercise_variants` - Übungsvarianten
|
||||
- `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:**
|
||||
- `training_templates` - Vorlagen / Standards
|
||||
- `training_sections` - Trainingsabschnitte
|
||||
- `section_exercises` - Übungen in Abschnitten
|
||||
- `training_units` - Konkrete Trainingseinheiten
|
||||
- `training_programs` - Trainingsprogramme
|
||||
**Trainingsplanung / Rahmen:**
|
||||
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
||||
- `training_units` — Kalender‑Instanzen **und** Rahmen‑Slot‑Blueprints (`framework_slot_id` ab **037**)
|
||||
- `training_framework_programs` + Ziele + Slots (Migration **035–036**) — Bibliotheks‑Rahmen
|
||||
- Legacy: `training_templates` / `section_exercises` o. ä. — in älteren Skizzen; produktiver Pfad siehe Migrationen **006**/**031**
|
||||
|
||||
**Governance:**
|
||||
- `content_change_requests` - Änderungsanfragen
|
||||
@@ -198,6 +203,10 @@ ALLOWED_ORIGINS=https://shinkan.jinkendo.de
|
||||
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
|
||||
|
||||
### 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
|
||||
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
|
||||
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
|
||||
- **Medien:** Zentrale **Medienbibliothek** (`/media`), Archiv mit Lifecycle/Papierkorb, Verknüpfung in Übungen — Norm: `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` · Einstieg: `docs/HANDOVER.md`
|
||||
|
||||
## Nicht in Shinkan
|
||||
|
||||
|
||||
@@ -13,8 +13,6 @@ import bcrypt
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
print("[AUTH.PY] Module loaded - require_auth_flexible will be defined")
|
||||
|
||||
|
||||
def hash_pin(pin: str) -> str:
|
||||
"""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:
|
||||
conn = get_connection()
|
||||
conn.close()
|
||||
print("✓ PostgreSQL ready")
|
||||
print("[OK] PostgreSQL ready")
|
||||
return True
|
||||
except OperationalError:
|
||||
print(f" Waiting for PostgreSQL... (attempt {i}/{max_retries})")
|
||||
time.sleep(2)
|
||||
|
||||
print(f"✗ PostgreSQL not ready after {max_retries} attempts")
|
||||
print(f"[FAIL] PostgreSQL not ready after {max_retries} attempts")
|
||||
return False
|
||||
|
||||
def check_table_exists(table_name="profiles"):
|
||||
@@ -71,10 +71,10 @@ def load_schema(schema_file="/app/schema.sql"):
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
print("✓ Schema loaded from schema.sql")
|
||||
print("[OK] Schema loaded from schema.sql")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"✗ Error loading schema: {e}")
|
||||
print(f"[FAIL] Error loading schema: {e}")
|
||||
return False
|
||||
|
||||
def get_profile_count():
|
||||
@@ -146,10 +146,10 @@ def apply_migration(filepath, filename):
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
print(f" ✓ Applied: {filename}")
|
||||
print(f" [OK] Applied: {filename}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f" ✗ Failed to apply {filename}: {e}")
|
||||
print(f" [FAIL] Failed to apply {filename}: {e}")
|
||||
return False
|
||||
|
||||
def run_migrations(migrations_dir="/app/migrations"):
|
||||
@@ -158,7 +158,7 @@ def run_migrations(migrations_dir="/app/migrations"):
|
||||
import re
|
||||
|
||||
if not os.path.exists(migrations_dir):
|
||||
print("✓ No migrations directory found")
|
||||
print("[OK] No migrations directory found")
|
||||
return True
|
||||
|
||||
# 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))]
|
||||
|
||||
if not migration_files:
|
||||
print("✓ No migration files found")
|
||||
print("[OK] No migration files found")
|
||||
return True
|
||||
|
||||
# Apply pending migrations
|
||||
@@ -185,7 +185,7 @@ def run_migrations(migrations_dir="/app/migrations"):
|
||||
pending.append((filepath, filename))
|
||||
|
||||
if not pending:
|
||||
print(f"✓ All {len(applied)} migrations already applied")
|
||||
print(f"[OK] All {len(applied)} migrations already applied")
|
||||
return True
|
||||
|
||||
print(f" Found {len(pending)} pending migration(s)...")
|
||||
@@ -211,12 +211,12 @@ if __name__ == "__main__":
|
||||
if not load_schema():
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("✓ Schema already exists")
|
||||
print("[OK] Schema already exists")
|
||||
|
||||
# Run migrations
|
||||
print("\nRunning database migrations...")
|
||||
if not run_migrations():
|
||||
print("✗ Migration failed")
|
||||
print("[FAIL] Migration failed")
|
||||
sys.exit(1)
|
||||
|
||||
# Check for migration
|
||||
@@ -232,14 +232,14 @@ if __name__ == "__main__":
|
||||
from migrate_to_postgres import main as migrate
|
||||
migrate()
|
||||
except Exception as e:
|
||||
print(f"✗ Migration failed: {e}")
|
||||
print(f"[FAIL] Migration failed: {e}")
|
||||
sys.exit(1)
|
||||
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)")
|
||||
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:
|
||||
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),
|
||||
},
|
||||
)
|
||||
+65
-14
@@ -6,7 +6,7 @@ Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
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
|
||||
|
||||
|
||||
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_migrations: pending *.sql in einer Transaktion pro Datei, Buchführung schema_migrations)
|
||||
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
|
||||
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:
|
||||
try:
|
||||
import run_migrations
|
||||
|
||||
rc = run_migrations.main()
|
||||
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)
|
||||
print("✓ Database migrations completed")
|
||||
print("[OK] Database migrations completed")
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"✗ Migration-Laufzeitfehler: {e}")
|
||||
print(f"[FAIL] Migration-Laufzeitfehler: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
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
|
||||
app = FastAPI(
|
||||
title="Shinkan Jinkendo API",
|
||||
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)
|
||||
@@ -62,7 +86,13 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 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)
|
||||
@app.get("/api/version")
|
||||
@@ -99,6 +129,8 @@ def health_ready():
|
||||
"skill_categories",
|
||||
"maturity_models",
|
||||
"sessions",
|
||||
"club_members",
|
||||
"club_member_roles",
|
||||
)
|
||||
tables: dict = {}
|
||||
err: Optional[str] = None
|
||||
@@ -130,7 +162,7 @@ def health_ready():
|
||||
migration_count = 0
|
||||
|
||||
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
|
||||
return {
|
||||
body = {
|
||||
"status": "ready" if complete else "degraded",
|
||||
"database": err is None,
|
||||
"detail": err,
|
||||
@@ -138,38 +170,57 @@ def health_ready():
|
||||
"tables": tables,
|
||||
"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
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
"""Root endpoint - API info"""
|
||||
return {
|
||||
out = {
|
||||
"app": "Shinkan Jinkendo API",
|
||||
"version": APP_VERSION,
|
||||
"docs": "/docs",
|
||||
"health": "/health"
|
||||
"health": "/health",
|
||||
}
|
||||
if _expose_docs:
|
||||
out["docs"] = "/docs"
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, clubs, skills, training_planning, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
app.include_router(exercises.router)
|
||||
app.include_router(exercise_progression_graphs.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(skills.router)
|
||||
app.include_router(training_planning.router)
|
||||
app.include_router(training_framework_programs.router)
|
||||
app.include_router(catalogs.router)
|
||||
app.include_router(maturity_models.router)
|
||||
app.include_router(matrix_stack_bundle.router)
|
||||
app.include_router(import_wiki.router)
|
||||
app.include_router(import_wiki_admin.router)
|
||||
|
||||
# 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"))
|
||||
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__":
|
||||
import uvicorn
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""
|
||||
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")))
|
||||
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "90")))
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
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
|
||||
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()""",
|
||||
(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,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))
|
||||
@@ -2,6 +2,18 @@
|
||||
-- One-time import of skills with categories from karatetrainer.net
|
||||
-- Source: https://karatetrainer.net/index.php?title=Fähigkeitsmatrix
|
||||
|
||||
-- ON CONFLICT (name) erfordert einen UNIQUE-Constraint auf skills.name (003/007 legten keinen an)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint c
|
||||
JOIN pg_class t ON c.conrelid = t.oid
|
||||
WHERE t.relname = 'skills' AND c.contype = 'u' AND c.conname = 'skills_name_unique'
|
||||
) THEN
|
||||
ALTER TABLE skills ADD CONSTRAINT skills_name_unique UNIQUE (name);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Create skill categories first
|
||||
INSERT INTO skill_categories (name, description, sort_order) VALUES
|
||||
('Kihon', 'Grundtechniken', 1),
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Migration 032: Progressionsgraph zwischen Übungen (Übung → Übung), getrennt von Varianten-Progression (014).
|
||||
-- CURR-002 (1): gerichtete Kanten mit optionalem Graph-Kontainer; FK auf exercises; MVP edge_type erweiterbar.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exercise_progression_graphs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
visibility VARCHAR(50) NOT NULL DEFAULT 'private'
|
||||
CHECK (visibility IN ('private', 'club', 'official')),
|
||||
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_club ON exercise_progression_graphs(club_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_creator ON exercise_progression_graphs(created_by);
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_visibility ON exercise_progression_graphs(visibility);
|
||||
|
||||
DROP TRIGGER IF EXISTS exercise_progression_graphs_update ON exercise_progression_graphs;
|
||||
CREATE TRIGGER exercise_progression_graphs_update
|
||||
BEFORE UPDATE ON exercise_progression_graphs
|
||||
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exercise_progression_edges (
|
||||
id SERIAL PRIMARY KEY,
|
||||
graph_id INT NOT NULL REFERENCES exercise_progression_graphs(id) ON DELETE CASCADE,
|
||||
from_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||
to_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||
edge_type VARCHAR(50) NOT NULL DEFAULT 'next_exercise',
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
CHECK (from_exercise_id <> to_exercise_id),
|
||||
UNIQUE (graph_id, from_exercise_id, to_exercise_id, edge_type)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_progression_edges_graph ON exercise_progression_edges(graph_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_progression_edges_from ON exercise_progression_edges(from_exercise_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_progression_edges_to ON exercise_progression_edges(to_exercise_id);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Migration 033: Optionale Notiz / Entwicklungsziel pro Progressions-Kante (Übung→Übung).
|
||||
|
||||
ALTER TABLE exercise_progression_edges
|
||||
ADD COLUMN IF NOT EXISTS notes TEXT;
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Migration 034: Progressionskanten optional mit Übungsvarianten (Knoten = Übung oder konkrete Variante).
|
||||
-- UNIQUE und CHECK angepasst; Kanten innerhalb derselben Übung nur zwischen verschiedenen Varianten.
|
||||
|
||||
ALTER TABLE exercise_progression_edges
|
||||
ADD COLUMN IF NOT EXISTS from_exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE CASCADE,
|
||||
ADD COLUMN IF NOT EXISTS to_exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE CASCADE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_progression_edges_from_variant ON exercise_progression_edges(from_exercise_variant_id)
|
||||
WHERE from_exercise_variant_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_progression_edges_to_variant ON exercise_progression_edges(to_exercise_variant_id)
|
||||
WHERE to_exercise_variant_id IS NOT NULL;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TABLE exercise_progression_edges
|
||||
DROP CONSTRAINT exercise_progression_edges_graph_id_from_exercise_id_to_exercise_id_edge_type_key;
|
||||
EXCEPTION
|
||||
WHEN undefined_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TABLE exercise_progression_edges DROP CONSTRAINT exercise_progression_edges_check;
|
||||
EXCEPTION
|
||||
WHEN undefined_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
ALTER TABLE exercise_progression_edges ADD CONSTRAINT exercise_progression_edges_endpoints_distinct CHECK (
|
||||
(from_exercise_id <> to_exercise_id)
|
||||
OR (
|
||||
from_exercise_variant_id IS NOT NULL
|
||||
AND to_exercise_variant_id IS NOT NULL
|
||||
AND from_exercise_variant_id <> to_exercise_variant_id
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS exercise_progression_edges_unique_endpoints
|
||||
ON exercise_progression_edges (
|
||||
graph_id,
|
||||
from_exercise_id,
|
||||
COALESCE(from_exercise_variant_id, 0),
|
||||
to_exercise_id,
|
||||
COALESCE(to_exercise_variant_id, 0),
|
||||
edge_type
|
||||
);
|
||||
@@ -0,0 +1,92 @@
|
||||
-- Migration 035: Trainingsrahmenprogramm (Rahmen‑Vorlage, CURR‑002 Stufe 2 / CURR‑009–013)
|
||||
-- + CURR‑007/008: training_plan_templates.visibility (Backfill club, dann NOT NULL + Default)
|
||||
|
||||
-- ── Trainings‑Mikrovorlagen: gemeinsamer Governance‑Kern (visibility) ─────
|
||||
ALTER TABLE training_plan_templates
|
||||
ADD COLUMN IF NOT EXISTS visibility VARCHAR(50)
|
||||
CHECK (visibility IN ('private', 'club', 'official'));
|
||||
|
||||
UPDATE training_plan_templates
|
||||
SET visibility = 'club'
|
||||
WHERE visibility IS NULL;
|
||||
|
||||
ALTER TABLE training_plan_templates
|
||||
ALTER COLUMN visibility SET DEFAULT 'club';
|
||||
|
||||
ALTER TABLE training_plan_templates
|
||||
ALTER COLUMN visibility SET NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_plan_templates_visibility ON training_plan_templates(visibility);
|
||||
|
||||
-- ── Rahmen‑Header ────────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_programs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
plan_mode VARCHAR(20) NOT NULL
|
||||
CHECK (plan_mode IN ('concrete', 'library')),
|
||||
-- Modus B (library): immer NULL · Modus A (concrete): optional gebunden an eine Trainingsgruppe
|
||||
group_id INT REFERENCES training_groups(id) ON DELETE SET NULL,
|
||||
planned_period_start DATE,
|
||||
planned_period_end DATE,
|
||||
visibility VARCHAR(50) NOT NULL DEFAULT 'private'
|
||||
CHECK (visibility IN ('private', 'club', 'official')),
|
||||
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
CHECK (
|
||||
(plan_mode = 'library' AND group_id IS NULL)
|
||||
OR plan_mode = 'concrete'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_creator ON training_framework_programs(created_by);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_club ON training_framework_programs(club_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_visibility ON training_framework_programs(visibility);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_mode ON training_framework_programs(plan_mode);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_group ON training_framework_programs(group_id);
|
||||
|
||||
DROP TRIGGER IF EXISTS training_framework_programs_update ON training_framework_programs;
|
||||
CREATE TRIGGER training_framework_programs_update
|
||||
BEFORE UPDATE ON training_framework_programs
|
||||
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||
|
||||
-- ── Zielliste (CURR‑011: ≥ 1 durch API beim Speichern) ─────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_goals (
|
||||
id SERIAL PRIMARY KEY,
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
sort_order INT NOT NULL,
|
||||
title VARCHAR(500) NOT NULL,
|
||||
notes TEXT,
|
||||
UNIQUE (framework_program_id, sort_order)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_goals_framework ON training_framework_goals(framework_program_id);
|
||||
|
||||
-- ── Slots (Sessions im Rahmen) ──────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_slots (
|
||||
id SERIAL PRIMARY KEY,
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
sort_order INT NOT NULL,
|
||||
title VARCHAR(200),
|
||||
notes TEXT,
|
||||
training_unit_id INT REFERENCES training_units(id) ON DELETE SET NULL,
|
||||
UNIQUE (framework_program_id, sort_order)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_slots_framework ON training_framework_slots(framework_program_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_slots_unit ON training_framework_slots(training_unit_id);
|
||||
|
||||
-- ── Übungen pro Slot (tragende „Stückliste“, CURR‑010) ────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_slot_exercises (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slot_id INT NOT NULL REFERENCES training_framework_slots(id) ON DELETE CASCADE,
|
||||
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
|
||||
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
|
||||
order_index INT NOT NULL,
|
||||
UNIQUE (slot_id, order_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_slot_exercises_slot ON training_framework_slot_exercises(slot_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_slot_exercises_exercise ON training_framework_slot_exercises(exercise_id);
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Migration 036: Rahmenprogramm — nur Bibliothek + Kontext-Stammdaten (Fokus, Stil, Typen, Zielgruppen)
|
||||
-- Grund: Zuordnung zu Gruppen/Kalender nur aus der Planung (Kopie + Lineage), nicht am Rahmenkopf.
|
||||
|
||||
-- ── Kontext am Rahmenkopf (Zuordenbarkeit / Filter) ─────────────────────────
|
||||
ALTER TABLE training_framework_programs
|
||||
ADD COLUMN IF NOT EXISTS focus_area_id INT REFERENCES focus_areas(id) ON DELETE SET NULL,
|
||||
ADD COLUMN IF NOT EXISTS style_direction_id INT REFERENCES style_directions(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_focus ON training_framework_programs(focus_area_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_style ON training_framework_programs(style_direction_id);
|
||||
|
||||
-- ── M:N Trainingsstile (training_types Katalog) ─────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_program_training_types (
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
training_type_id INT NOT NULL REFERENCES training_types(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (framework_program_id, training_type_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tfptt_type ON training_framework_program_training_types(training_type_id);
|
||||
|
||||
-- ── M:N Zielgruppen ─────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_framework_program_target_groups (
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
target_group_id INT NOT NULL REFERENCES target_groups(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (framework_program_id, target_group_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tfptg_tg ON training_framework_program_target_groups(target_group_id);
|
||||
|
||||
-- ── Kein „Konkret“ mehr: Slots nicht an Kalender-Einheiten hängen ───────────
|
||||
UPDATE training_framework_slots SET training_unit_id = NULL WHERE training_unit_id IS NOT NULL;
|
||||
|
||||
-- Gruppe/Modus vom Rahmen lösen (Historie: evtl. noch concrete + group_id gesetzt)
|
||||
UPDATE training_framework_programs SET group_id = NULL;
|
||||
|
||||
DROP INDEX IF EXISTS idx_training_framework_programs_group;
|
||||
|
||||
ALTER TABLE training_framework_programs DROP CONSTRAINT IF EXISTS training_framework_programs_group_id_fkey;
|
||||
|
||||
ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS group_id;
|
||||
|
||||
-- Inline-CHECK(s) aus Migration 035 (plan_mode + group-Kombination) entfernen
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT c.conname AS cn
|
||||
FROM pg_constraint c
|
||||
WHERE c.conrelid = 'public.training_framework_programs'::regclass
|
||||
AND c.contype = 'c'
|
||||
AND (
|
||||
pg_get_constraintdef(c.oid) ILIKE '%plan_mode%'
|
||||
OR pg_get_constraintdef(c.oid) ILIKE '%group_id%'
|
||||
)
|
||||
)
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE training_framework_programs DROP CONSTRAINT %I', r.cn);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS plan_mode;
|
||||
|
||||
DROP INDEX IF EXISTS idx_training_framework_programs_mode;
|
||||
@@ -0,0 +1,130 @@
|
||||
-- Migration 037: Rahmen-Slot-„Blueprint“ = eine training_units-Zeile (Ablauf wie echte Einheit)
|
||||
-- training_framework_slot_exercises migriert nach training_unit_sections / training_unit_section_items,
|
||||
-- dann entfernt.
|
||||
|
||||
-- ── Neue Spalten ───────────────────────────────────────────────────────────────
|
||||
ALTER TABLE training_units
|
||||
ADD COLUMN IF NOT EXISTS framework_slot_id INT REFERENCES training_framework_slots(id)
|
||||
ON DELETE CASCADE,
|
||||
ADD COLUMN IF NOT EXISTS origin_framework_slot_id INT REFERENCES training_framework_slots(id)
|
||||
ON DELETE SET NULL;
|
||||
|
||||
-- Genau eine Blueprint-Einheit pro Slot (PostgreSQL UNIQUE erlaubt mehrere NULLs — hier Partial Index)
|
||||
DROP INDEX IF EXISTS uq_training_units_blueprint_slot;
|
||||
|
||||
CREATE UNIQUE INDEX uq_training_units_blueprint_slot
|
||||
ON training_units(framework_slot_id)
|
||||
WHERE framework_slot_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_framework_blueprint_calendar
|
||||
ON training_units(planned_date, group_id)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_origin_slot
|
||||
ON training_units(origin_framework_slot_id)
|
||||
WHERE origin_framework_slot_id IS NOT NULL;
|
||||
|
||||
-- ── Nullable für Blueprint-Zeilen ────────────────────────────────────────────
|
||||
ALTER TABLE training_units ALTER COLUMN planned_date DROP NOT NULL;
|
||||
ALTER TABLE training_units ALTER COLUMN group_id DROP NOT NULL;
|
||||
|
||||
-- ── Für jeden Slot eine Blueprint-Einheit; vorhandene Übungen in erste Sektion ─
|
||||
DO $$
|
||||
DECLARE
|
||||
rec RECORD;
|
||||
new_uid INTEGER;
|
||||
new_sec INTEGER;
|
||||
BEGIN
|
||||
FOR rec IN
|
||||
SELECT s.id AS sid, fp.created_by AS fp_created_by
|
||||
FROM training_framework_slots s
|
||||
JOIN training_framework_programs fp ON fp.id = s.framework_program_id
|
||||
LOOP
|
||||
IF EXISTS (SELECT 1 FROM training_units tu WHERE tu.framework_slot_id = rec.sid) THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
|
||||
INSERT INTO training_units (
|
||||
group_id,
|
||||
planned_date,
|
||||
planned_time_start,
|
||||
planned_time_end,
|
||||
planned_focus,
|
||||
status,
|
||||
notes,
|
||||
trainer_notes,
|
||||
created_by,
|
||||
plan_template_id,
|
||||
framework_slot_id
|
||||
)
|
||||
VALUES (
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'planned',
|
||||
NULL,
|
||||
NULL,
|
||||
rec.fp_created_by,
|
||||
NULL,
|
||||
rec.sid
|
||||
)
|
||||
RETURNING id INTO new_uid;
|
||||
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id,
|
||||
order_index,
|
||||
title,
|
||||
guidance_notes
|
||||
)
|
||||
VALUES (new_uid, 0, 'Ablauf', NULL)
|
||||
RETURNING id INTO new_sec;
|
||||
|
||||
INSERT INTO training_unit_section_items (
|
||||
section_id,
|
||||
order_index,
|
||||
item_type,
|
||||
exercise_id,
|
||||
exercise_variant_id,
|
||||
planned_duration_min,
|
||||
actual_duration_min,
|
||||
notes,
|
||||
modifications,
|
||||
note_body
|
||||
)
|
||||
SELECT
|
||||
new_sec,
|
||||
sf.order_index,
|
||||
'exercise'::character varying(20),
|
||||
sf.exercise_id,
|
||||
sf.exercise_variant_id,
|
||||
NULL::integer,
|
||||
NULL::integer,
|
||||
NULL::text,
|
||||
NULL::text,
|
||||
NULL::text
|
||||
FROM training_framework_slot_exercises sf
|
||||
WHERE sf.slot_id = rec.sid
|
||||
ORDER BY sf.order_index;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
DROP TABLE IF EXISTS training_framework_slot_exercises;
|
||||
|
||||
ALTER TABLE training_units DROP CONSTRAINT IF EXISTS chk_training_units_blueprint_vs_scheduled;
|
||||
|
||||
ALTER TABLE training_units
|
||||
ADD CONSTRAINT chk_training_units_blueprint_vs_scheduled CHECK (
|
||||
(
|
||||
framework_slot_id IS NOT NULL
|
||||
AND group_id IS NULL
|
||||
AND planned_date IS NULL
|
||||
AND origin_framework_slot_id IS NULL
|
||||
)
|
||||
OR (
|
||||
framework_slot_id IS NULL
|
||||
AND group_id IS NOT NULL
|
||||
AND planned_date IS NOT NULL
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Migration 038: Optionale verantwortliche Person pro Trainingstermin (Vertretung)
|
||||
-- Für Vereins-/Trainerübersicht: COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) = wirksamer Leitungstrainer.
|
||||
|
||||
ALTER TABLE training_units
|
||||
ADD COLUMN IF NOT EXISTS lead_trainer_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL;
|
||||
|
||||
COMMENT ON COLUMN training_units.lead_trainer_profile_id IS 'Vertretung / expliziter Leiter dieses Terms; NULL = Standard (Haupttrainer der Gruppe)';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_lead_trainer
|
||||
ON training_units(lead_trainer_profile_id)
|
||||
WHERE lead_trainer_profile_id IS NOT NULL;
|
||||
@@ -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);
|
||||
+16
-3
@@ -4,7 +4,7 @@ Pydantic Models for Shinkan Jinkendo API
|
||||
Request/Response schemas for all endpoints
|
||||
"""
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional, List
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import date, time, datetime
|
||||
|
||||
# ============================================================================
|
||||
@@ -19,6 +19,7 @@ class RegisterRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
name: Optional[str] = None
|
||||
requested_club_id: Optional[int] = Field(default=None, ge=1)
|
||||
|
||||
class PasswordResetRequest(BaseModel):
|
||||
email: str
|
||||
@@ -28,12 +29,24 @@ class PasswordResetConfirm(BaseModel):
|
||||
new_password: str
|
||||
|
||||
class ProfileCreate(BaseModel):
|
||||
name: str
|
||||
email: Optional[str] = None
|
||||
"""Nur für POST /api/profiles (Plattform-Admin): neues Nutzerprofil ohne Self-Registration."""
|
||||
|
||||
name: str = Field(min_length=2, max_length=200)
|
||||
email: EmailStr
|
||||
|
||||
class ProfileUpdate(BaseModel):
|
||||
name: 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",
|
||||
)
|
||||
|
||||
class ProfileResponse(BaseModel):
|
||||
id: int
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Gemeinsame Passwort-Link-Erzeugung (Sessions) + Mailtext — wie /auth/forgot-password."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
RESET_TOKEN_PREFIX = "reset_"
|
||||
|
||||
|
||||
def public_reset_link(token: str) -> str:
|
||||
base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
return f"{base}/reset-password?token={token}"
|
||||
|
||||
|
||||
def revoke_pending_password_resets_for_profile(cur: Any, profile_id: int) -> None:
|
||||
"""Entfernt alte Reset-Sessions eines Profils, damit nur der neueste Link aktiv ist."""
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE profile_id = %s AND token LIKE %s
|
||||
""",
|
||||
(profile_id, f"{RESET_TOKEN_PREFIX}%"),
|
||||
)
|
||||
|
||||
|
||||
def insert_password_reset_session(cur: Any, profile_id: int, *, hours_valid: int = 1) -> str:
|
||||
"""
|
||||
Legt reset_<token>-Session an. Gibt den Klartext-Token zurück (wie bei forgot-password).
|
||||
"""
|
||||
raw = secrets.token_urlsafe(32)
|
||||
expires = datetime.now() + timedelta(hours=hours_valid)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token, profile_id, expires_at, created_at)
|
||||
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
|
||||
""",
|
||||
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def password_reset_email_body(*, recipient_name: str | None, token: str, intro: str) -> str:
|
||||
name = (recipient_name or "").strip() or "Kollege/Kollegin"
|
||||
link = public_reset_link(token)
|
||||
return f"""Hallo {name},
|
||||
|
||||
{intro}
|
||||
|
||||
Neues Passwort setzen:
|
||||
{link}
|
||||
|
||||
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
|
||||
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
|
||||
|
||||
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
|
||||
|
||||
def issue_password_reset_via_email(cur: Any, send_email_fn, *, profile_id: int, email: str, name: str | None, intro: str) -> bool:
|
||||
"""Session anlegen und Mail schicken (send_email_fn wie routers.auth.send_email)."""
|
||||
revoke_pending_password_resets_for_profile(cur, profile_id)
|
||||
raw_token = insert_password_reset_session(cur, profile_id)
|
||||
body = password_reset_email_body(recipient_name=name, token=raw_token, intro=intro)
|
||||
return send_email_fn(email, "Passwort-Link – Shinkan Jinkendo", body)
|
||||
@@ -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-Mandanten-Integration (ACCESS_LAYER_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
|
||||
+46
-28
@@ -20,13 +20,18 @@ from slowapi.util import get_remote_address
|
||||
from db import get_db, get_cursor
|
||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
||||
from password_reset_mail import (
|
||||
insert_password_reset_session,
|
||||
password_reset_email_body,
|
||||
revoke_pending_password_resets_for_profile,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
@limiter.limit("5/minute")
|
||||
@limiter.limit("30/minute")
|
||||
async def login(req: LoginRequest, request: Request):
|
||||
"""Login with email + password."""
|
||||
with get_db() as conn:
|
||||
@@ -78,8 +83,8 @@ def get_me(session: dict=Depends(require_auth)):
|
||||
"""Get current user info."""
|
||||
pid = session['profile_id']
|
||||
# Import here to avoid circular dependency
|
||||
from routers.profiles import get_profile
|
||||
return get_profile(pid, session)
|
||||
from routers.profiles import profile_document
|
||||
return profile_document(pid)
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
@@ -116,28 +121,14 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
|
||||
if not prof:
|
||||
# Don't reveal if email exists
|
||||
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||
revoke_pending_password_resets_for_profile(cur, prof["id"])
|
||||
raw_token = insert_password_reset_session(cur, prof["id"])
|
||||
|
||||
# Generate reset token
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now() + timedelta(hours=1)
|
||||
|
||||
# Store in sessions table (reuse mechanism)
|
||||
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||
(f"reset_{token}", prof['id'], expires.isoformat()))
|
||||
|
||||
app_base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
reset_body = f"""Hallo {prof['name']},
|
||||
|
||||
Du hast einen Passwort-Reset angefordert.
|
||||
|
||||
Reset-Link: {app_base}/reset-password?token={token}
|
||||
|
||||
Der Link ist 1 Stunde gültig.
|
||||
|
||||
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
reset_body = password_reset_email_body(
|
||||
recipient_name=prof.get("name"),
|
||||
token=raw_token,
|
||||
intro="Du hast einen Passwort-Reset angefordert.",
|
||||
)
|
||||
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
||||
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
||||
|
||||
@@ -187,9 +178,10 @@ def verification_link(token: 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).
|
||||
|
||||
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.
|
||||
"""
|
||||
bootstrap = {
|
||||
@@ -198,7 +190,7 @@ def registration_role(cur, email_lower: str) -> str:
|
||||
if x.strip()
|
||||
}
|
||||
if email_lower in bootstrap:
|
||||
return "admin"
|
||||
return "superadmin"
|
||||
if os.getenv("AUTO_ADMIN_FIRST_USER", "true").strip().lower() not in ("1", "true", "yes"):
|
||||
return "trainer"
|
||||
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
|
||||
except (KeyError, TypeError, ValueError):
|
||||
n = 0
|
||||
return "admin" if n == 0 else "trainer"
|
||||
return "superadmin" if n == 0 else "trainer"
|
||||
|
||||
|
||||
# ── Helper: Send Email ────────────────────────────────────────────────────────
|
||||
@@ -289,7 +281,7 @@ async def register(req: RegisterRequest, request: Request):
|
||||
verification_token = secrets.token_urlsafe(32)
|
||||
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)
|
||||
|
||||
# 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,
|
||||
trial_ends_at, created_at
|
||||
) 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))
|
||||
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)
|
||||
|
||||
|
||||
@@ -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}
|
||||
+431
-182
@@ -3,37 +3,101 @@ Club & Organization Management Endpoints for Shinkan Jinkendo
|
||||
|
||||
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 psycopg2.extras import Json
|
||||
|
||||
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"])
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> Any:
|
||||
"""Frontend sendet häufig '' für optionale Felder — ungültig für PostgreSQL TIME/INTEGER."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == "":
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _optional_int(value: Any) -> Optional[int]:
|
||||
v = _blank_to_none(value)
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
i = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return i if i > 0 else None
|
||||
|
||||
|
||||
def _normalize_co_trainer_ids(val: Any) -> List[int]:
|
||||
"""Listen von Profil-IDs für JSONB; ungültige Einträge werden verworfen."""
|
||||
if val is None:
|
||||
raw: List[Any] = []
|
||||
elif isinstance(val, list):
|
||||
raw = val
|
||||
else:
|
||||
raw = []
|
||||
out: List[int] = []
|
||||
seen = set()
|
||||
for x in raw:
|
||||
try:
|
||||
i = int(x)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if i <= 0 or i in seen:
|
||||
continue
|
||||
seen.add(i)
|
||||
out.append(i)
|
||||
return out
|
||||
|
||||
|
||||
def _co_trainer_ids_jsonb(val: Any) -> Json:
|
||||
"""psycopg2: reine list/dict für JSONB → ProgrammingError ohne Json()."""
|
||||
return Json(_normalize_co_trainer_ids(val))
|
||||
|
||||
|
||||
# ── List Clubs ────────────────────────────────────────────────────────
|
||||
@router.get("/clubs")
|
||||
def list_clubs(
|
||||
status: Optional[str] = Query(default=None),
|
||||
session=Depends(require_auth)
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
List all clubs (public for authenticated users).
|
||||
|
||||
Filters:
|
||||
- status: active, inactive
|
||||
Vereine: für normale Nutzer nur Mitgliedschaft-Vereine; Plattform-Admins sehen alle.
|
||||
"""
|
||||
role = tenant.global_role
|
||||
profile_id = tenant.profile_id
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
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:
|
||||
query += " WHERE status = %s"
|
||||
conds.append("status = %s")
|
||||
params.append(status)
|
||||
|
||||
if conds:
|
||||
query += " WHERE " + " AND ".join(conds)
|
||||
|
||||
query += " ORDER BY name"
|
||||
|
||||
cur.execute(query, params)
|
||||
@@ -41,12 +105,64 @@ def list_clubs(
|
||||
return [r2d(r) for r in rows]
|
||||
|
||||
|
||||
# ── Get Club ──────────────────────────────────────────────────────────
|
||||
@router.get("/clubs/{club_id}")
|
||||
def get_club(club_id: int, session=Depends(require_auth)):
|
||||
"""Get club by ID with divisions and groups."""
|
||||
# ── Öffentliches Vereinsverzeichnis (Registrierung / Antrag ohne Mitgliedschaft) ──
|
||||
@router.get("/clubs/public-directory")
|
||||
def public_club_directory():
|
||||
"""Aktive Vereine zur Auswahl bei Registrierung oder Beitrittsantrag (nur id, name, Kürzel)."""
|
||||
with get_db() as 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
|
||||
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)
|
||||
|
||||
# Get divisions
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT * FROM divisions
|
||||
WHERE club_id = %s
|
||||
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
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
p.name as trainer_name
|
||||
FROM training_groups g
|
||||
LEFT JOIN profiles p ON g.trainer_id = p.id
|
||||
WHERE g.club_id = %s
|
||||
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
|
||||
|
||||
|
||||
# ── Create Club ───────────────────────────────────────────────────────
|
||||
@router.post("/clubs")
|
||||
def create_club(data: dict, session=Depends(require_auth)):
|
||||
"""Create new club (Admin oder Trainer — MVP ohne separates Vereins-Onboarding)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
||||
raise HTTPException(403, "Keine Berechtigung, Vereine anzulegen")
|
||||
def create_club(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Neuen Verein anlegen – nur Plattform-Admin; Pflicht: primary_admin_profile_id (Hauptverwalter:in)."""
|
||||
role = tenant.global_role
|
||||
if not is_platform_admin(role):
|
||||
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:
|
||||
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:
|
||||
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("""
|
||||
INSERT INTO clubs (name, abbreviation, description, status)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO clubs (name, abbreviation, description, status, primary_admin_profile_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
name,
|
||||
data.get('abbreviation'),
|
||||
data.get('description'),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
""",
|
||||
(
|
||||
name,
|
||||
data.get("abbreviation"),
|
||||
data.get("description"),
|
||||
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()
|
||||
|
||||
return get_club(club_id, session)
|
||||
return get_club(club_id, tenant)
|
||||
|
||||
|
||||
# ── Update Club ───────────────────────────────────────────────────────
|
||||
@router.put("/clubs/{club_id}")
|
||||
def update_club(club_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update club (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Vereine bearbeiten")
|
||||
def update_club(club_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Verein bearbeiten – Plattform-Admin oder Vereinsadmin."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as 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():
|
||||
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
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE clubs SET
|
||||
name = %s,
|
||||
abbreviation = %s,
|
||||
description = %s,
|
||||
status = %s,
|
||||
name = COALESCE(%s, name),
|
||||
abbreviation = COALESCE(%s, abbreviation),
|
||||
description = COALESCE(%s, description),
|
||||
status = COALESCE(%s, status),
|
||||
primary_admin_profile_id = COALESCE(%s, primary_admin_profile_id),
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('abbreviation'),
|
||||
data.get('description'),
|
||||
data.get('status'),
|
||||
club_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("abbreviation"),
|
||||
data.get("description"),
|
||||
data.get("status"),
|
||||
data.get("primary_admin_profile_id"),
|
||||
club_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
return get_club(club_id, session)
|
||||
return get_club(club_id, tenant)
|
||||
|
||||
|
||||
# ── Delete Club ───────────────────────────────────────────────────────
|
||||
@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)."""
|
||||
role = session.get('role')
|
||||
role = tenant.global_role
|
||||
if role != 'superadmin':
|
||||
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")
|
||||
def list_divisions(
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
mine = club_ids_for_profile(cur, profile_id)
|
||||
if not is_platform_admin(role) and not mine:
|
||||
return []
|
||||
|
||||
query = """
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
"""
|
||||
where = []
|
||||
params = []
|
||||
|
||||
if club_id:
|
||||
query += " WHERE d.club_id = %s"
|
||||
if club_id is not None:
|
||||
where.append("d.club_id = %s")
|
||||
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"
|
||||
|
||||
@@ -202,14 +392,13 @@ def list_divisions(
|
||||
|
||||
# ── Create Division ───────────────────────────────────────────────────
|
||||
@router.post("/divisions")
|
||||
def create_division(data: dict, session=Depends(require_auth)):
|
||||
"""Create new division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten erstellen")
|
||||
def create_division(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Create new division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
club_id = data.get('club_id')
|
||||
name = data.get('name')
|
||||
club_id = data.get("club_id")
|
||||
name = data.get("name")
|
||||
|
||||
if not club_id or not name:
|
||||
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:
|
||||
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
|
||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Verein nicht gefunden")
|
||||
|
||||
# Insert
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO divisions (club_id, name, focus_area)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
club_id,
|
||||
name,
|
||||
data.get('focus_area')
|
||||
))
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
name,
|
||||
data.get("focus_area"),
|
||||
),
|
||||
)
|
||||
|
||||
division_id = cur.fetchone()['id']
|
||||
division_id = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
# Return created division
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
WHERE d.id = %s
|
||||
""", (division_id,))
|
||||
""",
|
||||
(division_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
# ── Update Division ───────────────────────────────────────────────────
|
||||
@router.put("/divisions/{division_id}")
|
||||
def update_division(division_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten bearbeiten")
|
||||
def update_division(division_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Update division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||
div = cur.fetchone()
|
||||
if not div:
|
||||
raise HTTPException(404, "Sparte nicht gefunden")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE divisions SET
|
||||
name = %s,
|
||||
focus_area = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('focus_area'),
|
||||
division_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("focus_area"),
|
||||
division_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Return updated division
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
WHERE d.id = %s
|
||||
""", (division_id,))
|
||||
""",
|
||||
(division_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
# ── Delete Division ───────────────────────────────────────────────────
|
||||
@router.delete("/divisions/{division_id}")
|
||||
def delete_division(division_id: int, session=Depends(require_auth)):
|
||||
"""Delete division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten löschen")
|
||||
def delete_division(division_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Delete division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||
div = cur.fetchone()
|
||||
if not div:
|
||||
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,))
|
||||
conn.commit()
|
||||
|
||||
@@ -316,19 +521,21 @@ def list_training_groups(
|
||||
club_id: Optional[int] = Query(default=None),
|
||||
division_id: Optional[int] = 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.
|
||||
|
||||
Filters:
|
||||
- club_id: Filter by club
|
||||
- division_id: Filter by division
|
||||
- status: active, inactive
|
||||
Trainingsgruppen – ohne Plattform-Admin nur in eigenen Vereinen.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
mine = club_ids_for_profile(cur, profile_id)
|
||||
if not is_platform_admin(role) and not mine:
|
||||
return []
|
||||
|
||||
query = """
|
||||
SELECT g.*,
|
||||
c.name as club_name,
|
||||
@@ -343,11 +550,13 @@ def list_training_groups(
|
||||
where = []
|
||||
params = []
|
||||
|
||||
if club_id:
|
||||
if club_id is not None:
|
||||
where.append("g.club_id = %s")
|
||||
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")
|
||||
params.append(division_id)
|
||||
|
||||
@@ -355,6 +564,10 @@ def list_training_groups(
|
||||
where.append("g.status = %s")
|
||||
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:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
|
||||
@@ -367,12 +580,15 @@ def list_training_groups(
|
||||
|
||||
# ── Get Training Group ────────────────────────────────────────────────
|
||||
@router.get("/groups/{group_id}")
|
||||
def get_training_group(group_id: int, session=Depends(require_auth)):
|
||||
"""Get training group by ID."""
|
||||
def get_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Trainingsgruppe – nur mit Vereinszugriff."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
c.name as club_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 profiles p ON g.trainer_id = p.id
|
||||
WHERE g.id = %s
|
||||
""", (group_id,))
|
||||
""",
|
||||
(group_id,),
|
||||
)
|
||||
|
||||
group = cur.fetchone()
|
||||
|
||||
if not group:
|
||||
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)
|
||||
|
||||
|
||||
# ── Create Training Group ─────────────────────────────────────────────
|
||||
@router.post("/groups")
|
||||
def create_training_group(data: dict, session=Depends(require_auth)):
|
||||
"""Create new training group (admin, trainer oder normaler Nutzer mit Vereinsbezug)."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
||||
def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Trainingsgruppe anlegen – Mitglied mit Planungs-/Admin-Rolle im Verein."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
if role not in ("admin", "superadmin", "trainer", "user"):
|
||||
raise HTTPException(403, "Keine Berechtigung, Trainingsgruppen anzulegen")
|
||||
|
||||
club_id = data.get('club_id')
|
||||
name = data.get('name')
|
||||
club_id = data.get("club_id")
|
||||
name = data.get("name")
|
||||
|
||||
if not club_id or not name:
|
||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||
|
||||
trainer_id = data.get('trainer_id')
|
||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
||||
trainer_id = profile_id
|
||||
raw_tid = data.get("trainer_id")
|
||||
if role in ("trainer", "user"):
|
||||
parsed_tid = _optional_int(raw_tid)
|
||||
trainer_id = parsed_tid if parsed_tid is not None else profile_id
|
||||
else:
|
||||
trainer_id = _optional_int(raw_tid)
|
||||
|
||||
division_id = _optional_int(data.get("division_id"))
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
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
|
||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Verein nicht gefunden")
|
||||
|
||||
# Insert
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_groups (
|
||||
club_id, division_id, name, focus, level, age_group,
|
||||
weekday, time_start, time_end, location,
|
||||
@@ -428,52 +660,66 @@ def create_training_group(data: dict, session=Depends(require_auth)):
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
%s, %s::jsonb, %s
|
||||
) RETURNING id
|
||||
""", (
|
||||
club_id,
|
||||
data.get('division_id'),
|
||||
name,
|
||||
data.get('focus'),
|
||||
data.get('level'),
|
||||
data.get('age_group'),
|
||||
data.get('weekday'),
|
||||
data.get('time_start'),
|
||||
data.get('time_end'),
|
||||
data.get('location'),
|
||||
trainer_id,
|
||||
data.get('co_trainer_ids'),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
""",
|
||||
(
|
||||
int(club_id),
|
||||
division_id,
|
||||
name,
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
trainer_id,
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
),
|
||||
)
|
||||
|
||||
group_id = cur.fetchone()['id']
|
||||
group_id = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
return get_training_group(group_id, session)
|
||||
return get_training_group(group_id, tenant)
|
||||
|
||||
|
||||
# ── Update Training Group ─────────────────────────────────────────────
|
||||
@router.put("/groups/{group_id}")
|
||||
def update_training_group(group_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update training group (admin or assigned trainer)."""
|
||||
profile_id = session['profile_id']
|
||||
role = session.get('role')
|
||||
def update_training_group(group_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Update training group – Vereinsadmin, Plattform-Admin oder zugewiesene Trainer."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence and ownership
|
||||
cur.execute("SELECT trainer_id FROM training_groups WHERE id = %s", (group_id,))
|
||||
cur.execute(
|
||||
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
|
||||
(group_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||
|
||||
# Only admin or assigned trainer can update
|
||||
if role not in ['admin', 'superadmin'] and row['trainer_id'] != profile_id:
|
||||
co_trainers = row["co_trainer_ids"] or []
|
||||
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")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE training_groups SET
|
||||
name = %s,
|
||||
division_id = %s,
|
||||
@@ -485,48 +731,51 @@ def update_training_group(group_id: int, data: dict, session=Depends(require_aut
|
||||
time_end = %s,
|
||||
location = %s,
|
||||
trainer_id = %s,
|
||||
co_trainer_ids = %s,
|
||||
co_trainer_ids = %s::jsonb,
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('division_id'),
|
||||
data.get('focus'),
|
||||
data.get('level'),
|
||||
data.get('age_group'),
|
||||
data.get('weekday'),
|
||||
data.get('time_start'),
|
||||
data.get('time_end'),
|
||||
data.get('location'),
|
||||
data.get('trainer_id'),
|
||||
data.get('co_trainer_ids'),
|
||||
data.get('status'),
|
||||
group_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
_optional_int(data.get("division_id")),
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
_optional_int(data.get("trainer_id")),
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
group_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
return get_training_group(group_id, session)
|
||||
return get_training_group(group_id, tenant)
|
||||
|
||||
|
||||
# ── Delete Training Group ─────────────────────────────────────────────
|
||||
@router.delete("/groups/{group_id}")
|
||||
def delete_training_group(group_id: int, session=Depends(require_auth)):
|
||||
"""Delete training group (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Gruppen löschen")
|
||||
def delete_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""Delete training group – Vereinsadmin oder Plattform-Admin."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM training_groups WHERE id = %s", (group_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM training_groups WHERE id = %s", (group_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
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,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
"""
|
||||
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
|
||||
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
||||
AuthZ analog training_plan_templates (_template_access / _has_planning_role).
|
||||
"""
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from psycopg2 import IntegrityError
|
||||
|
||||
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
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["exercises"])
|
||||
|
||||
|
||||
class ProgressionGraphCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=200)
|
||||
description: Optional[str] = None
|
||||
visibility: str = Field(default="private", pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
|
||||
|
||||
class ProgressionGraphUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||
description: Optional[str] = None
|
||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
|
||||
|
||||
class ProgressionEdgeCreate(BaseModel):
|
||||
from_exercise_id: int = Field(..., gt=0)
|
||||
to_exercise_id: int = Field(..., gt=0)
|
||||
from_exercise_variant_id: Optional[int] = Field(default=None)
|
||||
to_exercise_variant_id: Optional[int] = Field(default=None)
|
||||
edge_type: str = Field(default="next_exercise", min_length=1, max_length=50)
|
||||
notes: Optional[str] = Field(None, max_length=4000)
|
||||
|
||||
|
||||
class ProgressionEdgeUpdate(BaseModel):
|
||||
notes: Optional[str] = Field(None, max_length=4000)
|
||||
|
||||
|
||||
class SequenceStep(BaseModel):
|
||||
exercise_id: int = Field(..., gt=0)
|
||||
variant_id: Optional[int] = Field(default=None)
|
||||
|
||||
|
||||
class ProgressionSequenceCreate(BaseModel):
|
||||
steps: List[SequenceStep] = Field(..., min_length=2)
|
||||
segment_notes: Optional[List[Optional[str]]] = None
|
||||
"""Länge muss len(steps)-1 sein, wenn gesetzt; Notiz pro Kante Zwischen je zwei Schritten."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_segment_notes_len(self):
|
||||
if self.segment_notes is not None and len(self.segment_notes) != len(self.steps) - 1:
|
||||
raise ValueError(
|
||||
f"segment_notes muss genau {len(self.steps) - 1} Einträge haben (len(steps)-1)"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class EdgeIdsBatch(BaseModel):
|
||||
edge_ids: List[int] = Field(..., min_length=1)
|
||||
|
||||
|
||||
_EDGE_SELECT = """
|
||||
SELECT e.id, e.graph_id,
|
||||
e.from_exercise_id, e.from_exercise_variant_id,
|
||||
e.to_exercise_id, e.to_exercise_variant_id,
|
||||
e.edge_type, e.notes, e.created_at,
|
||||
ef.title AS from_exercise_title, et.title AS to_exercise_title,
|
||||
vf.variant_name AS from_variant_name, vt.variant_name AS to_variant_name
|
||||
FROM exercise_progression_edges e
|
||||
JOIN exercises ef ON ef.id = e.from_exercise_id
|
||||
JOIN exercises et ON et.id = e.to_exercise_id
|
||||
LEFT JOIN exercise_variants vf ON vf.id = e.from_exercise_variant_id
|
||||
LEFT JOIN exercise_variants vt ON vt.id = e.to_exercise_variant_id
|
||||
"""
|
||||
|
||||
|
||||
def _graph_row(cur, graph_id: int) -> dict:
|
||||
cur.execute(
|
||||
"SELECT * FROM exercise_progression_graphs WHERE id = %s",
|
||||
(graph_id,),
|
||||
)
|
||||
r = cur.fetchone()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Progressionsgraph nicht gefunden")
|
||||
return r2d(r)
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _assert_exercises_exist(cur, *exercise_ids: int) -> None:
|
||||
unique_ids = list(dict.fromkeys(exercise_ids))
|
||||
if not unique_ids:
|
||||
return
|
||||
cur.execute(
|
||||
f"SELECT id FROM exercises WHERE id IN ({','.join(['%s'] * len(unique_ids))})",
|
||||
tuple(unique_ids),
|
||||
)
|
||||
found = {r["id"] if isinstance(r, dict) else r[0] for r in cur.fetchall()}
|
||||
missing = set(unique_ids) - found
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unbekannte Übung(en): {sorted(missing)}",
|
||||
)
|
||||
|
||||
|
||||
def _assert_variant_for_exercise(cur, exercise_id: int, variant_id: Optional[int]) -> None:
|
||||
if variant_id is None:
|
||||
return
|
||||
cur.execute(
|
||||
"SELECT exercise_id FROM exercise_variants WHERE id = %s",
|
||||
(variant_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=400, detail=f"Unbekannte Variante: {variant_id}")
|
||||
ev_ex = row["exercise_id"] if isinstance(row, dict) else row[0]
|
||||
if ev_ex != exercise_id:
|
||||
raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung")
|
||||
|
||||
|
||||
def _insert_edge_row(
|
||||
cur,
|
||||
graph_id: int,
|
||||
from_exercise_id: int,
|
||||
from_variant_id: Optional[int],
|
||||
to_exercise_id: int,
|
||||
to_variant_id: Optional[int],
|
||||
edge_type: str,
|
||||
notes: Optional[str],
|
||||
) -> dict:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercise_progression_edges (
|
||||
graph_id,
|
||||
from_exercise_id, from_exercise_variant_id,
|
||||
to_exercise_id, to_exercise_variant_id,
|
||||
edge_type, notes
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
graph_id,
|
||||
from_exercise_id,
|
||||
from_variant_id,
|
||||
to_exercise_id,
|
||||
to_variant_id,
|
||||
edge_type,
|
||||
notes,
|
||||
),
|
||||
)
|
||||
new_id = cur.fetchone()["id"]
|
||||
cur.execute(_EDGE_SELECT + " WHERE e.id = %s", (new_id,))
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.get("/exercise-progression-graphs")
|
||||
def list_progression_graphs(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_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/exercise-progression-graphs/{graph_id}")
|
||||
def get_progression_graph(
|
||||
graph_id: int,
|
||||
include_edges: bool = Query(default=False),
|
||||
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 = _require_graph_read(cur, graph_id, profile_id, role)
|
||||
if include_edges:
|
||||
cur.execute(
|
||||
_EDGE_SELECT + " WHERE e.graph_id = %s ORDER BY e.id",
|
||||
(graph_id,),
|
||||
)
|
||||
row["edges"] = [r2d(r) for r in cur.fetchall()]
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/exercise-progression-graphs", status_code=201)
|
||||
def create_progression_graph(
|
||||
body: ProgressionGraphCreate,
|
||||
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="Keine Berechtigung zum Anlegen von Progressionsgraphen")
|
||||
|
||||
name = body.name.strip()
|
||||
if not name:
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, gov_club)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercise_progression_graphs (name, description, visibility, club_id, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(name, body.description, vis, cid if vis == "club" else None, profile_id),
|
||||
)
|
||||
gid = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
return get_progression_graph(gid, include_edges=False, tenant=tenant)
|
||||
|
||||
|
||||
@router.put("/exercise-progression-graphs/{graph_id}")
|
||||
def update_progression_graph(
|
||||
graph_id: int,
|
||||
body: ProgressionGraphUpdate,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
original = body.model_dump(exclude_unset=True)
|
||||
if not original:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
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] = []
|
||||
params: List[Any] = []
|
||||
if "name" in original:
|
||||
n = (original["name"] or "").strip()
|
||||
if not n:
|
||||
raise HTTPException(status_code=400, detail="name ist Pflicht")
|
||||
fields.append("name = %s")
|
||||
params.append(n)
|
||||
if "description" in original:
|
||||
fields.append("description = %s")
|
||||
params.append(original["description"])
|
||||
|
||||
vis_changed = next_vis != ex_vis
|
||||
if "visibility" in original or vis_changed:
|
||||
fields.append("visibility = %s")
|
||||
params.append(next_vis)
|
||||
|
||||
if "club_id" in original or vis_changed:
|
||||
fields.append("club_id = %s")
|
||||
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()")
|
||||
params.append(graph_id)
|
||||
cur.execute(
|
||||
f"UPDATE exercise_progression_graphs SET {', '.join(fields)} WHERE id = %s",
|
||||
tuple(params),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||
|
||||
|
||||
@router.delete("/exercise-progression-graphs/{graph_id}")
|
||||
def delete_progression_graph(graph_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)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/exercise-progression-graphs/{graph_id}/edges")
|
||||
def list_progression_edges(
|
||||
graph_id: int,
|
||||
from_exercise_id: Optional[int] = Query(default=None),
|
||||
to_exercise_id: Optional[int] = Query(default=None),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_read(cur, graph_id, profile_id, role)
|
||||
q = _EDGE_SELECT + " WHERE e.graph_id = %s"
|
||||
params: List[Any] = [graph_id]
|
||||
if from_exercise_id is not None:
|
||||
q += " AND e.from_exercise_id = %s"
|
||||
params.append(from_exercise_id)
|
||||
if to_exercise_id is not None:
|
||||
q += " AND e.to_exercise_id = %s"
|
||||
params.append(to_exercise_id)
|
||||
q += " ORDER BY e.id"
|
||||
cur.execute(q, tuple(params))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/exercise-progression-graphs/{graph_id}/edges", status_code=201)
|
||||
def create_progression_edge(
|
||||
graph_id: int,
|
||||
body: ProgressionEdgeCreate,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
||||
fv = body.from_exercise_variant_id
|
||||
tv = body.to_exercise_variant_id
|
||||
_assert_variant_for_exercise(cur, body.from_exercise_id, fv)
|
||||
_assert_variant_for_exercise(cur, body.to_exercise_id, tv)
|
||||
et = (body.edge_type or "next_exercise").strip() or "next_exercise"
|
||||
notes = (body.notes or "").strip() or None
|
||||
try:
|
||||
row = _insert_edge_row(
|
||||
cur,
|
||||
graph_id,
|
||||
body.from_exercise_id,
|
||||
fv,
|
||||
body.to_exercise_id,
|
||||
tv,
|
||||
et,
|
||||
notes,
|
||||
)
|
||||
conn.commit()
|
||||
except IntegrityError as e:
|
||||
conn.rollback()
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Kante existiert bereits oder Endpunkte unzulässig (gleiche Übung ohne zwei Varianten)",
|
||||
) from e
|
||||
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/exercise-progression-graphs/{graph_id}/edges/sequence", status_code=201)
|
||||
def create_progression_sequence(
|
||||
graph_id: int,
|
||||
body: ProgressionSequenceCreate,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Legt n−1 Nachfolger-Kanten (next_exercise) für eine geordnete Schrittliste an."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
steps = body.steps
|
||||
n_seg = len(steps) - 1
|
||||
seg_notes = body.segment_notes
|
||||
|
||||
created: List[dict] = []
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
|
||||
ex_ids = [s.exercise_id for s in steps]
|
||||
_assert_exercises_exist(cur, *ex_ids)
|
||||
|
||||
try:
|
||||
for i in range(n_seg):
|
||||
a, b = steps[i], steps[i + 1]
|
||||
_assert_variant_for_exercise(cur, a.exercise_id, a.variant_id)
|
||||
_assert_variant_for_exercise(cur, b.exercise_id, b.variant_id)
|
||||
note = None
|
||||
if seg_notes is not None:
|
||||
raw = seg_notes[i]
|
||||
note = (raw or "").strip() or None if raw is not None else None
|
||||
row = _insert_edge_row(
|
||||
cur,
|
||||
graph_id,
|
||||
a.exercise_id,
|
||||
a.variant_id,
|
||||
b.exercise_id,
|
||||
b.variant_id,
|
||||
"next_exercise",
|
||||
note,
|
||||
)
|
||||
created.append(row)
|
||||
conn.commit()
|
||||
except IntegrityError as e:
|
||||
conn.rollback()
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Sequenz konnte nicht vollständig angelegt werden (Duplikat oder ungültige Endpunkte). Keine Teilmenge gespeichert.",
|
||||
) from e
|
||||
|
||||
return {"created": created, "count": len(created)}
|
||||
|
||||
|
||||
@router.put("/exercise-progression-graphs/{graph_id}/edges/{edge_id}")
|
||||
def update_progression_edge(
|
||||
graph_id: int,
|
||||
edge_id: int,
|
||||
body: ProgressionEdgeUpdate,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if not data:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
"SELECT id FROM exercise_progression_edges WHERE id = %s AND graph_id = %s",
|
||||
(edge_id, graph_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Kante nicht gefunden")
|
||||
|
||||
if "notes" in data:
|
||||
n = data["notes"]
|
||||
notes_val = (n or "").strip() or None if n is not None else None
|
||||
cur.execute(
|
||||
"UPDATE exercise_progression_edges SET notes = %s WHERE id = %s AND graph_id = %s",
|
||||
(notes_val, edge_id, graph_id),
|
||||
)
|
||||
conn.commit()
|
||||
cur.execute(_EDGE_SELECT + " WHERE e.id = %s AND e.graph_id = %s", (edge_id, graph_id))
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.delete("/exercise-progression-graphs/{graph_id}/edges/{edge_id}")
|
||||
def delete_progression_edge(
|
||||
graph_id: int,
|
||||
edge_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)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM exercise_progression_edges
|
||||
WHERE id = %s AND graph_id = %s
|
||||
RETURNING id
|
||||
""",
|
||||
(edge_id, graph_id),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Kante nicht gefunden")
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/exercise-progression-graphs/{graph_id}/edges/delete-batch")
|
||||
def delete_progression_edges_batch(
|
||||
graph_id: int,
|
||||
body: EdgeIdsBatch,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Löscht mehrere Kanten (z. B. eine zusammenhängende Kette in einem Schritt)."""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
ids = body.edge_ids
|
||||
clean_ids = list(dict.fromkeys(ids))
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
cur.execute(
|
||||
f"""
|
||||
DELETE FROM exercise_progression_edges
|
||||
WHERE graph_id = %s AND id IN ({",".join(["%s"] * len(clean_ids))})
|
||||
""",
|
||||
(graph_id, *clean_ids),
|
||||
)
|
||||
deleted = cur.rowcount
|
||||
conn.commit()
|
||||
return {"ok": True, "deleted": deleted}
|
||||
+1851
-179
File diff suppressed because it is too large.
Load diff
@@ -120,7 +120,9 @@ async def preview_import(
|
||||
"wiki_page_title": page_title,
|
||||
"wiki_page_id": page_id,
|
||||
"already_imported": existing_ref is not None,
|
||||
"last_imported_at": existing_ref["last_imported"].isoformat() if existing_ref else None,
|
||||
"last_imported_at": existing_ref["last_imported"].isoformat()
|
||||
if existing_ref and existing_ref.get("last_imported") is not None
|
||||
else None,
|
||||
"mapped_fields": mapped_fields,
|
||||
"warnings": warnings,
|
||||
"errors": errors,
|
||||
@@ -639,21 +641,38 @@ def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
|
||||
return skill_id
|
||||
|
||||
|
||||
def _upsert_method(mapped: dict, reimport: bool) -> Optional[int]:
|
||||
"""Legt Trainingsmethode an oder aktualisiert Beschreibung."""
|
||||
def _upsert_method(mapped: dict, _reimport: bool) -> Optional[int]:
|
||||
"""Legt Trainingsmethode an oder aktualisiert Beschreibung nach Namen.
|
||||
|
||||
training_methods.name hat keinen UNIQUE-Constraint — daher kein ON CONFLICT (name).
|
||||
"""
|
||||
name = (mapped.get("name") or "").strip()
|
||||
desc = mapped.get("description")
|
||||
if not name:
|
||||
return None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""INSERT INTO training_methods (name, description)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT (name) DO UPDATE SET
|
||||
description = EXCLUDED.description
|
||||
RETURNING id""",
|
||||
(mapped["name"], mapped.get("description"))
|
||||
"SELECT id FROM training_methods WHERE TRIM(name) ILIKE TRIM(%s)",
|
||||
(name,),
|
||||
)
|
||||
method_id = cur.fetchone()['id']
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
mid = row["id"]
|
||||
cur.execute(
|
||||
"UPDATE training_methods SET description = %s, updated_at = NOW() WHERE id = %s",
|
||||
(desc, mid),
|
||||
)
|
||||
conn.commit()
|
||||
return mid
|
||||
cur.execute(
|
||||
"INSERT INTO training_methods (name, description) VALUES (%s, %s) RETURNING id",
|
||||
(name, desc),
|
||||
)
|
||||
mid = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
return method_id
|
||||
return mid
|
||||
|
||||
|
||||
def _upsert_wiki_ref(
|
||||
|
||||
@@ -3,7 +3,8 @@ Reifegradmodelle / Fähigkeitsmatrix (kontextbezogen)
|
||||
|
||||
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.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
@@ -534,6 +535,7 @@ def list_maturity_models(
|
||||
|
||||
@router.get("/maturity-models/{model_id}")
|
||||
def get_maturity_model(model_id: int, session: dict = Depends(require_auth)):
|
||||
_require_admin(session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
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),
|
||||
)
|
||||
+347
-53
@@ -3,90 +3,281 @@ Profile Management Endpoints for Mitai Jinkendo
|
||||
|
||||
Handles profile CRUD operations for both admin and current user.
|
||||
"""
|
||||
import uuid
|
||||
import secrets
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
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
|
||||
|
||||
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:
|
||||
"""Get profile_id - from header for legacy endpoints."""
|
||||
if x_profile_id:
|
||||
return x_profile_id
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM profiles ORDER BY created LIMIT 1")
|
||||
row = cur.fetchone()
|
||||
if row: return row['id']
|
||||
raise HTTPException(400, "Kein Profil gefunden")
|
||||
|
||||
class ManagementPasswordResetBody(BaseModel):
|
||||
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
|
||||
|
||||
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
|
||||
|
||||
@field_validator("new_password", mode="before")
|
||||
@classmethod
|
||||
def _empty_pw_none(cls, v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, str) and not v.strip():
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def _target_portal_role_lower(cur, target_pid: int) -> str:
|
||||
cur.execute("SELECT lower(trim(COALESCE(role, ''))) AS r FROM profiles WHERE id = %s", (target_pid,))
|
||||
row = cur.fetchone()
|
||||
return (row.get("r") or "user") if row else "user"
|
||||
|
||||
|
||||
def _assert_can_management_password_help(cur, tenant: TenantContext, target_pid: int, *, via_email: bool) -> None:
|
||||
"""
|
||||
Wer darf eines anderen Accounts Passwort-Helfer nutzen (E-Mail-Link oder — nur Superadmin — direktes Setzen)?
|
||||
Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied in gemeinsam verwaltetem Verein.
|
||||
"""
|
||||
viewer_pid = int(tenant.profile_id)
|
||||
if target_pid == viewer_pid:
|
||||
raise HTTPException(status_code=400, detail="Eigenes Passwort unter Einstellungen ändern")
|
||||
role_raw = tenant.global_role or ""
|
||||
if is_superadmin(role_raw):
|
||||
return
|
||||
if is_platform_admin(role_raw):
|
||||
return
|
||||
managed = club_ids_for_profile_with_roles(cur, viewer_pid, "club_admin")
|
||||
if not managed:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = ANY(%s) AND status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(target_pid, list(managed)),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur für Nutzer, die in mindestens einem deiner Vereine (als Admin) aktiv sind",
|
||||
)
|
||||
if via_email and _target_portal_role_lower(cur, target_pid) in _CLUB_BLOCKED_PORTAL_TARGETS:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Für Konten mit Portal-Administrator- oder Super-Administrator-Rolle ist das nur für Super-Admins möglich",
|
||||
)
|
||||
|
||||
|
||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||
@router.get("/profiles/me")
|
||||
def get_current_profile(session=Depends(require_auth)):
|
||||
"""Get current user's profile (for auth check on refresh)."""
|
||||
profile_id = session['profile_id']
|
||||
def get_current_profile(
|
||||
session=Depends(require_auth),
|
||||
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||
):
|
||||
"""Profil inkl. Vereinsmitgliedschaften (aktive und temporär deaktivierte Zugänge); effective_club_id nur bei aktivem Vereinszugang."""
|
||||
profile_id = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
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 ──────────────────────────────────────────────────
|
||||
@router.get("/profiles")
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM profiles ORDER BY created")
|
||||
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")
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""INSERT INTO profiles (id,name,avatar_color,sex,dob,height,goal_weight,goal_bf_pct,created,updated)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)""",
|
||||
(pid,p.name,p.avatar_color,p.sex,p.dob,p.height,p.goal_weight,p.goal_bf_pct))
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
return r2d(cur.fetchone())
|
||||
cur.execute(
|
||||
"SELECT id FROM profiles WHERE email IS NOT NULL AND lower(trim(email)) = %s",
|
||||
(email_norm,),
|
||||
)
|
||||
if cur.fetchone():
|
||||
raise HTTPException(status_code=409, detail="E-Mail bereits registriert")
|
||||
|
||||
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 get_profile(pid: str, session=Depends(require_auth)):
|
||||
"""Get profile by ID."""
|
||||
def profile_document(pid: str) -> dict:
|
||||
"""Profil ohne PIN — für Routen und interne Aufrufe (z. B. /auth/me)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
row = cur.fetchone()
|
||||
if not row: raise HTTPException(404, "Profil nicht gefunden")
|
||||
return r2d(row)
|
||||
if not row:
|
||||
raise HTTPException(404, "Profil nicht gefunden")
|
||||
d = r2d(row)
|
||||
d.pop("pin_hash", None)
|
||||
return d
|
||||
|
||||
|
||||
@router.put("/profiles/{pid}")
|
||||
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
"""Update profile — nur eigenes Profil oder Admin."""
|
||||
sess_pid = session.get('profile_id')
|
||||
role = (session.get('role') or '').lower()
|
||||
if str(sess_pid) != str(pid) and role not in ('admin', 'superadmin'):
|
||||
raise HTTPException(403, 'Keine Berechtigung für dieses Profil')
|
||||
@router.post("/profiles/{pid}/management-password-reset")
|
||||
def management_password_reset(
|
||||
pid: str,
|
||||
body: ManagementPasswordResetBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Standard: E-Mail mit Reset-Link wie „Passwort vergessen“ — der PIN-Hash bleibt bis zur Bestätigung unverändert.
|
||||
Nur Super-Admins können optional `new_password` setzen (Ausnahme).
|
||||
"""
|
||||
from routers.auth import send_email
|
||||
from password_reset_mail import issue_password_reset_via_email
|
||||
|
||||
try:
|
||||
target = int(pid)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||
|
||||
direct = body.new_password is not None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id, email, name FROM profiles WHERE id = %s", (target,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
|
||||
if direct:
|
||||
role_raw = tenant.global_role or ""
|
||||
if not is_superadmin(role_raw):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Direktes Setzen eines Passworts ist nur Super-Admins vorbehalten. Bitte E-Mail-Link verwenden.",
|
||||
)
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
||||
new_hash = hash_pin(body.new_password)
|
||||
cur.execute(
|
||||
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
|
||||
(new_hash, target),
|
||||
)
|
||||
return {"ok": True, "mode": "direct"}
|
||||
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
||||
email = (row.get("email") or "").strip()
|
||||
if not email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Für dieses Profil ist keine E-Mail-Adresse hinterlegt; ein Reset-Link kann nicht versendet werden.",
|
||||
)
|
||||
name = row.get("name")
|
||||
intro = "Ein Administrator hat für dein Konto einen sicheren Link zum Setzen eines neuen Passworts angefordert."
|
||||
sent = issue_password_reset_via_email(
|
||||
cur,
|
||||
send_email,
|
||||
profile_id=target,
|
||||
email=email.lower(),
|
||||
name=name,
|
||||
intro=intro,
|
||||
)
|
||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||
|
||||
|
||||
@router.get("/profiles/{pid}")
|
||||
def get_profile(pid: str, session=Depends(require_auth)):
|
||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
||||
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:
|
||||
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)
|
||||
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:
|
||||
ev = patch["email"]
|
||||
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
|
||||
@@ -127,49 +363,107 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
data["verification_token"] = 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")
|
||||
|
||||
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||
for k, v in patch.items():
|
||||
if k == "email":
|
||||
continue
|
||||
if k == "active_club_id":
|
||||
continue
|
||||
if v is None and k in nullable_keys:
|
||||
data[k] = None
|
||||
elif v is not None:
|
||||
data[k] = v
|
||||
|
||||
if not data:
|
||||
return get_profile(pid, session)
|
||||
return profile_document(pid)
|
||||
|
||||
data["updated_at"] = datetime.now()
|
||||
cols = ", ".join(f"{k}=%s" for k in data)
|
||||
vals = list(data.values()) + [pid]
|
||||
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}")
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT COUNT(*) as count FROM profiles")
|
||||
count = cur.fetchone()['count']
|
||||
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']:
|
||||
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
|
||||
# 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("DELETE FROM profiles WHERE id=%s", (pid,))
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||
@router.get("/profile")
|
||||
def get_active_profile(x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
||||
"""Legacy endpoint – returns active profile."""
|
||||
pid = get_pid(x_profile_id)
|
||||
return get_profile(pid, session)
|
||||
def get_active_profile(session: dict = Depends(require_auth)):
|
||||
"""Legacy-Alias für das eingeloggte Profil — immer Session, kein X-Profile-Id (SECURITY: kein IDOR)."""
|
||||
pid = str(session["profile_id"])
|
||||
return profile_document(pid)
|
||||
|
||||
|
||||
@router.put("/profile")
|
||||
def update_active_profile(p: ProfileUpdate, x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
||||
"""Update current user's profile."""
|
||||
pid = get_pid(x_profile_id)
|
||||
return update_profile(pid, p, session)
|
||||
def update_active_profile(
|
||||
p: ProfileUpdate,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Profil des eingeloggten Nutzers aktualisieren — dieselbe Quelle wie GET /profile."""
|
||||
pid = str(tenant.profile_id)
|
||||
return _run_profile_update(pid, p, tenant)
|
||||
@@ -0,0 +1,574 @@
|
||||
"""
|
||||
Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere Session-Slots.
|
||||
|
||||
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
||||
nicht über group_id oder training_unit_id am Rahmen.
|
||||
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
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 routers.training_planning import (
|
||||
_has_planning_role,
|
||||
_hydrate_training_unit_payload,
|
||||
_optional_positive_int,
|
||||
_insert_sections_from_legacy_exercises,
|
||||
_replace_unit_sections,
|
||||
_validate_variant_for_exercise,
|
||||
)
|
||||
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["training_framework_programs"])
|
||||
_VALID_VISIBILITY = frozenset({"private", "club", "official"})
|
||||
|
||||
|
||||
def _fetch_framework_row(cur, framework_id: int) -> Dict[str, Any]:
|
||||
cur.execute("SELECT * FROM training_framework_programs WHERE id = %s", (framework_id,))
|
||||
r = cur.fetchone()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Trainingsrahmen nicht gefunden")
|
||||
return r2d(r)
|
||||
|
||||
|
||||
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:
|
||||
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
|
||||
|
||||
|
||||
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]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT training_type_id
|
||||
FROM training_framework_program_training_types
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY training_type_id
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
return [r["training_type_id"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _target_group_ids(cur, framework_id: int) -> List[int]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT target_group_id
|
||||
FROM training_framework_program_target_groups
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY target_group_id
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
return [r["target_group_id"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
fid = row["id"]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, framework_program_id, sort_order, title, notes
|
||||
FROM training_framework_goals
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY sort_order
|
||||
""",
|
||||
(fid,),
|
||||
)
|
||||
row["goals"] = [r2d(g) for g in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, framework_program_id, sort_order, title, notes
|
||||
FROM training_framework_slots
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY sort_order
|
||||
""",
|
||||
(fid,),
|
||||
)
|
||||
slots = [r2d(s) for s in cur.fetchall()]
|
||||
for s in slots:
|
||||
cur.execute(
|
||||
"SELECT id FROM training_units WHERE framework_slot_id = %s",
|
||||
(s["id"],),
|
||||
)
|
||||
row_b = cur.fetchone()
|
||||
if not row_b:
|
||||
s["blueprint_training_unit_id"] = None
|
||||
s["sections"] = []
|
||||
s["exercises"] = []
|
||||
continue
|
||||
uid = row_b["id"]
|
||||
s["blueprint_training_unit_id"] = uid
|
||||
unit_min: Dict[str, Any] = {"id": uid}
|
||||
_hydrate_training_unit_payload(cur, unit_min)
|
||||
s["sections"] = unit_min.get("sections", [])
|
||||
s["exercises"] = unit_min.get("exercises", [])
|
||||
row["slots"] = slots
|
||||
row["training_type_ids"] = _training_type_ids(cur, fid)
|
||||
row["target_group_ids"] = _target_group_ids(cur, fid)
|
||||
return row
|
||||
|
||||
|
||||
def _assert_visibility(val: Optional[str]) -> Optional[str]:
|
||||
if val is None:
|
||||
return None
|
||||
if val not in _VALID_VISIBILITY:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="visibility muss private, club oder official sein",
|
||||
)
|
||||
return val
|
||||
|
||||
|
||||
def _parse_positive_int_ids(raw: Any, label: str) -> List[int]:
|
||||
if raw is None:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise HTTPException(status_code=400, detail=f"{label} muss eine Liste von IDs sein")
|
||||
out: List[int] = []
|
||||
for item in raw:
|
||||
if item in (None, ""):
|
||||
continue
|
||||
try:
|
||||
n = int(item)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID") from None
|
||||
if n <= 0:
|
||||
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID")
|
||||
if n not in out:
|
||||
out.append(n)
|
||||
return out
|
||||
|
||||
|
||||
def _replace_training_types(cur, framework_id: int, ids: Sequence[int]) -> None:
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_program_training_types WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
for tid in ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_program_training_types (framework_program_id, training_type_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(framework_id, tid),
|
||||
)
|
||||
|
||||
|
||||
def _replace_target_groups(cur, framework_id: int, ids: Sequence[int]) -> None:
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_program_target_groups WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
for gid in ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_program_target_groups (framework_program_id, target_group_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(framework_id, gid),
|
||||
)
|
||||
|
||||
|
||||
def _insert_goal_rows(cur, framework_id: int, goals_in: List[Any]) -> None:
|
||||
if not goals_in:
|
||||
raise HTTPException(status_code=400, detail="Mindestens ein Entwicklungsziel (goals) ist erforderlich")
|
||||
for gi, g in enumerate(goals_in):
|
||||
title_g = (g.get("title") or "").strip()
|
||||
if not title_g:
|
||||
raise HTTPException(status_code=400, detail="Jedes Ziel braucht ein nicht-leeres title")
|
||||
order_ix = g.get("sort_order")
|
||||
if order_ix is None:
|
||||
order_ix = gi
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_goals (
|
||||
framework_program_id, sort_order, title, notes
|
||||
) VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(framework_id, int(order_ix), title_g[:500], g.get("notes")),
|
||||
)
|
||||
|
||||
|
||||
def _insert_default_blueprint_section(cur, blueprint_unit_id: int) -> None:
|
||||
"""Leerer Ablauf, falls noch keine Sektionen existieren."""
|
||||
cur.execute(
|
||||
"SELECT 1 FROM training_unit_sections WHERE training_unit_id = %s",
|
||||
(blueprint_unit_id,),
|
||||
)
|
||||
if cur.fetchone():
|
||||
return
|
||||
_replace_unit_sections(
|
||||
cur,
|
||||
blueprint_unit_id,
|
||||
[{"title": "Ablauf", "order_index": 0, "guidance_notes": None, "items": []}],
|
||||
)
|
||||
|
||||
|
||||
def _insert_slots_and_blueprints(
|
||||
cur,
|
||||
framework_id: int,
|
||||
slots_in: Optional[List[Any]],
|
||||
profile_id: int,
|
||||
) -> None:
|
||||
if slots_in is None:
|
||||
return
|
||||
for si, slot in enumerate(slots_in):
|
||||
order_ix = slot.get("sort_order")
|
||||
if order_ix is None:
|
||||
order_ix = si
|
||||
title_s = slot.get("title")
|
||||
if title_s is not None:
|
||||
title_s = title_s.strip() or None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_slots (
|
||||
framework_program_id, sort_order, title, notes, training_unit_id
|
||||
) VALUES (%s, %s, %s, %s, NULL)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
framework_id,
|
||||
int(order_ix),
|
||||
title_s,
|
||||
slot.get("notes"),
|
||||
),
|
||||
)
|
||||
sid = cur.fetchone()["id"]
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date,
|
||||
planned_time_start, planned_time_end, planned_focus,
|
||||
status, notes, trainer_notes,
|
||||
created_by, plan_template_id, framework_slot_id
|
||||
) VALUES (
|
||||
NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
'planned', NULL, NULL,
|
||||
%s, NULL, %s
|
||||
)
|
||||
RETURNING id
|
||||
""",
|
||||
(profile_id, sid),
|
||||
)
|
||||
bid = cur.fetchone()["id"]
|
||||
|
||||
sections_in = slot.get("sections")
|
||||
exercises_in = slot.get("exercises")
|
||||
|
||||
if sections_in is not None:
|
||||
if len(sections_in) == 0:
|
||||
_insert_default_blueprint_section(cur, bid)
|
||||
else:
|
||||
_replace_unit_sections(cur, bid, sections_in)
|
||||
elif exercises_in is not None and len(exercises_in) > 0:
|
||||
for raw in exercises_in:
|
||||
eid = raw.get("exercise_id")
|
||||
if not eid:
|
||||
continue
|
||||
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
|
||||
_validate_variant_for_exercise(cur, int(eid), vid)
|
||||
_insert_sections_from_legacy_exercises(cur, bid, exercises_in)
|
||||
else:
|
||||
_insert_default_blueprint_section(cur, bid)
|
||||
|
||||
|
||||
@router.get("/training-framework-programs")
|
||||
def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
base_sel = """
|
||||
SELECT fp.*,
|
||||
fa.name AS focus_area_name,
|
||||
sd.name AS style_direction_name,
|
||||
(SELECT COUNT(*)::int FROM training_framework_goals g WHERE g.framework_program_id = fp.id)
|
||||
AS goals_count,
|
||||
(SELECT COUNT(*)::int FROM training_framework_slots s WHERE s.framework_program_id = fp.id)
|
||||
AS slots_count,
|
||||
(SELECT COUNT(*)::int FROM training_framework_program_training_types t
|
||||
WHERE t.framework_program_id = fp.id) AS training_types_count,
|
||||
(SELECT COUNT(*)::int FROM training_framework_program_target_groups tg
|
||||
WHERE tg.framework_program_id = fp.id) AS target_groups_count,
|
||||
(
|
||||
SELECT STRING_AGG(typ.name::text, ', ' ORDER BY typ.sort_order NULLS LAST, typ.name)
|
||||
FROM training_framework_program_training_types j
|
||||
JOIN training_types typ ON typ.id = j.training_type_id
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS training_type_names_agg,
|
||||
(
|
||||
SELECT STRING_AGG(tg.name::text, ', ' ORDER BY tg.name)
|
||||
FROM training_framework_program_target_groups j
|
||||
JOIN target_groups tg ON tg.id = j.target_group_id
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS target_group_names_agg
|
||||
FROM training_framework_programs fp
|
||||
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||
"""
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
base_sel
|
||||
+ f""" WHERE ({vis_clause})
|
||||
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/training-framework-programs/{framework_id}")
|
||||
def get_training_framework_program(
|
||||
framework_id: int, tenant: TenantContext = Depends(get_tenant_context)
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
return _response_framework_detail(framework_id, profile_id, role)
|
||||
|
||||
|
||||
@router.post("/training-framework-programs")
|
||||
def create_training_framework_program(
|
||||
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 Planungsberechtigte dürfen Rahmenprogramme anlegen")
|
||||
|
||||
title = (data.get("title") or "").strip()
|
||||
if not title:
|
||||
raise HTTPException(status_code=400, detail="title ist Pflicht")
|
||||
|
||||
vis = data.get("visibility") or "private"
|
||||
vis = _assert_visibility(vis)
|
||||
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")
|
||||
slots_in = data.get("slots")
|
||||
if not isinstance(goals_in, list) or not goals_in:
|
||||
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
|
||||
|
||||
fa_id = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
|
||||
sd_id = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
|
||||
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
|
||||
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, club_id)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_programs (
|
||||
title, description,
|
||||
planned_period_start, planned_period_end,
|
||||
visibility, club_id, created_by,
|
||||
focus_area_id, style_direction_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
title[:200],
|
||||
data.get("description"),
|
||||
data.get("planned_period_start"),
|
||||
data.get("planned_period_end"),
|
||||
vis,
|
||||
club_id,
|
||||
profile_id,
|
||||
fa_id,
|
||||
sd_id,
|
||||
),
|
||||
)
|
||||
fid = cur.fetchone()["id"]
|
||||
_insert_goal_rows(cur, fid, goals_in)
|
||||
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id)
|
||||
_replace_training_types(cur, fid, tt_ids)
|
||||
_replace_target_groups(cur, fid, tg_ids)
|
||||
conn.commit()
|
||||
|
||||
return _response_framework_detail(fid, profile_id, role)
|
||||
|
||||
|
||||
@router.put("/training-framework-programs/{framework_id}")
|
||||
def update_training_framework_program(
|
||||
framework_id: int, 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="Keine Berechtigung")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
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_params: List[Any] = []
|
||||
|
||||
if "title" in data:
|
||||
tit = (data.get("title") or "").strip()
|
||||
if not tit:
|
||||
raise HTTPException(status_code=400, detail="title ist Pflicht")
|
||||
header_fields.append("title = %s")
|
||||
header_params.append(tit[:200])
|
||||
|
||||
if "description" in data:
|
||||
header_fields.append("description = %s")
|
||||
header_params.append(data.get("description"))
|
||||
if "planned_period_start" in data:
|
||||
header_fields.append("planned_period_start = %s")
|
||||
header_params.append(data.get("planned_period_start"))
|
||||
if "planned_period_end" in data:
|
||||
header_fields.append("planned_period_end = %s")
|
||||
header_params.append(data.get("planned_period_end"))
|
||||
|
||||
if "visibility" in data:
|
||||
header_fields.append("visibility = %s")
|
||||
header_params.append(merged_vis)
|
||||
if "club_id" in data:
|
||||
header_fields.append("club_id = %s")
|
||||
header_params.append(merged_club)
|
||||
|
||||
if "focus_area_id" in data:
|
||||
fidv = data.get("focus_area_id")
|
||||
header_fields.append("focus_area_id = %s")
|
||||
header_params.append(
|
||||
None if fidv in (None, "") else _optional_positive_int(fidv, "focus_area_id")
|
||||
)
|
||||
if "style_direction_id" in data:
|
||||
sidv = data.get("style_direction_id")
|
||||
header_fields.append("style_direction_id = %s")
|
||||
header_params.append(
|
||||
None if sidv in (None, "") else _optional_positive_int(sidv, "style_direction_id")
|
||||
)
|
||||
|
||||
if header_fields:
|
||||
header_fields.append("updated_at = NOW()")
|
||||
header_params.append(framework_id)
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE training_framework_programs
|
||||
SET {", ".join(header_fields)}
|
||||
WHERE id = %s
|
||||
""",
|
||||
tuple(header_params),
|
||||
)
|
||||
|
||||
if "training_type_ids" in data:
|
||||
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
|
||||
_replace_training_types(cur, framework_id, tt_ids)
|
||||
|
||||
if "target_group_ids" in data:
|
||||
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
|
||||
_replace_target_groups(cur, framework_id, tg_ids)
|
||||
|
||||
if "goals" in data:
|
||||
goals_in = data["goals"]
|
||||
if not isinstance(goals_in, list) or not goals_in:
|
||||
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_goals WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
_insert_goal_rows(cur, framework_id, goals_in)
|
||||
|
||||
if "slots" in data:
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
_insert_slots_and_blueprints(cur, framework_id, data.get("slots") or [], profile_id)
|
||||
|
||||
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
|
||||
cur.execute(
|
||||
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
return _response_framework_detail(framework_id, profile_id, role)
|
||||
|
||||
|
||||
@router.delete("/training-framework-programs/{framework_id}")
|
||||
def delete_training_framework_program(
|
||||
framework_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_fw = _fetch_framework_row(cur, framework_id)
|
||||
_framework_assert_writable(cur, row_fw, profile_id, role)
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_programs WHERE id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
+1242
-165
File diff suppressed because it is too large.
Load diff
+23
-14
@@ -2,8 +2,17 @@
|
||||
"""
|
||||
Shinkan Jinkendo — Datenbank-Migrationen
|
||||
|
||||
**Idempotent** über `schema_migrations`: jede numerische Datei `migrations/*.sql` höchstens einmal
|
||||
als „erfolgreich“ eingetragen; bei erneutem Start werden nur noch fehlende Dateien abgearbeitet.
|
||||
**Deployment:** Beim Start importiert `main.py` dieses Modul und ruft `main()` auf, bevor FastAPI
|
||||
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
|
||||
alphabetisch nach Dateinamen — nicht bloß String-Sortierung (vermeidet z. B. `10_` vor `9_`).
|
||||
@@ -49,14 +58,14 @@ def get_db_connection():
|
||||
password=p["password"],
|
||||
)
|
||||
conn.autocommit = False
|
||||
print(f"✓ Connected to database: {p['dbname']}")
|
||||
print(f"[OK] Connected to database: {p['dbname']}")
|
||||
return conn
|
||||
except psycopg2.OperationalError:
|
||||
if i < max_retries - 1:
|
||||
print(f"Waiting for database... ({i+1}/{max_retries})")
|
||||
time.sleep(2)
|
||||
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
|
||||
|
||||
|
||||
@@ -72,7 +81,7 @@ def init_migrations_table(conn):
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
print("✓ schema_migrations initialisiert")
|
||||
print("[OK] schema_migrations initialisiert")
|
||||
|
||||
|
||||
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
||||
@@ -190,7 +199,7 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
||||
if shutil.which("psql"):
|
||||
ok, diag = _run_file_with_psql(filepath)
|
||||
if not ok:
|
||||
print(f" ✗ psql fehlgeschlagen:\n{diag or '(kein Output)'}")
|
||||
print(f" [FAIL] psql fehlgeschlagen:\n{diag or '(kein Output)'}")
|
||||
conn.rollback()
|
||||
return False
|
||||
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:
|
||||
body = fh.read()
|
||||
except OSError as e:
|
||||
print(f" ✗ kann Datei nicht lesen: {e}")
|
||||
print(f" [FAIL] kann Datei nicht lesen: {e}")
|
||||
conn.rollback()
|
||||
return False
|
||||
|
||||
@@ -207,7 +216,7 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
||||
with conn.cursor() as cur:
|
||||
if not statements:
|
||||
print(
|
||||
f" ⚠ keine ausführbaren Statements (leer?) — "
|
||||
f" [WARN] keine ausführbaren Statements (leer?) — "
|
||||
f"Eintrag trotzdem: {migration_name}"
|
||||
)
|
||||
else:
|
||||
@@ -217,12 +226,12 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
||||
|
||||
_record_migration(conn, migration_name)
|
||||
conn.commit()
|
||||
print(f" ✓ {migration_name} erfolgreich {detail_suffix}")
|
||||
print(f" [OK] {migration_name} erfolgreich {detail_suffix}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f" ✗ {migration_name}: {e}")
|
||||
print(f" [FAIL] {migration_name}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -243,7 +252,7 @@ def main():
|
||||
pending = get_pending(conn, migrations_dir)
|
||||
|
||||
if not pending:
|
||||
print("✓ Keine ausstehenden Migrationen — Schema aktuell.")
|
||||
print("[OK] Keine ausstehenden Migrationen — Schema aktuell.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
@@ -262,17 +271,17 @@ def main():
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
if failed:
|
||||
print(f"✗ Abbruch nach: {failed}")
|
||||
print(f"[FAIL] Abbruch nach: {failed}")
|
||||
print(" (Bereits erfolgreiche Dateien dieser Session sind committed.)")
|
||||
print("=" * 60)
|
||||
return 1
|
||||
|
||||
print(f"✓ {len(pending)} Migration(s) angewendet — Schema aktuell.")
|
||||
print(f"[OK] {len(pending)} Migration(s) angewendet — Schema aktuell.")
|
||||
print("=" * 60)
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n✗ Fehler: {e}")
|
||||
print(f"\n[FAIL] Fehler: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/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",
|
||||
"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())
|
||||
+32
-15
@@ -48,7 +48,11 @@ class SmwClient:
|
||||
"format": "json",
|
||||
})
|
||||
r1.raise_for_status()
|
||||
token = r1.json()["query"]["tokens"]["logintoken"]
|
||||
j = self._parse_mw_response(r1.json())
|
||||
tok = (((j.get("query") or {}).get("tokens") or {}).get("logintoken"))
|
||||
if not tok:
|
||||
raise SmwClientError("MediaWiki Login-Token fehlt in API-Antwort")
|
||||
|
||||
cookies = dict(r1.cookies)
|
||||
|
||||
# Schritt 2: Einloggen
|
||||
@@ -56,10 +60,10 @@ class SmwClient:
|
||||
"action": "login",
|
||||
"lgname": self.user,
|
||||
"lgpassword": self.password,
|
||||
"lgtoken": token,
|
||||
"lgtoken": tok,
|
||||
}, cookies=cookies)
|
||||
r2.raise_for_status()
|
||||
result = r2.json()
|
||||
result = self._parse_mw_response(r2.json())
|
||||
|
||||
if result.get("login", {}).get("result") != "Success":
|
||||
reason = result.get("login", {}).get("reason", "unbekannt")
|
||||
@@ -69,15 +73,31 @@ class SmwClient:
|
||||
self._logged_in = True
|
||||
logger.info("SMW Login erfolgreich als '%s'", self.user)
|
||||
|
||||
def _parse_mw_response(self, data: dict) -> dict:
|
||||
"""MediaWiki liefert oft HTTP 200 mit {\"error\": {...}} — sonst KeyErrors in Client-Code."""
|
||||
if not isinstance(data, dict):
|
||||
raise SmwClientError("Ungültige API-Antwort (kein JSON-Objekt)")
|
||||
err = data.get("error")
|
||||
if isinstance(err, dict):
|
||||
code = err.get("code", "")
|
||||
info = err.get("info") or err.get("*") or err.get("message") or ""
|
||||
raise SmwClientError(f"MediaWiki API: {code}: {info}".strip())
|
||||
return data
|
||||
|
||||
async def _get(self, params: dict) -> dict:
|
||||
"""Authentifizierter GET-Request gegen die API."""
|
||||
if not self._logged_in:
|
||||
await self.login()
|
||||
params["format"] = "json"
|
||||
async with httpx.AsyncClient(timeout=30, cookies=self._cookies) as client:
|
||||
r = await client.get(self.api_url, params=params)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30, cookies=self._cookies) as client:
|
||||
r = await client.get(self.api_url, params=params)
|
||||
r.raise_for_status()
|
||||
return self._parse_mw_response(r.json())
|
||||
except SmwClientError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise SmwClientError(str(e))
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Kategorien #
|
||||
@@ -104,7 +124,8 @@ class SmwClient:
|
||||
params["cmcontinue"] = cmcontinue
|
||||
|
||||
data = await self._get(params)
|
||||
members.extend(data["query"]["categorymembers"])
|
||||
q = data.get("query") or {}
|
||||
members.extend(q.get("categorymembers") or [])
|
||||
|
||||
if "continue" in data and len(members) < limit:
|
||||
cmcontinue = data["continue"].get("cmcontinue")
|
||||
@@ -143,7 +164,8 @@ class SmwClient:
|
||||
params["cmcontinue"] = cmcontinue
|
||||
|
||||
data = await self._get(params)
|
||||
subcats.extend(data["query"]["categorymembers"])
|
||||
q = data.get("query") or {}
|
||||
subcats.extend(q.get("categorymembers") or [])
|
||||
|
||||
if "continue" in data:
|
||||
cmcontinue = data["continue"].get("cmcontinue")
|
||||
@@ -193,12 +215,9 @@ class SmwClient:
|
||||
"action": "browsebysubject",
|
||||
"subject": title,
|
||||
})
|
||||
if "error" in data:
|
||||
raise SmwClientError(f"SMW Browse-Fehler für '{title}': {data['error']}")
|
||||
|
||||
# Normalisiere: {property_label: [wert1, wert2]}
|
||||
result = {}
|
||||
for prop_data in data.get("query", {}).get("data", []):
|
||||
for prop_data in (data.get("query") or {}).get("data") or []:
|
||||
prop_label = prop_data.get("property", "")
|
||||
if prop_label.startswith("_"): # Interne SMW-Properties überspringen
|
||||
continue
|
||||
@@ -223,8 +242,6 @@ class SmwClient:
|
||||
"action": "ask",
|
||||
"query": f"{query}|limit={limit}",
|
||||
})
|
||||
if "error" in data:
|
||||
raise SmwClientError(f"SMW Ask-Fehler: {data['error']}")
|
||||
|
||||
results = []
|
||||
for title, props in data.get("query", {}).get("results", {}).items():
|
||||
|
||||
@@ -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,108 @@
|
||||
"""Vereins-Übung: Copyright-Pflicht für angehängte Archiv-Dateien."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import routers.exercises as exercises_mod
|
||||
from routers.exercises import apply_club_exercise_media_copyright_rules
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_skips_non_club() -> None:
|
||||
apply_club_exercise_media_copyright_rules(object(), 1, "private")
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_missing_copyright() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, eid: int):
|
||||
assert eid == 42
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
assert ei.value.status_code == 422
|
||||
d = ei.value.detail
|
||||
assert isinstance(d, dict)
|
||||
assert d.get("code") == "CLUB_MEDIA_COPYRIGHT_REQUIRED"
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_ok() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Verein 2026",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_applies_default() -> None:
|
||||
"""Nach Bestätigung setzt der Client default_club_media_copyright — Backend schreibt auf Assets."""
|
||||
orig_fetch = exercises_mod._fetch_exercise_linked_file_assets
|
||||
calls = {"n": 0}
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Testverein",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
class MockCur:
|
||||
def execute(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(
|
||||
MockCur(),
|
||||
42,
|
||||
"club",
|
||||
default_club_media_copyright="© Testverein",
|
||||
)
|
||||
assert calls["n"] == 2
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig_fetch
|
||||
@@ -0,0 +1,51 @@
|
||||
"""POST /api/exercises: keine Inline-Medien-Platzhalter beim ersten Anlegen (§11)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides() -> None:
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def test_post_exercise_rejects_inline_media_placeholder(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.post(
|
||||
"/api/exercises",
|
||||
json={
|
||||
"title": "Mit Inline",
|
||||
"goal": "<p>Hallo {{exerciseMedia:7}}</p>",
|
||||
"execution": "<p>Schritt</p>",
|
||||
"visibility": "private",
|
||||
"status": "draft",
|
||||
},
|
||||
headers={"X-Auth-Token": "x"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
j = r.json()
|
||||
assert j.get("detail", {}).get("code") == "INLINE_EXERCISE_MEDIA_ON_CREATE"
|
||||
@@ -0,0 +1,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
|
||||
@@ -0,0 +1,107 @@
|
||||
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
|
||||
|
||||
_HEX64 = "a" * 64
|
||||
|
||||
|
||||
def test_library_media_kind_dir_mime_overrides_ext() -> None:
|
||||
assert library_media_kind_dir("image/png", ".bin") == "image"
|
||||
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
|
||||
|
||||
|
||||
def test_library_club_path_segment_slug_and_fallback() -> None:
|
||||
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
|
||||
assert library_club_path_segment(3, None) == "verein-c3"
|
||||
assert library_club_path_segment(3, " ") == "verein-c3"
|
||||
assert library_club_path_segment(12, "東道場") == "verein-c12"
|
||||
|
||||
|
||||
def test_library_club_path_segment_long_name_truncated() -> None:
|
||||
long = "a" * 80
|
||||
seg = library_club_path_segment(5, long)
|
||||
assert seg == "a" * 48 + "-c5"
|
||||
|
||||
|
||||
def test_library_storage_key_private_is_uploader_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key(
|
||||
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
|
||||
)
|
||||
== f"library/ost-dojo-muenchen-c7/image/{_HEX64}.u99.jpg"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_club_flat_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
|
||||
== f"library/demo-verein-c42/image/{_HEX64}.png"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_official() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
|
||||
== f"library/official/video/{_HEX64}.mp4"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_normalizes_visibility() -> None:
|
||||
assert (
|
||||
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
|
||||
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_other_bin() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
|
||||
== f"library/official/other/{_HEX64}.bin"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_uploader() -> None:
|
||||
with pytest.raises(ValueError, match="uploader_profile_id"):
|
||||
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_club() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
|
||||
|
||||
|
||||
def test_library_storage_key_club_requires_id() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_club_id_positive() -> None:
|
||||
with pytest.raises(ValueError, match="positiv"):
|
||||
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_visibility() -> None:
|
||||
with pytest.raises(ValueError, match="Sichtbarkeit"):
|
||||
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_sha() -> None:
|
||||
with pytest.raises(ValueError, match="64"):
|
||||
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_extension() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
library_storage_key(
|
||||
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_no_club_name_fallback() -> None:
|
||||
assert (
|
||||
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
|
||||
== f"library/verein-c2/image/{_HEX64}.u3.jpg"
|
||||
)
|
||||
@@ -0,0 +1,506 @@
|
||||
"""
|
||||
Medienarchiv: GET /api/media-assets und POST /api/exercises/{id}/media/from-asset (gemockte DB).
|
||||
"""
|
||||
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
|
||||
|
||||
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
|
||||
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
|
||||
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
|
||||
_SK_PRIV_C = f"library/verein-c1/video/{'c' * 64}.u1.mp4"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
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(mock_cur: MagicMock) -> 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_list_media_assets_ok_mocked(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.side_effect = [
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"mime_type": "image/png",
|
||||
"byte_size": 100,
|
||||
"original_filename": "a.png",
|
||||
"visibility": "official",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 2,
|
||||
"lifecycle_state": "active",
|
||||
"created_at": None,
|
||||
"sha256": "a" * 64,
|
||||
"copyright_notice": None,
|
||||
"storage_key": "media/a.png",
|
||||
"tags": ["demo"],
|
||||
"uploader_name": None,
|
||||
"uploader_email": None,
|
||||
"club_name": None,
|
||||
}
|
||||
],
|
||||
[],
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
|
||||
r = client.get("/api/media-assets?q=test", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["limit"] == 30
|
||||
assert len(body["items"]) == 1
|
||||
assert body["items"][0]["original_filename"] == "a.png"
|
||||
assert body["items"][0]["usage"] == {"exercises": [], "training_units": []}
|
||||
assert body["items"][0]["tags"] == ["demo"]
|
||||
assert "viewer" in body
|
||||
|
||||
|
||||
def test_list_media_assets_media_kind_image_ok_mocked(client: TestClient) -> None:
|
||||
"""media_kind=image setzt %% in SQL — Regression gegen psycopg2-%-Platzhalter."""
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.side_effect = [[], []]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
|
||||
r = client.get("/api/media-assets?media_kind=image", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
calls = [str(c) for c in mock_cur.execute.call_args_list]
|
||||
joined = " ".join(calls)
|
||||
assert "image/%%" in joined
|
||||
|
||||
|
||||
def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"c": 0},
|
||||
{
|
||||
"id": 5,
|
||||
"mime_type": "image/jpeg",
|
||||
"byte_size": 10,
|
||||
"original_filename": "x.jpg",
|
||||
"visibility": "official",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": _SK_OFF_A,
|
||||
},
|
||||
{"id": 1},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/exercises/3/media/from-asset",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={
|
||||
"media_asset_id": 5,
|
||||
"title": "",
|
||||
"description": "",
|
||||
"context": "ablauf",
|
||||
"is_primary": False,
|
||||
},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
assert "bereits" in (r.json().get("detail") or "").lower()
|
||||
|
||||
|
||||
def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
inserted = {
|
||||
"id": 99,
|
||||
"exercise_id": 3,
|
||||
"media_type": "image",
|
||||
"file_path": f"/media/{_SK_OFF_B}",
|
||||
"file_size": 10,
|
||||
"mime_type": "image/jpeg",
|
||||
"original_filename": "h.jpg",
|
||||
"embed_url": None,
|
||||
"embed_platform": None,
|
||||
"title": "h.jpg",
|
||||
"description": None,
|
||||
"sort_order": 1,
|
||||
"is_primary": False,
|
||||
"context": "ablauf",
|
||||
"created_at": None,
|
||||
"media_asset_id": 5,
|
||||
}
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"c": 0},
|
||||
{
|
||||
"id": 5,
|
||||
"mime_type": "image/jpeg",
|
||||
"byte_size": 10,
|
||||
"original_filename": "h.jpg",
|
||||
"visibility": "official",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": _SK_OFF_B,
|
||||
},
|
||||
None,
|
||||
inserted,
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/exercises/3/media/from-asset",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={
|
||||
"media_asset_id": 5,
|
||||
"context": "detail",
|
||||
"is_primary": False,
|
||||
},
|
||||
)
|
||||
|
||||
assert r.status_code == 201
|
||||
body = r.json()
|
||||
assert body["id"] == 99
|
||||
assert body["media_asset_id"] == 5
|
||||
assert body["asset_lifecycle_state"] == "active"
|
||||
|
||||
|
||||
def test_delete_exercise_media_returns_orphan_when_last_ref(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"media_asset_id": 88},
|
||||
{"c": 1},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.delete("/api/exercises/10/media/20", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["ok"] is True
|
||||
assert body["orphan_media_asset_id"] == 88
|
||||
|
||||
|
||||
def test_delete_exercise_media_no_orphan_when_shared(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"media_asset_id": 88},
|
||||
{"c": 2},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.delete("/api/exercises/10/media/20", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json()["orphan_media_asset_id"] is None
|
||||
|
||||
|
||||
def test_delete_exercise_media_embed_row_no_orphan(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{"created_by": 1, "visibility": "private", "club_id": None},
|
||||
{"media_asset_id": None},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.delete("/api/exercises/10/media/21", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"ok": True, "orphan_media_asset_id": None}
|
||||
|
||||
|
||||
def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{
|
||||
"id": 5,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "trash_soft",
|
||||
"storage_key": _SK_PRIV_C,
|
||||
"storage_backend": "local",
|
||||
"trash_soft_at": None,
|
||||
"trash_hidden_at": None,
|
||||
"purge_after_at": None,
|
||||
},
|
||||
{"id": 5, "lifecycle_state": "active"},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.post(
|
||||
"/api/media-assets/5/lifecycle",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"action": "reactivate"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json()["lifecycle_state"] == "active"
|
||||
|
||||
|
||||
def test_media_asset_lifecycle_purge_forbidden_for_non_superadmin(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="admin",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
mock_cur = MagicMock()
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
|
||||
fake_row = {
|
||||
"id": 99,
|
||||
"visibility": "official",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 2,
|
||||
"lifecycle_state": "trash_hidden",
|
||||
"storage_key": "x",
|
||||
"storage_backend": "local",
|
||||
"trash_soft_at": None,
|
||||
"trash_hidden_at": None,
|
||||
"purge_after_at": None,
|
||||
}
|
||||
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
), patch("routers.media_assets.fetch_media_asset_row", return_value=fake_row):
|
||||
r = client.post(
|
||||
"/api/media-assets/99/lifecycle",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"action": "purge"},
|
||||
)
|
||||
|
||||
assert r.status_code == 403
|
||||
assert "Superadmin" in (r.json().get("detail") or "")
|
||||
|
||||
|
||||
def test_list_media_assets_lifecycle_trash_soft_mocked(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.return_value = []
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
|
||||
r = client.get("/api/media-assets?lifecycle=trash_soft", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["lifecycle"] == "trash_soft"
|
||||
list_sql_calls = [c[0][0] for c in mock_cur.execute.call_args_list if c[0] and "FROM media_assets ma" in str(c[0][0])]
|
||||
assert list_sql_calls and "trash_soft" in list_sql_calls[0]
|
||||
|
||||
|
||||
def test_list_media_assets_invalid_media_kind_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get("/api/media-assets?media_kind=movies", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_list_media_assets_club_filter_forbidden_non_superadmin(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "admin"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="admin",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get("/api/media-assets?club_id=3", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_list_media_assets_invalid_lifecycle_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get("/api/media-assets?lifecycle=invalid", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_patch_media_asset_copyright_mocked(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=10,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [
|
||||
{
|
||||
"id": 9,
|
||||
"visibility": "private",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 10,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.png",
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"mime_type": "image/png",
|
||||
"byte_size": 10,
|
||||
"original_filename": "x.png",
|
||||
"visibility": "private",
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 10,
|
||||
"lifecycle_state": "active",
|
||||
"created_at": None,
|
||||
"sha256": "b" * 64,
|
||||
"copyright_notice": "© HoldCo",
|
||||
"tags": [],
|
||||
},
|
||||
]
|
||||
mock_cm = _mock_db(mock_cur)
|
||||
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
|
||||
"routers.media_assets.get_cursor", return_value=mock_cur
|
||||
), patch("media_lifecycle.assert_can_manage_media_asset_lifecycle", lambda *a, **k: None):
|
||||
r = client.patch(
|
||||
"/api/media-assets/9",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"copyright_notice": "© HoldCo"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["copyright_notice"] == "© HoldCo"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""§4.2: apply_official_exercise_media_rules — Lifecycle, Sichtbarkeit, Copyright."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from routers.exercises import apply_official_exercise_media_rules
|
||||
|
||||
|
||||
def _row(
|
||||
aid: int,
|
||||
*,
|
||||
vis: str = "private",
|
||||
lifecycle: str = "active",
|
||||
copyright_notice: str | None = "",
|
||||
name: str = "f.bin",
|
||||
) -> dict:
|
||||
return {
|
||||
"id": aid,
|
||||
"visibility": vis,
|
||||
"club_id": 1,
|
||||
"lifecycle_state": lifecycle,
|
||||
"copyright_notice": copyright_notice,
|
||||
"original_filename": name,
|
||||
}
|
||||
|
||||
|
||||
def test_non_official_visibility_noop() -> None:
|
||||
cur = MagicMock()
|
||||
apply_official_exercise_media_rules(
|
||||
cur,
|
||||
1,
|
||||
"private",
|
||||
promote_attached_media=False,
|
||||
default_official_media_copyright=None,
|
||||
)
|
||||
cur.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_lifecycle_not_active_422() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchall.return_value = [_row(1, lifecycle="trash_soft", copyright_notice="abc")]
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_official_exercise_media_rules(
|
||||
cur,
|
||||
1,
|
||||
"official",
|
||||
promote_attached_media=False,
|
||||
default_official_media_copyright=None,
|
||||
)
|
||||
assert ei.value.status_code == 422
|
||||
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_LIFECYCLE"
|
||||
|
||||
|
||||
def test_visibility_promotion_confirm_422() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchall.return_value = [_row(1, vis="club", copyright_notice="halten")]
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_official_exercise_media_rules(
|
||||
cur,
|
||||
1,
|
||||
"official",
|
||||
promote_attached_media=False,
|
||||
default_official_media_copyright=None,
|
||||
)
|
||||
assert ei.value.status_code == 422
|
||||
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_CONFIRM_REQUIRED"
|
||||
assert ei.value.detail["assets_need_visibility_promotion"]
|
||||
|
||||
|
||||
def test_copyright_required_422() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchall.return_value = [_row(1, vis="official", copyright_notice="")]
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_official_exercise_media_rules(
|
||||
cur,
|
||||
1,
|
||||
"official",
|
||||
promote_attached_media=True,
|
||||
default_official_media_copyright=None,
|
||||
)
|
||||
assert ei.value.status_code == 422
|
||||
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_CONFIRM_REQUIRED"
|
||||
assert ei.value.detail["assets_missing_copyright"]
|
||||
|
||||
|
||||
def test_promote_and_fill_copyright_updates() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchall.return_value = [_row(1, vis="private", copyright_notice=" ")]
|
||||
apply_official_exercise_media_rules(
|
||||
cur,
|
||||
42,
|
||||
"official",
|
||||
promote_attached_media=True,
|
||||
default_official_media_copyright="© Test Holding",
|
||||
)
|
||||
assert cur.execute.call_count == 3
|
||||
sql1 = cur.execute.call_args_list[1][0][0]
|
||||
sql2 = cur.execute.call_args_list[2][0][0]
|
||||
assert "visibility = 'official'" in sql1
|
||||
assert "copyright_notice" in sql2
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""GET/PUT /api/admin/platform-media-storage — Auth-Matrix (kein Live-DB nötig)."""
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
|
||||
|
||||
def test_platform_media_storage_get_requires_platform_admin(client: TestClient) -> None:
|
||||
def _trainer():
|
||||
return {"profile_id": 1, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _trainer
|
||||
r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_platform_media_storage_put_requires_superadmin(client: TestClient) -> None:
|
||||
def _admin():
|
||||
return {"profile_id": 1, "role": "admin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _admin
|
||||
r = client.put(
|
||||
"/api/admin/platform-media-storage",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"local_relative_root": "foo"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
@patch("routers.platform_media_storage.get_effective_media_root", return_value=__import__("pathlib").Path("/tmp/media"))
|
||||
def test_platform_media_storage_get_ok_for_admin(mock_root, client: TestClient) -> None:
|
||||
def _admin():
|
||||
return {"profile_id": 1, "role": "admin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _admin
|
||||
|
||||
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 = {
|
||||
"storage_backend": "local",
|
||||
"local_relative_root": "nas",
|
||||
}
|
||||
|
||||
with patch("routers.platform_media_storage.get_db", return_value=mock_cm), patch(
|
||||
"routers.platform_media_storage.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["storage_backend"] == "local"
|
||||
assert body["local_relative_root"] == "nas"
|
||||
@@ -0,0 +1,193 @@
|
||||
"""
|
||||
Zugriffsrechte Profile: POST/GET/DELETE /api/profiles/{pid}.
|
||||
|
||||
TestClient + Dependency-Override für Sessions; GET mockt profile_document, DELETE/POST mocken DB,
|
||||
damit keine echte Datenbank nötig ist.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_auth_override():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
|
||||
|
||||
def test_get_profile_forbidden_other_user(client: TestClient) -> None:
|
||||
def auth_viewer() -> dict:
|
||||
return {"profile_id": 42, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_viewer
|
||||
with patch("routers.profiles.profile_document") as pd_mock:
|
||||
r = client.get("/api/profiles/99", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 403
|
||||
assert pd_mock.call_count == 0
|
||||
|
||||
|
||||
def test_get_profile_ok_same_numeric_id(client: TestClient) -> None:
|
||||
payload = {"id": 42, "name": "Self"}
|
||||
|
||||
def auth_self() -> dict:
|
||||
return {"profile_id": 42, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_self
|
||||
with patch("routers.profiles.profile_document", return_value=payload) as pd_mock:
|
||||
r = client.get("/api/profiles/42", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 200
|
||||
assert r.json() == payload
|
||||
pd_mock.assert_called_once_with("42")
|
||||
|
||||
|
||||
def test_get_profile_ok_same_string_session_id(client: TestClient) -> None:
|
||||
"""Session liefert profile_id als String (Backward-Compatibility)."""
|
||||
payload = {"id": 7, "name": "S"}
|
||||
|
||||
def auth_self_str() -> dict:
|
||||
return {"profile_id": "7", "role": "user"}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_self_str
|
||||
with patch("routers.profiles.profile_document", return_value=payload):
|
||||
r = client.get("/api/profiles/7", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("admin_role", ["admin", "superadmin"])
|
||||
def test_get_profile_ok_platform_admin_views_other(client: TestClient, admin_role: str) -> None:
|
||||
payload = {"id": 99, "name": "Other"}
|
||||
|
||||
def auth_admin() -> dict:
|
||||
return {"profile_id": 1, "role": admin_role}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_admin
|
||||
with patch("routers.profiles.profile_document", return_value=payload) as pd_mock:
|
||||
r = client.get("/api/profiles/99", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 200
|
||||
assert r.json() == payload
|
||||
pd_mock.assert_called_once_with("99")
|
||||
|
||||
|
||||
def test_delete_profile_forbidden_non_admin(client: TestClient) -> None:
|
||||
def auth_trainer() -> dict:
|
||||
return {"profile_id": 1, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_trainer
|
||||
with patch("routers.profiles.get_db") as mock_get_db:
|
||||
r = client.delete("/api/profiles/1", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 403
|
||||
mock_get_db.assert_not_called()
|
||||
|
||||
|
||||
def test_delete_profile_admin_last_profile_protected(client: TestClient) -> None:
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = {"count": 1}
|
||||
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 99, "role": "admin"}
|
||||
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
|
||||
"routers.profiles.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.delete("/api/profiles/5", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_delete_profile_admin_ok_when_multiple_profiles(client: TestClient) -> None:
|
||||
mock_conn = MagicMock()
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = {"count": 4}
|
||||
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 99, "role": "superadmin"}
|
||||
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
|
||||
"routers.profiles.get_cursor", return_value=mock_cur
|
||||
):
|
||||
r = client.delete("/api/profiles/12", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"ok": True}
|
||||
|
||||
calls = mock_cur.execute.call_args_list
|
||||
assert any(
|
||||
args and "DELETE FROM profiles" in str(args[0][0]) for args in calls
|
||||
)
|
||||
|
||||
|
||||
def test_create_profile_forbidden_non_admin(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
with patch("routers.profiles.get_db") as mock_get_db:
|
||||
r = client.post(
|
||||
"/api/profiles",
|
||||
json={"name": "Neu", "email": "neu@example.com"},
|
||||
headers={"X-Auth-Token": "dummy"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
mock_get_db.assert_not_called()
|
||||
|
||||
|
||||
def test_create_profile_admin_duplicate_email(client: TestClient) -> None:
|
||||
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": 99}
|
||||
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
|
||||
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
|
||||
"routers.profiles.get_cursor", return_value=mock_cur
|
||||
), patch("routers.profiles.hash_pin", return_value="hashed"):
|
||||
r = client.post(
|
||||
"/api/profiles",
|
||||
json={"name": "Dup", "email": "dup@example.com"},
|
||||
headers={"X-Auth-Token": "dummy"},
|
||||
)
|
||||
assert r.status_code == 409
|
||||
|
||||
|
||||
def test_create_profile_admin_success(client: TestClient) -> None:
|
||||
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.side_effect = [None, {"id": 501}]
|
||||
|
||||
doc = {"id": 501, "name": "Nu User", "email": "nu@example.com"}
|
||||
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "superadmin"}
|
||||
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
|
||||
"routers.profiles.get_cursor", return_value=mock_cur
|
||||
), patch("routers.profiles.profile_document", return_value=doc), patch(
|
||||
"routers.profiles.hash_pin", return_value="hashed"
|
||||
):
|
||||
r = client.post(
|
||||
"/api/profiles",
|
||||
json={"name": "Nu User", "email": "nu@example.com"},
|
||||
headers={"X-Auth-Token": "dummy"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == doc
|
||||
|
||||
insert_calls = [
|
||||
c.args[0] for c in mock_cur.execute.call_args_list if c.args and "INSERT INTO profiles" in str(c.args[0])
|
||||
]
|
||||
assert len(insert_calls) >= 1
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
Sicherheits-Regression für Release-Konfiguration (OpenAPI, Health-Ready, Legacy-Routen).
|
||||
|
||||
Läuft ohne PostgreSQL, wo möglich (TestClient + Subprocess mit frischem Import).
|
||||
CI: scripts/security_release_checks.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_auth_override():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
|
||||
|
||||
def test_legacy_get_profile_uses_session_only(client: TestClient) -> None:
|
||||
"""SEC-01: /api/profile darf nur das Session-Profil liefern."""
|
||||
|
||||
def auth_user() -> dict:
|
||||
return {"profile_id": 901, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = auth_user
|
||||
with patch("routers.profiles.profile_document") as pd_mock:
|
||||
pd_mock.return_value = {"id": 901, "name": "T"}
|
||||
r = client.get("/api/profile", headers={"X-Auth-Token": "dummy"})
|
||||
assert r.status_code == 200
|
||||
pd_mock.assert_called_once_with("901")
|
||||
|
||||
|
||||
def _run_fresh_import_int(code: str, env: dict) -> subprocess.CompletedProcess:
|
||||
merged = {**os.environ, **env, "SKIP_DB_MIGRATE": "1"}
|
||||
return subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
cwd=str(BACKEND_ROOT),
|
||||
env=merged,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra_env, expect_openapi",
|
||||
[
|
||||
({"ENVIRONMENT": "development"}, True),
|
||||
({"ENVIRONMENT": "production"}, False),
|
||||
({"ENVIRONMENT": "production", "PUBLIC_OPENAPI": "true"}, True),
|
||||
],
|
||||
)
|
||||
def test_openapi_urls_match_environment(extra_env: dict, expect_openapi: bool) -> None:
|
||||
snippet = f"""
|
||||
from main import app
|
||||
assert (app.openapi_url is not None) == {expect_openapi}
|
||||
assert (app.docs_url is not None) == {expect_openapi}
|
||||
"""
|
||||
proc = _run_fresh_import_int(snippet, extra_env)
|
||||
assert proc.returncode == 0, proc.stderr + proc.stdout
|
||||
|
||||
|
||||
def test_health_ready_minimal_body_in_production() -> None:
|
||||
snippet = """
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
c = TestClient(app)
|
||||
r = c.get("/api/health/ready")
|
||||
r.raise_for_status()
|
||||
j = r.json()
|
||||
assert "tables" not in j
|
||||
assert "detail" not in j
|
||||
assert "schema_migrations_count" not in j
|
||||
assert "status" in j and "database" in j and "schema_complete" in j
|
||||
"""
|
||||
proc = _run_fresh_import_int(
|
||||
snippet,
|
||||
{"ENVIRONMENT": "production"},
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr + proc.stdout
|
||||
|
||||
|
||||
def test_health_ready_full_detail_when_flag_in_production() -> None:
|
||||
snippet = """
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
c = TestClient(app)
|
||||
r = c.get("/api/health/ready")
|
||||
r.raise_for_status()
|
||||
j = r.json()
|
||||
assert "tables" in j
|
||||
assert "schema_migrations_count" in j
|
||||
"""
|
||||
proc = _run_fresh_import_int(
|
||||
snippet,
|
||||
{"ENVIRONMENT": "production", "HEALTH_READY_PUBLIC_DETAIL": "1"},
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr + proc.stdout
|
||||
|
||||
|
||||
def test_api_attachments_x_content_type_options_nosniff(client: TestClient) -> None:
|
||||
"""Globales Middleware: keine MIME-Sniffing-Heuristik für API/Health."""
|
||||
r = client.get("/health")
|
||||
assert r.status_code == 200
|
||||
assert r.headers.get("x-content-type-options") == "nosniff"
|
||||
r2 = client.get("/api/version")
|
||||
assert r2.status_code == 200
|
||||
assert r2.headers.get("x-content-type-options") == "nosniff"
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Unit-Tests ohne DB: Zusammenführung Session-Co vs. Gruppe."""
|
||||
import pytest
|
||||
|
||||
from routers.training_planning import effective_co_trainer_profile_ids_for_merge
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"unit_side,group_side,expected",
|
||||
[
|
||||
(None, [10, 22], [10, 22]),
|
||||
(None, None, []),
|
||||
([], [10, 22], []),
|
||||
([7, "8", 7], None, [7, 8]),
|
||||
],
|
||||
)
|
||||
def test_effective_co_trainer_profile_ids_for_merge(unit_side, group_side, expected):
|
||||
assert effective_co_trainer_profile_ids_for_merge(unit_side, group_side) == expected
|
||||
+499
-9
@@ -1,20 +1,26 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.4"
|
||||
BUILD_DATE = "2026-04-27"
|
||||
DB_SCHEMA_VERSION = "20260428031"
|
||||
APP_VERSION = "0.8.65"
|
||||
BUILD_DATE = "2026-05-08"
|
||||
DB_SCHEMA_VERSION = "20260508049"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.0.0",
|
||||
"profiles": "1.0.0",
|
||||
"clubs": "0.1.0",
|
||||
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
|
||||
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
|
||||
"tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
|
||||
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
|
||||
"club_memberships": "1.0.1", # Depends(get_tenant_context)
|
||||
"club_join_requests": "1.0.1", # Depends(get_tenant_context)
|
||||
"admin_users": "1.0.0", # GET /api/admin/users
|
||||
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
|
||||
"media_assets": "1.12.1", # official: nur Superadmin Lifecycle/PATCH; UI Lesemodus; Superadmin Upload-Verein = aktiv
|
||||
"groups": "0.1.0",
|
||||
"skills": "0.1.0",
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.1.0", # Varianten-CRUD API + UI; Listen mit include_variants
|
||||
"training_units": "0.1.0",
|
||||
"exercises": "2.19.1", # Verein: PUT default_club_media_copyright + Prompt beim Speichern (fehlende File-Asset-Copyrights)
|
||||
"training_units": "0.2.0",
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.3.0",
|
||||
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||
"import_wiki": "1.0.0",
|
||||
"admin": "1.0.0",
|
||||
"membership": "1.0.0",
|
||||
@@ -23,6 +29,490 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.65",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Übung auf Verein: fehlende Copyrights an Datei-Assets wieder per Bestätigung + Eingabe beim Speichern setzbar (PUT default_club_media_copyright; Bulk-PATCH ebenfalls)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.64",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Übung bearbeiten: Auto-Scroll beim Drag von Medien zu Textfeldern; Medien-Kacheln mehrspaltig; Sektion/Ablauf-Zuordnung an Medien entfernt (nur noch Titel bearbeiten); Picker: Video-Vorschau-Frame; Katalogvorschau ohne Anhangs-Medienliste; Ansehen mit Speichern-Hinweis + Zurück zur Bearbeitung von der Ansicht",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.63",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE/Übung Medien: Picker-Thumbnails; Dateiauswahl-Anzeige; bereits verknüpfte Archive-Medien ins Fließtext einfügen; Platzhalter-Caption data-shinkan-exercise-media-caption + Caret nach ZWSP; Lesemodus: Medienliste nur für nicht eingebettete Anhänge; bearbeiten: kompakte Kacheln mit Drag-and-Drop in Textfelder, Upload unter Medien entfällt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.62",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE Inline-Medien: Modals Mediathek+Hochladen + „Embed im Text“; Darstellungsgröße small|medium|full (data-shinkan-exercise-media-size); Lesemodus begrenzt Bild/Video-Breite",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.61",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"RTE „Bild/Video im Text“: eingebaute Hilfe (Caret + insertHTML/Fallback); sichtbarer 📎-Chip im Editor; Hinweis bei fehlgeschlagener Einfügung/Prompt-ID",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.60",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Inline-Medien im Übungs-Fließtext (MEDIA_SPEC §11): {{exerciseMedia:id}} → kanonisches span; nur exercise_media dieser Übung; create ohne Platzhalter",
|
||||
"Frontend: ExerciseRichTextBlock mit Allowlist-Sanitize + Embed; Toolbar „Bild/Video im Text“ im RichTextEditor wenn Medien an der Übung; Detail/Katalog/Liste konsistent",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.59",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Aktiver Verein: Backend resolve_tenant_context für Plattform-Admin ohne X-Active-Club-Id nutzt gespeichertes active_club_id wenn der Verein existiert (kein effective=null nach hartem Reload mehr)",
|
||||
"Frontend: Nach Vereinswechsel Profil neu laden; Dropdown-Wert aus effective_club_id / active_club_id / LocalStorage abgestimmt (getResolvedActiveClubIdForUi)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.58",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek offiziell: Ändern/Lifecycle nur Superadmin (nicht Plattform-Admin); Bearbeiten-Dialog für andere nur Lesemodus; Superadmin: Vereinsauswahl beim Archiv-Upload folgt aktiv/gesetzt effective_club_id",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.57",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Governance: visibility=official nur noch Superadmin (nicht Plattform-Admin)",
|
||||
"Medienarchiv: private Uploads als Plattform-Admin erfordern explizites club_id; gleiche Ordnerstruktur wie „Verein“, private Kopien mit .u{Profil} vor Dateiendung",
|
||||
"Übung visibility=Verein: angebundene Archiv-Dateien müssen aktiv sein und Copyright (≥3 Zeichen) haben; UI- und API-Fehlercodes CLUB_MEDIA_*",
|
||||
"Frontend: „Offiziell“ nur Superadmin (Bibliothek, Übungsformular, Bulk-Sichtbarkeit, Progressionsgraphen)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.56",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: Vereinsmedien unter library/{aus Name abgeleitet}-c{club_id}/ statt festem library/club/c{id}/; Sonderzeichen/Umlaute zu sicheren Ordnernamen; fehlender Name → verein-c{id}; Governance-Umzug liest aktuellen Vereinsnamen aus DB",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.55",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: Speicherpfad library/* mit Medientyp-Unterordnern (image, video, pdf, other) vor SHA-Dateinamen; Umzug bei Governance-PATCH nutzt mime_type aus DB",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.54",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Medienpfade: vereinsgeteilt (club) direkt unter library/club/c{id}/; private unter library/club/c{id}/u{profile}/ (kein Ordner „private“/„shared“); Dedupe private inkl. uploaded_by_profile_id",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.53",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Medienablage vereinsbezogen: private → library/club/c{id}/private, Vereinssichtbarkeit → …/shared, official unverändert; private Archiv-Upload: club_id oder X-Active-Club-Id; DB club_id bei private gesetzt; PATCH/Bulk: club_id für private nicht mehr blind auf NULL",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.52",
|
||||
"date": "2026-05-08",
|
||||
"changes": [
|
||||
"Neue lokale media_assets: hierarchische library/* Pfade; Dedupe nach sha+visibility+club_id; bei PATCH/Bulk-Patch Sichtbarkeit/Verein: Datei umziehen, exercise_media.file_path aktualisieren (Details siehe 0.8.53)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.51",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek GET: Verknüpfung zu Trainingseinheiten nur wenn Tabelle training_unit_exercises existiert (ältere/kaputte Schemas → keine 500, Einheiten-Liste leer)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.50",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: DB 046 media_assets.tags (GIN); GET filter media_kind, club_id (Superadmin), uploaded_by; Suche über Copyright & Tags; Antwort usage exercises + training_units; PATCH/Bulk tags; UI volle Breite, Filterleiste, ©-Symbol auf Kacheln, Links zu Übungen/Planung, gleiche Sichtbarkeits-/Status-Symbole wie Übungsliste",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.49",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek UI: Kacheln/Liste, Modal Bearbeiten, Video-First-Frame-Thumbs, Mobile/Safe-Area, Bulk; API: permissions pro Zeile, Uploader/Verein für Admin, PATCH Sichtbarkeit+Bezeichner, trash_soft nur Trainer-Eigenes-Privat / Vereinsorga / Plattform; purge nur Superadmin; superadmin_force_lifecycle + hard_delete; bulk-lifecycle, bulk-patch",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.48",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienbibliothek: GET /api/media-assets mit lifecycle (active|trash_soft|trash_hidden|all), copyright_notice in Liste; PATCH /api/media-assets/{id} (Copyright); GET …/file für Papierkorb wenn Lifecycle-Recht; Frontend /media + Admin-Nav + Link Übungsformular",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.47",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Übung „offiziell“ (§4.2): angehängte Datei-Assets müssen aktiv sein; Sichtbarkeit/Copyright per Bestätigung anheben; PUT /api/exercises/{id} + PATCH bulk-metadata: Felder promote_attached_media_for_official, default_official_media_copyright; Frontend Bestätigungsdialog",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.46",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Übung Medien-Upload: bei 409-Konflikt (Papierkorb-Dedupe) logger.warning mit exercise_id, profile_id, media_asset_id, lifecycle, visibility, club_id, sha256_prefix, Dateinamen",
|
||||
"ExerciseFormPage: erklärende Medien-Hinweistexte in GUI entfernt (Kurzbeschreibung + Archiv-Dialog)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.45",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Upload Übungsmedien: gleicher Inhalt (SHA-256) wie Papierkorb-Asset → 409 MEDIA_ASSET_IN_TRASH statt DB-Fehler; Lifecycle action reactivate (trash_soft/hidden → active)",
|
||||
"Frontend: Dialog Reaktivieren + Verknüpfen; uploadExerciseMedia wertet strukturiertes 409 aus",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.44",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"DELETE /api/exercises/{id}/media/{mid}: entfernt nur exercise_media; keine Datei-/media_assets-Löschung; Response orphan_media_asset_id wenn letzte Referenz",
|
||||
"Übung bearbeiten: Video-Kachel (Erstframe), Dateiname; Papierkorb-Schalter entfernt; „Aus Übung entfernen“ + optional Papierkorb bei Waise",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.43",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medienarchiv: GET /api/media-assets (Suche, nur aktive Assets, Bibliotheks-Sichtbarkeit); GET /api/media-assets/{id}/file (Thumbnails/Vorschau, ssetoken)",
|
||||
"Übungen: POST /api/exercises/{id}/media/from-asset — bestehendes Archiv-Medium verknüpfen ohne Upload-Duplikat",
|
||||
"Frontend Übung bearbeiten: „Aus Archiv verknüpfen…“, Medienvorschau-Modal, Kachel-Thumbnails in der Medienliste",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.42",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"Medien-Papierkorb: POST /api/media-assets/{id}/lifecycle (trash_soft, trash_hidden, recover, purge); Retention-Job scripts/media_retention_job.py",
|
||||
"Übungen: GET-Detail inkl. asset_lifecycle_state; Bearbeitungsrechte Erweiterung (Vereinsplanung); Frontend Übung bearbeiten: Reihenfolge, Papierkorb-Actions; Detail/Katalog: trash_hidden ausgeblendet, Hinweis trash_soft",
|
||||
"Fix: ExerciseDetailPage zeigt „Hinweise für Trainer“ wieder an",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.41",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"DB 045: media_assets, exercise_media.media_asset_id, platform_media_storage; Migration bestehender Medien; Upload-Dedupe pro sha256+visibility+club_id",
|
||||
"Effektives Medien-Verzeichnis: MEDIA_ROOT + Superadmin local_relative_root (GET/PUT /api/admin/platform-media-storage)",
|
||||
"Neue Uploads: storage_key exercises/{sha256}{ext}; Download/Delete nutzen media_assets",
|
||||
"api.js: getPlatformMediaStorage, putPlatformMediaStorage",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.40",
|
||||
"date": "2026-05-06",
|
||||
"changes": [
|
||||
"Übungen Liste: Fokusfilter mit UND-+ (must_include) und UND-− (must_exclude), nur ohne Fokusbereich (focus_only_without); Frontend Dropdown + Mit / − Ohne",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.39",
|
||||
"date": "2026-05-06",
|
||||
"changes": [
|
||||
"Übungen DELETE: Nur eigene private / Vereinsadmin für Vereins-Übungen / Plattform für globale; keine harte Löschung bei Verwendung in Blöcken, Plan-Abschnitten oder Progressionskanten (409 → archivieren)",
|
||||
"GET /api/exercises: Negativfilter (visibility_exclude_any, status_exclude_any), exclude_without_focus, include_archived; archivierte standardmäßig ausgeblendet",
|
||||
"Profile exercise_list_prefs (JSONB, Migration 043): gespeicherte Standardfilter; Frontend Übungsliste Filterdialog + „Als Standard speichern“",
|
||||
"Übungspicker: gleiche Negativfilter; Planung lädt archivierte Übungen immer mit (bestehende Zuordnungen)",
|
||||
"pytest: tests/test_exercises_delete_policy.py",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.38",
|
||||
"date": "2026-05-06",
|
||||
"changes": [
|
||||
"Trainingsplanung: Vereinsadmins sehen alle Einheiten bei club_id-/Gruppenliste; GET/PUT Einheit & Löschen mit can_manage_club_org",
|
||||
"Planung UI: „Trainer zuweisen“ in Vereins-Ansicht (Liste + Kalender) + eigener Modal; Mitgliederverzeichnis für Vereinsorganisation",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.37",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 042: training_units.assistant_trainer_profile_ids (Co-Trainer-Zuweisung je Termin; NULL = Gruppen-Standard)",
|
||||
"Trainingseinheiten: POST/PUT lead_trainer_profile_id & assistant_trainer_profile_ids; Leitung für Vereinsmitglieder (Vertretung); GET-Listen inkl. Zuweisung für Sichtbarkeit/assigned_to_me",
|
||||
"Frontend Trainingsplanung: Leitung/Co-Trainer pro Einheit; Dashboard-Text",
|
||||
"pytest: tests/test_training_unit_assignments.py",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.36",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"POST /api/profiles: nur Plattform-Admin; Anlage schema-konform (SERIAL, E-Mail, temporärer PIN-Hash); ProfileCreate mit Pflichtfeldern name + email",
|
||||
"pytest: POST-Szenarien in test_profiles_read_access.py",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.35",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DELETE /api/profiles/{pid}: nur Plattform-Admin (403 sonst); Unit-Tests mit gemockter DB",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.34",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"GET /api/profiles/{pid}: Zugriff nur eigenes Profil oder Plattform-Admin (403 sonst); Unit-Tests ohne DB; zwei Integrationstests mit PostgreSQL",
|
||||
"Integration: zwei zusätzliche Profil-Lese-Tests in test_access_layer_integration",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.33",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"CI pytest-backend wie Mitai-Jinkendo: docker compose exec backend (deployte Stacks shinkan / shinkan-dev); keine Runner-Python/Postgres-Service",
|
||||
"pytest.ini: Marker smoke/slow, addopts/-q wie Schwesterprojekt; CI: -m \"not slow\", ACCESS_LAYER_STRICT + Integration im Container",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.32",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"CI pytest-backend: kein setup-python — venv aus System-python3 (arm64/Debian Self-Host, Raspi)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.31",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"CI (Gitea): Job pytest-backend — Checkout, Postgres-Service, run_migrations, pytest (+ ACCESS_LAYER_INTEGRATION), ACCESS_LAYER_STRICT auf Router-Hinweis-Script",
|
||||
"Workflow test.yml: pull_request auf main/develop zusätzlich zu push",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.30",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"pytest: optionale PostgreSQL-Integration tests/test_access_layer_integration.py (Cross-Verein Übungen Liste/Detail; ACCESS_LAYER_INTEGRATION=1)",
|
||||
"pytest.ini: Marker „integration“",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.29",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Übungen: PATCH /api/exercises/bulk-metadata (bis 500 IDs) — Sichtbarkeit und/oder Status; Ersteller oder Plattform-Admin; Governance wie Einzel-PUT",
|
||||
"Übungsliste: Mehrfachauswahl, Alle auf dieser Seite, Dialog Massenänderung (Verein/offiziell nur Admins)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.28",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"ACCESS_LAYER: Übungen-, Trainingsplanung-, Rahmenprogramme-Detail nutzen library_content_visible_to_profile (einheitliche Leseprüfung)",
|
||||
"pytest: backend/requirements-dev.txt, pytest.ini, backend/tests/test_access_layer.py — ohne DB (library_content_visibility_sql, parse_active_club_header)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.27",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"ACCESS_LAYER Governance-Disziplin: .cursor/rules/access-layer.mdc; ARCHITECTURE 1.4 + CODING_RULES Tenant-Pfad; CLAUDE Pflichtlektüre Zugriffsschicht",
|
||||
"backend/scripts/check_access_layer_hints.py — Router ohne get_tenant_context außerhalb EXEMPT melden (optional ACCESS_LAYER_STRICT=1)",
|
||||
"club_tenancy.library_content_visible_to_profile; Audit-Tabelle um globale Router (EXEMPT) ergänzt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.26",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"ACCESS_LAYER: clubs-, club_memberships-, club_join_requests-Router nutzen Depends(get_tenant_context) statt nur require_auth",
|
||||
"profiles: PUT /profiles/{id} und /profile mit TenantContext; profile_document für /auth/me und intern",
|
||||
"exercise_progression_graphs: Liste/Detail nach library_content_visibility_sql; Leserechte Vereins-Graphs; POST/PUT mit assert_valid_governance_visibility und club_id wie Übungen",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.25",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Übungen PUT: bei visibility club wird club_id aus aktivem Verein oder Body gesetzt (verhindert club ohne club_id für Vereinsnutzer)",
|
||||
"club_tenancy: governance visibility club für Plattform-Admins ohne Vereinsmitgliedschaft (nur Existenz clubs.id)",
|
||||
"Login POST /api/auth/login: Rate-Limit 30/minute pro IP (vorher 5/minute)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.24",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Übungen-Router: get/update/delete, Varianten, Medien — Depends(get_tenant_context); Upload-Limits via TenantContext; fehlenden DELETE decorator variants gefixt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.23",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"ACCESS_LAYER: library_content_visibility_sql + TenantContext an Übungen-Liste, Rahmenprogramme, Trainingsplanung",
|
||||
"POST Übung/Vorlage/Rahmenprogramm: visibility club ohne club_id → effective_club_id; POST Übung mit assert_valid_governance_visibility",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.22",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"ACCESS_LAYER Stufe B: Modul tenant_context (resolve_tenant_context, Depends(get_tenant_context)); GET /profiles/me liefert effective_club_id; veralteter X-Active-Club-Id wird dort verworfen (ignore), strikt auf anderen Endpoints via Depends",
|
||||
"Arbeitspapier ACCESS_LAYER_ENDPOINT_AUDIT.md für Router-Inventar",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.21",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"FastAPI: Router club_memberships und club_join_requests registriert (GET /api/clubs/{id}/members, join-requests u. a.) — behoben 404 auf Vereinsseite Tab Mitglieder",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.20",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Migration 041: wenn noch kein superadmin existiert, werden ältestes Profil mit role admin zu superadmin hochgestuft",
|
||||
"Registrierung: erster Nutzer und ADMIN_BOOTSTRAP_EMAILS erhalten superadmin (vorher admin)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.19",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Portal-Admin: GET /api/admin/users (alle Nutzer + Vereine); PUT /profiles/{id} mit role/tier (Super-Admin nur durch Super-Admin); Mitgliedschaft inaktiv in Übersicht",
|
||||
"GUI Admin → Nutzer: Portal-Rolle/Tier, Verein zuweisen, Vereinsrollen bearbeiten",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.18",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 040 club_membership_requests; API Antrag/Abrufen/annehmen/ablehnen; öffentliches Vereinsverzeichnis; Mitglieder-Directory für Trainerwahl",
|
||||
"GUI: Vereinsverwaltung Tab Mitglieder & Anträge; Registrierung/Einstellungen Vereinsantrag; Gruppenformular Haupt- und Co-Trainer",
|
||||
"GET /profiles nur noch für Plattform-Admins",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.17",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Multi-Tenancy Phase 4: training_plan_templates + training_framework_programs Listen und Lesen nach visibility/club wie Übungen; Schreiben nur Ersteller oder Plattform-Admin; club_tenancy.assert_valid_governance_visibility",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.16",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"API Vereinsmitglieder: GET/POST/GET-one/PUT/DELETE /api/clubs/{id}/members (Plattform- oder Vereinsadmin); Frontend api.js Hooks",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.15",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 039 Fix: Co-Trainer-Backfill über Subquery + CASE (kein jsonb_array_length/jsonb_array_elements auf Nicht-Arrays durch Planner/LATERAL-Reihenfolge)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.14",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 039 Fix: Co-Trainer-Backfill nur wenn co_trainer_ids ein JSON-Array ist (vermeidet jsonb_array_length auf Nicht-Array)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.13",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"Fix: Startup unter Windows (cp1252) — Emoji/Sonderzeichen in print durch ASCII ([OK]/[FAIL]/[WARN]) ersetzt (main, run_migrations, db_init)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.12",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 039: club_members, club_member_roles, clubs.primary_admin_profile_id, profiles.active_club_id + Backfill",
|
||||
"Multi-Tenancy: Vereinslisten gefiltert, Vereinsanlage nur Plattform-Admin mit primary_admin_profile_id",
|
||||
"Übungen: visibility club nur für Mitglieder des zugeordneten Vereins",
|
||||
"GET /api/profiles/me: clubs[], ohne pin_hash; active_club_id setzen via PUT",
|
||||
"Frontend: X-Active-Club-Id, Vereins-Umschalter, Vereinsseiten angepasst",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.11",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 038: training_units.lead_trainer_profile_id (Vertretung / Leitung pro Termin)",
|
||||
"API GET /api/training-units: club_id, assigned_to_me, sort, limit; Co-Trainer in Sichtbarkeit; lead_trainer_name / effective_lead_trainer_profile_id",
|
||||
"API PUT /api/training-units/{id}: lead_trainer_profile_id (Validierung über Gruppe)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.10",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 037: Rahmen-Slot-Blueprints als training_units (framework_slot_id); migration training_framework_slot_exercises → Sektionen/Items; origin_framework_slot_id für Kopien",
|
||||
"API: Rahmen-Slots mit sections/exercises aus Blueprint; Kalender list_training_units ohne Blueprints; POST /api/training-units/from-framework-slot",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.9",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 036: Rahmenprogramm Kontext (Fokusbereich, Stilrichtung, M:N Trainingsarten & Zielgruppen); nur Bibliothek — plan_mode/group_id/Slot-training_unit entfernt.",
|
||||
"API: /api/training-framework-programs ohne concrete/library; Payload focus_area_id, style_direction_id, training_type_ids, target_group_ids",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.8",
|
||||
"date": "2026-05-05",
|
||||
"changes": [
|
||||
"DB 035: Trainingsrahmenprogramm (Rahmen, Ziele, Slots, Slot-Übungen); plan_mode concrete|library",
|
||||
"DB 035: training_plan_templates.visibility + Backfill club (CURR-007/008)",
|
||||
"API: CRUD /api/training-framework-programs (AuthZ wie Übungs-/Planungsbibliothek)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.7",
|
||||
"date": "2026-04-30",
|
||||
"changes": [
|
||||
"DB 034: Progressionskanten mit optionalen Varianten-Endpunkten",
|
||||
"API: POST …/edges/sequence (Reihe auf einmal); POST …/edges/delete-batch",
|
||||
"Frontend Progressions-UI: Sequenz-Editor, Ketten-Ansicht, Variantenwahl",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.6",
|
||||
"date": "2026-04-30",
|
||||
"changes": [
|
||||
"DB 033: exercise_progression_edges.notes (Entwicklungsziel)",
|
||||
"API: Kanten mit notes; JOIN Übungstitel in Listen; PUT Kanten-Notiz",
|
||||
"Frontend: Progressionsgraphen-Tab unter Übungen + Bereich in Übung bearbeiten",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.5",
|
||||
"date": "2026-04-30",
|
||||
"changes": [
|
||||
"DB 032: exercise_progression_graphs + exercise_progression_edges (Übung→Übung, edge_type next_exercise)",
|
||||
"API: CRUD Progressionsgraphen und Kanten unter /api/exercise-progression-graphs",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.4",
|
||||
"date": "2026-04-27",
|
||||
|
||||
+21
-24
@@ -1,13 +1,14 @@
|
||||
version: '3.8'
|
||||
# Keine festen container_name — Compose-Namen haben Projektprefix (<projekt>-postgres-1).
|
||||
# Medien: In .env SHINKAN_MEDIA_HOST (Host-Pfad) und optional MEDIA_ROOT (Container-Pfad) setzen.
|
||||
# Default Host /shinkan-media/dev — Verzeichnis ggf. anlegen oder Compose legt es an.
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: dev-shinkan-postgres
|
||||
environment:
|
||||
POSTGRES_DB: shinkan_dev
|
||||
POSTGRES_USER: shinkan_dev
|
||||
POSTGRES_PASSWORD: dev_password
|
||||
POSTGRES_DB: "${DB_NAME:-shinkan_dev}"
|
||||
POSTGRES_USER: "${DB_USER:-shinkan_dev}"
|
||||
POSTGRES_PASSWORD: "${DB_PASSWORD:-dev_password}"
|
||||
volumes:
|
||||
- dev-shinkan-db-data:/var/lib/postgresql/data
|
||||
ports:
|
||||
@@ -20,13 +21,12 @@ services:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: dev-shinkan-api
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
DB_NAME: shinkan_dev
|
||||
DB_USER: shinkan_dev
|
||||
DB_PASSWORD: dev_password
|
||||
DB_NAME: "${DB_NAME:-shinkan_dev}"
|
||||
DB_USER: "${DB_USER:-shinkan_dev}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:-dev_password}"
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL}
|
||||
SMTP_HOST: ${SMTP_HOST}
|
||||
@@ -34,20 +34,19 @@ services:
|
||||
SMTP_USER: ${SMTP_USER}
|
||||
SMTP_PASS: ${SMTP_PASS}
|
||||
SMTP_FROM: ${SMTP_FROM}
|
||||
# Öffentliche Dev-URL (E-Mail-Links); lokaler Zugriff per IP bleibt über ALLOWED_ORIGINS möglich
|
||||
APP_URL: "${DEV_APP_URL:-https://dev.shinkan.jinkendo.de}"
|
||||
# Login/Register vom Browser: HTTPS-Subdomain und optional LAN-IP (Compose überschreibbar per .env)
|
||||
ALLOWED_ORIGINS: "${DEV_ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}"
|
||||
ENVIRONMENT: development
|
||||
MEDIAWIKI_API_URL: https://karatetrainer.net/api.php
|
||||
MEDIAWIKI_USER: Jinkendo
|
||||
MEDIAWIKI_PASSWORD: Jinkendo6970
|
||||
MEDIAWIKI_CATEGORY_EXERCISES: Übungen
|
||||
MEDIAWIKI_CATEGORY_SKILLS: Fähigkeitsbeschreibung
|
||||
MEDIAWIKI_CATEGORY_METHODS: Methodenbeschreibung
|
||||
MEDIAWIKI_CATEGORY_MODELS: Reifegradmodelle
|
||||
APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-development}"
|
||||
MEDIAWIKI_API_URL: "${MEDIAWIKI_API_URL:-https://karatetrainer.net/api.php}"
|
||||
MEDIAWIKI_USER: "${MEDIAWIKI_USER:-Jinkendo}"
|
||||
MEDIAWIKI_PASSWORD: "${MEDIAWIKI_PASSWORD:-CHANGE_ME}"
|
||||
MEDIAWIKI_CATEGORY_EXERCISES: "${MEDIAWIKI_CATEGORY_EXERCISES:-Übungen}"
|
||||
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
|
||||
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
|
||||
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
volumes:
|
||||
- dev-shinkan-media:/app/media
|
||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media/dev}:${MEDIA_ROOT:-/app/media}
|
||||
ports:
|
||||
- "8098:8000"
|
||||
depends_on:
|
||||
@@ -63,7 +62,6 @@ services:
|
||||
# Leer = relative /api/*-URLs → gleicher Host wie die SPA (vermeidet Mixed Content HTTPS→HTTP)
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
container_name: dev-shinkan-ui
|
||||
ports:
|
||||
- "3098:80"
|
||||
depends_on:
|
||||
@@ -74,7 +72,6 @@ services:
|
||||
|
||||
volumes:
|
||||
dev-shinkan-db-data:
|
||||
dev-shinkan-media:
|
||||
|
||||
networks:
|
||||
dev-shinkan-network:
|
||||
|
||||
+22
-10
@@ -1,17 +1,16 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: shinkan-db-prod
|
||||
environment:
|
||||
POSTGRES_DB: shinkan
|
||||
POSTGRES_USER: shinkan_user
|
||||
POSTGRES_DB: "${DB_NAME:-shinkan}"
|
||||
POSTGRES_USER: "${DB_USER:-shinkan_user}"
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
volumes:
|
||||
- shinkan-db-data:/var/lib/postgresql/data
|
||||
# Nur localhost: DB nicht im LAN exponieren (Beta/Prod). Entferne 127.0.0.1: nur wenn du bewusst remote willst.
|
||||
ports:
|
||||
- "5434:5432"
|
||||
- "127.0.0.1:5434:5432"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- shinkan-network
|
||||
@@ -40,11 +39,25 @@ services:
|
||||
# Erste Self-Registration → Admin; oder ADMIN_BOOTSTRAP_EMAILS=mail@…,weitere@…
|
||||
AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-true}"
|
||||
ADMIN_BOOTSTRAP_EMAILS: "${ADMIN_BOOTSTRAP_EMAILS:-}"
|
||||
APP_URL: https://shinkan.jinkendo.de
|
||||
ALLOWED_ORIGINS: https://shinkan.jinkendo.de
|
||||
ENVIRONMENT: production
|
||||
# Werte wie in .env (APP_URL, ALLOWED_ORIGINS, ENVIRONMENT) — keine zweite „Wahrheit“ in YAML
|
||||
APP_URL: "${APP_URL:-https://shinkan.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://shinkan.jinkendo.de}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-production}"
|
||||
# MediaWiki/SMW Import — in dev-env.yml bereits gesetzt; Prod brauchte diese Zeilen ebenfalls,
|
||||
# sonst: leere MEDIAWIKI_API_URL im Container → Import bricht ab (auf Test/Dev war es immer gesetzt).
|
||||
MEDIAWIKI_API_URL: "${MEDIAWIKI_API_URL:-https://karatetrainer.net/api.php}"
|
||||
MEDIAWIKI_USER: "${MEDIAWIKI_USER:-}"
|
||||
MEDIAWIKI_PASSWORD: "${MEDIAWIKI_PASSWORD:-}"
|
||||
MEDIAWIKI_CATEGORY_EXERCISES: "${MEDIAWIKI_CATEGORY_EXERCISES:-Übungen}"
|
||||
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
|
||||
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
|
||||
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
||||
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
# Bind-Mount: Verzeichnis muss auf dem Host existieren und chown für den Docker-Daemon
|
||||
# zulassen (lokale Platte). Bei NFS/SMB oft "chown … operation not permitted" → anderen Pfad.
|
||||
volumes:
|
||||
- shinkan-media:/app/media
|
||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
||||
ports:
|
||||
- "8003:8000"
|
||||
depends_on:
|
||||
@@ -70,7 +83,6 @@ services:
|
||||
|
||||
volumes:
|
||||
shinkan-db-data:
|
||||
shinkan-media:
|
||||
|
||||
networks:
|
||||
shinkan-network:
|
||||
|
||||
+83
-32
@@ -1,9 +1,9 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-04-28
|
||||
**App-Version / DB-Schema:** siehe `backend/version.py`
|
||||
**Stand:** 2026-05-07
|
||||
**App-Version / DB-Schema:** App **0.8.59**, DB-Schema siehe `backend/version.py` (`DB_SCHEMA_VERSION`)
|
||||
|
||||
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand** und **nächste Baustellen**.
|
||||
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
|
||||
|
||||
### Produktion: `relation … does not exist` (z. B. `skill_main_categories`)
|
||||
|
||||
@@ -21,10 +21,17 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Thema | Pfad |
|
||||
|--------|------|
|
||||
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
| Projekt-Status (Skills, Wiki, Stats) | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| Übungen: API, DB, Architektur, Routing | `.claude/docs/technical/EXERCISES_API_SPEC.md`, `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_FRONTEND_ROUTING.md` |
|
||||
| Media / Upload | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Media / Upload-Limits / Embed | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
|
||||
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
|
||||
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
|
||||
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
|
||||
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
|
||||
|
||||
---
|
||||
|
||||
@@ -35,64 +42,108 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **`maturity_models`**, **`model_levels`**, **`model_skills`**, **`model_skill_levels`**: Matrix-Inhalt pro Modell.
|
||||
- **Kontext am Modell (Legacy, M:N):** `maturity_model_focus_areas`, `maturity_model_style_directions`, `maturity_model_target_groups` (Migration 025).
|
||||
- **Hierarchische Kontext-Zuordnung (Resolve):** `maturity_model_context_bindings` mit optional `style_direction_id`, `training_type_id` (Migration 026, 027).
|
||||
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
|
||||
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
|
||||
|
||||
### 2.2 Resolve-Logik (Backend)
|
||||
|
||||
- **`GET /api/maturity-models/resolve`**: Bindings zum Fokus, die zur Anfrage passen; Merge nach Spezifität (weniger spezifisch zuerst); spezifischere Zeilen überschreiben Zelltexte.
|
||||
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard (z. B. Fokus+Trainingsstil gilt für alle Stilrichtungen, aber nur für diesen Trainingsstil).
|
||||
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert. Sonst bei fehlendem Treffer **`null`** (kein stilles Legacy mit falschem Trainingsstil).
|
||||
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard.
|
||||
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert.
|
||||
|
||||
### 2.3 Export / Import (einzelnes Modell & aufgelöst)
|
||||
|
||||
- **`GET /api/maturity-models/{id}/export`**: `shinkan.maturity_model.v1` inkl. `context_bindings_for_model` (IDs).
|
||||
- **`GET /api/maturity-models/export-resolved`**: `shinkan.maturity_matrix_resolved.v1` (Query: `focus_area_id`, optional `style_direction_id`, `training_type_id`).
|
||||
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings` (nur bei `maturity_model.v1`).
|
||||
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings`.
|
||||
|
||||
### 2.4 Komplett-Stack Test → Prod
|
||||
|
||||
- **`GET /api/admin/matrix-stack/export`**: `shinkan.matrix_stack.v1` – Katalog (`skill_main_categories`, `skill_categories`, `skills`, `skill_level_definitions`) + alle Reifegradmodelle + Bindings mit **Namen** (Fokus/Stil/Trainingsstil).
|
||||
- **`POST /api/admin/matrix-stack/import`**: Upsert Katalog per Slug; Skills per Kategorie+Name; Modelle neu anlegen; Bindings per Katalognamen. Optional **`replace_all_maturity_models`** + **`confirm_replace_all: "DELETE_MATURITY_STACK"`** (nur Superadmin).
|
||||
- Router: `backend/routers/matrix_stack_bundle.py`, in `main.py` registriert.
|
||||
- **`GET /api/admin/matrix-stack/export`**, **`POST /api/admin/matrix-stack/import`** — siehe `matrix_stack_bundle.py`.
|
||||
|
||||
### 2.5 Frontend (Admin)
|
||||
|
||||
- **`frontend/src/pages/AdminMaturityModelsPage.jsx`**: Tabs u. a. Katalog, Modelle, Kontext-Zuordnung, **Matrix-Ansicht und Export**.
|
||||
- **`MaturityModelBindingsAdmin.jsx`**: Bindings CRUD, Erklärung Merge/Legacy.
|
||||
- **`MaturityMatrixToolsAdmin.jsx`**: Kontext auflösen, hierarchische Matrix-Ansicht, Export einzelnes Modell / aufgelöst, Einzelmodell-Import; **Komplett-Stack** mit eigenem Export-Button und **eigenem Dateifeld für Stack-Import** (`POST /api/admin/matrix-stack/import`).
|
||||
- **`frontend/src/utils/api.js`**: u. a. `exportMatrixStackBundle`, `importMatrixStackBundle`, Reifegrad-APIs.
|
||||
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Stand: Übungen (Lücke für nächste Session)
|
||||
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
|
||||
|
||||
**Ist (laut Projektdoku und aktuellem Produktziel):**
|
||||
|
||||
- Backend: Übungen-CRUD, M:N, Suche, Blöcke, Medien-Struktur u. a. sind in `PROJECT_STATUS.md` als umgesetzt geführt; viele Übungen stammen aus **MediaWiki-Import** (Wiki-Tracking-Tabellen).
|
||||
- **Soll / Nutzerfeedback:** In der Praxis fehlt oder ist unzureichend: **stabile Liste**, **gerenderte Detailansicht**, **Bearbeiten/Anlegen**, **Medien zuweisen/Upload** – konkrete Fehler (404, leere Liste, falsche Route) sind vor Ort zu verifizieren.
|
||||
|
||||
**Nächste Session sollte:**
|
||||
|
||||
1. Aktuelle Routen und Seiten prüfen (`App.jsx`, `EXERCISES_FRONTEND_ROUTING.md`).
|
||||
2. `GET /api/exercises` (Filter, Auth) und eine Beispiel-Übung gegen die Dev-DB testen.
|
||||
3. UI schrittweise: Liste → Detail → Formular → Medien (an Specs in `.claude/docs/technical/` ausrichten).
|
||||
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Technische Referenz (kurz)
|
||||
## 4. Stand: Medien-Management (Ist, 2026-05-07)
|
||||
|
||||
**Datenmodell (Kurz):**
|
||||
|
||||
- **`media_assets`:** Physische oder logische Archiv-Datei (u. a. `sha256`, `visibility`, `club_id`, `lifecycle_state`, `copyright_notice`, Speicherpfad/`storage_key`, `tags` ab passender Migration).
|
||||
- **`exercise_media`:** optional **`media_asset_id`**; weiterhin Embeds ohne Asset; Kontext/Sortierung/Titel wie bisher.
|
||||
- **`platform_media_storage`:** Superadmin — relativer Unterpfad unter `MEDIA_ROOT`.
|
||||
|
||||
**API (Auszug):**
|
||||
|
||||
- **`GET /api/media-assets`**, Filter (Lifecycle, `media_kind`, Verein, Suche, Tags), Berechtigungen pro Zeile.
|
||||
- **`PATCH /api/media-assets/{id}`** / Bulk-PATCH, **Lifecycle** (`POST …/lifecycle`, Bulk).
|
||||
- **`GET …/media-assets/{id}/file`** (inkl. Kontext `ssetoken` wo vorgesehen).
|
||||
- **`POST /api/exercises/{id}/media/from-asset`:** bestehendes Asset verknüpfen.
|
||||
- Übungs-Uploads erzeugen/verknüpfen **`media_assets`**; Governance wie **`library_content_*`** / TenantContext.
|
||||
|
||||
**Frontend:**
|
||||
|
||||
- Route **`/media`** (Medienbibliothek): Kacheln/Liste, Filter, Copyright, Lifecycle-Actions (Rollen gemäß Spec; **`official`:** bearbeiten/Lifecycle im Wesentlichen **Superadmin**, andere Rollen **Lesemodus** im Bearbeiten-Dialog).
|
||||
- Übungsformular: Archiv-Picker, Vorschau, Reaktivierung bei Dedupe-Konflikt (Papierkorb).
|
||||
|
||||
**Speicher & Pfade:**
|
||||
|
||||
- Struktur unter **`library/`** mit Vereinssegment (aus Vereinsname abgeleitet + `c{id}`), Unterordner nach Medienkind (`image`/`video`/`pdf`/`other`), Dateiname z. B. SHA-basiert — Details und Drift-Vermeidung in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
**Governance & Mandant:**
|
||||
|
||||
- **`visibility=official`** für Übungen: nur **Superadmin**; Medien **`official`:** Lifecycle/PATCH schwerpunktmäßig Superadmin (Plattform-Admin nicht gleich Superadmin).
|
||||
- **Aktiver Verein:** `profiles.active_club_id`, Header **`X-Active-Club-Id`**, Response **`effective_club_id`** — nach **0.8.59** konsistent inkl. Plattform-Admin beim Reload (Backend **`tenant_context`**, Frontend **`getResolvedActiveClubIdForUi`** + Profil-Refresh nach Vereinswechsel).
|
||||
|
||||
---
|
||||
|
||||
## 5. Geplant: Inline-Medienverlinkung (nicht umgesetzt)
|
||||
|
||||
**Ziel:** Mediendarstellung **innerhalb** von Fließtext-Feldern (Ablauf, Ziele, Trainerhinweise), konsistent mit derselben **`exercise_media`‑** bzw. Asset-Governance wie die Medienliste.
|
||||
|
||||
**Norm:** **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — u. a.:
|
||||
|
||||
- Verweis auf **`exercise_media.id`** (oder kanonisch übersetzte Markup-Syntax), **keine** zweite Sichtbarkeitslogik.
|
||||
- **Ein** zentraler Render-/Sanitize-Pfad für Übungstexte; keine verstreuten „roh `dangerouslySetInnerHTML`“-Pfade.
|
||||
- XSS/CSP: nur Allowlist-HTML und kontrollierte Player-Komponenten.
|
||||
|
||||
**Reihenfolge:** Archiv & aktuelle Governance gelten als Basis; Inline ist die **nächste** inhaltliche Ausbaustufe für Medien (siehe **`PROJECT_STATUS.md`** Nächste Schritte).
|
||||
|
||||
---
|
||||
|
||||
## 6. Nächste Session — sinnvolle Arbeitspakete
|
||||
|
||||
1. **Inline §11:** Syntax festlegen (z. B. `{{exerciseMedia:id}}` → kanonisches HTML), Server normalisieren bei Speichern, einen **`renderExerciseRichText()`**-Pfad im Frontend.
|
||||
2. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
3. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
4. **S3/Adapter:** Speicher-Abstraktion §7 — wenn Produkt es verlangt.
|
||||
5. **Rahmen/UI:** Kalender „aus Rahmen übernehmen“ weiter anbinden (parallel, unabhängig von Medien).
|
||||
|
||||
---
|
||||
|
||||
## 7. Technische Referenz (kurz)
|
||||
|
||||
| Bereich | Einstieg |
|
||||
|---------|----------|
|
||||
| Backend API | `backend/main.py`, `backend/routers/maturity_models.py`, `matrix_stack_bundle.py`, `exercises.py`, `catalogs.py`, `skills.py` |
|
||||
| Migrationen | `backend/migrations/` (u. a. 024–027 Reifegrad/Bindings) |
|
||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
||||
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
|
||||
| Frontend API | `frontend/src/utils/api.js` |
|
||||
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
|
||||
| Version / Changelog | `backend/version.py` |
|
||||
|
||||
---
|
||||
|
||||
## 5. Veraltete Hinweise
|
||||
## 8. Veraltete Hinweise
|
||||
|
||||
Die Datei `.claude/docs/working/HANDOVER_NEXT_SESSION.md` (2026-04-22) ist **historisch**; für den aktuellen Stand gilt **`docs/HANDOVER.md`**.
|
||||
`.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+10
-5
@@ -5,16 +5,21 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="description" content="Shinkan Jinkendo - Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung" />
|
||||
|
||||
<!-- PWA Meta Tags -->
|
||||
<!-- PWA / iOS Web App -->
|
||||
<meta name="theme-color" content="#1D9E75" media="(prefers-color-scheme: light)">
|
||||
<meta name="theme-color" content="#181816" media="(prefers-color-scheme: dark)">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
<!-- black-translucent: Inhalt bis unter die Statusleiste; passt zu viewport-fit=cover -->
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="Shinkan">
|
||||
<link rel="apple-touch-icon" href="/icon-192.png">
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
|
||||
<!-- Icons -->
|
||||
<!-- Icons (Dateien in public/) -->
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png">
|
||||
<link rel="shortcut icon" href="/favicon.ico">
|
||||
<link rel="icon" type="image/png" sizes="512x512" href="/icon-512.png">
|
||||
|
||||
<title>Shinkan Jinkendo</title>
|
||||
</head>
|
||||
|
||||
+24
-4
@@ -4,13 +4,29 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
|
||||
# Docker-Embedded DNS: Hostname »backend« bei Container-Neustarts neu auflösen
|
||||
# — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
# Uploads (Übungsmedien) und API erreichen Clients unter derselben Host-URL wie die SPA —
|
||||
# dafür muss Nginx zur FastAPI-Instanz im Compose-Netz weiterleiten.
|
||||
client_max_body_size 64m;
|
||||
# Uploads (Übungsmedien, Medienarchiv-Bulk) — Limit muss >= größte Einzeldatei und
|
||||
# bei multipart ggf. Summe mehrerer Dateien sein (Backend praxis: bis 1024 MB Admin).
|
||||
client_max_body_size 1024m;
|
||||
|
||||
# Medienbibliothek (React /media) — vor location ^~ /media/: sonst liefert ein Reload
|
||||
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
|
||||
location = /media {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
location = /media/ {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
set $docker_backend_svc backend;
|
||||
@@ -26,6 +42,8 @@ server {
|
||||
}
|
||||
|
||||
location ^~ /media/ {
|
||||
# Auslieferung Übungsdateien erfolgt geschützt über /api/exercises/.../media/.../file (?ssetoken).
|
||||
# Optional: Backend mit ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder /media/ ohne Auth.
|
||||
set $docker_backend_svc backend;
|
||||
proxy_pass http://$docker_backend_svc:8000$request_uri;
|
||||
proxy_http_version 1.1;
|
||||
@@ -42,8 +60,10 @@ server {
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# SPA routing - serve index.html for all routes
|
||||
location / {
|
||||
# Document-CSP für SPA/PWA — React nutzt häufig inline-styles; Mediendateien & API sind same-origin (Proxy).
|
||||
# Bei separater API-Origin: connect-src hier erweitern oder nginx-Envsubst nutzen.
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 611 B |
Binary file not shown.
|
After Width: | Height: | Size: 158 B |
Binary file not shown.
|
After Width: | Height: | Size: 642 B |
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "Shinkan Jinkendo",
|
||||
"short_name": "Shinkan",
|
||||
"description": "Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f4f3ef",
|
||||
"theme_color": "#1D9E75",
|
||||
"lang": "de",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
+84
-16
@@ -9,18 +9,23 @@ import {
|
||||
Outlet,
|
||||
} from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
||||
import DesktopSidebar from './components/DesktopSidebar'
|
||||
import { getMainNavItems } from './config/appNav'
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import VerifyPage from './pages/VerifyPage'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import AccountSettingsPage from './pages/AccountSettingsPage'
|
||||
import SettingsSystemInfoPage from './pages/SettingsSystemInfoPage'
|
||||
import ExercisesListPage from './pages/ExercisesListPage'
|
||||
import ExerciseDetailPage from './pages/ExerciseDetailPage'
|
||||
import ExerciseFormPage from './pages/ExerciseFormPage'
|
||||
import ClubsPage from './pages/ClubsPage'
|
||||
import InboxPage from './pages/InboxPage'
|
||||
import SkillsPage from './pages/SkillsPage'
|
||||
import TrainingPlanningPage from './pages/TrainingPlanningPage'
|
||||
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
|
||||
import TrainingFrameworkProgramEditPage from './pages/TrainingFrameworkProgramEditPage'
|
||||
import TrainingUnitRunPage from './pages/TrainingUnitRunPage'
|
||||
import TrainingCoachPage from './pages/TrainingCoachPage'
|
||||
import AdminCatalogsPage from './pages/AdminCatalogsPage'
|
||||
@@ -28,11 +33,23 @@ import AdminHierarchyPage from './pages/AdminHierarchyPage'
|
||||
import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
|
||||
import TrainerContextsPage from './pages/TrainerContextsPage'
|
||||
import MediaWikiImportPage from './pages/MediaWikiImportPage'
|
||||
import AdminUsersPage from './pages/AdminUsersPage'
|
||||
import AdminHomeRedirect from './components/AdminHomeRedirect'
|
||||
import PlatformAdminRoute from './components/PlatformAdminRoute'
|
||||
import MediaLibraryPage from './pages/MediaLibraryPage'
|
||||
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
||||
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
|
||||
import './app.css'
|
||||
|
||||
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||
function computeShowAdminNav(currentUser) {
|
||||
return currentUser?.role === 'superadmin'
|
||||
}
|
||||
|
||||
// Bottom Navigation (Mobile)
|
||||
function Nav({ isAdmin }) {
|
||||
const items = getMainNavItems(isAdmin)
|
||||
function Nav({ showAdminNav }) {
|
||||
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||
const loc = useLocation()
|
||||
|
||||
const navItemActive = (pathname, item, routerIsActive) => {
|
||||
@@ -51,7 +68,12 @@ function Nav({ isAdmin }) {
|
||||
'nav-item' + (navItemActive(loc.pathname, item, isActive) ? ' active' : '')
|
||||
}
|
||||
>
|
||||
<item.Icon size={20} strokeWidth={2} />
|
||||
<item.Icon size={26} strokeWidth={2} />
|
||||
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||
<span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
|
||||
{inboxCount > 99 ? '99+' : inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
<span>{item.shortLabel || item.label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
@@ -89,23 +111,27 @@ function ProtectedLayout() {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
const isAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const showAdminNav = computeShowAdminNav(user)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DesktopSidebar isAdmin={isAdmin} user={user} onLogout={handleLogout} />
|
||||
<OrgInboxProvider user={user}>
|
||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||
<div className="app-shell">
|
||||
<div className="app-shell__column">
|
||||
<div className="app-header app-header--mobile">
|
||||
<div className="app-logo">🥋 Shinkan</div>
|
||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||
<div className="app-header-mobile__top">
|
||||
<div className="app-logo">🥋 Shinkan</div>
|
||||
</div>
|
||||
<ActiveClubSwitcher variant="mobile" />
|
||||
</div>
|
||||
<div className="app-main">
|
||||
<InactiveMembershipBanner />
|
||||
<Outlet />
|
||||
</div>
|
||||
<Nav isAdmin={isAdmin} />
|
||||
<Nav showAdminNav={showAdminNav} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</OrgInboxProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -149,6 +175,8 @@ function AppRoutes() {
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="profile" element={<Navigate to="/settings" replace />} />
|
||||
<Route path="settings" element={<AccountSettingsPage />} />
|
||||
<Route path="settings/system" element={<SettingsSystemInfoPage />} />
|
||||
<Route path="media" element={<MediaLibraryPage />} />
|
||||
<Route path="exercises">
|
||||
<Route index element={<ExercisesListPage />} />
|
||||
<Route path="new" element={<ExerciseFormPage />} />
|
||||
@@ -156,15 +184,55 @@ function AppRoutes() {
|
||||
<Route path=":id" element={<ExerciseDetailPage />} />
|
||||
</Route>
|
||||
<Route path="clubs" element={<ClubsPage />} />
|
||||
<Route path="inbox" element={<InboxPage />} />
|
||||
<Route path="skills" element={<SkillsPage />} />
|
||||
<Route path="planning" element={<TrainingPlanningPage />} />
|
||||
<Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
|
||||
<Route path="planning/framework-programs/:id" element={<TrainingFrameworkProgramEditPage />} />
|
||||
<Route path="planning/framework-programs" element={<TrainingFrameworkProgramsListPage />} />
|
||||
<Route path="planning/run/:unitId/coach" element={<TrainingCoachPage />} />
|
||||
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
|
||||
<Route path="admin" element={<Navigate to="/admin/hierarchy" replace />} />
|
||||
<Route path="admin/hierarchy" element={<AdminHierarchyPage />} />
|
||||
<Route path="admin/maturity-models" element={<AdminMaturityModelsPage />} />
|
||||
<Route path="admin/catalogs" element={<AdminCatalogsPage />} />
|
||||
<Route path="admin/mediawiki-import" element={<MediaWikiImportPage />} />
|
||||
<Route path="planning" element={<TrainingPlanningPage />} />
|
||||
<Route path="admin" element={<AdminHomeRedirect />} />
|
||||
<Route
|
||||
path="admin/users"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminUsersPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/hierarchy"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminHierarchyPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/maturity-models"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminMaturityModelsPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/catalogs"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<AdminCatalogsPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/mediawiki-import"
|
||||
element={
|
||||
<PlatformAdminRoute>
|
||||
<MediaWikiImportPage />
|
||||
</PlatformAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="trainer-contexts" element={<TrainerContextsPage />} />
|
||||
</Route>
|
||||
|
||||
|
||||
+3929
-163
File diff suppressed because it is too large.
Load diff
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user