Compare commits
47
Commits
Safe-Point1
...
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 | ||
|
|
696cb09bf4 | ||
|
|
33fedd5ec6 | ||
|
|
c8a08f8a94 | ||
|
|
d04ebee1f6 | ||
|
|
0c1fbab0ef | ||
|
|
a7d68c0646 | ||
|
|
a34dc19f5d | ||
|
|
9227b98431 | ||
|
|
390b0ecb73 | ||
|
|
7e7adfab54 | ||
|
|
bce235b9f6 | ||
|
|
5334836207 | ||
|
|
38d78abc3b | ||
|
|
a143532486 | ||
|
|
2f54fef88e |
No files matched your search
@@ -1,29 +1,29 @@
|
||||
# Shinkan Jinkendo - Projekt-Status
|
||||
|
||||
**Stand:** 2026-05-07
|
||||
**Version (Code):** 0.8.48 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260507045` (u. a. `media_assets`, `platform_media_storage`)
|
||||
**Stand:** 2026-05-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 (Medien):** **Medienbibliothek `/media`** ergänzt den Archiv-Picker: **Lifecycle-Filter** (aktiv / Papierkorb / ausgeblendet), **Copyright bearbeiten** (`PATCH`), **Vorschau** inkl. Papierkorb bei Verwaltungsrecht; API-Liste `copyright_notice`; zuvor **§4.2 Promotion official** (Übung + Medien).
|
||||
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (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).
|
||||
|
||||
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
|
||||
|
||||
**Nächste Schritte — Medien & Archiv** (neu priorisiert, Stand 2026-05-07):
|
||||
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
|
||||
|
||||
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
|
||||
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`): Filter, Copyright, Lifecycle-Aktionen; Ausbau: Sichtbarkeit bearbeiten, Bulk, Quotas.
|
||||
3. **Tests & Observability:** gezielte pytest-Abdeckung für Archiv/Verknüpfen; optional Retention-Job-Dry-Run dokumentieren.
|
||||
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
|
||||
3. **Tests & Observability:** gezielte pytest-Abdeckung für Archiv/Verknüpfen/Lifecycle; Retention-Job (`scripts/media_retention_job.py`) in Betrieb/Doku verankern.
|
||||
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
|
||||
5. **Inline-Medien im Fließtext** (Spec §11) — bewusst **nach** Promotion/Copyright und tragfähigem Archiv-Workflow.
|
||||
5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
|
||||
|
||||
**Inline:** Leitplanken in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; kein Big-Bang vor stabiler Archiv-/Governance-Basis.
|
||||
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||
|
||||
---
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
|
||||
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
|
||||
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
|
||||
| **040–045** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets`, Plattform-Speicherpfad** | ✅ | 🔲 |
|
||||
| **040–046** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets` (046 z. B. Tags/GIN), Plattform-Speicherpfad** | ✅ Dev | 🔲 Prod |
|
||||
|
||||
---
|
||||
|
||||
@@ -103,10 +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 (Release 0.8.42 ff.)
|
||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` (Spec §4.2) — 0.8.47
|
||||
- [x] **Medien:** Medienbibliothek `/media` (Lifecycle-Filter, Copyright PATCH, Vorschau); Ausbau Manager/Bulk/S3 — Roadmap
|
||||
- [ ] **Medien:** Inline im Fließtext — nach Spec §11, nach Promotion/Archiv-Reife
|
||||
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (0.8.42 ff.)
|
||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
|
||||
- [x] **Medien:** Medienbibliothek `/media` (Filter, Tags, Copyright, Bulk-Lifecycle/PATCH, Lesemodus für eingeschränkte Rollen bei `official`)
|
||||
- [x] **Medien:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
|
||||
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
|
||||
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
||||
- [ ] Responsive Design / Dark Mode / PWA
|
||||
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
||||
@@ -137,7 +138,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
|
||||
### Dev
|
||||
|
||||
Branch `develop`; Migrations bis mindestens **045** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
|
||||
Branch `develop`; Migrations bis mindestens **046** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
|
||||
|
||||
### Prod
|
||||
|
||||
@@ -149,17 +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-05-05 | ✅ Aktualisiert (u. a. 036–037) |
|
||||
| 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-05-05 | ✅ Aktualisiert (037) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-05 | ✅ Aktualisiert |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-30 | ✅ Ergänzt Progressions-API |
|
||||
| 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) |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-07 | ✅ §11 Inline-Plan, Drift-Tab |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-07 | ✅ Medien-Meilenstein aktualisiert |
|
||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
|
||||
|
||||
---
|
||||
|
||||
@@ -170,4 +171,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-07
|
||||
**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.3
|
||||
**Stand:** 2026-05-05 (Migration **036–037:** Rahmen nur Bibliothek; Slot‑Inhalt über Blueprint‑`training_units` + Sektionen/Items wie Planung — siehe `TRAINING_FRAMEWORK_SPEC.md` §2)
|
||||
**Version:** 0.4.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
|
||||
|
||||
---
|
||||
@@ -476,6 +476,16 @@ skill_level_definitions (
|
||||
|
||||
---
|
||||
|
||||
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||
|
||||
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
|
||||
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
|
||||
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
|
||||
- **Geplant:** **Inline-Verweise** in Fließtextfeldern auf dieselbe Verknüpfung (`exercise_media.id`) — **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
|
||||
|
||||
---
|
||||
|
||||
## Methodenbezug (§11.5)
|
||||
|
||||
**Prinzip:** Genau EINE Hauptmethode, optional weitere Nebenmethoden.
|
||||
|
||||
@@ -5,9 +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.
|
||||
@@ -1,9 +1,9 @@
|
||||
# Gelieferte Features & technische Basis (Q2 2026)
|
||||
|
||||
**Stand:** 2026-05-05
|
||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.10**, **DB_SCHEMA_VERSION 20260505037**
|
||||
**Stand:** 2026-05-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**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
|
||||
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
|
||||
|
||||
---
|
||||
|
||||
@@ -17,7 +17,7 @@ Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren**
|
||||
| **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL |
|
||||
| **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** |
|
||||
| **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` |
|
||||
| **037** | **`training_units.framework_slot_id`**, strukturierter Ablauf wie Planung; Entfall **`training_framework_slot_exercises`**; **`origin_framework_slot_id`** |
|
||||
| **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
|
||||
---
|
||||
|
||||
@@ -79,7 +79,7 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`)
|
||||
|
||||
- **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante.
|
||||
- **Medien** wie zuvor (Formularteil).
|
||||
- **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
|
||||
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
|
||||
|
||||
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
|
||||
@@ -123,16 +123,44 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
|
||||
---
|
||||
|
||||
## 12. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
||||
|
||||
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
||||
|
||||
### 12.1 Datenbank & Router
|
||||
|
||||
- **`media_assets`**, **`platform_media_storage`**, **`exercise_media.media_asset_id`** (Dedupe `sha256` + Sichtbarkeit + `club_id` je nach Policy).
|
||||
- Router **`media_assets.py`**: Listen, PATCH, Lifecycle, Dateiauslieferung, Bulk; Integration in **`exercises.py`** (Upload, `from-asset`, Promotion/Copyright-Regeln bei `official` / Vereinsübungen).
|
||||
|
||||
### 12.2 Funktional (Ist)
|
||||
|
||||
- Zentrale **Medienbibliothek** Frontend **`/media`**: Filter (Lifecycle, Medientyp, Verein für Admins), Suche, Tags, Copyright bearbeiten (rollengerecht), Kacheln/Liste, Nutzungs-Hinweise (Übungen/Planung wo implementiert).
|
||||
- **Papierkorb** mehrstufig (`trash_soft` / `trash_hidden`), Recovery, Superadmin-Purge; strukturierte Fehlercodes bei Governance (u. a. Übung **`CLUB_MEDIA_*`**).
|
||||
- **Speicher:** Pfadkonvention **`library/{vereinssegment}/…`** mit Medienkind-Unterordnern; Umzug bei Sichtbarkeits-/Vereinsänderung; effektives Wurzelverzeichnis `MEDIA_ROOT` + Superadmin-`local_relative_root`.
|
||||
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
|
||||
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
|
||||
|
||||
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
|
||||
|
||||
- Platzhalter-Syntax: `{{exerciseMedia:id}}` (normalisiert auf `data-shinkan-exercise-media`), Validierung gegen `exercise_media` der aktuellen Übung.
|
||||
- Zentraler Anzeigepfad über `ExerciseRichTextBlock` inkl. Sanitize und Lifecycle-Hinweisen.
|
||||
- RTE-Workflow: Modal „Medien im Text“ (Mediathek + Upload), separates „Embed im Text“-Modal, Größenwahl (`small|medium|full`) und sprechende Platzhalter-Captions.
|
||||
- Bearbeiten: kompakte Medien-Kacheln + Drag&Drop in Textfelder; Auto-Scroll beim Drag aktiv.
|
||||
- UX-Schutz: Warnung bei Wechsel „Ansehen“ mit ungespeicherten Änderungen; Detailseite bietet Rückweg zur Bearbeitung.
|
||||
|
||||
---
|
||||
|
||||
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
|
||||
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
||||
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
|
||||
|
||||
---
|
||||
|
||||
## 13. Verweise
|
||||
## 14. Verweise
|
||||
|
||||
| Thema | Dokument |
|
||||
|--------|----------|
|
||||
@@ -140,5 +168,6 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
||||
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||
| Upload formal | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
||||
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
|
||||
|
||||
**Version:** 0.5.2
|
||||
**Stand:** 2026-05-05
|
||||
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints in `training_units`; Entfall `training_framework_slot_exercises`) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`).
|
||||
**Version:** 0.5.3
|
||||
**Stand:** 2026-05-07
|
||||
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints) und für Medien-Archiv bis **045+** (`media_assets`, …) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`) und **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
---
|
||||
|
||||
@@ -47,8 +47,7 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
|
||||
| **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ |
|
||||
| **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ |
|
||||
| **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ |
|
||||
|
||||
---
|
||||
| **040–046** | **2026-05** | **Mitgliedschaft/Anträge, Übungs-Governance-Erweiterungen, `media_assets`, `platform_media_storage`, `exercise_media.media_asset_id`, Tags/GIN u. a.** — exakte Nummern: `backend/migrations/`; fachliche Norm Medien: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** | ✅ je Umgebung |
|
||||
|
||||
## Migration 022: Skills Schema Complete (BREAKING CHANGE)
|
||||
|
||||
@@ -267,9 +266,11 @@ exercise_skills (
|
||||
UNIQUE (exercise_id, skill_id) -- Migration 020
|
||||
)
|
||||
|
||||
-- Varianten & Medien
|
||||
-- Varianten & Medien (028+ Embed/Datei; 045+ optional media_asset_id → media_assets)
|
||||
exercise_variants (id, exercise_id, name, description, ...)
|
||||
exercise_media (id, exercise_id, type, url, title, description, ...)
|
||||
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
||||
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
||||
platform_media_storage (id, local_relative_root, …)
|
||||
```
|
||||
|
||||
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# Exercises API Specification
|
||||
|
||||
**Version:** 1.4
|
||||
**Datum:** 2026-04-30
|
||||
**Version:** 1.5
|
||||
**Datum:** 2026-05-08
|
||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
|
||||
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
||||
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
||||
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||
@@ -335,7 +336,8 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
|
||||
### `PUT /exercises/{id}`
|
||||
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Request Body:** Same as POST (all fields optional except id)
|
||||
**Inline-Hinweis:** Rich-Text-Felder (`summary`, `goal`, `execution`, `preparation`, `trainer_notes` sowie `execution_changes` bei Varianten) unterstützen Platzhalter `{{exerciseMedia:id}}`, die serverseitig auf kanonisches Span-Markup normalisiert werden. Beim erstmaligen Anlegen ohne vorhandene `exercise_media` wird dies mit 400 abgelehnt.
|
||||
|
||||
**Response:** `200 OK` (full exercise object)
|
||||
|
||||
@@ -459,7 +461,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
- `media_type` (enum, required) - `image | video | document | sketch`
|
||||
- `title` (string, optional)
|
||||
- `description` (string, optional)
|
||||
- `context` (enum, optional) - `ablauf | detail | trainer_hint`
|
||||
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
|
||||
|
||||
**Entweder `file` ODER `embed_url` (nicht beides).**
|
||||
|
||||
@@ -505,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
{
|
||||
"title": "Neuer Titel",
|
||||
"description": "Neue Beschreibung",
|
||||
"is_primary": true,
|
||||
"context": "detail"
|
||||
"is_primary": true
|
||||
}
|
||||
```
|
||||
|
||||
`context` bleibt backendseitig kompatibel, wird in aktuellen Bearbeitungsflüssen jedoch nicht mehr aktiv zur UI-Zuordnung verwendet (Inline-Platzhalter priorisiert).
|
||||
|
||||
**Response:** `200 OK` (media object)
|
||||
|
||||
---
|
||||
@@ -893,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
- File size: max 50MB
|
||||
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
||||
- Embed platforms: `youtube, instagram, vimeo`
|
||||
- Inline-Rich-Text: `{{exerciseMedia:id}}` bzw. `data-shinkan-exercise-media="<id>"`; optional `data-shinkan-exercise-media-size="small|medium|full"` für Layout.
|
||||
|
||||
### Exercise Block
|
||||
- `name`: 3-200 chars
|
||||
@@ -947,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0
|
||||
**Letzte Änderung:** 2026-04-24
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Version:** 1.5
|
||||
**Letzte Änderung:** 2026-05-08
|
||||
**Status:** Living Spec
|
||||
@@ -1,7 +1,7 @@
|
||||
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
|
||||
|
||||
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
|
||||
**Stand:** 2026-05-07 (§11 Inline-Plan ergänzt)
|
||||
**Stand:** 2026-05-08 (Ist-Changelog Medien bis 0.8.64; §11 Inline umgesetzt und erweitert)
|
||||
**ersetzt/ergänzt:** operatives Upload-Format/Größen siehe weiterhin `MEDIA_UPLOAD_SPEC.md`
|
||||
**normative Governance:** Sichtbarkeit & Mandanten wie `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`; bei Abweichung zwischen Dokumenten hat der Zugriffsplan Vorrang, **außer** dieses Dokument präzisiert explizit nur den Medien-Domain.
|
||||
|
||||
@@ -186,26 +186,33 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung mit Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
|
||||
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Zeitpunkt der Umsetzung; Drift-Vermeidung ohne jetzigen Vollbau. |
|
||||
| 2026-05-08 | **0.8.64:** Bearbeiten-UX erweitert: Drag&Drop mit Auto-Scroll in Richtung Rich-Text, Medienliste in Kachel-Grid, Warnhinweis vor Wechsel „Ansehen“ bei ungespeicherten Änderungen + Rückweg „Zurück zur Bearbeitung“, Katalogvorschau ohne separaten Anhangs-Medienstreifen. |
|
||||
| 2026-05-08 | **0.8.63:** Inline-Medien-Picker als Modal (Mediathek/Upload + separates Embed-Modal), Größenwahl `small|medium|full`, Platzhalter-Caption (`data-shinkan-exercise-media-caption`), Wiederverwendung bereits verknüpfter Assets im Picker, kompakter Medienbereich mit Drag&Drop in Textfelder. |
|
||||
| 2026-05-08 | **0.8.60 §11:** Inline in Übungstexten (`{{exerciseMedia:id}}` / `data-shinkan-exercise-media`); Server-Normalisierung + Validierung; Client-Sanitize und zentraler Block-Renderer (`ExerciseRichTextBlock`); CREATE ohne bestehende `exercise_media` lehnt Platzhalter ab. |
|
||||
| 2026-05-07 | **0.8.59:** Dokumentation — Aktiver Verein (Profil/Header/`effective_club_id`) für Plattform-Admin und UI-Dropdown synchron; kein fachliches Archiv-Schema-Change. |
|
||||
| 2026-05-07 | **0.8.58:** Medien **`official`:** Lifecycle schwerpunktmäßig **Superadmin** (nicht Plattform-Admin); Bearbeitungsdialog Bibliothek für andere Rollen **Lesemodus**; Superadmin-Upload: Vereinskontext folgt aktiv gesetztem Verein / `effective_club_id`. |
|
||||
| 2026-05-07 | **0.8.47–0.8.57 (Auszug):** Übung **`official`** nur Superadmin; Vereinsübungen mit File-Assets: **Copyright-Pflicht**; Speicherpfade **`library/`** mit Vereinsordner (Name+c{id}), Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeit; Bibliothek-GET mit Filtern/Tags/Nutzungs-Anzeige; Bulk-Lifecycle/PATCH; Lesemodus/Kacheln; Konflikt **409** bei Upload-Dedupe vs. Papierkorb + UI-Reaktivierung. |
|
||||
| 2026-05-07 | **0.8.42–0.8.43:** Papierkorb-Lifecycle API, Retention-Skript; **`POST …/exercises/{id}/media/from-asset`**; Übungs-UI Archiv verknüpfen / Vorschau. |
|
||||
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
|
||||
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Umsetzung **nach** tragfähigem Archiv — siehe **`docs/HANDOVER.md`** §5. |
|
||||
| 2026-05-07 | **Medienmanager (Basis):** `GET /api/media-assets?lifecycle=…`, `copyright_notice` in Response; `PATCH` Copyright; `GET …/file` für Papierkorb-Zeilen bei Verwaltungsrecht; UI-Route `/media` (Medienbibliothek). |
|
||||
|
||||
---
|
||||
|
||||
## 11. Inline-Medien im Fließtext (Planung, Leitplanken)
|
||||
## 11. Inline-Medien im Fließtext (Umsetzung & Leitplanken)
|
||||
|
||||
**Status:** nicht implementiert; verbindlich nur als **Richtschnur**, damit später **kein Big-Bang-Refactor** nötig ist.
|
||||
**Status:** Frontend-Renderer und API-Validierung/Normalisierung umgesetzt (App ≥ 0.8.60); verbindliche Leitplanken unten.
|
||||
|
||||
### 11.1 Ziel
|
||||
|
||||
- Medien (Player, Bild) sollen **an definierter Stelle** in Feldern wie Ablauf / Ziel / Notizen erscheinen können – zusätzlich oder statt reiner Zuordnung zu den Sektionen `ablauf` / `detail` / `trainer_hint`.
|
||||
- **Keine zweite Sichtbarkeit:** Inline verweist immer auf dieselbe **Übungs-Medium-Zeile** (`exercise_media.id`) bzw. indirekt auf das gleiche Asset wie die Medienliste; **Lesen/Ausliefern** nur nach **bestehender** Übungs- + Medien-Governance (§4.1).
|
||||
|
||||
### 11.2 Platzhalter-Konvention (Vorschlag für spätere Umsetzung)
|
||||
### 11.2 Platzhalter-Konvention (**festgelegt**)
|
||||
|
||||
- Beim **Speichern** im Rich-Text: markierter Verweis, z. B.
|
||||
`data-shinkan-exercise-media="<numerische exercise_media.id>"` auf einem **neutralen** Element (`span`/`figure`), **oder** eine interne Kurzsyntax (`{{exerciseMedia:123}}`), die der Server beim Speichern in eine **kanonische** HTML-Form überführt.
|
||||
- **Final festlegen** beim Start der Implementierung (ein Format, nicht mehrere parallele).
|
||||
- **Kanonisches Markup nach Speichern:** `<span data-shinkan-exercise-media="<numerische exercise_media.id>" class="shinkan-inline-media"></span>`.
|
||||
- **Erweiterung (UI/Lesbarkeit):** optionales Attribut `data-shinkan-exercise-media-size="small|medium|full"` (Default `medium`) und optional `data-shinkan-exercise-media-caption="..."` für sprechende Platzhalter-Chips im Editor.
|
||||
- **Kurzsyntax (Eingabe/Import):** `{{exerciseMedia:123}}` — Server normalisiert beim Speichern (PUT Übung / Varianten) in das kanonische `span`; **CREATE** ohne bestehende `exercise_media`-Zeilen verwirft Platzhalter mit **400**.
|
||||
|
||||
### 11.3 Rendering & Sicherheit
|
||||
|
||||
@@ -214,14 +221,15 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
||||
|
||||
### 11.4 Koexistenz mit Sektions-Medien
|
||||
|
||||
- **Liste + Inline** dürfen dasselbe `exercise_media` referenzieren (ein Player an zwei Stellen) – Produktentscheidung: später optional „Duplikat vermeiden“-Hinweis in der UI.
|
||||
- **Liste + Inline** dürfen dasselbe `exercise_media` referenzieren (ein Player an zwei Stellen).
|
||||
- Stand 0.8.64: Katalog-/Vorschaupfade priorisieren Inline-Darstellung; ein zusätzlicher Anhangsblock wird dort nicht mehr parallel erzwungen.
|
||||
- Import/Wiki: vor großen Content-Migrationen **Syntax festlegen**, damit nicht irreversibel „falsches“ HTML importiert wird.
|
||||
|
||||
### 11.5 Wann umsetzen (Reihenfolge)
|
||||
|
||||
1. **Vorher:** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Basis-Papierkorb (§5) – jeweils stabil.
|
||||
2. **Danach:** Inline implementieren, sobald Trainer-Feedback oder Content-Menge den Bedarf **konkret** bestätigt (typisch nach 1–2 Beta-Zyklen).
|
||||
3. **Nicht nötig:** vorher kompletten Block-Editor einführen; **Platzhalter im bestehenden RTE** ist der vorgesehene **schlanke** Einstieg.
|
||||
1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
|
||||
2. **Umgesetzt (Stand 0.8.64):** Platzhalter/Kurzsyntax + zentraler Frontend-Render-Pfad + Server-Validierung gemäß §11.1–11.4; Editor-Einstieg „Medium einfügen“ inkl. Modal-Picker (Mediathek/Upload), separates Embed-Modal, Größenwahl und Drag&Drop aus der Medienliste.
|
||||
3. **Editor:** kein Zwang zum vollen Block-Editor vorab; **Platzhalter im bestehenden RTE** ist der vorgesehene schlanke Einstieg.
|
||||
|
||||
### 11.6 Refactor-Vermeidung (jetzt schon)
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
# Media Upload & Embed Specification
|
||||
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-04-27
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
|
||||
**Version:** 1.2
|
||||
**Datum:** 2026-05-07
|
||||
**Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
|
||||
|
||||
> **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:**
|
||||
> Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung).
|
||||
|
||||
@@ -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.*
|
||||
@@ -58,7 +58,8 @@ return {"message": "Fehler", "success": False}
|
||||
### 1.4 Mandanten & Zugriffsschicht (Shinkan / ACCESS_LAYER)
|
||||
|
||||
**Verbindlicher Rahmen:** `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
|
||||
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher, geplante Inline-Verlinkung §11):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
**Session-Handover (Ist + nächste Schritte):** `docs/HANDOVER.md`
|
||||
**Fortlaufendes Inventar:** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
|
||||
|
||||
**Definition of Done für neue oder geänderte geschützte APIs**, sobald Daten **Verein**, **Sichtbarkeit** oder **mandantenbezogene Listen** betreffen:
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
|
||||
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
|
||||
3. Spez-Index: **`.claude/docs/README.md`**
|
||||
4. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
4. **Session-Handover (aktuelle Prioritäten, Medien-Ist):** **`docs/HANDOVER.md`**
|
||||
5. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ ENVIRONMENT=production
|
||||
|
||||
# Medien (Docker Compose): SHINKAN_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
|
||||
# MEDIA_ROOT = gleicher Pfad im Container (muss mit dem Mount-Ziel übereinstimmen — FastAPI).
|
||||
# Prod: Verzeichnis VOR erstem "docker compose up" anlegen (z. B. sudo mkdir -p …/prod).
|
||||
# Wenn Docker meldet "chown … operation not permitted": oft NAS/NFS oder Rechte — lokalen Pfad nutzen.
|
||||
SHINKAN_MEDIA_HOST=/shinkan-media
|
||||
MEDIA_ROOT=/app/media
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
|
||||
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
||||
> | Medien-Archiv, Lifecycle, Promotion | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
@@ -57,7 +58,7 @@ backend/
|
||||
└── routers/ # Router-Module
|
||||
auth · profiles · clubs · groups · skills · methods
|
||||
exercises · exercise_progression_graphs · training_units · training_programs
|
||||
planning · import_wiki · admin · membership
|
||||
planning · import_wiki · admin · membership · media_assets
|
||||
|
||||
frontend/src/
|
||||
├── App.jsx # Root, Auth-Gates, Navigation
|
||||
@@ -82,10 +83,11 @@ frontend/src/
|
||||
|
||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||
|
||||
Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**; Kern: Übungen, Varianten, Medien, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md` und `TRAINING_FRAMEWORK_SPEC.md` §2.
|
||||
Kurz (Stand 2026-05-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`.
|
||||
|
||||
@@ -106,7 +108,7 @@ Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**
|
||||
- `exercises` - Übungen (Kernobjekt)
|
||||
- `exercise_variants` - Übungsvarianten
|
||||
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
||||
- `exercise_media` - Medien (Bilder, Videos); Zielbild Archiv & Lifecycle: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. **Inline im Fließtext** (Übungstexte): geplant §11 derselben Spec — Anker `exercise_media.id`, einheitlicher Render-Pfad; noch nicht implementiert.
|
||||
- `exercise_media` - Medien (Bilder, Videos); Zielbild Archiv & Lifecycle: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. **Inline im Fließtext** (Übungstexte) ist implementiert (Spec §11): Anker `exercise_media.id`, einheitlicher Render-Pfad.
|
||||
|
||||
**Trainingsplanung / Rahmen:**
|
||||
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
||||
|
||||
@@ -13,6 +13,7 @@ Shinkan ist eine moderne Web- und Mobile-App für Kampfsport-Trainer und Vereine
|
||||
- **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten
|
||||
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
|
||||
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
|
||||
- **Medien:** Zentrale **Medienbibliothek** (`/media`), Archiv mit Lifecycle/Papierkorb, Verknüpfung in Übungen — Norm: `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` · Einstieg: `docs/HANDOVER.md`
|
||||
|
||||
## Nicht in Shinkan
|
||||
|
||||
|
||||
+48
-23
@@ -91,7 +91,12 @@ def can_manage_club_org(cur, profile_id: int, club_id: int, global_role: Optiona
|
||||
|
||||
|
||||
def can_plan_in_club(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
|
||||
"""Trainingsgruppen anlegen / planen: Admin-Rollen im Verein oder Plattform."""
|
||||
"""Trainingsgruppe anlegen u.Ä.; Vereins-rollentrainer, Content-Editor, Spartenleitung …
|
||||
|
||||
Hinweis: ``content_editor`` ist derzeit zusammen mit ``trainer``/``division_lead`` in diesem
|
||||
gemeinsamen Strang gebündelt — u.a. Vereinsübungen bearbeiten (s. exercises) und
|
||||
Trainingsgruppen unter ``clubs``. Es gibt noch keine eigene Nur-Content-Guard pro Endpunkt.
|
||||
"""
|
||||
if is_platform_admin(global_role):
|
||||
return True
|
||||
return has_club_role(
|
||||
@@ -157,13 +162,13 @@ def assert_valid_governance_visibility(
|
||||
visibility: str,
|
||||
club_id: Optional[int],
|
||||
) -> None:
|
||||
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Plattform-Admin."""
|
||||
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Superadmin."""
|
||||
if visibility not in _GOVERNANCE_VISIBILITY:
|
||||
raise HTTPException(status_code=400, detail="Ungültige visibility")
|
||||
if visibility == "official" and not is_platform_admin(role):
|
||||
if visibility == "official" and not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Plattform-Admins dürfen offizielle Inhalte setzen",
|
||||
detail="Nur Superadmins dürfen offizielle Inhalte setzen",
|
||||
)
|
||||
if visibility == "club":
|
||||
if club_id is None:
|
||||
@@ -198,25 +203,45 @@ def exercise_visible_to_profile(
|
||||
created_by: Optional[int],
|
||||
global_role: Optional[str],
|
||||
) -> bool:
|
||||
"""Leserechte einer Übung. Für neue Codepfade lieber `library_content_visible_to_profile` verwenden."""
|
||||
if is_platform_admin(global_role):
|
||||
"""
|
||||
Leserechte einer Übung (und analoger Bibliotheksobjekte).
|
||||
|
||||
Vereinsbezogene Inhalte (visibility club): aktiv nur mit **aktiver** Mitgliedschaft in diesem Verein.
|
||||
Mitgliedschaft mit status **inactive** sperrt — auch für Plattform-/Super-Admins — solange eine
|
||||
Mitgliedschaft existiert.
|
||||
|
||||
Ist man kein Mitglied dieses Vereins, behalten Plattform-Admins den bisherigen „Audit“-Zugang
|
||||
zum Vereinskontext ohne eigene Mitgliedschaft.
|
||||
"""
|
||||
vis = (visibility or "").strip().lower()
|
||||
plat = is_platform_admin(global_role)
|
||||
pid = int(profile_id)
|
||||
|
||||
if vis == "official":
|
||||
return True
|
||||
if visibility == "official":
|
||||
if created_by is not None and int(created_by) == pid:
|
||||
return True
|
||||
if created_by is not None and created_by == profile_id:
|
||||
return True
|
||||
if visibility == "private":
|
||||
if vis == "private":
|
||||
return plat
|
||||
if vis != "club":
|
||||
return False
|
||||
if visibility == "club":
|
||||
if exercise_club_id is None:
|
||||
return False
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(profile_id, exercise_club_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
return False
|
||||
if exercise_club_id is None:
|
||||
return False
|
||||
try:
|
||||
ecid = int(exercise_club_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.status
|
||||
FROM club_members cm
|
||||
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(pid, ecid),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return plat
|
||||
st_raw = row["status"] if isinstance(row, dict) else row[0]
|
||||
return str(st_raw or "active").strip().lower() == "active"
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
Übungs-Fließtext: Inline-Verweise auf exercise_media.id (MEDIA_ASSETS_AND_ARCHIVE_SPEC §11).
|
||||
|
||||
- Kurzsyntax beim Speichern → kanonisches <span data-shinkan-exercise-media="…">.
|
||||
- Verweise müssen für die betreffende Übung gültige exercise_media-Zeilen sein.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import FrozenSet, Optional, Set
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
# {{exerciseMedia:123}} (Whitespace tolerant, case-insensitive Schlüssel)
|
||||
_BRACE_PATTERN = re.compile(r"\{\{\s*exerciseMedia\s*:\s*(\d+)\s*\}\}", re.IGNORECASE)
|
||||
# bereits gespeichertes Markup (einfache Anführungszeichen-varianten durch Regex abgedeckt)
|
||||
_DATA_ATTR_PATTERN = re.compile(r'data-shinkan-exercise-media\s*=\s*["\']?(\d+)["\']?', re.IGNORECASE)
|
||||
|
||||
RICH_HTML_EXERCISE_FIELDS: FrozenSet[str] = frozenset(
|
||||
{"summary", "goal", "execution", "preparation", "trainer_notes"}
|
||||
)
|
||||
|
||||
|
||||
def normalize_inline_exercise_media_markup(html: Optional[str]) -> Optional[str]:
|
||||
"""Wandelt {{exerciseMedia:id}} in kanonisches span mit data-shinkan-exercise-media."""
|
||||
|
||||
if html is None:
|
||||
return None
|
||||
if not isinstance(html, str):
|
||||
html = str(html)
|
||||
stripped = html.strip()
|
||||
if not stripped:
|
||||
return html
|
||||
|
||||
def _repl(match: re.Match) -> str:
|
||||
mid = int(match.group(1))
|
||||
return (
|
||||
f'<span data-shinkan-exercise-media="{mid}" data-shinkan-exercise-media-size="medium" '
|
||||
f'class="shinkan-inline-media"></span>'
|
||||
)
|
||||
|
||||
return _BRACE_PATTERN.sub(_repl, html)
|
||||
|
||||
|
||||
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
|
||||
"""Sammelt alle referenzierten exercise_media.ids aus Kurzsyntax und kanonischem Span."""
|
||||
if html is None or not isinstance(html, str):
|
||||
return set()
|
||||
if not html.strip():
|
||||
return set()
|
||||
ids: Set[int] = set()
|
||||
ids.update(int(m) for m in _BRACE_PATTERN.findall(html))
|
||||
ids.update(int(m) for m in _DATA_ATTR_PATTERN.findall(html))
|
||||
return ids
|
||||
|
||||
|
||||
def assert_no_inline_media_references_on_create(ids: Set[int]) -> None:
|
||||
"""Neue Übung hat noch keine exercise_media-Zeilen — Platzhalter verboten."""
|
||||
|
||||
if not ids:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "INLINE_EXERCISE_MEDIA_ON_CREATE",
|
||||
"message": (
|
||||
"Medienverweise im Fließtext sind beim ersten Anlegen der Übung nicht möglich. "
|
||||
"Bitte Übung ohne Platzhalter speichern, Medien hochladen oder verknüpfen "
|
||||
"und die Verweise dann bearbeiten ({{exerciseMedia:id}} oder „Medium einfügen“)."
|
||||
),
|
||||
"invalid_exercise_media_ids": sorted(ids),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def validate_inline_exercise_media_ids_for_exercise(cur, exercise_id: int, ids: Set[int]) -> None:
|
||||
"""Prüft, dass jede genannte exercise_media.id zu dieser Übung gehört."""
|
||||
|
||||
if not ids:
|
||||
return
|
||||
sid = sorted(ids)
|
||||
ph = ",".join(["%s"] * len(sid))
|
||||
cur.execute(
|
||||
f"SELECT id FROM exercise_media WHERE exercise_id = %s AND id IN ({ph})",
|
||||
(exercise_id, *sid),
|
||||
)
|
||||
found = set()
|
||||
for row in cur.fetchall():
|
||||
rid = row["id"] if isinstance(row, dict) else row[0]
|
||||
found.add(int(rid))
|
||||
missing = ids - found
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "INLINE_EXERCISE_MEDIA_INVALID",
|
||||
"message": "Ein oder mehrere eingebettete Medien-Verweise gehören nicht zu dieser Übung.",
|
||||
"invalid_exercise_media_ids": sorted(missing),
|
||||
},
|
||||
)
|
||||
@@ -27,20 +27,26 @@ HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS",
|
||||
def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
"""
|
||||
Papierkorb Stufe 2 / Recovery / Reaktivierung — nicht für trash_soft (siehe assert_can_trash_soft).
|
||||
§5.2: official nur Plattform-Admin; club Vereinsorga; privat nur Uploader.
|
||||
§5.2: official nur Superadmin; club Vereinsorga; privat nur Uploader (Plattform-Admin sonst wie bisher).
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = (tenant.global_role or "").strip().lower()
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Offizielle Medien dürfen nur von Superadmins geändert oder gelöscht werden",
|
||||
)
|
||||
return
|
||||
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
uid = asset.get("uploaded_by_profile_id")
|
||||
if vis == "private":
|
||||
if uid is not None and int(uid) == int(profile_id):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||
if vis == "official":
|
||||
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
|
||||
if vis == "club":
|
||||
cid = asset.get("club_id")
|
||||
if cid is None:
|
||||
@@ -54,15 +60,20 @@ def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict)
|
||||
def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
"""
|
||||
Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads.
|
||||
Vereinsmedien: Vereinsorga; official: Plattform-Admin; Superadmin: immer.
|
||||
Vereinsmedien: Vereinsorga; official: nur Superadmin; Plattform-Admin: sonst wie Verein/privat.
|
||||
"""
|
||||
role_raw = tenant.global_role
|
||||
role = (role_raw or "").strip().lower()
|
||||
if is_superadmin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Offizielle Medien dürfen nur von Superadmins in den Papierkorb gelegt werden",
|
||||
)
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = (asset.get("visibility") or "private").strip().lower()
|
||||
uid = asset.get("uploaded_by_profile_id")
|
||||
cid = asset.get("club_id")
|
||||
pid = int(tenant.profile_id)
|
||||
@@ -80,8 +91,6 @@ def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
|
||||
status_code=403,
|
||||
detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen",
|
||||
)
|
||||
if vis == "official":
|
||||
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,23 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
_CLUB_SLUG_TRANS = str.maketrans(
|
||||
{
|
||||
"ä": "ae",
|
||||
"ö": "oe",
|
||||
"ü": "ue",
|
||||
"ß": "ss",
|
||||
"Ä": "ae",
|
||||
"Ö": "oe",
|
||||
"Ü": "ue",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _default_media_root() -> Path:
|
||||
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
|
||||
@@ -44,6 +58,70 @@ def get_effective_media_root(cur: Any) -> Path:
|
||||
return (base / rel).resolve()
|
||||
|
||||
|
||||
def library_media_kind_dir(mime_type: Optional[str], ext: str) -> str:
|
||||
"""
|
||||
Unterordner unter library/* — an API-Filter media_kind angelehnt (image/video/pdf/other).
|
||||
|
||||
Bei fehlendem MIME wird anhand der Dateiendung geraten (letzte Instanz: other).
|
||||
"""
|
||||
m = (mime_type or "").strip().lower()
|
||||
x = (ext or "").strip().lower()
|
||||
if x and not x.startswith("."):
|
||||
x = "." + x
|
||||
|
||||
if m.startswith("image/"):
|
||||
return "image"
|
||||
if m.startswith("video/"):
|
||||
return "video"
|
||||
if m == "application/pdf" or (m and "pdf" in m):
|
||||
return "pdf"
|
||||
|
||||
if x in (
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".gif",
|
||||
".webp",
|
||||
".heic",
|
||||
".heif",
|
||||
".bmp",
|
||||
".svg",
|
||||
".avif",
|
||||
):
|
||||
return "image"
|
||||
if x in (".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"):
|
||||
return "video"
|
||||
if x == ".pdf":
|
||||
return "pdf"
|
||||
return "other"
|
||||
|
||||
|
||||
def library_club_path_segment(club_id: int, club_name: Optional[str]) -> str:
|
||||
"""
|
||||
Ein Verzeichnissegment pro Verein: aus Anzeigenamen abgeleitet + „-c{id}“ für Eindeutigkeit
|
||||
(Umbenennung, Kollisionen nach Slugify). Nur [a-z0-9-], keine Pfad-Sonderzeichen.
|
||||
Fehlt der Name / Slug leer → „verein-c{id}“.
|
||||
"""
|
||||
cid = int(club_id)
|
||||
if cid < 1:
|
||||
raise ValueError("club_id muss eine positive Ganzzahl sein")
|
||||
|
||||
raw = unicodedata.normalize("NFKC", (club_name or "").strip()).translate(_CLUB_SLUG_TRANS).lower()
|
||||
raw = re.sub(r"[^a-z0-9]+", "-", raw)
|
||||
raw = raw.strip("-")
|
||||
if len(raw) > 48:
|
||||
raw = raw[:48].rstrip("-")
|
||||
|
||||
if not raw:
|
||||
base = f"verein-c{cid}"
|
||||
else:
|
||||
base = f"{raw}-c{cid}"
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", base):
|
||||
raise ValueError("Ungültiger abgeleiteter Vereins-Ordnername")
|
||||
return base
|
||||
|
||||
|
||||
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
|
||||
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
|
||||
key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
|
||||
@@ -55,3 +133,97 @@ def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
|
||||
except ValueError:
|
||||
return None
|
||||
return p
|
||||
|
||||
|
||||
def library_storage_key(
|
||||
visibility: str,
|
||||
club_id: Optional[int],
|
||||
sha256_hex: str,
|
||||
ext: str,
|
||||
*,
|
||||
uploader_profile_id: Optional[int] = None,
|
||||
mime_type: Optional[str] = None,
|
||||
club_name: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Relativer Speicherpfad unter MEDIA_ROOT für lokale media_assets.
|
||||
|
||||
- official → library/official/{kind}/{sha256}{ext}
|
||||
- club (vereinsgeteilt) → library/{vereins-segment}/{kind}/{sha256}{ext}
|
||||
- private → dieselbe Ordnerlogik wie Verein: library/{vereins-segment}/{kind}/{sha}.u{profile}{ext}
|
||||
|
||||
Dateiname bei private: „{sha}.u{profile_id}{ext}“ (nicht Unterordner u{…}), damit Ordnerstruktur wie bei „Verein“.
|
||||
|
||||
Vereins-Segment: aus club_name abgeleitet + „-c{club_id}“ — siehe library_club_path_segment.
|
||||
|
||||
kind ∈ {image, video, pdf, other} — siehe library_media_kind_dir.
|
||||
|
||||
Kein Ordnername „private“ auf der Platte. Private Dateien unterscheiden sich nur im Dateinamen (.u{Profil} vor Endung).
|
||||
"""
|
||||
vis = (visibility or "private").strip().lower()
|
||||
if vis not in ("private", "club", "official"):
|
||||
raise ValueError(f"Ungültige Sichtbarkeit für Speicherpfad: {visibility!r}")
|
||||
|
||||
sha = (sha256_hex or "").strip().lower()
|
||||
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
||||
raise ValueError("sha256_hex muss 64 Hex-Zeichen sein")
|
||||
|
||||
e = (ext or "").strip()
|
||||
if not e:
|
||||
e = ".bin"
|
||||
if not e.startswith("."):
|
||||
e = "." + e
|
||||
if ".." in e or "/" in e or "\\" in e or "\x00" in e:
|
||||
raise ValueError("Ungültige Dateiendung")
|
||||
|
||||
kind = library_media_kind_dir(mime_type, e)
|
||||
e = e[:16]
|
||||
club_blob = f"{kind}/{sha}{e}"
|
||||
if vis == "official":
|
||||
return f"library/official/{club_blob}"
|
||||
if club_id is None:
|
||||
raise ValueError("Verein (club_id) ist für diese Sichtbarkeit auf der Platte erforderlich")
|
||||
cid = int(club_id)
|
||||
if cid < 1:
|
||||
raise ValueError("club_id muss eine positive Ganzzahl sein")
|
||||
club_seg = library_club_path_segment(cid, club_name)
|
||||
if vis == "club":
|
||||
return f"library/{club_seg}/{club_blob}"
|
||||
if uploader_profile_id is None:
|
||||
raise ValueError("uploader_profile_id ist für private Archiv-Medien erforderlich")
|
||||
up = int(uploader_profile_id)
|
||||
if up < 1:
|
||||
raise ValueError("uploader_profile_id muss positiv sein")
|
||||
priv_name = f"{sha}.u{up}{e}"
|
||||
return f"library/{club_seg}/{kind}/{priv_name}"
|
||||
|
||||
|
||||
def relocate_local_media_file(media_root: Path, old_storage_key: str, new_storage_key: str) -> None:
|
||||
"""
|
||||
Physisches Verschieben bei geändertem library_*-Pfad (z. B. nach PATCH visibility/club_id).
|
||||
|
||||
- Kein Op, wenn Quelle fehlt aber Ziel bereits existiert (idempotent).
|
||||
- Erwartet storage_backend=local; Aufrufer prüft das.
|
||||
"""
|
||||
if (old_storage_key or "").replace("\\", "/").lstrip("/") == (new_storage_key or "").replace(
|
||||
"\\", "/"
|
||||
).lstrip("/"):
|
||||
return
|
||||
|
||||
old_p = path_under_media_root(media_root, old_storage_key)
|
||||
new_p = path_under_media_root(media_root, new_storage_key)
|
||||
if old_p is None or new_p is None:
|
||||
raise ValueError("Ungültiger Speicherpfad (Path-Traversal)")
|
||||
|
||||
if new_p.is_file():
|
||||
if not old_p.is_file():
|
||||
return
|
||||
if old_p.resolve() == new_p.resolve():
|
||||
return
|
||||
raise FileExistsError(f"Zieldatei existiert bereits: {new_storage_key}")
|
||||
|
||||
if not old_p.is_file():
|
||||
raise FileNotFoundError(f"Medien-Quelldatei nicht gefunden: {old_storage_key}")
|
||||
|
||||
new_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(old_p), str(new_p))
|
||||
@@ -0,0 +1,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)
|
||||
+12
-21
@@ -20,6 +20,11 @@ from slowapi.util import get_remote_address
|
||||
from db import get_db, get_cursor
|
||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
||||
from password_reset_mail import (
|
||||
insert_password_reset_session,
|
||||
password_reset_email_body,
|
||||
revoke_pending_password_resets_for_profile,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
@@ -116,28 +121,14 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
|
||||
if not prof:
|
||||
# Don't reveal if email exists
|
||||
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||
revoke_pending_password_resets_for_profile(cur, prof["id"])
|
||||
raw_token = insert_password_reset_session(cur, prof["id"])
|
||||
|
||||
# Generate reset token
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now() + timedelta(hours=1)
|
||||
|
||||
# Store in sessions table (reuse mechanism)
|
||||
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||
(f"reset_{token}", prof['id'], expires.isoformat()))
|
||||
|
||||
app_base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
||||
reset_body = f"""Hallo {prof['name']},
|
||||
|
||||
Du hast einen Passwort-Reset angefordert.
|
||||
|
||||
Reset-Link: {app_base}/reset-password?token={token}
|
||||
|
||||
Der Link ist 1 Stunde gültig.
|
||||
|
||||
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
|
||||
|
||||
Dein Shinkan Jinkendo Team
|
||||
"""
|
||||
reset_body = password_reset_email_body(
|
||||
recipient_name=prof.get("name"),
|
||||
token=raw_token,
|
||||
intro="Du hast einen Passwort-Reset angefordert.",
|
||||
)
|
||||
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
||||
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import can_manage_club_org
|
||||
from club_tenancy import can_manage_club_org, is_platform_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
@@ -106,6 +106,72 @@ def _response_one(cur, req_id: int, viewer_profile_id: int) -> Dict[str, Any]:
|
||||
return r2d(row)
|
||||
|
||||
|
||||
def _can_access_org_inbox(cur, profile_id: int, global_role: Optional[str]) -> bool:
|
||||
"""Posteingang (Beitrittsanträge bearbeiten): Plattform-Admin oder Vereinsadmin in mind. einem Verein."""
|
||||
if is_platform_admin(global_role):
|
||||
return True
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _club_ids_manageable_by_user(cur, profile_id: int, global_role: Optional[str]) -> List[int]:
|
||||
"""Club-IDs, für die der Nutzer Beitrittsanträge sehen darf."""
|
||||
if is_platform_admin(global_role):
|
||||
cur.execute("SELECT id FROM clubs WHERE status = 'active' ORDER BY name")
|
||||
return [int(r["id"]) for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT cm.club_id
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.profile_id = %s AND cm.status = 'active'
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
return [int(r["club_id"]) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/me/inbox/join-requests")
|
||||
def list_inbox_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""
|
||||
Alle offenen Beitrittsanträge, die der Nutzer bearbeiten darf:
|
||||
Plattform-Admin: alle Vereine; sonst nur Vereine mit Rolle club_admin.
|
||||
"""
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _can_access_org_inbox(cur, pid, role):
|
||||
raise HTTPException(status_code=403, detail="Kein Zugriff auf den Organisations-Posteingang")
|
||||
club_ids = _club_ids_manageable_by_user(cur, pid, role)
|
||||
if not club_ids:
|
||||
return []
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT r.id, r.profile_id, r.club_id, r.status, r.message, r.created_at,
|
||||
c.name AS club_name, c.abbreviation AS club_abbreviation,
|
||||
p.name AS applicant_name, p.email AS applicant_email
|
||||
FROM club_membership_requests r
|
||||
INNER JOIN clubs c ON c.id = r.club_id
|
||||
INNER JOIN profiles p ON p.id = r.profile_id
|
||||
WHERE r.status = 'pending'
|
||||
AND r.club_id = ANY(%s)
|
||||
ORDER BY r.created_at ASC
|
||||
""",
|
||||
(club_ids,),
|
||||
)
|
||||
return [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/me/club-join-requests")
|
||||
def get_my_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
pid = tenant.profile_id
|
||||
|
||||
@@ -50,6 +50,44 @@ def _club_exists(cur, club_id: int) -> bool:
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _count_other_active_club_admins(cur, club_id: int, exclude_profile_id: int) -> int:
|
||||
"""Aktive Vereinsadmins im Verein, außer exclude_profile_id."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(DISTINCT cm.profile_id)::int AS n
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.club_id = %s AND cm.status = 'active' AND cm.profile_id <> %s
|
||||
""",
|
||||
(club_id, exclude_profile_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
try:
|
||||
return int(row["n"]) if row is not None else 0
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _member_is_active_club_admin(cur, club_id: int, profile_id: int) -> bool:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM club_members cm
|
||||
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
|
||||
WHERE cm.club_id = %s AND cm.profile_id = %s AND cm.status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(club_id, profile_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
_LAST_CLUB_ADMIN_MSG = (
|
||||
"Mindestens ein aktiver Vereinsadmin muss im Verein verbleiben. "
|
||||
"Weise die Rolle zuerst einem anderen Mitglied zu oder aktiviere einen anderen Vereinsadmin."
|
||||
)
|
||||
|
||||
|
||||
class ClubMemberUpsert(BaseModel):
|
||||
profile_id: int = Field(..., ge=1)
|
||||
roles: List[str] = Field(default_factory=list, description="Mindestens eine Vereinsrolle")
|
||||
@@ -77,7 +115,8 @@ def list_club_members(
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
||||
p.email, p.name,
|
||||
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
|
||||
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
|
||||
COALESCE(
|
||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
@@ -86,7 +125,7 @@ def list_club_members(
|
||||
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.club_id = %s {status_clause}
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
|
||||
ORDER BY p.name NULLS LAST, p.email
|
||||
""",
|
||||
(club_id,),
|
||||
@@ -153,7 +192,8 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
||||
p.email, p.name,
|
||||
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
|
||||
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
|
||||
COALESCE(
|
||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
@@ -162,7 +202,7 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
|
||||
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.club_id = %s AND cm.profile_id = %s
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name
|
||||
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
|
||||
""",
|
||||
(club_id, profile_id),
|
||||
)
|
||||
@@ -217,21 +257,50 @@ def update_club_member(
|
||||
if body.roles is None and body.status is None:
|
||||
return _one_member(cur, club_id, profile_id)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT cm.status,
|
||||
COALESCE(
|
||||
ARRAY_AGG(r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||
ARRAY[]::varchar[]
|
||||
) AS roles
|
||||
FROM club_members cm
|
||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||
WHERE cm.id = %s
|
||||
GROUP BY cm.status
|
||||
""",
|
||||
(cm_id,),
|
||||
)
|
||||
cur_row = cur.fetchone()
|
||||
current_status = (cur_row["status"] or "active").strip().lower() if cur_row else "active"
|
||||
cr = cur_row.get("roles") if cur_row else []
|
||||
if hasattr(cr, "tolist"):
|
||||
cr = cr.tolist()
|
||||
current_roles = list(cr)
|
||||
|
||||
new_status = body.status.strip().lower() if body.status is not None else current_status
|
||||
if body.status is not None and new_status not in _ALLOWED_STATUS:
|
||||
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
|
||||
|
||||
new_roles = _normalize_roles(body.roles) if body.roles is not None else current_roles
|
||||
if not new_roles:
|
||||
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||
|
||||
effective_admin = new_status == "active" and "club_admin" in set(new_roles)
|
||||
if not effective_admin:
|
||||
others = _count_other_active_club_admins(cur, club_id, profile_id)
|
||||
if others < 1:
|
||||
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
|
||||
|
||||
if body.status is not None:
|
||||
st = body.status.strip().lower()
|
||||
if st not in _ALLOWED_STATUS:
|
||||
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
|
||||
cur.execute(
|
||||
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
|
||||
(st, cm_id),
|
||||
(new_status, cm_id),
|
||||
)
|
||||
|
||||
if body.roles is not None:
|
||||
roles = _normalize_roles(body.roles)
|
||||
if not roles:
|
||||
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
|
||||
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
|
||||
for rc in roles:
|
||||
for rc in new_roles:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||
@@ -258,6 +327,10 @@ def delete_club_member(
|
||||
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||
_assert_manage(cur, tenant, club_id)
|
||||
|
||||
if _member_is_active_club_admin(cur, club_id, profile_id):
|
||||
if _count_other_active_club_admins(cur, club_id, profile_id) < 1:
|
||||
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
|
||||
|
||||
cur.execute(
|
||||
"DELETE FROM club_members WHERE club_id = %s AND profile_id = %s RETURNING id",
|
||||
(club_id, profile_id),
|
||||
|
||||
+83
-27
@@ -5,6 +5,7 @@ Handles CRUD operations for clubs, divisions, and training groups.
|
||||
"""
|
||||
from typing import Any, List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
@@ -19,6 +20,53 @@ from club_tenancy import (
|
||||
router = APIRouter(prefix="/api", tags=["clubs"])
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> Any:
|
||||
"""Frontend sendet häufig '' für optionale Felder — ungültig für PostgreSQL TIME/INTEGER."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == "":
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _optional_int(value: Any) -> Optional[int]:
|
||||
v = _blank_to_none(value)
|
||||
if v is None:
|
||||
return None
|
||||
try:
|
||||
i = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return i if i > 0 else None
|
||||
|
||||
|
||||
def _normalize_co_trainer_ids(val: Any) -> List[int]:
|
||||
"""Listen von Profil-IDs für JSONB; ungültige Einträge werden verworfen."""
|
||||
if val is None:
|
||||
raw: List[Any] = []
|
||||
elif isinstance(val, list):
|
||||
raw = val
|
||||
else:
|
||||
raw = []
|
||||
out: List[int] = []
|
||||
seen = set()
|
||||
for x in raw:
|
||||
try:
|
||||
i = int(x)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if i <= 0 or i in seen:
|
||||
continue
|
||||
seen.add(i)
|
||||
out.append(i)
|
||||
return out
|
||||
|
||||
|
||||
def _co_trainer_ids_jsonb(val: Any) -> Json:
|
||||
"""psycopg2: reine list/dict für JSONB → ProgrammingError ohne Json()."""
|
||||
return Json(_normalize_co_trainer_ids(val))
|
||||
|
||||
|
||||
# ── List Clubs ────────────────────────────────────────────────────────
|
||||
@router.get("/clubs")
|
||||
def list_clubs(
|
||||
@@ -581,9 +629,15 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
||||
if not club_id or not name:
|
||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||
|
||||
trainer_id = data.get("trainer_id")
|
||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
||||
trainer_id = profile_id
|
||||
raw_tid = data.get("trainer_id")
|
||||
if role in ("trainer", "user"):
|
||||
parsed_tid = _optional_int(raw_tid)
|
||||
trainer_id = parsed_tid if parsed_tid is not None else profile_id
|
||||
else:
|
||||
trainer_id = _optional_int(raw_tid)
|
||||
|
||||
division_id = _optional_int(data.get("division_id"))
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -606,23 +660,23 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
%s, %s::jsonb, %s
|
||||
) RETURNING id
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
data.get("division_id"),
|
||||
int(club_id),
|
||||
division_id,
|
||||
name,
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
trainer_id,
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status", "active"),
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -662,6 +716,8 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
||||
if not allowed:
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE training_groups SET
|
||||
@@ -675,24 +731,24 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
||||
time_end = %s,
|
||||
location = %s,
|
||||
trainer_id = %s,
|
||||
co_trainer_ids = %s,
|
||||
co_trainer_ids = %s::jsonb,
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("division_id"),
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
data.get("trainer_id"),
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status"),
|
||||
_optional_int(data.get("division_id")),
|
||||
_blank_to_none(data.get("focus")),
|
||||
_blank_to_none(data.get("level")),
|
||||
_blank_to_none(data.get("age_group")),
|
||||
_blank_to_none(data.get("weekday")),
|
||||
_blank_to_none(data.get("time_start")),
|
||||
_blank_to_none(data.get("time_end")),
|
||||
_blank_to_none(data.get("location")),
|
||||
_optional_int(data.get("trainer_id")),
|
||||
co_json,
|
||||
data.get("status") or "active",
|
||||
group_id,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -206,32 +206,22 @@ def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context))
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if is_platform_admin(role):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
"""
|
||||
)
|
||||
else:
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.*,
|
||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_sql})
|
||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
|
||||
+294
-28
@@ -28,7 +28,14 @@ from club_tenancy import (
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||
from media_storage import get_effective_media_root, path_under_media_root
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
|
||||
from exercise_rich_text import (
|
||||
RICH_HTML_EXERCISE_FIELDS,
|
||||
assert_no_inline_media_references_on_create,
|
||||
collect_inline_exercise_media_ids,
|
||||
normalize_inline_exercise_media_markup,
|
||||
validate_inline_exercise_media_ids_for_exercise,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -258,6 +265,8 @@ class ExerciseUpdate(BaseModel):
|
||||
# §4.2: Übung → official — angehängte Datei-Assets anheben + Copyright (nur mit expliziter Bestätigung)
|
||||
promote_attached_media_for_official: Optional[bool] = None
|
||||
default_official_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
||||
# Vereins-Übung: fehlende Copyrights an Datei-Assets nach Prompt-Text setzen (PUT-Retry)
|
||||
default_club_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_goal_execution(self):
|
||||
@@ -340,6 +349,7 @@ class ExerciseBulkMetadataPatch(BaseModel):
|
||||
target_group_ids: Optional[list[int]] = Field(default=None, max_length=_MAX_BULK_RELATION_IDS_PER_KIND)
|
||||
promote_attached_media_for_official: bool = False
|
||||
default_official_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
||||
default_club_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def at_least_one_patch_field(self):
|
||||
@@ -642,6 +652,140 @@ def apply_official_exercise_media_rules(
|
||||
)
|
||||
|
||||
|
||||
def apply_club_exercise_media_copyright_rules(
|
||||
cur,
|
||||
exercise_id: int,
|
||||
next_visibility: str,
|
||||
*,
|
||||
default_club_media_copyright: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Vereins-sichtbare Übung: angehängte Archiv-Dateien müssen aktiv sein und einen Copyright-Vermerk haben
|
||||
(wie bei offiziellen Übungen, ohne Sichtbarkeits-Promotion der Assets).
|
||||
|
||||
Fehlt das Copyright, kann der Client nach Nutzerbestätigung `default_club_media_copyright`
|
||||
mitsenden (mind. 3 Zeichen) — wird auf alle betroffenen Assets mit zu kurzem/leerem Vermerk gesetzt.
|
||||
"""
|
||||
nv = (next_visibility or "private").strip().lower()
|
||||
if nv != "club":
|
||||
return
|
||||
|
||||
rows = _fetch_exercise_linked_file_assets(cur, exercise_id)
|
||||
if not rows:
|
||||
return
|
||||
|
||||
blocking_lc: List[Dict[str, Any]] = []
|
||||
missing_cr: List[Dict[str, Any]] = []
|
||||
|
||||
for r in rows:
|
||||
aid = int(r["id"])
|
||||
lc = (r.get("lifecycle_state") or "").strip().lower()
|
||||
cr = _normalize_media_copyright_notice(r.get("copyright_notice"))
|
||||
|
||||
if lc != "active":
|
||||
blocking_lc.append(
|
||||
{
|
||||
"media_asset_id": aid,
|
||||
"lifecycle_state": lc,
|
||||
"visibility": (r.get("visibility") or "").strip().lower(),
|
||||
"original_filename": r.get("original_filename"),
|
||||
}
|
||||
)
|
||||
continue
|
||||
if len(cr) < _MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN:
|
||||
missing_cr.append(
|
||||
{
|
||||
"media_asset_id": aid,
|
||||
"original_filename": r.get("original_filename"),
|
||||
}
|
||||
)
|
||||
|
||||
if blocking_lc:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail={
|
||||
"code": "CLUB_MEDIA_LIFECYCLE",
|
||||
"message": (
|
||||
"Nicht aktive Archiv-Medien dürfen nicht an einer vereinsöffentlichen Übung hängen "
|
||||
"(Papierkorb/Recovery zuerst)."
|
||||
),
|
||||
"media_assets": blocking_lc,
|
||||
},
|
||||
)
|
||||
|
||||
if not missing_cr:
|
||||
return
|
||||
|
||||
default_cr = _normalize_media_copyright_notice(default_club_media_copyright)
|
||||
if len(default_cr) < _MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail={
|
||||
"code": "CLUB_MEDIA_COPYRIGHT_REQUIRED",
|
||||
"message": (
|
||||
f"Für vereinsöffentliche Übungen ist ein Copyright-Vermerk pro Datei erforderlich "
|
||||
f"(mind. {_MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN} Zeichen)."
|
||||
),
|
||||
"media_assets": missing_cr,
|
||||
},
|
||||
)
|
||||
|
||||
ids = [int(x["media_asset_id"]) for x in missing_cr]
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE media_assets
|
||||
SET copyright_notice = %s, updated_at = NOW()
|
||||
WHERE id IN ({ph})
|
||||
AND (
|
||||
copyright_notice IS NULL
|
||||
OR LENGTH(TRIM(copyright_notice)) < %s
|
||||
)
|
||||
""",
|
||||
(default_cr, *ids, _MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN),
|
||||
)
|
||||
|
||||
rows2 = _fetch_exercise_linked_file_assets(cur, exercise_id)
|
||||
missing_after: List[Dict[str, Any]] = []
|
||||
blocking_after: List[Dict[str, Any]] = []
|
||||
for r in rows2:
|
||||
aid = int(r["id"])
|
||||
lc = (r.get("lifecycle_state") or "").strip().lower()
|
||||
cr = _normalize_media_copyright_notice(r.get("copyright_notice"))
|
||||
if lc != "active":
|
||||
blocking_after.append({"media_asset_id": aid})
|
||||
continue
|
||||
if len(cr) < _MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN:
|
||||
missing_after.append(
|
||||
{
|
||||
"media_asset_id": aid,
|
||||
"original_filename": r.get("original_filename"),
|
||||
}
|
||||
)
|
||||
|
||||
if blocking_after:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail={
|
||||
"code": "CLUB_MEDIA_LIFECYCLE",
|
||||
"message": "Archiv-Medium nach Copyright-Update nicht mehr aktiv.",
|
||||
"media_assets": blocking_after,
|
||||
},
|
||||
)
|
||||
if missing_after:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail={
|
||||
"code": "CLUB_MEDIA_COPYRIGHT_REQUIRED",
|
||||
"message": (
|
||||
f"Copyright konnte nicht auf alle Dateien angewendet werden "
|
||||
f"(mind. {_MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN} Zeichen pro Eintrag prüfen)."
|
||||
),
|
||||
"media_assets": missing_after,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _abs_media_path(file_path_db: str, media_root: Path) -> Optional[Path]:
|
||||
if not file_path_db or file_path_db.startswith("http"):
|
||||
return None
|
||||
@@ -1247,6 +1391,28 @@ def bulk_patch_exercises_metadata(
|
||||
failed.append(entry)
|
||||
continue
|
||||
|
||||
if (next_vis or "").strip().lower() == "club":
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(
|
||||
cur,
|
||||
ex_id,
|
||||
next_vis,
|
||||
default_club_media_copyright=body.default_club_media_copyright,
|
||||
)
|
||||
except HTTPException as he:
|
||||
d = he.detail
|
||||
entry: Dict[str, Any] = {"id": ex_id}
|
||||
if isinstance(d, dict):
|
||||
entry["detail"] = str(d.get("message") or d.get("code") or "Vereins-Medien-Validierung fehlgeschlagen")
|
||||
if "code" in d:
|
||||
entry["code"] = d["code"]
|
||||
if "media_assets" in d:
|
||||
entry["media_assets"] = d["media_assets"]
|
||||
else:
|
||||
entry["detail"] = _fail_msg(he)
|
||||
failed.append(entry)
|
||||
continue
|
||||
|
||||
sets: List[str] = []
|
||||
vals: List[Any] = []
|
||||
if patch_visibility:
|
||||
@@ -1376,15 +1542,14 @@ def list_exercises(
|
||||
params = []
|
||||
|
||||
role = tenant.global_role
|
||||
if not is_platform_admin(role):
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="e",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
where.append(vis_sql)
|
||||
params.extend(vis_params)
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="e",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
where.append(vis_sql)
|
||||
params.extend(vis_params)
|
||||
|
||||
if created_by_me:
|
||||
where.append("e.created_by = %s")
|
||||
@@ -1729,6 +1894,16 @@ def create_exercise(
|
||||
if body.visibility == "club" and club_id is None:
|
||||
club_id = tenant.effective_club_id
|
||||
|
||||
# §11 Inline-Medien: Kurzsyntax → kanonisches Markup; Verweise erst nach Medien-Anlage möglich
|
||||
create_ids: set[int] = set()
|
||||
for fld in sorted(RICH_HTML_EXERCISE_FIELDS):
|
||||
raw_html = getattr(body, fld, None)
|
||||
if raw_html:
|
||||
normed = normalize_inline_exercise_media_markup(raw_html)
|
||||
setattr(body, fld, normed)
|
||||
create_ids |= collect_inline_exercise_media_ids(normed or "")
|
||||
assert_no_inline_media_references_on_create(create_ids)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
assert_valid_governance_visibility(
|
||||
@@ -1757,13 +1932,13 @@ def create_exercise(
|
||||
)
|
||||
row = cur.fetchone()
|
||||
exercise_id = row['id'] if isinstance(row, dict) else row[0]
|
||||
|
||||
data = body.dict()
|
||||
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
||||
if (body.visibility or "").strip().lower() == "club":
|
||||
apply_club_exercise_media_copyright_rules(cur, exercise_id, "club")
|
||||
conn.commit()
|
||||
|
||||
# M:N Relations zuweisen
|
||||
data = body.dict()
|
||||
assign_exercise_relations(cur, conn, exercise_id, data)
|
||||
|
||||
# Vollständiges Objekt zurückgeben
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
|
||||
return exercise
|
||||
@@ -1785,16 +1960,25 @@ def update_exercise(
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute(
|
||||
"SELECT created_by, visibility, club_id FROM exercises WHERE id = %s",
|
||||
f"""SELECT created_by, visibility, club_id,
|
||||
{", ".join(sorted(RICH_HTML_EXERCISE_FIELDS))}
|
||||
FROM exercises WHERE id = %s""",
|
||||
(exercise_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
|
||||
rd_full = r2d(row)
|
||||
rich_row = {fld: rd_full.get(fld) for fld in RICH_HTML_EXERCISE_FIELDS}
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
|
||||
rd = r2d(row)
|
||||
rd = {
|
||||
"created_by": rd_full.get("created_by"),
|
||||
"visibility": rd_full.get("visibility"),
|
||||
"club_id": rd_full.get("club_id"),
|
||||
}
|
||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||
ex_cid = rd.get("club_id")
|
||||
if ex_cid is not None:
|
||||
@@ -1804,6 +1988,24 @@ def update_exercise(
|
||||
raw_promo = data.pop("promote_attached_media_for_official", None)
|
||||
promote_media_flag = raw_promo is True
|
||||
default_official_copy = data.pop("default_official_media_copyright", None)
|
||||
default_club_copy = data.pop("default_club_media_copyright", None)
|
||||
|
||||
merged_rich = {fld: rich_row.get(fld) for fld in RICH_HTML_EXERCISE_FIELDS}
|
||||
for fld in RICH_HTML_EXERCISE_FIELDS:
|
||||
if fld not in data:
|
||||
continue
|
||||
raw_v = data[fld]
|
||||
if raw_v is None:
|
||||
merged_rich[fld] = None
|
||||
continue
|
||||
if isinstance(raw_v, str):
|
||||
nv = normalize_inline_exercise_media_markup(raw_v)
|
||||
data[fld] = nv
|
||||
merged_rich[fld] = nv
|
||||
inline_union: set[int] = set()
|
||||
for val in merged_rich.values():
|
||||
inline_union |= collect_inline_exercise_media_ids(val if isinstance(val, str) else None)
|
||||
validate_inline_exercise_media_ids_for_exercise(cur, exercise_id, inline_union)
|
||||
|
||||
next_vis = ex_vis
|
||||
if "visibility" in data and data["visibility"] is not None:
|
||||
@@ -1866,6 +2068,16 @@ def update_exercise(
|
||||
cur.execute(query, params)
|
||||
|
||||
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(
|
||||
cur,
|
||||
exercise_id,
|
||||
next_vis,
|
||||
default_club_media_copyright=default_club_copy,
|
||||
)
|
||||
except HTTPException:
|
||||
conn.rollback()
|
||||
raise
|
||||
conn.commit()
|
||||
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
@@ -1976,7 +2188,11 @@ def create_exercise_variant(
|
||||
seq = cur.fetchone()["n"]
|
||||
|
||||
desc = (body.description or "").strip() or None
|
||||
exec_ch = (body.execution_changes or "").strip() or None
|
||||
exec_ch_raw = (body.execution_changes or "").strip() or None
|
||||
exec_ch = normalize_inline_exercise_media_markup(exec_ch_raw) if exec_ch_raw else None
|
||||
if exec_ch:
|
||||
v_ids = collect_inline_exercise_media_ids(exec_ch)
|
||||
validate_inline_exercise_media_ids_for_exercise(cur, exercise_id, v_ids)
|
||||
diff = (body.difficulty_adjustment or "").strip() or None
|
||||
|
||||
cur.execute(
|
||||
@@ -2030,7 +2246,13 @@ def update_exercise_variant(
|
||||
if "description" in data:
|
||||
old["description"] = (data["description"] or "").strip() or None
|
||||
if "execution_changes" in data:
|
||||
old["execution_changes"] = (data["execution_changes"] or "").strip() or None
|
||||
ec_raw = (data["execution_changes"] or "").strip() or None
|
||||
ec_norm = normalize_inline_exercise_media_markup(ec_raw) if ec_raw else None
|
||||
if ec_norm:
|
||||
validate_inline_exercise_media_ids_for_exercise(
|
||||
cur, exercise_id, collect_inline_exercise_media_ids(ec_norm)
|
||||
)
|
||||
old["execution_changes"] = ec_norm
|
||||
if "duration_min" in data:
|
||||
old["duration_min"] = data["duration_min"]
|
||||
if "duration_max" in data:
|
||||
@@ -2397,13 +2619,41 @@ async def upload_exercise_media(
|
||||
media_root = get_effective_media_root(cur)
|
||||
full_sha = hashlib.sha256(raw).hexdigest()
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, ex_vis, ex_club),
|
||||
)
|
||||
if ex_vis == "official":
|
||||
dedupe_club: Optional[int] = None
|
||||
elif ex_vis == "private":
|
||||
dedupe_club = int(ex_club) if ex_club is not None else tenant.effective_club_id
|
||||
if dedupe_club is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Private Übungsmedien werden pro Verein gespeichert. Bitte der Übung einen Verein zuordnen "
|
||||
"oder einen aktiven Verein wählen (X-Active-Club-Id)."
|
||||
),
|
||||
)
|
||||
dedupe_club = int(dedupe_club)
|
||||
else:
|
||||
if ex_club is None:
|
||||
raise HTTPException(status_code=400, detail="Vereinsübung ohne club_id")
|
||||
dedupe_club = int(ex_club)
|
||||
|
||||
if ex_vis == "private":
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = 'private'
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, dedupe_club, profile_id),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, ex_vis, dedupe_club),
|
||||
)
|
||||
existing_asset = cur.fetchone()
|
||||
|
||||
if existing_asset:
|
||||
@@ -2490,7 +2740,23 @@ async def upload_exercise_media(
|
||||
},
|
||||
)
|
||||
else:
|
||||
storage_key = f"exercises/{full_sha}{ext}"
|
||||
club_nm = ""
|
||||
if dedupe_club is not None:
|
||||
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(dedupe_club),))
|
||||
cnr = cur.fetchone()
|
||||
club_nm = str(r2d(cnr).get("name") or "") if cnr else ""
|
||||
try:
|
||||
storage_key = library_storage_key(
|
||||
ex_vis,
|
||||
dedupe_club if ex_vis != "official" else None,
|
||||
full_sha,
|
||||
ext,
|
||||
uploader_profile_id=profile_id if ex_vis == "private" else None,
|
||||
mime_type=mime,
|
||||
club_name=club_nm,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
dest_path = path_under_media_root(media_root, storage_key)
|
||||
if dest_path is None:
|
||||
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
|
||||
@@ -2510,7 +2776,7 @@ async def upload_exercise_media(
|
||||
full_sha,
|
||||
file.filename,
|
||||
ex_vis,
|
||||
ex_club,
|
||||
dedupe_club,
|
||||
profile_id,
|
||||
storage_key,
|
||||
),
|
||||
|
||||
+308
-63
@@ -10,6 +10,7 @@ from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Reques
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from club_tenancy import (
|
||||
assert_club_member,
|
||||
assert_valid_governance_visibility,
|
||||
club_ids_for_profile_with_roles,
|
||||
is_platform_admin,
|
||||
@@ -33,7 +34,7 @@ from media_lifecycle import (
|
||||
transition_to_trash_hidden,
|
||||
transition_to_trash_soft,
|
||||
)
|
||||
from media_storage import get_effective_media_root, path_under_media_root
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root, relocate_local_media_file
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible
|
||||
|
||||
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
|
||||
@@ -293,28 +294,194 @@ def _fetch_filter_uploaders(cur: Any, is_adm: bool, profile_id: int) -> list[dic
|
||||
|
||||
|
||||
def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict:
|
||||
"""Nach visibility-Wechsel club_id konsistent setzen (official/private → NULL)."""
|
||||
"""
|
||||
Nach visibility-Wechsel club_id konsistent setzen.
|
||||
|
||||
official → club_id NULL. private/club: club_id aus Patch oder bisheriger Zeile beibehalten
|
||||
(private nutzt club_id für Vereinsordner auf der Platte).
|
||||
"""
|
||||
eff = dict(patch_fields)
|
||||
if eff.get("visibility") is not None:
|
||||
v = str(eff["visibility"]).strip().lower()
|
||||
if v in ("official", "private"):
|
||||
if v == "official":
|
||||
eff["club_id"] = None
|
||||
elif v == "club" and "club_id" not in eff:
|
||||
eff["club_id"] = asset.get("club_id")
|
||||
elif v == "private" and "club_id" not in eff:
|
||||
eff["club_id"] = asset.get("club_id")
|
||||
return eff
|
||||
|
||||
|
||||
def _lifecycle_where_sql(lifecycle: str) -> str:
|
||||
def _club_display_name_for_storage(cur: Any, club_id: int) -> str:
|
||||
"""Anzeigename für library_club_path_segment; leer wenn Verein fehlt."""
|
||||
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(club_id),))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return ""
|
||||
return str(r2d(row).get("name") or "")
|
||||
|
||||
|
||||
def _relocate_asset_file_if_governance_changed(
|
||||
cur: Any,
|
||||
media_root: Path,
|
||||
asset_id: int,
|
||||
asset: dict,
|
||||
next_vis: str,
|
||||
next_club_id: Optional[int],
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Passt bei local-Assets den Dateipfad an, wenn sich Sichtbarkeit/Verein ändert.
|
||||
Aktualisiert exercise_media.file_path. Gibt neuen storage_key oder None zurück.
|
||||
"""
|
||||
if (asset.get("storage_backend") or "local") != "local":
|
||||
return None
|
||||
old_key = (asset.get("storage_key") or "").strip()
|
||||
sha = (asset.get("sha256") or "").strip().lower()
|
||||
if not old_key or len(sha) != 64:
|
||||
return None
|
||||
ext = Path(old_key.replace("\\", "/")).suffix or ".bin"
|
||||
try:
|
||||
up = asset.get("uploaded_by_profile_id")
|
||||
up_i = int(up) if up is not None else None
|
||||
club_nm: Optional[str] = None
|
||||
if next_vis in ("club", "private") and next_club_id is not None:
|
||||
club_nm = _club_display_name_for_storage(cur, next_club_id)
|
||||
new_key = library_storage_key(
|
||||
next_vis,
|
||||
next_club_id if next_vis != "official" else None,
|
||||
sha,
|
||||
ext,
|
||||
uploader_profile_id=up_i if next_vis == "private" else None,
|
||||
mime_type=str(asset.get("mime_type") or "") or None,
|
||||
club_name=club_nm,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
old_norm = old_key.replace("\\", "/").lstrip("/")
|
||||
if new_key == old_norm:
|
||||
return None
|
||||
try:
|
||||
relocate_local_media_file(media_root, old_key, new_key)
|
||||
except FileNotFoundError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Mediendatei fehlt auf der Platte: {e}") from e
|
||||
except FileExistsError as e:
|
||||
raise HTTPException(status_code=409, detail=str(e)) from e
|
||||
except (ValueError, OSError) as e:
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
db_path = f"/media/{new_key}"
|
||||
cur.execute(
|
||||
"UPDATE exercise_media SET file_path = %s WHERE media_asset_id = %s",
|
||||
(db_path, asset_id),
|
||||
)
|
||||
return new_key
|
||||
|
||||
|
||||
|
||||
|
||||
def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str, list[Any]]:
|
||||
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL."""
|
||||
parts = ["lower(trim(ma.visibility)) = 'official'"]
|
||||
vals: list[Any] = []
|
||||
|
||||
if is_plat:
|
||||
parts.append("lower(trim(ma.visibility)) = 'private'")
|
||||
else:
|
||||
parts.append("(lower(trim(ma.visibility)) = 'private' AND ma.uploaded_by_profile_id = %s)")
|
||||
vals.append(profile_id)
|
||||
|
||||
club_plat = (
|
||||
"(lower(trim(ma.visibility)) = 'club' AND ma.club_id IS NOT NULL AND ("
|
||||
"EXISTS (SELECT 1 FROM club_members cm WHERE cm.profile_id = %s AND cm.club_id = ma.club_id "
|
||||
"AND cm.status = 'active') OR NOT EXISTS (SELECT 1 FROM club_members cm2 "
|
||||
"WHERE cm2.profile_id = %s AND cm2.club_id = ma.club_id)))"
|
||||
)
|
||||
|
||||
if is_plat:
|
||||
parts.append(club_plat)
|
||||
vals.extend([profile_id, profile_id])
|
||||
else:
|
||||
parts.append(
|
||||
"""(
|
||||
lower(trim(ma.visibility)) = 'club'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM club_members cm
|
||||
WHERE cm.profile_id = %s
|
||||
AND cm.club_id = ma.club_id
|
||||
AND cm.status = 'active'
|
||||
)
|
||||
)"""
|
||||
)
|
||||
vals.append(profile_id)
|
||||
|
||||
sql = "(" + " OR ".join(parts) + ")"
|
||||
return sql, vals
|
||||
|
||||
|
||||
def _list_trash_visibility_clause(
|
||||
is_plat: bool,
|
||||
is_sup: bool,
|
||||
profile_id: int,
|
||||
admin_club_ids: set[int],
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""
|
||||
Papierkorb nur für eigene private Medien; Vereins-Admins zusätzlich Vereins-Papierkorb ihres Vereins.
|
||||
Official/Plattform: Superadmin oder Plattform-Admin sieht alles im Papierkorb.
|
||||
"""
|
||||
if is_plat or is_sup:
|
||||
return "(TRUE)", []
|
||||
parts: list[str] = []
|
||||
vals: list[Any] = []
|
||||
parts.append(
|
||||
"(lower(trim(ma.visibility)) = 'private' AND ma.uploaded_by_profile_id = %s)",
|
||||
)
|
||||
vals.append(profile_id)
|
||||
if admin_club_ids:
|
||||
parts.append(
|
||||
"(lower(trim(ma.visibility)) = 'club' AND ma.club_id = ANY(%s))",
|
||||
)
|
||||
vals.append(list(admin_club_ids))
|
||||
return "(" + " OR ".join(parts) + ")", vals
|
||||
|
||||
|
||||
def _list_main_visibility_where(
|
||||
lifecycle: str,
|
||||
is_plat: bool,
|
||||
is_sup: bool,
|
||||
profile_id: int,
|
||||
admin_club_ids: set[int],
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""
|
||||
Kombiniert lifecycle mit Leserechten. Papierkorb-Stufen für normale Nutzer stark eingeschränkt.
|
||||
"""
|
||||
lc = (lifecycle or "active").strip().lower()
|
||||
if lc not in _LIFECYCLE_LIST_FILTERS:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger lifecycle-Filter")
|
||||
|
||||
active_sql, active_params = _list_active_visibility_clause(is_plat, profile_id)
|
||||
trash_sql, trash_params = _list_trash_visibility_clause(
|
||||
is_plat, is_sup, profile_id, admin_club_ids
|
||||
)
|
||||
active_block = f"(ma.lifecycle_state = 'active' AND {active_sql})"
|
||||
trash_block = (
|
||||
f"(ma.lifecycle_state IN ('trash_soft', 'trash_hidden') AND {trash_sql})"
|
||||
)
|
||||
|
||||
if lc == "active":
|
||||
return "ma.lifecycle_state = 'active'"
|
||||
return active_block, active_params
|
||||
if lc == "trash_soft":
|
||||
return "ma.lifecycle_state = 'trash_soft'"
|
||||
return (
|
||||
f"(ma.lifecycle_state = 'trash_soft' AND {trash_sql})",
|
||||
trash_params,
|
||||
)
|
||||
if lc == "trash_hidden":
|
||||
return "ma.lifecycle_state = 'trash_hidden'"
|
||||
return "ma.lifecycle_state IN ('active', 'trash_soft', 'trash_hidden')"
|
||||
return (
|
||||
f"(ma.lifecycle_state = 'trash_hidden' AND {trash_sql})",
|
||||
trash_params,
|
||||
)
|
||||
# all
|
||||
combined = f"(({active_block}) OR ({trash_block}))"
|
||||
return combined, active_params + trash_params
|
||||
|
||||
|
||||
def _fetch_asset_file_row(cur: Any, asset_id: int) -> Optional[dict]:
|
||||
@@ -354,25 +521,25 @@ def _item_permissions(row: dict, tenant: TenantContext, admin_club_ids: set[int]
|
||||
is_owner = uid is not None and int(uid) == pid
|
||||
club_mgr = plat or (cid is not None and int(cid) in admin_club_ids)
|
||||
|
||||
edit_metadata = (
|
||||
sup
|
||||
or (vis == "official" and plat)
|
||||
or (vis == "club" and club_mgr)
|
||||
or (vis == "private" and is_owner)
|
||||
)
|
||||
|
||||
trash_soft = lc == "active" and (
|
||||
sup or plat or (vis == "private" and is_owner) or (vis == "club" and club_mgr)
|
||||
)
|
||||
if vis == "official" and not (sup or plat):
|
||||
trash_soft = False
|
||||
|
||||
can_manage_adv = (
|
||||
sup
|
||||
or plat
|
||||
or (vis == "private" and is_owner)
|
||||
or (vis == "club" and club_mgr)
|
||||
)
|
||||
if vis == "official":
|
||||
edit_metadata = sup
|
||||
trash_soft = lc == "active" and sup
|
||||
can_manage_adv = sup
|
||||
else:
|
||||
edit_metadata = (
|
||||
sup
|
||||
or (vis == "club" and club_mgr)
|
||||
or (vis == "private" and is_owner)
|
||||
)
|
||||
trash_soft = lc == "active" and (
|
||||
sup or plat or (vis == "private" and is_owner) or (vis == "club" and club_mgr)
|
||||
)
|
||||
can_manage_adv = (
|
||||
sup
|
||||
or plat
|
||||
or (vis == "private" and is_owner)
|
||||
or (vis == "club" and club_mgr)
|
||||
)
|
||||
|
||||
trash_hidden = lc in ("active", "trash_soft") and can_manage_adv
|
||||
recover_from_hidden = lc == "trash_hidden" and can_manage_adv
|
||||
@@ -474,8 +641,32 @@ def _ingest_library_media_file(
|
||||
if club_id_form is None:
|
||||
raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“")
|
||||
next_cid = int(club_id_form)
|
||||
elif vis == "private":
|
||||
if club_id_form is not None:
|
||||
next_cid = int(club_id_form)
|
||||
elif is_platform_admin(role):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Private Archiv-Uploads als Plattform-Admin: bitte den Zielverein wählen und "
|
||||
"club_id im Formular setzen (nicht vom allgemeinen Kontext ableiten)."
|
||||
),
|
||||
)
|
||||
else:
|
||||
cid = tenant.effective_club_id
|
||||
next_cid = int(cid) if cid is not None else None
|
||||
if next_cid is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Private Medien werden pro Verein abgelegt. Bitte aktiven Verein setzen "
|
||||
"(Header X-Active-Club-Id) oder club_id im Formular übergeben — auch für Plattform-Admins."
|
||||
),
|
||||
)
|
||||
if not is_platform_admin(role):
|
||||
assert_club_member(cur, profile_id, next_cid)
|
||||
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid if vis == "club" else None)
|
||||
|
||||
max_b = _upload_limit_bytes(tenant)
|
||||
if len(raw) > max_b:
|
||||
@@ -490,13 +681,23 @@ def _ingest_library_media_file(
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
|
||||
full_sha = hashlib.sha256(raw).hexdigest()
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, vis, next_cid),
|
||||
)
|
||||
if vis == "private":
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, vis, next_cid, profile_id),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
LIMIT 1""",
|
||||
(full_sha, vis, next_cid),
|
||||
)
|
||||
existing_asset = cur.fetchone()
|
||||
|
||||
if existing_asset:
|
||||
@@ -537,8 +738,23 @@ def _ingest_library_media_file(
|
||||
elif not ext and mime == "video/quicktime":
|
||||
ext = ".mov"
|
||||
|
||||
club_nm = ""
|
||||
if next_cid is not None:
|
||||
club_nm = _club_display_name_for_storage(cur, next_cid)
|
||||
|
||||
media_root = get_effective_media_root(cur)
|
||||
storage_key = f"exercises/{full_sha}{ext}"
|
||||
try:
|
||||
storage_key = library_storage_key(
|
||||
vis,
|
||||
next_cid,
|
||||
full_sha,
|
||||
ext,
|
||||
uploader_profile_id=profile_id if vis == "private" else None,
|
||||
mime_type=mime,
|
||||
club_name=club_nm,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
dest_path = path_under_media_root(media_root, storage_key)
|
||||
if dest_path is None:
|
||||
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
|
||||
@@ -667,7 +883,6 @@ def list_media_assets(
|
||||
limit: int = Query(30, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
):
|
||||
lc_where = _lifecycle_where_sql(lifecycle)
|
||||
mk = (media_kind or "all").strip().lower()
|
||||
if mk not in _MEDIA_KIND_FILTERS:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger media_kind")
|
||||
@@ -709,6 +924,9 @@ def list_media_assets(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
admin_club_ids = club_ids_for_profile_with_roles(cur, profile_id, "club_admin")
|
||||
vis_main_sql, vis_params = _list_main_visibility_where(
|
||||
lifecycle, is_adm, sup, profile_id, admin_club_ids
|
||||
)
|
||||
show_uploader = sup or is_adm or bool(admin_club_ids)
|
||||
if uploaded_by is not None and not show_uploader:
|
||||
raise HTTPException(status_code=403, detail="Uploader-Filter nicht erlaubt")
|
||||
@@ -741,7 +959,7 @@ def list_media_assets(
|
||||
)
|
||||
|
||||
params: list[Any] = (
|
||||
[is_adm, profile_id, profile_id]
|
||||
vis_params
|
||||
+ club_sql_params
|
||||
+ uploaded_params
|
||||
+ search_params
|
||||
@@ -758,24 +976,7 @@ def list_media_assets(
|
||||
FROM media_assets ma
|
||||
LEFT JOIN profiles pr ON pr.id = ma.uploaded_by_profile_id
|
||||
LEFT JOIN clubs cl ON cl.id = ma.club_id
|
||||
WHERE {lc_where}
|
||||
AND (
|
||||
%s
|
||||
OR lower(trim(ma.visibility)) = 'official'
|
||||
OR (
|
||||
lower(trim(ma.visibility)) = 'private'
|
||||
AND ma.uploaded_by_profile_id = %s
|
||||
)
|
||||
OR (
|
||||
lower(trim(ma.visibility)) = 'club'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM club_members cm
|
||||
WHERE cm.profile_id = %s
|
||||
AND cm.club_id = ma.club_id
|
||||
AND cm.status = 'active'
|
||||
)
|
||||
)
|
||||
)
|
||||
WHERE {vis_main_sql}
|
||||
{club_sql}
|
||||
{uploaded_sql}
|
||||
{media_kind_sql}
|
||||
@@ -785,7 +986,7 @@ def list_media_assets(
|
||||
params,
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
show_club = sup or is_adm
|
||||
show_club = sup or is_adm or bool(admin_club_ids)
|
||||
asset_ids = [int(r["id"]) for r in rows]
|
||||
usage_map = _usage_for_media_assets(cur, asset_ids)
|
||||
for r in rows:
|
||||
@@ -915,7 +1116,7 @@ def bulk_media_patch(
|
||||
try:
|
||||
cur.execute(
|
||||
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
|
||||
copyright_notice, original_filename
|
||||
copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
@@ -937,7 +1138,7 @@ def bulk_media_patch(
|
||||
|
||||
eff = _effective_media_patch_fields(patch_fields, asset)
|
||||
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
|
||||
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id")
|
||||
next_cid = eff.get("club_id", asset.get("club_id"))
|
||||
if "visibility" in patch_fields or "club_id" in patch_fields:
|
||||
assert_valid_governance_visibility(
|
||||
cur,
|
||||
@@ -946,6 +1147,26 @@ def bulk_media_patch(
|
||||
next_vis,
|
||||
int(next_cid) if next_cid is not None else None,
|
||||
)
|
||||
if next_vis in ("private", "club") and next_cid is None:
|
||||
failed.append(
|
||||
{
|
||||
"id": asset_id,
|
||||
"detail": (
|
||||
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner)."
|
||||
),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
new_sk: Optional[str] = None
|
||||
if "visibility" in patch_fields or "club_id" in patch_fields:
|
||||
next_club_param: Optional[int] = None
|
||||
if next_vis in ("club", "private"):
|
||||
next_club_param = int(next_cid) if next_cid is not None else None
|
||||
media_root = get_effective_media_root(cur)
|
||||
new_sk = _relocate_asset_file_if_governance_changed(
|
||||
cur, media_root, asset_id, asset, next_vis, next_club_param
|
||||
)
|
||||
|
||||
sets: list[str] = []
|
||||
vals: list[Any] = []
|
||||
@@ -962,7 +1183,10 @@ def bulk_media_patch(
|
||||
sets.append("visibility = %s")
|
||||
vals.append(str(eff.get("visibility", asset["visibility"])).strip())
|
||||
sets.append("club_id = %s")
|
||||
vals.append(eff.get("club_id"))
|
||||
vals.append(next_cid)
|
||||
if new_sk:
|
||||
sets.append("storage_key = %s")
|
||||
vals.append(new_sk)
|
||||
if not sets:
|
||||
failed.append({"id": asset_id, "detail": "Nichts zu aktualisieren"})
|
||||
continue
|
||||
@@ -996,7 +1220,7 @@ def patch_media_asset(
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
|
||||
copyright_notice, original_filename
|
||||
copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
@@ -1014,7 +1238,7 @@ def patch_media_asset(
|
||||
|
||||
eff = _effective_media_patch_fields(data, asset)
|
||||
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
|
||||
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id")
|
||||
next_cid = eff.get("club_id", asset.get("club_id"))
|
||||
if "visibility" in data or "club_id" in data:
|
||||
assert_valid_governance_visibility(
|
||||
cur,
|
||||
@@ -1023,6 +1247,24 @@ def patch_media_asset(
|
||||
next_vis,
|
||||
int(next_cid) if next_cid is not None else None,
|
||||
)
|
||||
if next_vis in ("private", "club") and next_cid is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner). "
|
||||
"Bitte im PATCH setzen, z. B. bei Wechsel von „offiziell“ zu „privat“."
|
||||
),
|
||||
)
|
||||
|
||||
new_sk: Optional[str] = None
|
||||
if "visibility" in data or "club_id" in data:
|
||||
next_club_param: Optional[int] = None
|
||||
if next_vis in ("club", "private"):
|
||||
next_club_param = int(next_cid) if next_cid is not None else None
|
||||
media_root = get_effective_media_root(cur)
|
||||
new_sk = _relocate_asset_file_if_governance_changed(
|
||||
cur, media_root, asset_id, asset, next_vis, next_club_param
|
||||
)
|
||||
|
||||
sets: list[str] = []
|
||||
vals: list[Any] = []
|
||||
@@ -1039,7 +1281,10 @@ def patch_media_asset(
|
||||
sets.append("visibility = %s")
|
||||
vals.append(str(eff.get("visibility", asset["visibility"])).strip())
|
||||
sets.append("club_id = %s")
|
||||
vals.append(eff.get("club_id"))
|
||||
vals.append(next_cid)
|
||||
if new_sk:
|
||||
sets.append("storage_key = %s")
|
||||
vals.append(new_sk)
|
||||
if sets:
|
||||
sets.append("updated_at = NOW()")
|
||||
vals.append(asset_id)
|
||||
|
||||
+131
-3
@@ -11,15 +11,81 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, hash_pin
|
||||
from club_tenancy import assert_club_member, memberships_with_roles, is_platform_admin
|
||||
from club_tenancy import (
|
||||
assert_club_member,
|
||||
club_ids_for_profile_with_roles,
|
||||
is_platform_admin,
|
||||
is_superadmin,
|
||||
memberships_with_roles,
|
||||
)
|
||||
from tenant_context import resolve_tenant_context, TenantContext, get_tenant_context
|
||||
from models import ProfileCreate, ProfileUpdate
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||
|
||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
||||
|
||||
|
||||
class ManagementPasswordResetBody(BaseModel):
|
||||
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
|
||||
|
||||
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
|
||||
|
||||
@field_validator("new_password", mode="before")
|
||||
@classmethod
|
||||
def _empty_pw_none(cls, v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, str) and not v.strip():
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def _target_portal_role_lower(cur, target_pid: int) -> str:
|
||||
cur.execute("SELECT lower(trim(COALESCE(role, ''))) AS r FROM profiles WHERE id = %s", (target_pid,))
|
||||
row = cur.fetchone()
|
||||
return (row.get("r") or "user") if row else "user"
|
||||
|
||||
|
||||
def _assert_can_management_password_help(cur, tenant: TenantContext, target_pid: int, *, via_email: bool) -> None:
|
||||
"""
|
||||
Wer darf eines anderen Accounts Passwort-Helfer nutzen (E-Mail-Link oder — nur Superadmin — direktes Setzen)?
|
||||
Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied in gemeinsam verwaltetem Verein.
|
||||
"""
|
||||
viewer_pid = int(tenant.profile_id)
|
||||
if target_pid == viewer_pid:
|
||||
raise HTTPException(status_code=400, detail="Eigenes Passwort unter Einstellungen ändern")
|
||||
role_raw = tenant.global_role or ""
|
||||
if is_superadmin(role_raw):
|
||||
return
|
||||
if is_platform_admin(role_raw):
|
||||
return
|
||||
managed = club_ids_for_profile_with_roles(cur, viewer_pid, "club_admin")
|
||||
if not managed:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM club_members
|
||||
WHERE profile_id = %s AND club_id = ANY(%s) AND status = 'active'
|
||||
LIMIT 1
|
||||
""",
|
||||
(target_pid, list(managed)),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur für Nutzer, die in mindestens einem deiner Vereine (als Admin) aktiv sind",
|
||||
)
|
||||
if via_email and _target_portal_role_lower(cur, target_pid) in _CLUB_BLOCKED_PORTAL_TARGETS:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Für Konten mit Portal-Administrator- oder Super-Administrator-Rolle ist das nur für Super-Admins möglich",
|
||||
)
|
||||
|
||||
|
||||
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||
@@ -28,7 +94,7 @@ def get_current_profile(
|
||||
session=Depends(require_auth),
|
||||
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
||||
):
|
||||
"""Profil inkl. Vereinsmitgliedschaften; effective_club_id = aufgelöster Request-Kontext (Header vor Profilfeld)."""
|
||||
"""Profil inkl. Vereinsmitgliedschaften (aktive und temporär deaktivierte Zugänge); effective_club_id nur bei aktivem Vereinszugang."""
|
||||
profile_id = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -38,7 +104,7 @@ def get_current_profile(
|
||||
raise HTTPException(404, "Profil nicht gefunden")
|
||||
data = r2d(row)
|
||||
data.pop("pin_hash", None)
|
||||
clubs = memberships_with_roles(cur, profile_id)
|
||||
clubs = memberships_with_roles(cur, profile_id, active_only=False)
|
||||
data["clubs"] = clubs
|
||||
ac_raw = data.get("active_club_id")
|
||||
stored_ac = int(ac_raw) if ac_raw is not None and ac_raw != "" else None
|
||||
@@ -136,6 +202,68 @@ def profile_document(pid: str) -> dict:
|
||||
return d
|
||||
|
||||
|
||||
@router.post("/profiles/{pid}/management-password-reset")
|
||||
def management_password_reset(
|
||||
pid: str,
|
||||
body: ManagementPasswordResetBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Standard: E-Mail mit Reset-Link wie „Passwort vergessen“ — der PIN-Hash bleibt bis zur Bestätigung unverändert.
|
||||
Nur Super-Admins können optional `new_password` setzen (Ausnahme).
|
||||
"""
|
||||
from routers.auth import send_email
|
||||
from password_reset_mail import issue_password_reset_via_email
|
||||
|
||||
try:
|
||||
target = int(pid)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||
|
||||
direct = body.new_password is not None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id, email, name FROM profiles WHERE id = %s", (target,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
|
||||
if direct:
|
||||
role_raw = tenant.global_role or ""
|
||||
if not is_superadmin(role_raw):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Direktes Setzen eines Passworts ist nur Super-Admins vorbehalten. Bitte E-Mail-Link verwenden.",
|
||||
)
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
||||
new_hash = hash_pin(body.new_password)
|
||||
cur.execute(
|
||||
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
|
||||
(new_hash, target),
|
||||
)
|
||||
return {"ok": True, "mode": "direct"}
|
||||
|
||||
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
||||
email = (row.get("email") or "").strip()
|
||||
if not email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Für dieses Profil ist keine E-Mail-Adresse hinterlegt; ein Reset-Link kann nicht versendet werden.",
|
||||
)
|
||||
name = row.get("name")
|
||||
intro = "Ein Administrator hat für dein Konto einen sicheren Link zum Setzen eines neuen Passworts angefordert."
|
||||
sent = issue_password_reset_via_email(
|
||||
cur,
|
||||
send_email,
|
||||
profile_id=target,
|
||||
email=email.lower(),
|
||||
name=name,
|
||||
intro=intro,
|
||||
)
|
||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||
|
||||
|
||||
@router.get("/profiles/{pid}")
|
||||
def get_profile(pid: str, session=Depends(require_auth)):
|
||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
||||
|
||||
@@ -350,21 +350,18 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
|
||||
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||
"""
|
||||
if is_platform_admin(role):
|
||||
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
|
||||
else:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
base_sel
|
||||
+ f""" WHERE ({vis_clause})
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
base_sel
|
||||
+ f""" WHERE ({vis_clause})
|
||||
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
||||
vis_params,
|
||||
)
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
|
||||
@@ -896,25 +896,14 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if is_platform_admin(role):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT t.*,
|
||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||
AS sections_count
|
||||
FROM training_plan_templates t
|
||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||
"""
|
||||
)
|
||||
else:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="t",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="t",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT t.*,
|
||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||
AS sections_count
|
||||
@@ -922,8 +911,8 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
vis_params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
|
||||
+60
-19
@@ -21,6 +21,22 @@ def _club_exists(cur, club_id: int) -> bool:
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def memberships_for_tenant_resolution(
|
||||
memberships: List[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Nur Zeilen mit aktivem Vereinszugang (cm.status = 'active').
|
||||
Wird genutzt, wenn /profiles/me alle Mitgliedschaften inkl. inaktiver liefert.
|
||||
"""
|
||||
out: List[Dict[str, Any]] = []
|
||||
for r in memberships:
|
||||
st_raw = r.get("membership_status")
|
||||
st = str(st_raw if st_raw is not None else "active").strip().lower()
|
||||
if st == "active":
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def parse_active_club_header(raw: Optional[str]) -> Optional[int]:
|
||||
"""Parst X-Active-Club-Id; leer → None. Ungültig → HTTP 400."""
|
||||
if raw is None:
|
||||
@@ -45,21 +61,36 @@ def library_content_visibility_sql(
|
||||
effective_club_id: Optional[int],
|
||||
) -> tuple[str, List[Any]]:
|
||||
"""
|
||||
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme):
|
||||
official, eigene private, club nur im aktiven Vereinskontext (effective_club_id).
|
||||
Plattform-Admin: keine Einschränkung (TRUE).
|
||||
Ohne effective_club_id: kein club-Zweig (nur official + private).
|
||||
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme, …):
|
||||
|
||||
- official immer
|
||||
- private: eigene (Norm) bzw. alle (Plattform-Admin/Superadmin)
|
||||
- club: nur mit **aktivem** Vereinszugang; Existenz einer nur **inactive** Mitgliedschaft schließt
|
||||
aus — auch bei Plattform-Rolle. Ist man **kein** Mitglied des Vereins, behalten Plattform-Admins
|
||||
Zugriff (Audit).
|
||||
Für Nicht-Plattform: club-Zweig nur mit effective_club_id (Mandantenfilter).
|
||||
"""
|
||||
if is_platform_admin(role):
|
||||
return "TRUE", []
|
||||
plat = is_platform_admin(role)
|
||||
parts: List[str] = [f"{alias}.visibility = 'official'"]
|
||||
params: List[Any] = []
|
||||
|
||||
parts: List[str] = [
|
||||
f"{alias}.visibility = 'official'",
|
||||
f"({alias}.visibility = 'private' AND {alias}.created_by = %s)",
|
||||
]
|
||||
params: List[Any] = [profile_id]
|
||||
if plat:
|
||||
parts.append(f"({alias}.visibility = 'private')")
|
||||
else:
|
||||
parts.append(f"({alias}.visibility = 'private' AND {alias}.created_by = %s)")
|
||||
params.append(profile_id)
|
||||
|
||||
if effective_club_id is not None:
|
||||
club_ok_plat = (
|
||||
f"({alias}.visibility = 'club' AND {alias}.club_id IS NOT NULL AND ("
|
||||
f"EXISTS (SELECT 1 FROM club_members cm WHERE cm.profile_id = %s AND cm.club_id = {alias}.club_id "
|
||||
f"AND cm.status = 'active') OR NOT EXISTS (SELECT 1 FROM club_members cm2 WHERE cm2.profile_id = %s "
|
||||
f"AND cm2.club_id = {alias}.club_id)))"
|
||||
)
|
||||
|
||||
if plat:
|
||||
parts.append(club_ok_plat)
|
||||
params.extend([profile_id, profile_id])
|
||||
elif effective_club_id is not None:
|
||||
parts.append(
|
||||
f"""(
|
||||
{alias}.visibility = 'club'
|
||||
@@ -80,7 +111,7 @@ def library_content_visibility_sql(
|
||||
class TenantContext:
|
||||
profile_id: int
|
||||
global_role: str
|
||||
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header oft None
|
||||
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header: Profil-Verein wenn existent
|
||||
effective_club_id: Optional[int]
|
||||
club_ids: frozenset[int]
|
||||
memberships: List[Dict[str, Any]]
|
||||
@@ -97,10 +128,13 @@ def resolve_tenant_context(
|
||||
invalid_header_policy: str = "reject",
|
||||
) -> TenantContext:
|
||||
"""
|
||||
Mitgliedschaften: wenn nicht übergeben, wird aus der DB geladen (aktive Mitgliedschaften).
|
||||
Mitgliedschaften: wenn nicht übergeben, lädt ``active_only=True`` aus der DB.
|
||||
Übergabe z. B. von ``/profiles/me``: Liste darf auch **deaktivierte** Vereinszugänge
|
||||
(`membership_status` = inactive) enthalten — für ``club_ids`` und Mandantenwahl werden nur aktive verwendet.
|
||||
|
||||
Auflösung effective_club_id:
|
||||
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → None.
|
||||
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
|
||||
active_club_id falls der Verein existiert, sonst None.
|
||||
- Sonst: gültiger Header zwingend Mitgliedschaft — bei ``reject`` sonst 403, bei ``ignore`` wie ohne Header.
|
||||
Ohne gültigen Header: gespeichertes active_club_id wenn Mitglied; sonst einziger Verein;
|
||||
bei mehreren ohne gültige Vorgabe → min(club_ids) (Fallback).
|
||||
@@ -109,15 +143,22 @@ def resolve_tenant_context(
|
||||
header_cid = parse_active_club_header(header_raw)
|
||||
|
||||
if memberships is None:
|
||||
memberships = memberships_with_roles(cur, profile_id, active_only=True)
|
||||
membership_rows = memberships_with_roles(cur, profile_id, active_only=True)
|
||||
else:
|
||||
membership_rows = memberships_for_tenant_resolution(memberships)
|
||||
|
||||
club_ids = frozenset(int(r["id"]) for r in memberships if r.get("id") is not None)
|
||||
club_ids = frozenset(int(r["id"]) for r in membership_rows if r.get("id") is not None)
|
||||
|
||||
if is_platform_admin(role_lc):
|
||||
if header_cid is not None:
|
||||
if not _club_exists(cur, header_cid):
|
||||
raise HTTPException(status_code=400, detail="Verein nicht gefunden")
|
||||
effective = header_cid
|
||||
elif (
|
||||
stored_active_club_id is not None
|
||||
and _club_exists(cur, stored_active_club_id)
|
||||
):
|
||||
effective = stored_active_club_id
|
||||
else:
|
||||
effective = None
|
||||
return TenantContext(
|
||||
@@ -125,7 +166,7 @@ def resolve_tenant_context(
|
||||
global_role=role_lc,
|
||||
effective_club_id=effective,
|
||||
club_ids=club_ids,
|
||||
memberships=memberships,
|
||||
memberships=membership_rows,
|
||||
)
|
||||
|
||||
chosen_header = header_cid
|
||||
@@ -153,7 +194,7 @@ def resolve_tenant_context(
|
||||
global_role=role_lc,
|
||||
effective_club_id=effective,
|
||||
club_ids=club_ids,
|
||||
memberships=memberships,
|
||||
memberships=membership_rows,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -2,29 +2,30 @@
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from tenant_context import library_content_visibility_sql, parse_active_club_header
|
||||
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
|
||||
|
||||
|
||||
def test_library_visibility_sql_platform_admin_no_filter():
|
||||
def test_library_visibility_sql_platform_admin_restricts_club_by_membership():
|
||||
sql, params = library_content_visibility_sql(
|
||||
alias="e",
|
||||
profile_id=1,
|
||||
role="admin",
|
||||
effective_club_id=None,
|
||||
)
|
||||
assert sql == "TRUE"
|
||||
assert params == []
|
||||
assert "e.visibility = 'official'" in sql
|
||||
assert "club_members" in sql
|
||||
assert params == [1, 1]
|
||||
|
||||
|
||||
def test_library_visibility_sql_superadmin():
|
||||
def test_library_visibility_sql_superadmin_uses_membership_clause_for_club_visibility():
|
||||
sql, params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=2,
|
||||
role="superadmin",
|
||||
effective_club_id=100,
|
||||
)
|
||||
assert sql == "TRUE"
|
||||
assert params == []
|
||||
assert "club_members" in sql
|
||||
assert params == [2, 2]
|
||||
|
||||
|
||||
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
|
||||
@@ -74,3 +75,88 @@ def test_parse_active_club_header_non_positive():
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
parse_active_club_header("0")
|
||||
assert exc.value.status_code == 400
|
||||
|
||||
|
||||
def test_resolve_platform_admin_uses_stored_club_without_header(monkeypatch):
|
||||
"""Ohne X-Active-Club-Id: effective wie gespeichertes Profil (Sync mit Dropdown/DB)."""
|
||||
cur = object()
|
||||
|
||||
def fake_exists(c, cid):
|
||||
return cid == 99
|
||||
|
||||
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="admin",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 10}],
|
||||
stored_active_club_id=99,
|
||||
)
|
||||
assert ctx.effective_club_id == 99
|
||||
|
||||
|
||||
def test_resolve_platform_admin_header_overrides_stored(monkeypatch):
|
||||
cur = object()
|
||||
|
||||
def fake_exists(c, cid):
|
||||
return cid in (5, 99)
|
||||
|
||||
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="superadmin",
|
||||
header_raw="5",
|
||||
memberships=[{"id": 10}],
|
||||
stored_active_club_id=99,
|
||||
)
|
||||
assert ctx.effective_club_id == 5
|
||||
|
||||
|
||||
def test_resolve_platform_admin_no_header_stored_invalid(monkeypatch):
|
||||
cur = object()
|
||||
monkeypatch.setattr("tenant_context._club_exists", lambda c, cid: False)
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=1,
|
||||
global_role="admin",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 1}],
|
||||
stored_active_club_id=123,
|
||||
)
|
||||
assert ctx.effective_club_id is None
|
||||
|
||||
|
||||
def test_resolve_trainer_club_ids_excludes_inactive_memberships():
|
||||
"""Nur aktive Vereinszugänge zählen für Mandant / Header-Validierung."""
|
||||
cur = object()
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=9,
|
||||
global_role="user",
|
||||
header_raw=None,
|
||||
memberships=[
|
||||
{"id": 10, "membership_status": "inactive"},
|
||||
{"id": 20, "membership_status": "active"},
|
||||
],
|
||||
stored_active_club_id=None,
|
||||
invalid_header_policy="ignore",
|
||||
)
|
||||
assert ctx.club_ids == frozenset({20})
|
||||
assert ctx.effective_club_id == 20
|
||||
|
||||
|
||||
def test_resolve_all_memberships_inactive_no_effective_club():
|
||||
cur = object()
|
||||
ctx = resolve_tenant_context(
|
||||
cur,
|
||||
profile_id=9,
|
||||
global_role="user",
|
||||
header_raw=None,
|
||||
memberships=[{"id": 10, "membership_status": "inactive"}],
|
||||
stored_active_club_id=10,
|
||||
invalid_header_policy="ignore",
|
||||
)
|
||||
assert ctx.club_ids == frozenset()
|
||||
assert ctx.effective_club_id is None
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Vereins-Übung: Copyright-Pflicht für angehängte Archiv-Dateien."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import routers.exercises as exercises_mod
|
||||
from routers.exercises import apply_club_exercise_media_copyright_rules
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_skips_non_club() -> None:
|
||||
apply_club_exercise_media_copyright_rules(object(), 1, "private")
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_missing_copyright() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, eid: int):
|
||||
assert eid == 42
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
assert ei.value.status_code == 422
|
||||
d = ei.value.detail
|
||||
assert isinstance(d, dict)
|
||||
assert d.get("code") == "CLUB_MEDIA_COPYRIGHT_REQUIRED"
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_ok() -> None:
|
||||
orig = exercises_mod._fetch_exercise_linked_file_assets
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Verein 2026",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
||||
|
||||
|
||||
def test_apply_club_exercise_media_copyright_applies_default() -> None:
|
||||
"""Nach Bestätigung setzt der Client default_club_media_copyright — Backend schreibt auf Assets."""
|
||||
orig_fetch = exercises_mod._fetch_exercise_linked_file_assets
|
||||
calls = {"n": 0}
|
||||
|
||||
def mock_fetch(_cur, _eid: int):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
return [
|
||||
{
|
||||
"id": 10,
|
||||
"visibility": "private",
|
||||
"club_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"copyright_notice": "© Testverein",
|
||||
"original_filename": "x.jpg",
|
||||
}
|
||||
]
|
||||
|
||||
class MockCur:
|
||||
def execute(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
|
||||
try:
|
||||
apply_club_exercise_media_copyright_rules(
|
||||
MockCur(),
|
||||
42,
|
||||
"club",
|
||||
default_club_media_copyright="© Testverein",
|
||||
)
|
||||
assert calls["n"] == 2
|
||||
finally:
|
||||
exercises_mod._fetch_exercise_linked_file_assets = orig_fetch
|
||||
@@ -0,0 +1,51 @@
|
||||
"""POST /api/exercises: keine Inline-Medien-Platzhalter beim ersten Anlegen (§11)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides() -> None:
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
|
||||
|
||||
def test_post_exercise_rejects_inline_media_placeholder(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=5,
|
||||
club_ids=frozenset({5}),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.post(
|
||||
"/api/exercises",
|
||||
json={
|
||||
"title": "Mit Inline",
|
||||
"goal": "<p>Hallo {{exerciseMedia:7}}</p>",
|
||||
"execution": "<p>Schritt</p>",
|
||||
"visibility": "private",
|
||||
"status": "draft",
|
||||
},
|
||||
headers={"X-Auth-Token": "x"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
j = r.json()
|
||||
assert j.get("detail", {}).get("code") == "INLINE_EXERCISE_MEDIA_ON_CREATE"
|
||||
@@ -0,0 +1,44 @@
|
||||
"""exercise_rich_text: §11 Normalisierung und ID-Sammlung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from exercise_rich_text import (
|
||||
assert_no_inline_media_references_on_create,
|
||||
collect_inline_exercise_media_ids,
|
||||
normalize_inline_exercise_media_markup,
|
||||
validate_inline_exercise_media_ids_for_exercise,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_curly_to_span() -> None:
|
||||
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
|
||||
out = normalize_inline_exercise_media_markup(s)
|
||||
assert 'data-shinkan-exercise-media="42"' in out
|
||||
assert 'data-shinkan-exercise-media-size="medium"' in out
|
||||
assert "{{" not in out
|
||||
|
||||
|
||||
def test_collect_merges_braces_and_data_attr() -> None:
|
||||
html = '{{ExercisemEDIA: 1}}\n<span data-shinkan-exercise-media="2"></span>'
|
||||
assert collect_inline_exercise_media_ids(html) == {1, 2}
|
||||
|
||||
|
||||
def test_assert_no_inline_on_create_raises() -> None:
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
assert_no_inline_media_references_on_create({5})
|
||||
assert ei.value.status_code == 400
|
||||
body = ei.value.detail
|
||||
assert isinstance(body, dict)
|
||||
assert body["code"] == "INLINE_EXERCISE_MEDIA_ON_CREATE"
|
||||
|
||||
|
||||
def test_validate_ids_sql_mock() -> None:
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchall.return_value = [{"id": 1}]
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
validate_inline_exercise_media_ids_for_exercise(mock_cur, 100, {1, 99})
|
||||
assert ei.value.detail["invalid_exercise_media_ids"] == [99]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
|
||||
|
||||
_HEX64 = "a" * 64
|
||||
|
||||
|
||||
def test_library_media_kind_dir_mime_overrides_ext() -> None:
|
||||
assert library_media_kind_dir("image/png", ".bin") == "image"
|
||||
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
|
||||
|
||||
|
||||
def test_library_club_path_segment_slug_and_fallback() -> None:
|
||||
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
|
||||
assert library_club_path_segment(3, None) == "verein-c3"
|
||||
assert library_club_path_segment(3, " ") == "verein-c3"
|
||||
assert library_club_path_segment(12, "東道場") == "verein-c12"
|
||||
|
||||
|
||||
def test_library_club_path_segment_long_name_truncated() -> None:
|
||||
long = "a" * 80
|
||||
seg = library_club_path_segment(5, long)
|
||||
assert seg == "a" * 48 + "-c5"
|
||||
|
||||
|
||||
def test_library_storage_key_private_is_uploader_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key(
|
||||
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
|
||||
)
|
||||
== f"library/ost-dojo-muenchen-c7/image/{_HEX64}.u99.jpg"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_club_flat_under_club() -> None:
|
||||
assert (
|
||||
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
|
||||
== f"library/demo-verein-c42/image/{_HEX64}.png"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_official() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
|
||||
== f"library/official/video/{_HEX64}.mp4"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_normalizes_visibility() -> None:
|
||||
assert (
|
||||
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
|
||||
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_other_bin() -> None:
|
||||
assert (
|
||||
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
|
||||
== f"library/official/other/{_HEX64}.bin"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_uploader() -> None:
|
||||
with pytest.raises(ValueError, match="uploader_profile_id"):
|
||||
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
|
||||
|
||||
|
||||
def test_library_storage_key_private_requires_club() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
|
||||
|
||||
|
||||
def test_library_storage_key_club_requires_id() -> None:
|
||||
with pytest.raises(ValueError, match="Verein"):
|
||||
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_club_id_positive() -> None:
|
||||
with pytest.raises(ValueError, match="positiv"):
|
||||
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_visibility() -> None:
|
||||
with pytest.raises(ValueError, match="Sichtbarkeit"):
|
||||
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_invalid_sha() -> None:
|
||||
with pytest.raises(ValueError, match="64"):
|
||||
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
|
||||
|
||||
|
||||
def test_library_storage_key_extension() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
library_storage_key(
|
||||
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
|
||||
)
|
||||
|
||||
|
||||
def test_library_storage_key_private_no_club_name_fallback() -> None:
|
||||
assert (
|
||||
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
|
||||
== f"library/verein-c2/image/{_HEX64}.u3.jpg"
|
||||
)
|
||||
@@ -15,6 +15,11 @@ from auth import require_auth
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
|
||||
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
|
||||
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
|
||||
_SK_PRIV_C = f"library/verein-c1/video/{'c' * 64}.u1.mp4"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
@@ -136,7 +141,7 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": "exercises/x.jpg",
|
||||
"storage_key": _SK_OFF_A,
|
||||
},
|
||||
{"id": 1},
|
||||
]
|
||||
@@ -175,7 +180,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
"id": 99,
|
||||
"exercise_id": 3,
|
||||
"media_type": "image",
|
||||
"file_path": "/media/exercises/h.jpg",
|
||||
"file_path": f"/media/{_SK_OFF_B}",
|
||||
"file_size": 10,
|
||||
"mime_type": "image/jpeg",
|
||||
"original_filename": "h.jpg",
|
||||
@@ -202,7 +207,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
|
||||
"club_id": None,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "active",
|
||||
"storage_key": "exercises/h.jpg",
|
||||
"storage_key": _SK_OFF_B,
|
||||
},
|
||||
None,
|
||||
inserted,
|
||||
@@ -326,10 +331,10 @@ def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
|
||||
{
|
||||
"id": 5,
|
||||
"visibility": "private",
|
||||
"club_id": None,
|
||||
"club_id": 1,
|
||||
"uploaded_by_profile_id": 1,
|
||||
"lifecycle_state": "trash_soft",
|
||||
"storage_key": "exercises/a.mp4",
|
||||
"storage_key": _SK_PRIV_C,
|
||||
"storage_backend": "local",
|
||||
"trash_soft_at": None,
|
||||
"trash_hidden_at": None,
|
||||
|
||||
+109
-6
@@ -1,23 +1,23 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.51"
|
||||
BUILD_DATE = "2026-05-07"
|
||||
DB_SCHEMA_VERSION = "20260507046"
|
||||
APP_VERSION = "0.8.65"
|
||||
BUILD_DATE = "2026-05-08"
|
||||
DB_SCHEMA_VERSION = "20260508049"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
|
||||
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
|
||||
"tenant_context": "1.0.4", # pytest: Unit test_access_layer.py + optional Integration test_access_layer_integration (PostgreSQL)
|
||||
"tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
|
||||
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
|
||||
"club_memberships": "1.0.1", # Depends(get_tenant_context)
|
||||
"club_join_requests": "1.0.1", # Depends(get_tenant_context)
|
||||
"admin_users": "1.0.0", # GET /api/admin/users
|
||||
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
|
||||
"media_assets": "1.5.1", # usage: training_unit_exercises optional (Schema ohne planning-Tabelle)
|
||||
"media_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.16.0", # §4.2 official: angehängte media_assets + Copyright (PUT + bulk-metadata)
|
||||
"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.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||
@@ -29,6 +29,109 @@ 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",
|
||||
|
||||
@@ -54,6 +54,8 @@ services:
|
||||
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
||||
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
|
||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
||||
# Bind-Mount: Verzeichnis muss auf dem Host existieren und chown für den Docker-Daemon
|
||||
# zulassen (lokale Platte). Bei NFS/SMB oft "chown … operation not permitted" → anderen Pfad.
|
||||
volumes:
|
||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
||||
ports:
|
||||
|
||||
+75
-34
@@ -1,9 +1,9 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-05
|
||||
**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,11 +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` |
|
||||
| Rahmenprogramm · Planung (`training_units` Blueprints), Progressionsgraph | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md`; Überblick DB → `.claude/docs/technical/DATABASE_SCHEMA.md`; Domäne → `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
|
||||
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
|
||||
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| Ü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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -36,73 +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. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
|
||||
|
||||
- **Migration 036:** Rahmenkopf nur Bibliothek (Kontext: Fokusbereich, Stilrichtung; M:N Trainingsarten/Zielgruppen); keine `plan_mode`/keine Kopf‑`group_id`.
|
||||
- **Migration 037:** Pro Rahmen‑Slot eine **`training_units`‑Zeile mit `framework_slot_id`**; strukturierter Ablauf wie echte Einheiten (`training_unit_sections` / `training_unit_section_items`). Tabelle **`training_framework_slot_exercises`** entfällt.
|
||||
- **API:** Rahmen unter **`/api/training-framework-programs`** (Slots liefern u. a. **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`**); Kalenderliste **`GET /api/training-units`** ohne Blueprints; Übernahme **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `backend/routers/training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**; **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Stand: Übungen (Lücke für nächste Session)
|
||||
## 4. Stand: Medien-Management (Ist, 2026-05-07)
|
||||
|
||||
**Ist (laut Projektdoku und aktuellem Produktziel):**
|
||||
**Datenmodell (Kurz):**
|
||||
|
||||
- Backend: Übungen-CRUD, M:N, Suche, Blöcke, Medien-Struktur u. a. sind in `PROJECT_STATUS.md` als umgesetzt geführt; viele Übungen stammen aus **MediaWiki-Import** (Wiki-Tracking-Tabellen).
|
||||
- **Soll / Nutzerfeedback:** In der Praxis fehlt oder ist unzureichend: **stabile Liste**, **gerenderte Detailansicht**, **Bearbeiten/Anlegen**, **Medien zuweisen/Upload** – konkrete Fehler (404, leere Liste, falsche Route) sind vor Ort zu verifizieren.
|
||||
- **`media_assets`:** Physische oder logische Archiv-Datei (u. a. `sha256`, `visibility`, `club_id`, `lifecycle_state`, `copyright_notice`, Speicherpfad/`storage_key`, `tags` ab passender Migration).
|
||||
- **`exercise_media`:** optional **`media_asset_id`**; weiterhin Embeds ohne Asset; Kontext/Sortierung/Titel wie bisher.
|
||||
- **`platform_media_storage`:** Superadmin — relativer Unterpfad unter `MEDIA_ROOT`.
|
||||
|
||||
**Nächste Session sollte:**
|
||||
**API (Auszug):**
|
||||
|
||||
1. Aktuelle Routen und Seiten prüfen (`App.jsx`, `EXERCISES_FRONTEND_ROUTING.md`).
|
||||
2. `GET /api/exercises` (Filter, Auth) und eine Beispiel-Übung gegen die Dev-DB testen.
|
||||
3. UI schrittweise: Liste → Detail → Formular → Medien (an Specs in `.claude/docs/technical/` ausrichten).
|
||||
- **`GET /api/media-assets`**, Filter (Lifecycle, `media_kind`, Verein, Suche, Tags), Berechtigungen pro Zeile.
|
||||
- **`PATCH /api/media-assets/{id}`** / Bulk-PATCH, **Lifecycle** (`POST …/lifecycle`, Bulk).
|
||||
- **`GET …/media-assets/{id}/file`** (inkl. Kontext `ssetoken` wo vorgesehen).
|
||||
- **`POST /api/exercises/{id}/media/from-asset`:** bestehendes Asset verknüpfen.
|
||||
- Übungs-Uploads erzeugen/verknüpfen **`media_assets`**; Governance wie **`library_content_*`** / TenantContext.
|
||||
|
||||
**Frontend:**
|
||||
|
||||
- Route **`/media`** (Medienbibliothek): Kacheln/Liste, Filter, Copyright, Lifecycle-Actions (Rollen gemäß Spec; **`official`:** bearbeiten/Lifecycle im Wesentlichen **Superadmin**, andere Rollen **Lesemodus** im Bearbeiten-Dialog).
|
||||
- Übungsformular: Archiv-Picker, Vorschau, Reaktivierung bei Dedupe-Konflikt (Papierkorb).
|
||||
|
||||
**Speicher & Pfade:**
|
||||
|
||||
- Struktur unter **`library/`** mit Vereinssegment (aus Vereinsname abgeleitet + `c{id}`), Unterordner nach Medienkind (`image`/`video`/`pdf`/`other`), Dateiname z. B. SHA-basiert — Details und Drift-Vermeidung in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||
|
||||
**Governance & Mandant:**
|
||||
|
||||
- **`visibility=official`** für Übungen: nur **Superadmin**; Medien **`official`:** Lifecycle/PATCH schwerpunktmäßig Superadmin (Plattform-Admin nicht gleich Superadmin).
|
||||
- **Aktiver Verein:** `profiles.active_club_id`, Header **`X-Active-Club-Id`**, Response **`effective_club_id`** — nach **0.8.59** konsistent inkl. Plattform-Admin beim Reload (Backend **`tenant_context`**, Frontend **`getResolvedActiveClubIdForUi`** + Profil-Refresh nach Vereinswechsel).
|
||||
|
||||
---
|
||||
|
||||
## 5. Technische Referenz (kurz)
|
||||
## 5. 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`; Router u. a. **`training_framework_programs.py`**, **`training_planning.py`**, `maturity_models.py`, `matrix_stack_bundle.py`, `exercises.py`, `catalogs.py`, `skills.py` |
|
||||
| Migrationen | `backend/migrations/` (u. a. 024–027 Reifegrad/Bindings; **035–037** Rahmenprogramm / Slot‑Blueprint) |
|
||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`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` |
|
||||
|
||||
---
|
||||
|
||||
## 6. 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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+14
-3
@@ -13,9 +13,20 @@ server {
|
||||
# — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
# Uploads (Übungsmedien) und API erreichen Clients unter derselben Host-URL wie die SPA —
|
||||
# dafür muss Nginx zur FastAPI-Instanz im Compose-Netz weiterleiten.
|
||||
client_max_body_size 64m;
|
||||
# Uploads (Übungsmedien, Medienarchiv-Bulk) — Limit muss >= größte Einzeldatei und
|
||||
# bei multipart ggf. Summe mehrerer Dateien sein (Backend praxis: bis 1024 MB Admin).
|
||||
client_max_body_size 1024m;
|
||||
|
||||
# Medienbibliothek (React /media) — vor location ^~ /media/: sonst liefert ein Reload
|
||||
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
|
||||
location = /media {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
location = /media/ {
|
||||
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
set $docker_backend_svc backend;
|
||||
|
||||
+66
-13
@@ -9,6 +9,7 @@ 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'
|
||||
@@ -20,6 +21,7 @@ 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'
|
||||
@@ -32,13 +34,22 @@ 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) => {
|
||||
@@ -58,6 +69,11 @@ function Nav({ isAdmin }) {
|
||||
}
|
||||
>
|
||||
<item.Icon size={26} strokeWidth={2} />
|
||||
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||
<span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
|
||||
{inboxCount > 99 ? '99+' : inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
<span>{item.shortLabel || item.label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
@@ -95,11 +111,11 @@ function ProtectedLayout() {
|
||||
return <Navigate to="/login" replace />
|
||||
}
|
||||
|
||||
const isAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const showAdminNav = computeShowAdminNav(user)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DesktopSidebar isAdmin={isAdmin} user={user} onLogout={handleLogout} />
|
||||
<OrgInboxProvider user={user}>
|
||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||
<div className="app-shell">
|
||||
<div className="app-shell__column">
|
||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||
@@ -109,12 +125,13 @@ function ProtectedLayout() {
|
||||
<ActiveClubSwitcher variant="mobile" />
|
||||
</div>
|
||||
<div className="app-main">
|
||||
<InactiveMembershipBanner />
|
||||
<Outlet />
|
||||
</div>
|
||||
<Nav isAdmin={isAdmin} />
|
||||
<Nav showAdminNav={showAdminNav} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</OrgInboxProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -167,6 +184,7 @@ 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/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
|
||||
<Route path="planning/framework-programs/:id" element={<TrainingFrameworkProgramEditPage />} />
|
||||
@@ -174,12 +192,47 @@ function AppRoutes() {
|
||||
<Route path="planning/run/:unitId/coach" element={<TrainingCoachPage />} />
|
||||
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
|
||||
<Route path="planning" element={<TrainingPlanningPage />} />
|
||||
<Route path="admin" element={<Navigate to="/admin/hierarchy" replace />} />
|
||||
<Route path="admin/users" element={<AdminUsersPage />} />
|
||||
<Route path="admin/hierarchy" element={<AdminHierarchyPage />} />
|
||||
<Route path="admin/maturity-models" element={<AdminMaturityModelsPage />} />
|
||||
<Route path="admin/catalogs" element={<AdminCatalogsPage />} />
|
||||
<Route path="admin/mediawiki-import" element={<MediaWikiImportPage />} />
|
||||
<Route path="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>
|
||||
|
||||
|
||||
+424
-1
@@ -198,6 +198,7 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
|
||||
min-width: 68px;
|
||||
max-width: 108px;
|
||||
min-height: 48px;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
@@ -3895,7 +3896,30 @@ a.analysis-split__nav-item {
|
||||
overflow-y: auto;
|
||||
resize: vertical;
|
||||
}
|
||||
/* Listen im Editor (nicht nur in .rich-text-content) – sonst „unsichtbare“ Bullets */
|
||||
|
||||
/* §11 Inline-Marker: im Editor sichtbar (DOM ist nur leeres span + ZWJ — sonst „passiert nichts“-Effekt) */
|
||||
.rich-text-editor span.shinkan-inline-media {
|
||||
display: inline-block;
|
||||
vertical-align: baseline;
|
||||
margin: 2px 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
border: 1px dashed var(--accent);
|
||||
background: var(--surface2);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--accent-dark);
|
||||
line-height: 1.35;
|
||||
cursor: default;
|
||||
}
|
||||
.rich-text-editor span.shinkan-inline-media::before {
|
||||
content: '📎 #' attr(data-shinkan-exercise-media) ' · ' attr(data-shinkan-exercise-media-size);
|
||||
}
|
||||
.rich-text-editor span.shinkan-inline-media[data-shinkan-exercise-media-caption]::before {
|
||||
content: '📎 ' attr(data-shinkan-exercise-media-caption) ' · #' attr(data-shinkan-exercise-media) ' · ' attr(data-shinkan-exercise-media-size);
|
||||
}
|
||||
|
||||
/* Listen im Editor */
|
||||
.rich-text-editor ul,
|
||||
.rich-text-editor ol {
|
||||
margin: 0.35rem 0;
|
||||
@@ -3921,6 +3945,252 @@ a.analysis-split__nav-item {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.rich-text-content .shinkan-inline-media-wrap--sm {
|
||||
max-width: min(280px, 92vw);
|
||||
}
|
||||
.rich-text-content .shinkan-inline-media-wrap--md {
|
||||
max-width: min(560px, 92vw);
|
||||
}
|
||||
.rich-text-content .shinkan-inline-media-wrap--full {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.btn-secondary.rte-tab--active {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px rgba(29, 158, 117, 0.22);
|
||||
}
|
||||
|
||||
.rte-inline-asset-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(148px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.rte-inline-asset-tile {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
text-align: left;
|
||||
gap: 4px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
.rte-inline-asset-tile:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.rte-inline-asset-tile--selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px rgba(29, 158, 117, 0.2);
|
||||
}
|
||||
.rte-inline-asset-tile__meta {
|
||||
font-size: 11px;
|
||||
color: var(--text3);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
.rte-inline-asset-tile__name {
|
||||
font-size: 13px;
|
||||
line-height: 1.3;
|
||||
color: var(--text1);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rte-inline-asset-tile__thumb {
|
||||
width: 100%;
|
||||
aspect-ratio: 4 / 3;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: var(--surface2);
|
||||
border: 1px solid rgba(127, 127, 127, 0.12);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.rte-inline-asset-tile__thumb-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.rte-inline-asset-tile__thumb-video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
pointer-events: none;
|
||||
}
|
||||
.rte-inline-asset-tile__thumb-fallback {
|
||||
font-size: 11px;
|
||||
color: var(--text3);
|
||||
}
|
||||
.rte-inline-asset-tile__badge {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--accent-dark);
|
||||
}
|
||||
|
||||
.rte-inline-file-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
position: relative;
|
||||
}
|
||||
.rte-inline-file-input-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
.rte-inline-file-pick-btn {
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
margin: 0;
|
||||
}
|
||||
.rte-inline-file-name {
|
||||
flex: 1 1 160px;
|
||||
font-size: 13px;
|
||||
color: var(--text2);
|
||||
line-height: 1.35;
|
||||
min-width: 0;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.exercise-edit-media-strip {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 14px 0 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 12px;
|
||||
align-items: stretch;
|
||||
}
|
||||
.exercise-edit-media-strip__item {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: stretch;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.exercise-edit-media-strip__lead {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 96px;
|
||||
}
|
||||
.exercise-edit-media-strip__handle {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
line-height: 1.2;
|
||||
padding: 6px 4px;
|
||||
border-radius: 8px;
|
||||
border: 1px dashed var(--accent);
|
||||
background: rgba(29, 158, 117, 0.08);
|
||||
color: var(--accent-dark);
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
}
|
||||
.exercise-edit-media-strip__handle:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.exercise-edit-media-strip__handle-text {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.exercise-edit-media-strip__embed-badge--solo {
|
||||
width: 76px;
|
||||
min-height: 76px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--surface2);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text2);
|
||||
padding: 6px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.exercise-edit-media-strip__body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.exercise-edit-media-strip__toolbar {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.exercise-edit-media-strip__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.exercise-orphan-media-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.exercise-orphan-media-card {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.exercise-orphan-media-card__head {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.exercise-orphan-media-card__meta {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.exercise-orphan-media-card__title {
|
||||
font-size: 14px;
|
||||
display: block;
|
||||
line-height: 1.3;
|
||||
word-break: break-word;
|
||||
}
|
||||
.exercise-orphan-media-card__sub {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--text3);
|
||||
margin-top: 4px;
|
||||
}
|
||||
.exercise-orphan-media-card__warn {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--danger);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.rich-text-content {
|
||||
font-size: 16px;
|
||||
line-height: 1.55;
|
||||
@@ -6107,3 +6377,156 @@ a.analysis-split__nav-item {
|
||||
.media-library__preview-fallback .btn {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* Organisation: Posteingang (Nav-Badge, Sidebar, Dashboard-Widget) */
|
||||
.nav-item__badge {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 6px;
|
||||
min-width: 1.1rem;
|
||||
padding: 1px 5px;
|
||||
border-radius: 999px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
box-shadow: 0 0 0 1px var(--surface);
|
||||
}
|
||||
.desktop-sidebar__badge {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
min-width: 1.25rem;
|
||||
padding: 2px 6px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.desktop-sidebar__link > span:not(.desktop-sidebar__badge) {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-org-inbox-widget {
|
||||
display: none;
|
||||
}
|
||||
@media (min-width: 1024px) {
|
||||
.dashboard-org-inbox-widget {
|
||||
display: block;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
}
|
||||
.dashboard-org-inbox-widget__inner {
|
||||
padding: 1rem 1.1rem;
|
||||
}
|
||||
.dashboard-org-inbox-widget__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.dashboard-org-inbox-widget__title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
.dashboard-org-inbox-widget__icon {
|
||||
color: var(--accent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.dashboard-org-inbox-widget__badge {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
min-width: 1.5rem;
|
||||
text-align: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.dashboard-org-inbox-widget__lead {
|
||||
margin: 0 0 0.65rem;
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
.dashboard-org-inbox-widget__list {
|
||||
list-style: none;
|
||||
margin: 0 0 0.85rem;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
.dashboard-org-inbox-widget__item {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem 0.75rem;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.35rem 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.dashboard-org-inbox-widget__item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.dashboard-org-inbox-widget__club {
|
||||
font-weight: 600;
|
||||
color: var(--text1);
|
||||
}
|
||||
.dashboard-org-inbox-widget__applicant {
|
||||
color: var(--text2);
|
||||
}
|
||||
.dashboard-org-inbox-widget__footer {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.inbox-page__header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.inbox-page__list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.inbox-request-card {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.inbox-request-card__club {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
.inbox-request-card__applicant {
|
||||
display: block;
|
||||
font-size: 1.02rem;
|
||||
}
|
||||
.inbox-request-card__meta {
|
||||
font-size: 0.86rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.inbox-request-card__message {
|
||||
margin: 0.5rem 0 0;
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.inbox-request-card__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { activeClubMemberships, getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
||||
|
||||
/**
|
||||
* Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
|
||||
@@ -6,13 +7,10 @@ import { useAuth } from '../context/AuthContext'
|
||||
*/
|
||||
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
|
||||
const { user, setActiveClub } = useAuth()
|
||||
const clubs = user?.clubs || []
|
||||
const clubs = activeClubMemberships(user?.clubs)
|
||||
if (clubs.length <= 1) return null
|
||||
|
||||
const selectClubId =
|
||||
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
|
||||
? user.active_club_id
|
||||
: clubs[0]?.id
|
||||
const selectClubId = getResolvedActiveClubIdForUi(user)
|
||||
|
||||
const isMobile = variant === 'mobile'
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export default function AdminHomeRedirect() {
|
||||
const { user } = useAuth()
|
||||
const isSuper = user?.role === 'superadmin'
|
||||
return <Navigate to={isSuper ? '/admin/hierarchy' : '/'} replace />
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Images } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal)
|
||||
* Wechselt zwischen verschiedenen Admin-Seiten
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
*/
|
||||
export default function AdminPageNav() {
|
||||
const pages = [
|
||||
@@ -11,8 +10,7 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/users', label: 'Nutzer', icon: Users },
|
||||
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
|
||||
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
|
||||
{ to: '/media', label: 'Medien', icon: Images },
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download }
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Inbox } from 'lucide-react'
|
||||
import { useOrgInbox } from '../context/OrgInboxContext'
|
||||
|
||||
/**
|
||||
* Desktop-Dashboard: Hinweis auf offene Beitrittsanträge (nur ab 1024px sichtbar via CSS).
|
||||
*/
|
||||
export default function DashboardOrgInboxWidget() {
|
||||
const { canAccessOrgInbox, inboxJoinRequests, inboxCount } = useOrgInbox()
|
||||
|
||||
if (!canAccessOrgInbox) return null
|
||||
|
||||
const preview = (inboxJoinRequests || []).slice(0, 5)
|
||||
|
||||
return (
|
||||
<section
|
||||
className="dashboard-org-inbox-widget"
|
||||
aria-labelledby="dash-org-inbox-title"
|
||||
>
|
||||
<div className="dashboard-org-inbox-widget__inner card">
|
||||
<div className="dashboard-org-inbox-widget__head">
|
||||
<h2 id="dash-org-inbox-title" className="dashboard-org-inbox-widget__title">
|
||||
<Inbox size={20} strokeWidth={2} aria-hidden className="dashboard-org-inbox-widget__icon" />
|
||||
Posteingang
|
||||
</h2>
|
||||
{inboxCount > 0 ? (
|
||||
<span className="dashboard-org-inbox-widget__badge" aria-live="polite">
|
||||
{inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="muted dashboard-org-inbox-widget__lead">
|
||||
{inboxCount === 0
|
||||
? 'Keine offenen Beitrittsanträge.'
|
||||
: `${inboxCount} offene Beitrittsantrag${inboxCount === 1 ? '' : 'e'}.`}
|
||||
</p>
|
||||
{preview.length > 0 ? (
|
||||
<ul className="dashboard-org-inbox-widget__list">
|
||||
{preview.map((req) => (
|
||||
<li key={`${req.club_id}-${req.id}`} className="dashboard-org-inbox-widget__item">
|
||||
<span className="dashboard-org-inbox-widget__club">{req.club_name || 'Verein'}</span>
|
||||
<span className="dashboard-org-inbox-widget__applicant">
|
||||
{req.applicant_name || req.applicant_email || 'Bewerber/in'}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<div className="dashboard-org-inbox-widget__footer">
|
||||
<Link to="/inbox" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
|
||||
Zum Posteingang
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NavLink, useLocation } from 'react-router-dom'
|
||||
import { LogOut } from 'lucide-react'
|
||||
import { getMainNavItems } from '../config/appNav'
|
||||
import { useOrgInbox } from '../context/OrgInboxContext'
|
||||
import ActiveClubSwitcher from './ActiveClubSwitcher'
|
||||
|
||||
function sidebarLinkActive(pathname, item, routerIsActive) {
|
||||
@@ -12,12 +13,13 @@ function sidebarLinkActive(pathname, item, routerIsActive) {
|
||||
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
|
||||
*/
|
||||
export default function DesktopSidebar({
|
||||
isAdmin,
|
||||
showAdminNav,
|
||||
user,
|
||||
onLogout
|
||||
}) {
|
||||
const loc = useLocation()
|
||||
const items = getMainNavItems(isAdmin)
|
||||
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||
const tier = user?.tier || ''
|
||||
|
||||
return (
|
||||
@@ -42,6 +44,11 @@ export default function DesktopSidebar({
|
||||
>
|
||||
<item.Icon size={20} strokeWidth={2} />
|
||||
<span>{item.label}</span>
|
||||
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||
<span className="desktop-sidebar__badge" aria-label={`${inboxCount} offen`}>
|
||||
{inboxCount > 99 ? '99+' : inboxCount}
|
||||
</span>
|
||||
) : null}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Nur Medien, die noch nicht im Fließtext eingebettet sind — ohne Doppel-Darstellung.
|
||||
*/
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
|
||||
import ExerciseMediaThumbTile from './ExerciseMediaThumbTile'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import {
|
||||
collectInlineExerciseMediaIdsFromExercise,
|
||||
} from '../utils/exerciseInlineMediaRefs'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
|
||||
}
|
||||
|
||||
export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
|
||||
const [preview, setPreview] = useState(null)
|
||||
const inlineIds = useMemo(() => collectInlineExerciseMediaIdsFromExercise(exercise), [exercise])
|
||||
|
||||
const orphans = useMemo(() => {
|
||||
const list = (exercise?.media || []).filter((m) => m && !isTrashHidden(m))
|
||||
return list.filter((m) => !inlineIds.has(Number(m.id)))
|
||||
}, [exercise, inlineIds])
|
||||
|
||||
if (!orphans.length || exerciseId == null) return null
|
||||
|
||||
return (
|
||||
<section className="card exercise-detail-section exercise-attachment-media-strip">
|
||||
<h2>Angehängte Medien</h2>
|
||||
<p style={{ marginTop: '6px', color: 'var(--text2)', fontSize: '0.88rem' }}>
|
||||
Hier erscheinen nur Verknüpfungen, die noch nicht im Fließtext eingebettet sind (reine Material-Anhänge).
|
||||
</p>
|
||||
<div className="exercise-orphan-media-grid">
|
||||
{orphans.map((m) => {
|
||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
||||
const caption = (m.title || '').trim() || (m.original_filename || '').trim() || `Medium #${m.id}`
|
||||
return (
|
||||
<article key={m.id} className="exercise-orphan-media-card">
|
||||
<div className="exercise-orphan-media-card__head">
|
||||
<ExerciseMediaThumbTile
|
||||
exerciseId={exerciseId}
|
||||
media={m}
|
||||
onOpenPreview={setPreview}
|
||||
size={88}
|
||||
/>
|
||||
<div className="exercise-orphan-media-card__meta">
|
||||
<strong className="exercise-orphan-media-card__title">{caption}</strong>
|
||||
<span className="exercise-orphan-media-card__sub">
|
||||
#{m.id}
|
||||
{m.embed_platform ? ` · ${m.embed_platform}` : ''}
|
||||
{m.media_type ? ` · ${m.media_type}` : ''}
|
||||
</span>
|
||||
{lc === 'trash_soft' && (
|
||||
<span className="exercise-orphan-media-card__warn">Papierkorb (Stufe 1)</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ExerciseMediaEmbed exerciseId={exerciseId} media={m} layoutSize="medium" />
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{preview && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Medienvorschau"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.55)',
|
||||
zIndex: 1001,
|
||||
overflow: 'auto',
|
||||
padding: '16px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
onClick={() => setPreview(null)}
|
||||
onKeyDown={(e) => e.key === 'Escape' && setPreview(null)}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{ maxWidth: 720, width: '100%', maxHeight: '90vh', overflow: 'auto' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h3 style={{ marginTop: 0, fontSize: '1.05rem' }}>Vorschau</h3>
|
||||
{preview.embed_url ? (
|
||||
<p style={{ fontSize: '14px', wordBreak: 'break-all' }}>
|
||||
<a href={preview.embed_url} target="_blank" rel="noreferrer">
|
||||
{preview.embed_url}
|
||||
</a>
|
||||
</p>
|
||||
) : preview.mime_type?.startsWith('video/') || preview.media_type === 'video' ? (
|
||||
<video
|
||||
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
controls
|
||||
style={{ width: '100%', borderRadius: '8px', maxHeight: '70vh' }}
|
||||
/>
|
||||
) : preview.mime_type?.startsWith('image/') || preview.media_type === 'image' ? (
|
||||
<img
|
||||
alt=""
|
||||
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', maxHeight: '70vh', objectFit: 'contain' }}
|
||||
/>
|
||||
) : (
|
||||
<p style={{ fontSize: '14px' }}>
|
||||
<a href={resolveExerciseMediaFileUrl(exerciseId, preview)} target="_blank" rel="noreferrer">
|
||||
Datei öffnen
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<div style={{ marginTop: '16px' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setPreview(null)}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,52 +3,7 @@
|
||||
*/
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
|
||||
function HtmlBlock({ html, className = '' }) {
|
||||
if (!html || !String(html).trim()) return null
|
||||
const safe = sanitizeTrainerHtml(html)
|
||||
return (
|
||||
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
|
||||
)
|
||||
}
|
||||
|
||||
function MediaBlock({ media, exerciseId }) {
|
||||
if (media.embed_url) {
|
||||
return (
|
||||
<div style={{ marginTop: '0.5rem' }}>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">
|
||||
{media.embed_url}
|
||||
</a>
|
||||
{media.embed_platform && (
|
||||
<span style={{ color: 'var(--text2)', marginLeft: '0.5rem', fontSize: '0.8rem' }}>
|
||||
({media.embed_platform})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt={media.title || media.original_filename || ''}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', marginTop: '0.5rem' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
|
||||
return <video src={src} controls style={{ width: '100%', marginTop: '0.5rem', borderRadius: '8px' }} />
|
||||
}
|
||||
return (
|
||||
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.5rem' }}>
|
||||
{media.title || media.original_filename || 'Datei öffnen'}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
|
||||
function TagRow({ exercise }) {
|
||||
const tags = []
|
||||
@@ -112,11 +67,8 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
}
|
||||
if (!exercise) return null
|
||||
|
||||
const resolvedId = exercise.id ?? exerciseId
|
||||
const meta = metaParts(exercise)
|
||||
const visibleMedia = (exercise.media || []).filter((m) => {
|
||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
||||
return lc !== 'trash_hidden'
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="exercise-coach-catalog" style={{ fontSize: '0.93rem', lineHeight: 1.5 }}>
|
||||
@@ -132,13 +84,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px', letterSpacing: '0.04em' }}>
|
||||
Kurzbeschreibung
|
||||
</h3>
|
||||
<HtmlBlock html={exercise.summary} />
|
||||
<ExerciseRichTextBlock html={exercise.summary} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.goal && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ziel</h3>
|
||||
<HtmlBlock html={exercise.goal} />
|
||||
<ExerciseRichTextBlock html={exercise.goal} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{(exercise.equipment || []).length > 0 && (
|
||||
@@ -156,32 +108,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
{exercise.preparation && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Vorbereitung</h3>
|
||||
<HtmlBlock html={exercise.preparation} />
|
||||
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.execution && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ablauf</h3>
|
||||
<HtmlBlock html={exercise.execution} />
|
||||
</section>
|
||||
)}
|
||||
{visibleMedia.length > 0 && (
|
||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||
Medien
|
||||
</h3>
|
||||
{visibleMedia.map((m) => (
|
||||
<div key={m.id} style={{ marginBottom: '12px' }}>
|
||||
<strong style={{ fontSize: '0.9rem' }}>{m.title || m.original_filename || m.media_type}</strong>
|
||||
{String(m.asset_lifecycle_state || 'active').toLowerCase() === 'trash_soft' && (
|
||||
<p style={{ fontSize: '0.75rem', color: 'var(--danger)', margin: '4px 0 0' }}>
|
||||
Hinweis: Dieses Medium ist im Papierkorb und steht künftig nicht mehr zur Verfügung.
|
||||
</p>
|
||||
)}
|
||||
{m.description && <p style={{ color: 'var(--text2)', fontSize: '0.82rem', marginTop: '4px' }}>{m.description}</p>}
|
||||
<MediaBlock media={m} exerciseId={exercise.id ?? exerciseId} />
|
||||
</div>
|
||||
))}
|
||||
<ExerciseRichTextBlock html={exercise.execution} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exercise.trainer_notes && (
|
||||
@@ -189,7 +122,7 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||
Hinweise Trainer (Katalog)
|
||||
</h3>
|
||||
<HtmlBlock html={exercise.trainer_notes} />
|
||||
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={resolvedId} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
{exerciseId != null && (
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Modal: Embed-URL als exercise_media anlegen und §11-Platzhalter einfügen.
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
import {
|
||||
INLINE_MEDIA_SIZES,
|
||||
DEFAULT_INLINE_MEDIA_SIZE,
|
||||
sanitizeInlineMediaSize,
|
||||
} from '../constants/inlineExerciseMedia'
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* open: boolean,
|
||||
* onClose: () => void,
|
||||
* exerciseId: number,
|
||||
* onMediaListChanged: () => Promise<void>,
|
||||
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
|
||||
* }} props
|
||||
*/
|
||||
export default function ExerciseInlineEmbedModal({
|
||||
open,
|
||||
onClose,
|
||||
exerciseId,
|
||||
onMediaListChanged,
|
||||
onInserted,
|
||||
}) {
|
||||
const [url, setUrl] = useState('')
|
||||
const [title, setTitle] = useState('')
|
||||
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setUrl('')
|
||||
setTitle('')
|
||||
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
}, [open])
|
||||
|
||||
const submit = async () => {
|
||||
const u = url.trim()
|
||||
if (!u) {
|
||||
alert('Bitte eine Embed-URL eingeben (https://…).')
|
||||
return
|
||||
}
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const fd = new FormData()
|
||||
fd.append('embed_url', u)
|
||||
fd.append('media_type', 'video')
|
||||
fd.append('title', title.trim())
|
||||
fd.append('description', '')
|
||||
fd.append('context', 'ablauf')
|
||||
fd.append('is_primary', 'false')
|
||||
setBusy(true)
|
||||
try {
|
||||
const row = await api.uploadExerciseMedia(exerciseId, fd)
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
const cap = sanitizeInlineMediaCaption(
|
||||
title.trim() || u.replace(/^https?:\/\//i, '').slice(0, 96),
|
||||
)
|
||||
onInserted(Number(mid), size, cap)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
|
||||
<div
|
||||
className="admin-modal-sheet"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="rte-inline-embed-title"
|
||||
style={{ maxWidth: '480px', width: '100%' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="rte-inline-embed-title" className="admin-modal-sheet__title">
|
||||
Embed im Textfeld
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ padding: '14px 16px' }}>
|
||||
<label className="form-label">Embed-URL</label>
|
||||
<input
|
||||
type="url"
|
||||
className="form-input"
|
||||
placeholder="https://…"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Titel (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Darstellung im Text
|
||||
</label>
|
||||
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
|
||||
{INLINE_MEDIA_SIZES.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="button" className="btn btn-primary btn-full" style={{ marginTop: '16px' }} disabled={busy} onClick={submit}>
|
||||
{busy ? 'Speichern…' : 'Hinzufügen & in Text einfügen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
/**
|
||||
* Modal: Medium aus Archiv verknüpfen oder neue Datei hochladen, dann Inline-Platzhalter §11 einfügen.
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback, useMemo } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import {
|
||||
INLINE_MEDIA_SIZES,
|
||||
DEFAULT_INLINE_MEDIA_SIZE,
|
||||
sanitizeInlineMediaSize,
|
||||
} from '../constants/inlineExerciseMedia'
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
|
||||
function RtePickerAssetThumb({ asset }) {
|
||||
const id = asset.id
|
||||
const src = resolveMediaAssetFileUrl(id)
|
||||
const mt = (asset.mime_type || '').toLowerCase()
|
||||
if (mt.startsWith('image/') && src) {
|
||||
return <img alt="" src={src} className="rte-inline-asset-tile__thumb-img" />
|
||||
}
|
||||
if (mt.startsWith('video/') && src) {
|
||||
return (
|
||||
<video
|
||||
key={`v-${id}`}
|
||||
className="rte-inline-asset-tile__thumb-video"
|
||||
src={src}
|
||||
muted
|
||||
playsInline
|
||||
preload="metadata"
|
||||
onLoadedMetadata={(e) => {
|
||||
try {
|
||||
const el = e.currentTarget
|
||||
const d = el.duration
|
||||
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const nameLow = String(asset.original_filename || '').toLowerCase()
|
||||
if (mt.includes('pdf') || nameLow.endsWith('.pdf')) {
|
||||
return <span className="rte-inline-asset-tile__thumb-fallback">PDF</span>
|
||||
}
|
||||
return <span className="rte-inline-asset-tile__thumb-fallback">Datei</span>
|
||||
}
|
||||
|
||||
/** MIME/Dateiname → Übungs-media_type */
|
||||
function inferExerciseMediaType(file) {
|
||||
if (!file) return 'image'
|
||||
const mime = (file.type || '').toLowerCase()
|
||||
if (mime.startsWith('image/')) return 'image'
|
||||
if (mime.startsWith('video/')) return 'video'
|
||||
if (mime === 'application/pdf' || mime.includes('pdf')) return 'document'
|
||||
const name = (file.name || '').toLowerCase()
|
||||
if (/\.(mp4|webm|mov|mkv|avi|m4v|mpeg|mpg)$/.test(name)) return 'video'
|
||||
if (/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/.test(name)) return 'image'
|
||||
if (/\.pdf$/.test(name)) return 'document'
|
||||
return 'image'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* open: boolean,
|
||||
* onClose: () => void,
|
||||
* exerciseId: number,
|
||||
* linkedExerciseMedia?: object[],
|
||||
* onMediaListChanged: () => Promise<void>,
|
||||
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
|
||||
* }} props
|
||||
*/
|
||||
export default function ExerciseInlineFileMediaModal({
|
||||
open,
|
||||
onClose,
|
||||
exerciseId,
|
||||
linkedExerciseMedia = [],
|
||||
onMediaListChanged,
|
||||
onInserted,
|
||||
}) {
|
||||
const [tab, setTab] = useState('library')
|
||||
const [q, setQ] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [items, setItems] = useState([])
|
||||
const [err, setErr] = useState(null)
|
||||
const [selectedAssetId, setSelectedAssetId] = useState(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [uploadFile, setUploadFile] = useState(null)
|
||||
const [uploadTitle, setUploadTitle] = useState('')
|
||||
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
const [uploadInputKey, setUploadInputKey] = useState(0)
|
||||
|
||||
const assetToExerciseMedia = useMemo(() => {
|
||||
const m = new Map()
|
||||
for (const row of linkedExerciseMedia || []) {
|
||||
const aid = row?.media_asset_id
|
||||
if (aid != null) m.set(Number(aid), row)
|
||||
}
|
||||
return m
|
||||
}, [linkedExerciseMedia])
|
||||
|
||||
const loadAssets = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const res = await api.listMediaAssets({
|
||||
q: q.trim() || undefined,
|
||||
limit: 48,
|
||||
lifecycle: 'active',
|
||||
})
|
||||
setItems(Array.isArray(res.items) ? res.items : [])
|
||||
} catch (e) {
|
||||
setErr(e.message || String(e))
|
||||
setItems([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [q])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return undefined
|
||||
setTab('library')
|
||||
setSelectedAssetId(null)
|
||||
setUploadFile(null)
|
||||
setUploadTitle('')
|
||||
setUploadInputKey((k) => k + 1)
|
||||
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
|
||||
setErr(null)
|
||||
const t = setTimeout(loadAssets, 280)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || tab !== 'library') return undefined
|
||||
const t = setTimeout(loadAssets, 300)
|
||||
return () => clearTimeout(t)
|
||||
}, [q, open, tab, loadAssets])
|
||||
|
||||
const handleLinkSelected = async () => {
|
||||
if (!selectedAssetId) {
|
||||
alert('Bitte ein Archiv-Medium auswählen.')
|
||||
return
|
||||
}
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const assetMeta = items.find((x) => x.id === selectedAssetId)
|
||||
const capFromExisting = (row) =>
|
||||
sanitizeInlineMediaCaption(row?.original_filename || row?.title || assetMeta?.original_filename || '')
|
||||
|
||||
const existing = assetToExerciseMedia.get(Number(selectedAssetId))
|
||||
if (existing?.id != null) {
|
||||
onInserted(Number(existing.id), size, capFromExisting(existing))
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
setBusy(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const row = await api.attachExerciseMediaFromAsset(exerciseId, {
|
||||
media_asset_id: selectedAssetId,
|
||||
title: '',
|
||||
description: '',
|
||||
context: 'ablauf',
|
||||
is_primary: false,
|
||||
})
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
onInserted(
|
||||
Number(mid),
|
||||
size,
|
||||
sanitizeInlineMediaCaption(assetMeta?.original_filename || ''),
|
||||
)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
const msg = e.message || String(e)
|
||||
setErr(msg)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadAndInsert = async () => {
|
||||
if (!uploadFile) {
|
||||
alert('Bitte eine Datei wählen.')
|
||||
return
|
||||
}
|
||||
const size = sanitizeInlineMediaSize(displaySize)
|
||||
const inferred = inferExerciseMediaType(uploadFile)
|
||||
const fd = new FormData()
|
||||
fd.append('file', uploadFile)
|
||||
fd.append('media_type', inferred)
|
||||
fd.append('title', uploadTitle.trim())
|
||||
fd.append('description', '')
|
||||
fd.append('context', 'ablauf')
|
||||
fd.append('is_primary', 'false')
|
||||
setBusy(true)
|
||||
setErr(null)
|
||||
try {
|
||||
const row = await api.uploadExerciseMedia(exerciseId, fd)
|
||||
const mid = row?.id
|
||||
if (mid == null) {
|
||||
throw new Error('Antwort ohne exercise_media-ID')
|
||||
}
|
||||
await onMediaListChanged()
|
||||
const cap = sanitizeInlineMediaCaption(
|
||||
uploadTitle.trim() || uploadFile.name || '',
|
||||
)
|
||||
onInserted(Number(mid), size, cap)
|
||||
setUploadFile(null)
|
||||
setUploadTitle('')
|
||||
setUploadInputKey((k) => k + 1)
|
||||
onClose()
|
||||
} catch (e) {
|
||||
if (e.code === 'MEDIA_ASSET_IN_TRASH' && e.payload?.media_asset_id != null) {
|
||||
alert(
|
||||
'Dieselbe Datei existiert bereits im Papierkorb — bitte in der Medienbibliothek reaktivieren oder eine andere Datei wählen.',
|
||||
)
|
||||
} else {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
setErr(e.message || String(e))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedLinked = selectedAssetId != null && assetToExerciseMedia.has(Number(selectedAssetId))
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
|
||||
<div
|
||||
className="admin-modal-sheet rte-inline-media-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="rte-inline-file-title"
|
||||
style={{
|
||||
maxWidth: '560px',
|
||||
width: '100%',
|
||||
maxHeight: '90vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="rte-inline-file-title" className="admin-modal-sheet__title">
|
||||
Medium im Textfeld
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-secondary ${tab === 'library' ? 'rte-tab--active' : ''}`}
|
||||
style={{ fontSize: '13px' }}
|
||||
onClick={() => setTab('library')}
|
||||
disabled={busy}
|
||||
>
|
||||
Aus Mediathek
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-secondary ${tab === 'upload' ? 'rte-tab--active' : ''}`}
|
||||
style={{ fontSize: '13px' }}
|
||||
onClick={() => setTab('upload')}
|
||||
disabled={busy}
|
||||
>
|
||||
Neu hochladen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ overflowY: 'auto', flex: 1, padding: '12px 14px' }}>
|
||||
{err && !loading ? (
|
||||
<p style={{ color: 'var(--danger)', marginTop: '0', marginBottom: '12px', fontSize: '0.9rem' }}>{err}</p>
|
||||
) : null}
|
||||
{tab === 'library' && (
|
||||
<>
|
||||
<label className="form-label">Suche in der Bibliothek</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Name, Tag, © …"
|
||||
disabled={busy}
|
||||
/>
|
||||
{loading ? <p style={{ color: 'var(--text3)', marginTop: '12px' }}>Laden…</p> : null}
|
||||
<div className="rte-inline-asset-grid" style={{ marginTop: '14px' }}>
|
||||
{items.map((it) => {
|
||||
const id = it.id
|
||||
const selected = selectedAssetId === id
|
||||
const label = it.original_filename || it.copyright_notice || `Archiv #${id}`
|
||||
const linked = assetToExerciseMedia.has(Number(id))
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
className={`rte-inline-asset-tile${selected ? ' rte-inline-asset-tile--selected' : ''}`}
|
||||
onClick={() => setSelectedAssetId(id)}
|
||||
disabled={busy}
|
||||
>
|
||||
<div className="rte-inline-asset-tile__thumb" aria-hidden>
|
||||
<RtePickerAssetThumb asset={it} />
|
||||
</div>
|
||||
{linked ? (
|
||||
<span className="rte-inline-asset-tile__badge">Bereits verknüpft</span>
|
||||
) : null}
|
||||
<span className="rte-inline-asset-tile__meta">
|
||||
{(it.mime_type || '').split('/')[0] || 'datei'}
|
||||
</span>
|
||||
<span className="rte-inline-asset-tile__name">{label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{!loading && items.length === 0 ? (
|
||||
<p style={{ color: 'var(--text3)', marginTop: '12px' }}>Keine Treffer — Suche anpassen oder „Neu hochladen“.</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'upload' && (
|
||||
<>
|
||||
<label className="form-label">Datei</label>
|
||||
<div className="rte-inline-file-row">
|
||||
<input
|
||||
key={uploadInputKey}
|
||||
id="rte-inline-file-upload-input"
|
||||
type="file"
|
||||
accept="image/*,video/*,application/pdf"
|
||||
className="rte-inline-file-input-hidden"
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0] || null
|
||||
setUploadFile(f)
|
||||
}}
|
||||
/>
|
||||
<label htmlFor="rte-inline-file-upload-input" className="btn btn-secondary rte-inline-file-pick-btn">
|
||||
Datei auswählen
|
||||
</label>
|
||||
<span className="rte-inline-file-name" title={uploadFile?.name || ''}>
|
||||
{uploadFile ? uploadFile.name : 'Keine Datei ausgewählt'}
|
||||
</span>
|
||||
</div>
|
||||
<label className="form-label" style={{ marginTop: '12px' }}>
|
||||
Titel (optional)
|
||||
</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={uploadTitle}
|
||||
onChange={(e) => setUploadTitle(e.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '12px 14px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
||||
<div className="form-row" style={{ marginBottom: '12px' }}>
|
||||
<label className="form-label" style={{ marginBottom: '4px' }}>
|
||||
Darstellung im Text
|
||||
</label>
|
||||
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
|
||||
{INLINE_MEDIA_SIZES.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{tab === 'library' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-full"
|
||||
disabled={busy || !selectedAssetId}
|
||||
onClick={handleLinkSelected}
|
||||
>
|
||||
{busy ? 'Bitte warten…' : selectedLinked ? 'In Text einfügen (bereits verknüpft)' : 'Verknüpfen & in Text einfügen'}
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn btn-primary btn-full" disabled={busy || !uploadFile} onClick={handleUploadAndInsert}>
|
||||
{busy ? 'Hochladen…' : 'Hochladen & in Text einfügen'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'
|
||||
|
||||
/**
|
||||
* Ein ausgeliefertes exercise_media für Übungslisten (Liste + Inline gleiche Darstellung).
|
||||
* @param {{ media: object, exerciseId: number, layoutSize?: string }} props
|
||||
*/
|
||||
export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'medium' }) {
|
||||
const sz = sanitizeInlineMediaSize(layoutSize)
|
||||
const box =
|
||||
sz === 'small'
|
||||
? { maxWidth: 'min(280px, 33vw)', marginTop: '0.5rem' }
|
||||
: sz === 'full'
|
||||
? { maxWidth: '100%', marginTop: '0.5rem' }
|
||||
: { maxWidth: 'min(560px, 85vw)', marginTop: '0.5rem' }
|
||||
|
||||
if (!media || exerciseId == null) return null
|
||||
if (media.embed_url) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
...box,
|
||||
wordBreak: 'break-word',
|
||||
overflowWrap: 'anywhere',
|
||||
fontSize: sz === 'small' ? '0.88rem' : undefined,
|
||||
}}
|
||||
>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">
|
||||
{media.title?.trim() || media.embed_url}
|
||||
</a>
|
||||
{media.embed_platform && (
|
||||
<span style={{ color: 'var(--text2)', marginLeft: '0.35rem', fontSize: '0.82rem', display: 'inline' }}>
|
||||
({media.embed_platform})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
<div style={box}>
|
||||
<img
|
||||
src={src}
|
||||
alt={media.title || media.original_filename || ''}
|
||||
style={{ width: '100%', maxWidth: '100%', height: 'auto', borderRadius: '8px', display: 'block' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
|
||||
return (
|
||||
<div style={box}>
|
||||
<video
|
||||
src={src}
|
||||
controls
|
||||
style={{ width: '100%', maxWidth: '100%', borderRadius: '8px', verticalAlign: 'top' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div style={box}>
|
||||
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.25rem' }}>
|
||||
{media.title || media.original_filename || 'Datei öffnen'}
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Kachelvorschau: Video nutzt ersten Frame (metadata), Bild = img, Embed = Label.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
|
||||
export default function ExerciseMediaThumbTile({ exerciseId, media, onOpenPreview, size = 72 }) {
|
||||
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media) : null
|
||||
const commonStyle = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'cover',
|
||||
}
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
title="Vorschau"
|
||||
onClick={() => onOpenPreview(media)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
onOpenPreview(media)
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
flexShrink: 0,
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden',
|
||||
background: 'var(--surface2, rgba(127,127,127,0.12))',
|
||||
border: '1px solid var(--border)',
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{media.embed_url ? (
|
||||
<span style={{ fontSize: '11px', padding: '4px', color: 'var(--text2)', textAlign: 'center' }}>
|
||||
{media.embed_platform || 'Embed'}
|
||||
</span>
|
||||
) : (media.mime_type?.startsWith('image/') || media.media_type === 'image') && src ? (
|
||||
<img alt="" src={src} style={commonStyle} />
|
||||
) : (media.mime_type?.startsWith('video/') || media.media_type === 'video') && src ? (
|
||||
<video
|
||||
src={src}
|
||||
muted
|
||||
playsInline
|
||||
preload="metadata"
|
||||
style={{ ...commonStyle, pointerEvents: 'none' }}
|
||||
onLoadedMetadata={(e) => {
|
||||
try {
|
||||
const el = e.currentTarget
|
||||
const d = el.duration
|
||||
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ fontSize: '11px', color: 'var(--text2)' }}>Datei</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,15 +4,7 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
||||
|
||||
function HtmlBlock({ html, className = '' }) {
|
||||
if (!html || !String(html).trim()) return null
|
||||
const safe = sanitizeTrainerHtml(html)
|
||||
return (
|
||||
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
|
||||
)
|
||||
}
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
|
||||
function TagMini({ exercise }) {
|
||||
const parts = []
|
||||
@@ -129,7 +121,7 @@ export default function ExercisePeekModal({
|
||||
</div>
|
||||
{variant.description ? (
|
||||
<div style={{ marginTop: 8, fontSize: '0.9rem', color: 'var(--text2)' }}>
|
||||
<HtmlBlock html={variant.description} />
|
||||
<ExerciseRichTextBlock html={variant.description} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
{variant.execution_changes ? (
|
||||
@@ -137,14 +129,14 @@ export default function ExercisePeekModal({
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>
|
||||
Durchführung (Variante)
|
||||
</h4>
|
||||
<HtmlBlock html={variant.execution_changes} />
|
||||
<ExerciseRichTextBlock html={variant.execution_changes} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{exercise.summary && (
|
||||
<div style={{ fontSize: '0.95rem', color: 'var(--text2)' }}>
|
||||
<HtmlBlock html={exercise.summary} />
|
||||
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
)}
|
||||
<TagMini exercise={exercise} />
|
||||
@@ -154,25 +146,25 @@ export default function ExercisePeekModal({
|
||||
{exercise.goal && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>Ziel</h4>
|
||||
<HtmlBlock html={exercise.goal} />
|
||||
<ExerciseRichTextBlock html={exercise.goal} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.preparation && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Vorbereitung</h4>
|
||||
<HtmlBlock html={exercise.preparation} />
|
||||
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.execution && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Ablauf</h4>
|
||||
<HtmlBlock html={exercise.execution} />
|
||||
<ExerciseRichTextBlock html={exercise.execution} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
{exercise.trainer_notes && (
|
||||
<>
|
||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Trainer-Hinweise</h4>
|
||||
<HtmlBlock html={exercise.trainer_notes} />
|
||||
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={exercise.id} media={exercise.media} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import ExercisePickerModal from './ExercisePickerModal'
|
||||
|
||||
const VIS_OPTIONS = [
|
||||
@@ -99,6 +100,13 @@ export default function ExerciseProgressionGraphPanel({
|
||||
anchorExerciseId = null,
|
||||
anchorTitle = null,
|
||||
}) {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const filteredGraphVisOptions = useMemo(
|
||||
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
||||
[isSuperadmin],
|
||||
)
|
||||
|
||||
const [graphs, setGraphs] = useState([])
|
||||
const [selectedGraphId, setSelectedGraphId] = useState(null)
|
||||
const [edges, setEdges] = useState([])
|
||||
@@ -566,7 +574,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
value={newGraphVisibility}
|
||||
onChange={(e) => setNewGraphVisibility(e.target.value)}
|
||||
>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{filteredGraphVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
@@ -599,7 +607,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
<div className="form-row">
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{filteredGraphVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { sanitizeExerciseRichDisplayHtml } from '../utils/exerciseRichTextSanitize'
|
||||
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
|
||||
|
||||
function isTrashHidden(m) {
|
||||
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
|
||||
}
|
||||
|
||||
function buildVisibleMediaMap(mediaList) {
|
||||
const map = new Map()
|
||||
for (const m of mediaList || []) {
|
||||
if (!m || m.id == null || isTrashHidden(m)) continue
|
||||
map.set(Number(m.id), m)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function domToReactNodes(node, exerciseId, mediaById, path) {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const t = node.textContent
|
||||
return t ? t : null
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) return null
|
||||
|
||||
const el = node
|
||||
const tag = el.tagName.toLowerCase()
|
||||
const key = path.join('.')
|
||||
|
||||
if (tag === 'span' && el.getAttribute('data-shinkan-exercise-media')) {
|
||||
const raw = el.getAttribute('data-shinkan-exercise-media')
|
||||
const mid = parseInt(raw, 10)
|
||||
if (!Number.isFinite(mid) || mid < 1) {
|
||||
return (
|
||||
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
|
||||
[Ungültiger Medienverweis]
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const media = mediaById.get(mid)
|
||||
if (!media) {
|
||||
return (
|
||||
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
|
||||
[Medium nicht verfügbar]
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const rawSize = (el.getAttribute('data-shinkan-exercise-media-size') || 'medium').toLowerCase().trim()
|
||||
const layoutSize = rawSize === 'small' || rawSize === 'full' ? rawSize : 'medium'
|
||||
const wrapClass =
|
||||
layoutSize === 'small'
|
||||
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--sm'
|
||||
: layoutSize === 'full'
|
||||
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--full'
|
||||
: 'shinkan-inline-media-wrap shinkan-inline-media-wrap--md'
|
||||
const lc = String(media.asset_lifecycle_state || 'active').toLowerCase()
|
||||
return (
|
||||
<span key={key} className={wrapClass} style={{ display: 'inline-block', verticalAlign: 'top' }}>
|
||||
{lc === 'trash_soft' && (
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--danger)', display: 'block', marginBottom: '4px' }}>
|
||||
Dieses Medium ist im Papierkorb.
|
||||
</span>
|
||||
)}
|
||||
<ExerciseMediaEmbed exerciseId={exerciseId} media={media} layoutSize={layoutSize} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const children = []
|
||||
const childNodes = Array.from(el.childNodes)
|
||||
childNodes.forEach((ch, i) => {
|
||||
const sub = domToReactNodes(ch, exerciseId, mediaById, [...path, String(i)])
|
||||
if (sub != null && sub !== false) children.push(sub)
|
||||
})
|
||||
|
||||
const props = { key }
|
||||
if (tag === 'a' && el.getAttribute('href')) {
|
||||
props.href = el.getAttribute('href')
|
||||
props.target = '_blank'
|
||||
props.rel = 'noreferrer'
|
||||
}
|
||||
return React.createElement(tag, props, children.length ? children : null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentraler Anzeige-Pfad für Übungs-Rich-Text inkl. §11 Inline-Medien.
|
||||
* @param {{ html?: string|null, exerciseId?: number|null, media?: object[]|null, className?: string }} props
|
||||
*/
|
||||
export default function ExerciseRichTextBlock({ html, exerciseId, media, className = '' }) {
|
||||
const safe = useMemo(() => sanitizeExerciseRichDisplayHtml(html), [html])
|
||||
const mediaById = useMemo(() => buildVisibleMediaMap(media), [media])
|
||||
|
||||
const body = useMemo(() => {
|
||||
if (!safe.trim()) return null
|
||||
const tpl = document.createElement('template')
|
||||
tpl.innerHTML = safe
|
||||
const nodes = []
|
||||
Array.from(tpl.content.childNodes).forEach((ch, i) => {
|
||||
const r = domToReactNodes(ch, exerciseId, mediaById, [String(i)])
|
||||
if (r != null) nodes.push(r)
|
||||
})
|
||||
return nodes
|
||||
}, [safe, exerciseId, mediaById])
|
||||
|
||||
if (!body || body.length === 0) return null
|
||||
|
||||
return <div className={`rich-text-content ${className}`.trim()}>{body}</div>
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
/**
|
||||
* Hinweis, wenn der Vereinszugang (Mitgliedschaft) deaktiviert wurde — Login bleibt möglich.
|
||||
*/
|
||||
export default function InactiveMembershipBanner() {
|
||||
const { user } = useAuth()
|
||||
const inactive = (user?.clubs || []).filter(
|
||||
(c) => (c.membership_status || '').toString().trim().toLowerCase() === 'inactive'
|
||||
)
|
||||
if (!inactive.length) return null
|
||||
|
||||
const names = inactive.map((c) => c.name || `Verein #${c.id}`).join(', ')
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="inactive-membership-banner"
|
||||
style={{
|
||||
marginBottom: '0.75rem',
|
||||
padding: '0.65rem 0.85rem',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface2, #2a2a2a)',
|
||||
border: '1px solid color-mix(in srgb, var(--warning, #d4a012) 45%, transparent)',
|
||||
color: 'var(--text1)',
|
||||
fontSize: '0.88rem',
|
||||
lineHeight: 1.45,
|
||||
}}
|
||||
>
|
||||
<strong>Vereinszugang vorübergehend deaktiviert</strong>
|
||||
<span style={{ display: 'block', marginTop: '0.35rem' }}>
|
||||
Für {inactive.length === 1 ? 'den Verein' : 'die Vereine'}{' '}
|
||||
<strong>{names}</strong>{' '}
|
||||
ist der Zugang zu Vereinsinhalten ausgesetzt — du kannst dich weiterhin anmelden und z. B.
|
||||
öffentliche Inhalte oder andere Vereine nutzen. Bei Fragen wende dich an eine:n Vereinsadministrator:in.
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getResolvedActiveClubIdForUi, activeClubMemberships } from '../utils/activeClub'
|
||||
|
||||
function Navigation() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { user, logout, setActiveClub } = useAuth()
|
||||
|
||||
const clubs = user?.clubs || []
|
||||
const selectClubId =
|
||||
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
|
||||
? user.active_club_id
|
||||
: clubs[0]?.id
|
||||
const clubs = activeClubMemberships(user?.clubs)
|
||||
const selectClubId = getResolvedActiveClubIdForUi(user)
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout()
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
/** Nur Super-Admins; andere Nutzer → Startseite. */
|
||||
export default function PlatformAdminRoute({ children }) {
|
||||
const { user } = useAuth()
|
||||
const ok = user?.role === 'superadmin'
|
||||
if (!ok) return <Navigate to="/" replace />
|
||||
return children
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
import React, { useRef, useEffect, useState, useCallback } from 'react'
|
||||
import ExerciseInlineFileMediaModal from './ExerciseInlineFileMediaModal'
|
||||
import ExerciseInlineEmbedModal from './ExerciseInlineEmbedModal'
|
||||
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
|
||||
import {
|
||||
SHINKAN_EXERCISE_MEDIA_DRAG_MIME,
|
||||
parseExerciseMediaDragPayload,
|
||||
} from '../utils/exerciseInlineMediaRefs'
|
||||
import { autoScrollForDragNearEdges } from '../utils/dragAutoScroll'
|
||||
|
||||
function exec(cmd, value = null) {
|
||||
try {
|
||||
@@ -45,12 +53,140 @@ function normalText() {
|
||||
formatBlock('p')
|
||||
}
|
||||
|
||||
function escapeHtmlAttr(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
}
|
||||
|
||||
function buildInlineExerciseMediaHtml(mediaId, displaySize = 'medium', caption = '') {
|
||||
const sid = parseInt(String(mediaId), 10)
|
||||
if (!Number.isFinite(sid) || sid < 1) return null
|
||||
const sz = ['small', 'medium', 'full'].includes(displaySize) ? displaySize : 'medium'
|
||||
const cap = sanitizeInlineMediaCaption(caption)
|
||||
let attrs = `data-shinkan-exercise-media="${sid}" data-shinkan-exercise-media-size="${sz}" class="shinkan-inline-media"`
|
||||
if (cap) attrs += ` data-shinkan-exercise-media-caption="${escapeHtmlAttr(cap)}"`
|
||||
return `<span ${attrs}>\u2060</span>`
|
||||
}
|
||||
|
||||
function patchExitGlyphAfterPlaceholder(editorEl, mediaId, sel) {
|
||||
const sid = String(parseInt(String(mediaId), 10))
|
||||
const hits = editorEl.querySelectorAll(`span.shinkan-inline-media[data-shinkan-exercise-media="${sid}"]`)
|
||||
const span = hits[hits.length - 1]
|
||||
if (!span?.parentNode || !sel) return
|
||||
let n = span.nextSibling
|
||||
if (!n || n.nodeType !== Node.TEXT_NODE || !n.textContent.includes('\u200B')) {
|
||||
const zn = document.createTextNode('\u200B')
|
||||
span.parentNode.insertBefore(zn, span.nextSibling)
|
||||
n = zn
|
||||
}
|
||||
try {
|
||||
const r = document.createRange()
|
||||
r.setStart(n, n.textContent.length)
|
||||
r.collapse(true)
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(r)
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
|
||||
function insertExerciseMediaPlaceholder(editorEl, mediaId, displaySize = 'medium', caption = '') {
|
||||
if (!editorEl || mediaId == null) return false
|
||||
const html = buildInlineExerciseMediaHtml(mediaId, displaySize, caption)
|
||||
if (!html) return false
|
||||
|
||||
editorEl.focus()
|
||||
const sel = window.getSelection()
|
||||
if (!sel) return false
|
||||
|
||||
let caretInside = false
|
||||
if (sel.rangeCount > 0) {
|
||||
try {
|
||||
const r0 = sel.getRangeAt(0)
|
||||
caretInside = editorEl.contains(r0.commonAncestorContainer)
|
||||
} catch {
|
||||
caretInside = false
|
||||
}
|
||||
}
|
||||
if (!caretInside) {
|
||||
const anchor = document.createRange()
|
||||
try {
|
||||
anchor.selectNodeContents(editorEl)
|
||||
anchor.collapse(false)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(anchor)
|
||||
}
|
||||
|
||||
let inserted = false
|
||||
try {
|
||||
inserted = document.execCommand('insertHTML', false, html)
|
||||
} catch {
|
||||
inserted = false
|
||||
}
|
||||
if (inserted) {
|
||||
patchExitGlyphAfterPlaceholder(editorEl, mediaId, sel)
|
||||
return true
|
||||
}
|
||||
|
||||
let range = null
|
||||
try {
|
||||
range = sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null
|
||||
} catch {
|
||||
range = null
|
||||
}
|
||||
if (!range || !editorEl.contains(range.commonAncestorContainer)) {
|
||||
range = document.createRange()
|
||||
range.selectNodeContents(editorEl)
|
||||
range.collapse(false)
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(range)
|
||||
}
|
||||
try {
|
||||
const tpl = document.createElement('template')
|
||||
tpl.innerHTML = html
|
||||
const span = tpl.content.firstChild
|
||||
if (!span) return false
|
||||
range.deleteContents()
|
||||
range.insertNode(span)
|
||||
const zn = document.createTextNode('\u200B')
|
||||
span.parentNode.insertBefore(zn, span.nextSibling)
|
||||
range.setStart(zn, zn.textContent.length)
|
||||
range.collapse(true)
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(range)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Leichter WYSIWYG (contenteditable). Wert kommt von außen zuverlässig ins DOM (Edit-Modus).
|
||||
* Leichter WYSIWYG (contenteditable).
|
||||
* @param {{
|
||||
* linkedExerciseMedia?: object[],
|
||||
* }} [extra]
|
||||
*/
|
||||
export default function RichTextEditor({ value, onChange, placeholder, minHeight = '140px' }) {
|
||||
export default function RichTextEditor({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
minHeight = '140px',
|
||||
inlineExerciseId = null,
|
||||
linkedExerciseMedia = [],
|
||||
onExerciseMediaListChanged,
|
||||
}) {
|
||||
const ref = useRef(null)
|
||||
const pendingRangeRef = useRef(null)
|
||||
const [focused, setFocused] = useState(false)
|
||||
const [fileModalOpen, setFileModalOpen] = useState(false)
|
||||
const [embedModalOpen, setEmbedModalOpen] = useState(false)
|
||||
|
||||
const showInlineToolbar = inlineExerciseId != null && Number(inlineExerciseId) > 0
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
@@ -66,6 +202,129 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
|
||||
onChange(ref.current.innerHTML)
|
||||
}, [onChange])
|
||||
|
||||
const refreshExerciseMedia = useCallback(async () => {
|
||||
if (onExerciseMediaListChanged) {
|
||||
await onExerciseMediaListChanged()
|
||||
}
|
||||
}, [onExerciseMediaListChanged])
|
||||
|
||||
const stashRangeAndOpen = useCallback((openFn) => (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
const el = ref.current
|
||||
pendingRangeRef.current = el ? saveSelectionInside(el) : null
|
||||
openFn()
|
||||
}, [])
|
||||
|
||||
const finalizeInsertFromModal = useCallback(
|
||||
(mediaId, displaySize, caption) => {
|
||||
queueMicrotask(() => {
|
||||
const shell = ref.current
|
||||
if (!shell) return
|
||||
shell.focus()
|
||||
restoreSelection(pendingRangeRef.current)
|
||||
const ok = insertExerciseMediaPlaceholder(shell, mediaId, displaySize, caption)
|
||||
if (!ok) {
|
||||
alert(
|
||||
'Einfügen ist fehlgeschlagen — bitte Cursor ins Textfeld setzen und den Schalter erneut verwenden.',
|
||||
)
|
||||
return
|
||||
}
|
||||
sync()
|
||||
shell.focus()
|
||||
})
|
||||
},
|
||||
[sync],
|
||||
)
|
||||
|
||||
const onEditorKeyDown = useCallback(
|
||||
(e) => {
|
||||
const el = ref.current
|
||||
if (!el || e.key !== 'Enter') return
|
||||
const sel = window.getSelection()
|
||||
if (!sel || sel.rangeCount === 0 || !el.contains(sel.focusNode)) return
|
||||
let node = sel.focusNode
|
||||
let elNode = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement
|
||||
const host = elNode?.closest?.('.shinkan-inline-media')
|
||||
if (!host || !el.contains(host)) return
|
||||
e.preventDefault()
|
||||
patchExitGlyphAfterPlaceholder(el, host.getAttribute('data-shinkan-exercise-media'), sel)
|
||||
try {
|
||||
exec('insertParagraph')
|
||||
} catch {
|
||||
exec('insertLineBreak')
|
||||
}
|
||||
sync()
|
||||
},
|
||||
[sync],
|
||||
)
|
||||
|
||||
const onEditorDragOver = useCallback(
|
||||
(e) => {
|
||||
if (!showInlineToolbar) return
|
||||
const types = e.dataTransfer?.types ? Array.from(e.dataTransfer.types) : []
|
||||
if (types.includes(SHINKAN_EXERCISE_MEDIA_DRAG_MIME)) {
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = 'copy'
|
||||
autoScrollForDragNearEdges(e)
|
||||
}
|
||||
},
|
||||
[showInlineToolbar],
|
||||
)
|
||||
|
||||
const onEditorDrop = useCallback(
|
||||
(e) => {
|
||||
const el = ref.current
|
||||
if (!el || !showInlineToolbar) return
|
||||
const raw = e.dataTransfer?.getData(SHINKAN_EXERCISE_MEDIA_DRAG_MIME)
|
||||
const parsed = parseExerciseMediaDragPayload(raw)
|
||||
if (!parsed) return
|
||||
e.preventDefault()
|
||||
el.focus()
|
||||
const sel = window.getSelection()
|
||||
if (!sel) return
|
||||
let r = null
|
||||
try {
|
||||
if (document.caretRangeFromPoint) {
|
||||
r = document.caretRangeFromPoint(e.clientX, e.clientY)
|
||||
}
|
||||
} catch {
|
||||
r = null
|
||||
}
|
||||
if (!r) {
|
||||
try {
|
||||
const p = document.caretPositionFromPoint?.(e.clientX, e.clientY)
|
||||
if (p?.offsetNode) {
|
||||
const nr = document.createRange()
|
||||
nr.setStart(p.offsetNode, p.offset)
|
||||
nr.collapse(true)
|
||||
r = nr
|
||||
}
|
||||
} catch {
|
||||
r = null
|
||||
}
|
||||
}
|
||||
if (r && el.contains(r.commonAncestorContainer)) {
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(r)
|
||||
} else {
|
||||
const anchor = document.createRange()
|
||||
try {
|
||||
anchor.selectNodeContents(el)
|
||||
anchor.collapse(false)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(anchor)
|
||||
}
|
||||
insertExerciseMediaPlaceholder(el, parsed.exerciseMediaId, 'medium', parsed.caption)
|
||||
sync()
|
||||
el.focus()
|
||||
},
|
||||
[sync, showInlineToolbar],
|
||||
)
|
||||
|
||||
const run = (fn) => (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
@@ -133,6 +392,26 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
|
||||
<button type="button" className="rte-btn" title="Link einfügen" onMouseDown={onLink}>
|
||||
Link
|
||||
</button>
|
||||
{showInlineToolbar ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="rte-btn"
|
||||
title="Datei aus Mediathek oder neu hochladen, in den Text einfügen"
|
||||
onMouseDown={stashRangeAndOpen(() => setFileModalOpen(true))}
|
||||
>
|
||||
Medien im Text
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rte-btn"
|
||||
title="Embed-URL hinzufügen und im Text einfügen"
|
||||
onMouseDown={stashRangeAndOpen(() => setEmbedModalOpen(true))}
|
||||
>
|
||||
Embed im Text
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="rte-btn"
|
||||
@@ -158,7 +437,31 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
|
||||
sync()
|
||||
}}
|
||||
onInput={sync}
|
||||
onKeyDown={onEditorKeyDown}
|
||||
onDragEnter={onEditorDragOver}
|
||||
onDragOver={onEditorDragOver}
|
||||
onDrop={onEditorDrop}
|
||||
/>
|
||||
|
||||
{showInlineToolbar ? (
|
||||
<ExerciseInlineFileMediaModal
|
||||
open={fileModalOpen}
|
||||
onClose={() => setFileModalOpen(false)}
|
||||
exerciseId={Number(inlineExerciseId)}
|
||||
linkedExerciseMedia={linkedExerciseMedia}
|
||||
onMediaListChanged={refreshExerciseMedia}
|
||||
onInserted={(mid, sz, cap) => finalizeInsertFromModal(mid, sz, cap)}
|
||||
/>
|
||||
) : null}
|
||||
{showInlineToolbar ? (
|
||||
<ExerciseInlineEmbedModal
|
||||
open={embedModalOpen}
|
||||
onClose={() => setEmbedModalOpen(false)}
|
||||
exerciseId={Number(inlineExerciseId)}
|
||||
onMediaListChanged={refreshExerciseMedia}
|
||||
onInserted={(mid, sz, cap) => finalizeInsertFromModal(mid, sz, cap)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
|
||||
const VIS_LABELS = {
|
||||
private: 'Privat',
|
||||
@@ -48,7 +49,7 @@ function userMayPromote(user, targetClubId, createdBy) {
|
||||
const role = String(user.role || '').toLowerCase()
|
||||
if (role === 'admin' || role === 'superadmin') return true
|
||||
if (createdBy != null && Number(createdBy) === Number(user.id)) return true
|
||||
const row = (user.clubs || []).find((c) => Number(c.id) === Number(targetClubId))
|
||||
const row = activeClubMemberships(user?.clubs).find((c) => Number(c.id) === Number(targetClubId))
|
||||
if (!row || !Array.isArray(row.roles)) return false
|
||||
return row.roles.includes('club_admin')
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@ import {
|
||||
LayoutDashboard,
|
||||
BookOpen,
|
||||
Calendar,
|
||||
Images,
|
||||
Building2,
|
||||
Settings,
|
||||
Shield,
|
||||
Target
|
||||
Inbox
|
||||
} from 'lucide-react'
|
||||
|
||||
/**
|
||||
@@ -15,30 +16,35 @@ import {
|
||||
* @typedef {{ to: string, label: string, shortLabel?: string, end?: boolean, Icon: import('react').ForwardRefExoticComponent }} AppNavItem
|
||||
*/
|
||||
|
||||
/** @returns {Omit<AppNavItem, 'Icon'>[]} */
|
||||
function baseItems() {
|
||||
return [
|
||||
/** @param {{ showInbox?: boolean }} opts */
|
||||
function baseItems(opts = {}) {
|
||||
const showInbox = !!opts.showInbox
|
||||
const items = [
|
||||
{ to: '/', label: 'Übersicht', end: true },
|
||||
...(showInbox ? [{ to: '/inbox', label: 'Posteingang', shortLabel: 'Post' }] : []),
|
||||
{ to: '/exercises', label: 'Übungen', shortLabel: 'Übungen' },
|
||||
{ to: '/planning', label: 'Planung' },
|
||||
{ to: '/media', label: 'Medien', shortLabel: 'Medien' },
|
||||
{ to: '/clubs', label: 'Vereine' },
|
||||
{ to: '/trainer-contexts', label: 'Meine Bereiche', shortLabel: 'Bereiche' },
|
||||
{ to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' }
|
||||
]
|
||||
return items
|
||||
}
|
||||
|
||||
/** @param {boolean} isAdmin */
|
||||
export function getMainNavItems(isAdmin) {
|
||||
/** @param {boolean} isAdmin @param {{ showInbox?: boolean }} opts */
|
||||
export function getMainNavItems(isAdmin, opts = {}) {
|
||||
const showInbox = !!opts.showInbox
|
||||
const icons = [
|
||||
LayoutDashboard,
|
||||
...(showInbox ? [Inbox] : []),
|
||||
BookOpen,
|
||||
Calendar,
|
||||
Images,
|
||||
Building2,
|
||||
Target,
|
||||
Settings
|
||||
Settings,
|
||||
]
|
||||
|
||||
const raw = baseItems().map((item, i) => ({
|
||||
const raw = baseItems(opts).map((item, i) => ({
|
||||
...item,
|
||||
Icon: icons[i]
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Inline-Medium im Fließtext §11 — Darstellung (CSS + data-shinkan-exercise-media-size). */
|
||||
export const INLINE_MEDIA_SIZES = [
|
||||
{ value: 'small', label: 'Klein (~33 %)' },
|
||||
{ value: 'medium', label: 'Mittel (~66 %)', default: true },
|
||||
{ value: 'full', label: 'Volle Breite' },
|
||||
]
|
||||
|
||||
export const DEFAULT_INLINE_MEDIA_SIZE = 'medium'
|
||||
|
||||
export function sanitizeInlineMediaSize(v) {
|
||||
const s = String(v || '').toLowerCase().trim()
|
||||
if (s === 'small' || s === 'medium' || s === 'full') return s
|
||||
return DEFAULT_INLINE_MEDIA_SIZE
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react'
|
||||
import api, { ACTIVE_CLUB_STORAGE_KEY } from '../utils/api'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
|
||||
const AuthContext = createContext(null)
|
||||
|
||||
function syncStoredActiveClub(profile) {
|
||||
const clubs = profile?.clubs || []
|
||||
const clubs = activeClubMemberships(profile?.clubs)
|
||||
const ids = new Set(clubs.map((c) => String(c.id)))
|
||||
const eff = profile?.effective_club_id
|
||||
if (eff != null && eff !== '' && ids.has(String(eff))) {
|
||||
@@ -24,6 +25,12 @@ function syncStoredActiveClub(profile) {
|
||||
}
|
||||
if (clubs.length >= 1) {
|
||||
localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(clubs[0].id))
|
||||
return
|
||||
}
|
||||
try {
|
||||
localStorage.removeItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,11 +71,25 @@ export function AuthProvider({ children }) {
|
||||
const uid = userRef.current?.id
|
||||
if (!Number.isFinite(cid) || cid < 1 || !uid) return
|
||||
localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(cid))
|
||||
setUser((prev) => (prev?.id ? { ...prev, active_club_id: cid } : prev))
|
||||
setUser((prev) =>
|
||||
prev?.id
|
||||
? { ...prev, active_club_id: cid, effective_club_id: cid }
|
||||
: prev
|
||||
)
|
||||
try {
|
||||
await api.updateProfile(uid, { active_club_id: cid })
|
||||
const profile = await api.getCurrentProfile()
|
||||
syncStoredActiveClub(profile)
|
||||
setUser(profile)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
try {
|
||||
const profile = await api.getCurrentProfile()
|
||||
syncStoredActiveClub(profile)
|
||||
setUser(profile)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import api from '../utils/api'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
|
||||
const OrgInboxContext = createContext(null)
|
||||
|
||||
export function canAccessOrgInbox(user) {
|
||||
if (!user?.id) return false
|
||||
if (user.role === 'admin' || user.role === 'superadmin') return true
|
||||
return activeClubMemberships(user.clubs).some((c) => (c.roles || []).includes('club_admin'))
|
||||
}
|
||||
|
||||
/** Nach Annahme/Ablehnung: Posteingang-Badges & Widget aktualisieren */
|
||||
export function notifyOrgInboxChanged() {
|
||||
window.dispatchEvent(new Event('shinkan:inbox-changed'))
|
||||
}
|
||||
|
||||
export function OrgInboxProvider({ user, children }) {
|
||||
const [items, setItems] = useState([])
|
||||
const canAccess = useMemo(() => canAccessOrgInbox(user), [user])
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!canAccess) {
|
||||
setItems([])
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await api.getInboxJoinRequests()
|
||||
setItems(Array.isArray(data) ? data : [])
|
||||
} catch {
|
||||
setItems([])
|
||||
}
|
||||
}, [canAccess])
|
||||
|
||||
useEffect(() => {
|
||||
if (!canAccess) {
|
||||
setItems([])
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const data = await api.getInboxJoinRequests()
|
||||
if (!cancelled) setItems(Array.isArray(data) ? data : [])
|
||||
} catch {
|
||||
if (!cancelled) setItems([])
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [canAccess, user?.id])
|
||||
|
||||
useEffect(() => {
|
||||
const onChange = () => {
|
||||
refresh()
|
||||
}
|
||||
window.addEventListener('shinkan:inbox-changed', onChange)
|
||||
return () => window.removeEventListener('shinkan:inbox-changed', onChange)
|
||||
}, [refresh])
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
inboxJoinRequests: items,
|
||||
inboxCount: items.length,
|
||||
refreshOrgInbox: refresh,
|
||||
canAccessOrgInbox: canAccess,
|
||||
}),
|
||||
[items, refresh, canAccess]
|
||||
)
|
||||
|
||||
return <OrgInboxContext.Provider value={value}>{children}</OrgInboxContext.Provider>
|
||||
}
|
||||
|
||||
export function useOrgInbox() {
|
||||
const ctx = useContext(OrgInboxContext)
|
||||
if (!ctx) {
|
||||
throw new Error('useOrgInbox must be used within OrgInboxProvider')
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -252,13 +252,22 @@ function AccountSettingsPage() {
|
||||
<span style={{ lineHeight: 1.45 }}>
|
||||
{user?.clubs?.length ? (
|
||||
<>
|
||||
{user.clubs.map((c) => (
|
||||
<div key={c.id}>
|
||||
<strong style={{ color: 'var(--text1)' }}>{c.name}</strong>
|
||||
{': '}
|
||||
{(c.roles || []).length ? (c.roles || []).join(', ') : '—'}
|
||||
</div>
|
||||
))}
|
||||
{user.clubs.map((c) => {
|
||||
const mem = (c.membership_status || 'active').toString().trim().toLowerCase()
|
||||
const inactive = mem === 'inactive'
|
||||
return (
|
||||
<div key={c.id}>
|
||||
<strong style={{ color: 'var(--text1)' }}>{c.name}</strong>
|
||||
{inactive ? (
|
||||
<span style={{ color: 'var(--warning, #d4a012)', marginLeft: '0.35rem', fontSize: '0.82rem' }}>
|
||||
(Vereinszugang deaktiviert)
|
||||
</span>
|
||||
) : null}
|
||||
{': '}
|
||||
{(c.roles || []).length ? (c.roles || []).join(', ') : '—'}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
'—'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
@@ -11,24 +11,37 @@ const CLUB_ROLE_OPTIONS = [
|
||||
{ code: 'content_editor', label: 'Inhalte bearbeiten' },
|
||||
]
|
||||
|
||||
const TIER_OPTIONS = ['free', 'premium', 'pro', 'enterprise']
|
||||
|
||||
const ROLE_LABEL = {
|
||||
const PORTAL_ROLE_LABEL = {
|
||||
user: 'Nutzer',
|
||||
trainer: 'Trainer',
|
||||
admin: 'Portal-Admin',
|
||||
superadmin: 'Super-Admin',
|
||||
trainer: 'Portal-Trainer',
|
||||
admin: 'Portal-Administrator',
|
||||
superadmin: 'Super-Administrator',
|
||||
}
|
||||
|
||||
function AdminUsersPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuper = user?.role === 'superadmin'
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const portalRoleChoices = isSuper
|
||||
? ['user', 'trainer', 'admin', 'superadmin']
|
||||
: ['user', 'trainer', 'admin']
|
||||
function portalRoleSelectOptions(viewerIsSuperadmin, currentRole) {
|
||||
const base = [
|
||||
{ value: 'user', label: PORTAL_ROLE_LABEL.user },
|
||||
{ value: 'trainer', label: `${PORTAL_ROLE_LABEL.trainer} (Legacy)` },
|
||||
{ value: 'admin', label: PORTAL_ROLE_LABEL.admin },
|
||||
]
|
||||
const cur = (currentRole || 'user').toLowerCase()
|
||||
if (viewerIsSuperadmin) base.push({ value: 'superadmin', label: PORTAL_ROLE_LABEL.superadmin })
|
||||
const values = new Set(base.map((x) => x.value))
|
||||
if (cur && !values.has(cur)) {
|
||||
base.unshift({ value: cur, label: cur })
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
const [users, setUsers] = useState([])
|
||||
/**
|
||||
* Nur Super-Admins — globale Nutzer- und Portal-Rollen plus Vereinszuordnung pro Profil.
|
||||
* Vereinsorganisation (Mitglieder, Anträge, Rollen vor Ort): unter Vereine → Mitglieder.
|
||||
*/
|
||||
export default function AdminUsersPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadminViewer = user?.role === 'superadmin'
|
||||
|
||||
const [platformUsers, setPlatformUsers] = useState([])
|
||||
const [clubs, setClubs] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
@@ -36,43 +49,48 @@ function AdminUsersPage() {
|
||||
const [assignModal, setAssignModal] = useState(null)
|
||||
const [assignRoles, setAssignRoles] = useState(['trainer'])
|
||||
const [clubEditModal, setClubEditModal] = useState(null)
|
||||
const [pwdModal, setPwdModal] = useState(null)
|
||||
const [pwdNew, setPwdNew] = useState('')
|
||||
const [pwdNew2, setPwdNew2] = useState('')
|
||||
|
||||
const load = async () => {
|
||||
setError('')
|
||||
try {
|
||||
const [u, c] = await Promise.all([api.listAdminUsers(), api.listClubs()])
|
||||
setUsers(u)
|
||||
setClubs(c)
|
||||
const d = {}
|
||||
for (const row of u) {
|
||||
d[row.id] = {
|
||||
role: (row.role || 'user').toLowerCase(),
|
||||
tier: row.tier || 'free',
|
||||
}
|
||||
}
|
||||
setPortalDraft(d)
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
const loadPlatform = useCallback(async () => {
|
||||
const [u, c] = await Promise.all([api.listAdminUsers(), api.listClubs()])
|
||||
setPlatformUsers(Array.isArray(u) ? u : [])
|
||||
setClubs(Array.isArray(c) ? c : [])
|
||||
const d = {}
|
||||
for (const row of u || []) {
|
||||
d[row.id] = { role: (row.role || 'user').toLowerCase() }
|
||||
}
|
||||
}
|
||||
setPortalDraft(d)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlatformAdmin) return
|
||||
load()
|
||||
}, [isPlatformAdmin])
|
||||
if (!isSuperadminViewer) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadminViewer, loadPlatform])
|
||||
|
||||
if (!isPlatformAdmin) {
|
||||
return <Navigate to="/" replace />
|
||||
}
|
||||
if (!isSuperadminViewer) return <Navigate to="/" replace />
|
||||
|
||||
const savePortal = async (profileId) => {
|
||||
const dr = portalDraft[profileId]
|
||||
if (!dr) return
|
||||
try {
|
||||
await api.updateProfile(profileId, { role: dr.role, tier: dr.tier })
|
||||
await load()
|
||||
await api.updateProfile(profileId, { role: dr.role })
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
@@ -90,7 +108,7 @@ function AdminUsersPage() {
|
||||
await api.addClubMember(clubId, { profile_id: profileId, roles: assignRoles })
|
||||
setAssignModal(null)
|
||||
setAssignRoles(['trainer'])
|
||||
await load()
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
@@ -102,7 +120,7 @@ function AdminUsersPage() {
|
||||
try {
|
||||
await api.updateClubMember(clubId, profileId, { roles, status })
|
||||
setClubEditModal(null)
|
||||
await load()
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
@@ -114,7 +132,46 @@ function AdminUsersPage() {
|
||||
try {
|
||||
await api.removeClubMember(clubEditModal.clubId, clubEditModal.profileId)
|
||||
setClubEditModal(null)
|
||||
await load()
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
const submitPasswordEmail = async () => {
|
||||
if (!pwdModal) return
|
||||
try {
|
||||
const res = await api.managementPasswordReset(pwdModal.profileId, null)
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
let msg =
|
||||
'Sofern eine E-Mail-Adresse hinterlegt ist, wurde ein Link zum Setzen eines neuen Passworts versendet. Das bisherige Passwort bleibt bis zur Bestätigung im Link aktiv.'
|
||||
if (res?.email_sent === false) {
|
||||
msg += ' Hinweis: Der E-Mail-Versand ist fehlgeschlagen (SMTP prüfen).'
|
||||
}
|
||||
alert(msg)
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
const submitPasswordDirect = async () => {
|
||||
if (!pwdModal) return
|
||||
if (pwdNew.length < 8) {
|
||||
alert('Mindestens 8 Zeichen.')
|
||||
return
|
||||
}
|
||||
if (pwdNew !== pwdNew2) {
|
||||
alert('Die beiden Passwörter stimmen nicht überein.')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await api.managementPasswordReset(pwdModal.profileId, pwdNew)
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
alert('Neues Passwort wurde direkt gesetzt.')
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
@@ -123,12 +180,45 @@ function AdminUsersPage() {
|
||||
return (
|
||||
<div className="app-page">
|
||||
<AdminPageNav />
|
||||
<h1 style={{ marginTop: 0 }}>Portal-Nutzer & Vereine</h1>
|
||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '1.25rem' }}>
|
||||
Alle Konten mit Vereinszuordnungen. Hier kannst du die <strong>Portal-Rolle</strong> (Zugriff auf
|
||||
Admin-Funktionen) und das <strong>Tier</strong> setzen sowie Nutzer explizit einem Verein mit Rollen
|
||||
zuordnen.
|
||||
</p>
|
||||
|
||||
<h1 style={{ marginTop: 0 }}>Globale Nutzer & Portal-Rollen</h1>
|
||||
|
||||
<>
|
||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '0.75rem' }}>
|
||||
Plattformweite Konten und Vereinszuordnungen im Überblick. <strong>Vereinsmitgliedschaft vor Ort</strong>{' '}
|
||||
(Mitglieder, Beitrittsanträge, Vereinszugriffe) liegt unter <strong>Vereine → Mitglieder</strong>. Die
|
||||
geschützten <strong>/admin</strong>-Menüpunkte (Hierarchie, Kataloge, …) gibt es nur noch hier für Super-Admins.
|
||||
</p>
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1.25rem',
|
||||
padding: '0.85rem 1rem',
|
||||
maxWidth: '52rem',
|
||||
fontSize: '0.92rem',
|
||||
lineHeight: 1.5,
|
||||
color: 'var(--text2)',
|
||||
}}
|
||||
>
|
||||
<strong style={{ color: 'var(--text1)' }}>Portal-Rollen auf Profil-Ebene:</strong>
|
||||
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
|
||||
<li>
|
||||
<strong>Nutzer</strong> — Standard ohne globale Administrationsbereiche.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Portal-Trainer (Legacy)</strong> — historische Kennzeichnung; organisatorisch ist „Trainer“ meist eine{' '}
|
||||
<strong>Vereinsrolle</strong>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Portal-Administrator</strong> — erhöhte API-/Operativ-Rechte nach Backend-Policies; die{' '}
|
||||
<strong>Admin-Navigation dieser App</strong> sieht jedoch nur noch der Super-Admin.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Super-Administrator</strong> — volle Plattform-Governance (diese Oberfläche, offizielle Inhalte, …).
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</>
|
||||
|
||||
{loading ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Laden…</p>
|
||||
@@ -138,140 +228,156 @@ function AdminUsersPage() {
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: '1rem' }}>
|
||||
{users.map((row) => {
|
||||
const tierValue = portalDraft[row.id]?.tier ?? row.tier ?? 'free'
|
||||
const tierChoices = [...TIER_OPTIONS]
|
||||
if (tierValue && !tierChoices.includes(tierValue)) tierChoices.unshift(tierValue)
|
||||
{platformUsers.map((row) => {
|
||||
const portalRoleChoices = portalRoleSelectOptions(isSuperadminViewer, row.role)
|
||||
return (
|
||||
<div key={row.id} className="card">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<strong style={{ fontSize: '1.05rem' }}>
|
||||
{row.name || '—'} <span style={{ color: 'var(--text2)', fontWeight: 400 }}>#{row.id}</span>
|
||||
</strong>
|
||||
<div style={{ fontSize: '0.875rem', color: 'var(--text2)' }}>{row.email || '—'}</div>
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginTop: '0.35rem' }}>
|
||||
Verifiziert: {row.email_verified ? 'ja' : 'nein'}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'flex-end' }}>
|
||||
<div key={row.id} className="card">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<label className="form-label" style={{ fontSize: '0.75rem' }}>
|
||||
Portal-Rolle
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ minWidth: '140px' }}
|
||||
value={(portalDraft[row.id]?.role || row.role || 'user').toLowerCase()}
|
||||
onChange={(e) =>
|
||||
setPortalDraft((prev) => ({
|
||||
...prev,
|
||||
[row.id]: { ...prev[row.id], role: e.target.value, tier: prev[row.id]?.tier ?? row.tier },
|
||||
}))
|
||||
<strong style={{ fontSize: '1.05rem' }}>
|
||||
{row.name || '—'} <span style={{ color: 'var(--text2)', fontWeight: 400 }}>#{row.id}</span>
|
||||
</strong>
|
||||
<div style={{ fontSize: '0.875rem', color: 'var(--text2)' }}>{row.email || '—'}</div>
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginTop: '0.35rem' }}>
|
||||
Verifiziert: {row.email_verified ? 'ja' : 'nein'}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'flex-end' }}>
|
||||
<div>
|
||||
<label className="form-label" style={{ fontSize: '0.75rem' }}>
|
||||
Portal-Zugriff
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ minWidth: '200px' }}
|
||||
value={(portalDraft[row.id]?.role || row.role || 'user').toLowerCase()}
|
||||
onChange={(e) =>
|
||||
setPortalDraft((prev) => ({
|
||||
...prev,
|
||||
[row.id]: { role: e.target.value },
|
||||
}))
|
||||
}
|
||||
>
|
||||
{portalRoleChoices.map((r) => (
|
||||
<option key={r.value} value={r.value}>
|
||||
{r.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={row.id === user?.id}
|
||||
title={row.id === user?.id ? 'Eigenes Passwort unter Einstellungen' : undefined}
|
||||
onClick={() =>
|
||||
setPwdModal({
|
||||
profileId: row.id,
|
||||
label: row.name || row.email || `#${row.id}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
{portalRoleChoices.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{ROLE_LABEL[r] || r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" style={{ fontSize: '0.75rem' }}>
|
||||
Tier
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ minWidth: '120px' }}
|
||||
value={tierValue}
|
||||
onChange={(e) =>
|
||||
setPortalDraft((prev) => ({
|
||||
...prev,
|
||||
[row.id]: {
|
||||
...prev[row.id],
|
||||
tier: e.target.value,
|
||||
role: prev[row.id]?.role ?? row.role,
|
||||
},
|
||||
}))
|
||||
}
|
||||
Passwort / Link
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => savePortal(row.id)}>
|
||||
Portal speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={!clubs.length}
|
||||
title={!clubs.length ? 'Zuerst einen Verein anlegen' : undefined}
|
||||
onClick={() => {
|
||||
if (!clubs.length) return
|
||||
setAssignRoles(['trainer'])
|
||||
setAssignModal({
|
||||
profileId: row.id,
|
||||
profileLabel: row.name || row.email || `#${row.id}`,
|
||||
clubId: clubs[0]?.id ?? '',
|
||||
})
|
||||
}}
|
||||
>
|
||||
{tierChoices.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
Verein zuweisen
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => savePortal(row.id)}>
|
||||
Portal speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={!clubs.length}
|
||||
title={!clubs.length ? 'Zuerst einen Verein anlegen' : undefined}
|
||||
onClick={() => {
|
||||
if (!clubs.length) return
|
||||
setAssignRoles(['trainer'])
|
||||
setAssignModal({
|
||||
profileId: row.id,
|
||||
profileLabel: row.name || row.email || `#${row.id}`,
|
||||
clubId: clubs[0]?.id ?? '',
|
||||
})
|
||||
}}
|
||||
>
|
||||
Verein zuweisen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: '1rem', paddingTop: '0.75rem', borderTop: '1px solid var(--border)' }}>
|
||||
<strong style={{ fontSize: '0.85rem' }}>Vereinsmitgliedschaften</strong>
|
||||
{!row.clubs?.length ? (
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', margin: '0.35rem 0 0' }}>
|
||||
Keine Zuordnung.
|
||||
</p>
|
||||
) : (
|
||||
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem', fontSize: '0.9rem' }}>
|
||||
{row.clubs.map((c) => (
|
||||
<li key={c.id} style={{ marginBottom: '0.35rem' }}>
|
||||
<strong>{c.name}</strong>
|
||||
{c.abbreviation ? ` (${c.abbreviation})` : ''} —{' '}
|
||||
{(c.roles || []).join(', ') || '—'}
|
||||
{c.membership_status === 'inactive' ? (
|
||||
<span style={{ color: 'var(--text3)', fontSize: '0.8rem' }}> (inaktiv)</span>
|
||||
) : null}{' '}
|
||||
<button
|
||||
type="button"
|
||||
style={{
|
||||
marginLeft: '0.35rem',
|
||||
fontSize: '0.75rem',
|
||||
padding: '0.12rem 0.45rem',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={() =>
|
||||
setClubEditModal({
|
||||
clubId: c.id,
|
||||
clubName: c.name,
|
||||
profileId: row.id,
|
||||
profileLabel: row.name || row.email,
|
||||
roles: [...(c.roles || [])],
|
||||
status: (c.membership_status || 'active').toLowerCase(),
|
||||
})
|
||||
}
|
||||
>
|
||||
bearbeiten
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div style={{ marginTop: '1rem', paddingTop: '0.75rem', borderTop: '1px solid var(--border)' }}>
|
||||
<strong style={{ fontSize: '0.85rem' }}>Vereinsmitgliedschaften</strong>
|
||||
{!row.clubs?.length ? (
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', margin: '0.35rem 0 0' }}>
|
||||
Keine Zuordnung.
|
||||
</p>
|
||||
) : (
|
||||
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem', fontSize: '0.9rem' }}>
|
||||
{(row.clubs || []).map((c) => (
|
||||
<li key={c.id} style={{ marginBottom: '0.35rem' }}>
|
||||
<strong>{c.name}</strong>
|
||||
{c.abbreviation ? ` (${c.abbreviation})` : ''} —{' '}
|
||||
{(c.roles || []).join(', ') || '—'}
|
||||
{c.membership_status === 'inactive' ? (
|
||||
<span style={{ color: 'var(--warning, #d4a012)', fontSize: '0.8rem', fontWeight: 600 }}>
|
||||
{' '}
|
||||
(Vereinszugang deaktiviert)
|
||||
</span>
|
||||
) : null}{' '}
|
||||
<button
|
||||
type="button"
|
||||
style={{
|
||||
marginLeft: '0.35rem',
|
||||
fontSize: '0.75rem',
|
||||
padding: '0.12rem 0.45rem',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={() =>
|
||||
setClubEditModal({
|
||||
clubId: c.id,
|
||||
clubName: c.name,
|
||||
profileId: row.id,
|
||||
profileLabel: row.name || row.email,
|
||||
roles: [...(c.roles || [])],
|
||||
status: (c.membership_status || 'active').toLowerCase(),
|
||||
})
|
||||
}
|
||||
>
|
||||
bearbeiten
|
||||
</button>
|
||||
{c.membership_status === 'inactive' ? (
|
||||
<button
|
||||
type="button"
|
||||
style={{
|
||||
marginLeft: '0.35rem',
|
||||
fontSize: '0.75rem',
|
||||
padding: '0.12rem 0.45rem',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid var(--accent, #0366d6)',
|
||||
background: 'var(--surface)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await api.updateClubMember(c.id, row.id, {
|
||||
roles: [...(c.roles || [])],
|
||||
status: 'active',
|
||||
})
|
||||
await loadPlatform()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}}
|
||||
>
|
||||
Zugang aktivieren
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
@@ -346,11 +452,7 @@ function AdminUsersPage() {
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 1 }} onClick={submitAssignClub}>
|
||||
Zuweisen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setAssignModal(null)}
|
||||
>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setAssignModal(null)}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
@@ -384,8 +486,11 @@ function AdminUsersPage() {
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>
|
||||
{clubEditModal.profileLabel} → {clubEditModal.clubName}
|
||||
</p>
|
||||
<p className="muted" style={{ fontSize: '0.82rem', lineHeight: 1.45 }}>
|
||||
„Deaktiviert“ betrifft nur den Zugriff auf Inhalte dieses Vereins; Login und andere Vereine bleiben unberührt.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Status</label>
|
||||
<label className="form-label">Vereinszugang</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={clubEditModal.status}
|
||||
@@ -393,8 +498,8 @@ function AdminUsersPage() {
|
||||
setClubEditModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
||||
}
|
||||
>
|
||||
<option value="active">aktiv</option>
|
||||
<option value="inactive">inaktiv</option>
|
||||
<option value="active">aktiv — sieht Vereinsinhalte</option>
|
||||
<option value="inactive">deaktiviert — kein Zugriff auf Vereinsinhalte</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
@@ -441,8 +546,86 @@ function AdminUsersPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pwdModal ? (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1250,
|
||||
padding: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: '1.5rem',
|
||||
maxWidth: '440px',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginTop: 0 }}>Passwort zurücksetzen</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>{pwdModal.label}</p>
|
||||
<p className="muted" style={{ fontSize: '0.82rem', marginBottom: '0.75rem' }}>
|
||||
Standard: Es wird ein sicherer Link per E-Mail verschickt (wie „Passwort vergessen“). Das bisherige Passwort
|
||||
bleibt gültig, bis die Person den Link nutzt und ein neues Passwort wählt.
|
||||
</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<button type="button" className="btn btn-primary" onClick={submitPasswordEmail}>
|
||||
Reset-Link per E-Mail senden
|
||||
</button>
|
||||
</div>
|
||||
<>
|
||||
<hr style={{ margin: '1rem 0', borderColor: 'var(--border, #333)' }} />
|
||||
<p className="muted" style={{ fontSize: '0.82rem', marginBottom: '0.5rem' }}>
|
||||
Ausnahme: Passwort direkt setzen (nur bei Bedarf). Das bisherige Passwort ist danach ungültig.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Neues Passwort</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
autoComplete="new-password"
|
||||
value={pwdNew}
|
||||
onChange={(e) => setPwdNew(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Wiederholen</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
autoComplete="new-password"
|
||||
value={pwdNew2}
|
||||
onChange={(e) => setPwdNew2(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" style={{ width: '100%' }} onClick={submitPasswordDirect}>
|
||||
Passwort direkt setzen
|
||||
</button>
|
||||
</>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%' }}
|
||||
onClick={() => {
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
}}
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AdminUsersPage
|
||||
@@ -1,6 +1,9 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { notifyOrgInboxChanged } from '../context/OrgInboxContext'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
import { isEscalatedPortalRole } from '../utils/portalRoles'
|
||||
import PageSectionNav from '../components/PageSectionNav'
|
||||
|
||||
const CLUB_ROLE_OPTIONS = [
|
||||
@@ -33,6 +36,9 @@ function ClubsPage() {
|
||||
|
||||
const [editMemberModal, setEditMemberModal] = useState(null)
|
||||
const [acceptJoinModal, setAcceptJoinModal] = useState(null)
|
||||
const [pwdModal, setPwdModal] = useState(null)
|
||||
const [pwdNew, setPwdNew] = useState('')
|
||||
const [pwdNew2, setPwdNew2] = useState('')
|
||||
|
||||
// Form state
|
||||
const [formData, setFormData] = useState({})
|
||||
@@ -40,7 +46,7 @@ function ClubsPage() {
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperAdmin = user?.role === 'superadmin'
|
||||
const clubAdminClubIds = new Set(
|
||||
(user?.clubs || [])
|
||||
activeClubMemberships(user?.clubs)
|
||||
.filter((c) => (c.roles || []).includes('club_admin'))
|
||||
.map((c) => c.id)
|
||||
)
|
||||
@@ -48,7 +54,7 @@ function ClubsPage() {
|
||||
const canCreateClub = isPlatformAdmin
|
||||
const canManageOrgSomewhere = isPlatformAdmin || clubAdminClubIds.size > 0
|
||||
const canCreateTrainingGroup =
|
||||
isPlatformAdmin || (Array.isArray(user?.clubs) && user.clubs.length > 0)
|
||||
isPlatformAdmin || activeClubMemberships(user?.clubs).length > 0
|
||||
|
||||
const canEditGroup = (g) =>
|
||||
isPlatformAdmin ||
|
||||
@@ -194,6 +200,65 @@ function ClubsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const toggleMembersAdminClubAccess = async (m, activate) => {
|
||||
if (!membersAdminClubId || !canManageClub(membersAdminClubId)) return
|
||||
const st = activate ? 'active' : 'inactive'
|
||||
if (
|
||||
!activate &&
|
||||
!confirm(
|
||||
`Vereinszugang für „${m.name || m.email || '#' + m.profile_id}“ hier deaktivieren? Login bleibt möglich, Vereinsinhalte nicht — auch bei Super-Admins.`,
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await api.updateClubMember(membersAdminClubId, m.profile_id, {
|
||||
roles: [...(m.roles || [])],
|
||||
status: st,
|
||||
})
|
||||
await reloadMembersAdmin()
|
||||
} catch (err) {
|
||||
alert(err.message || String(err))
|
||||
}
|
||||
}
|
||||
|
||||
const submitMembersPasswordEmail = async () => {
|
||||
if (!pwdModal) return
|
||||
try {
|
||||
const res = await api.managementPasswordReset(pwdModal.profileId, null)
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
let msg =
|
||||
'Sofern eine E-Mail-Adresse hinterlegt ist, wurde ein Link zum Setzen eines neuen Passworts versendet. Das bisherige Passwort bleibt bis zur Bestätigung im Link aktiv.'
|
||||
if (res?.email_sent === false) msg += ' Hinweis: E-Mail-Versand fehlgeschlagen (SMTP).'
|
||||
alert(msg)
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
const submitMembersPasswordDirect = async () => {
|
||||
if (!pwdModal || !isSuperAdmin) return
|
||||
if (pwdNew.length < 8) {
|
||||
alert('Mindestens 8 Zeichen.')
|
||||
return
|
||||
}
|
||||
if (pwdNew !== pwdNew2) {
|
||||
alert('Die beiden Passwörter stimmen nicht überein.')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await api.managementPasswordReset(pwdModal.profileId, pwdNew)
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
alert('Neues Passwort wurde direkt gesetzt.')
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (item, type) => {
|
||||
setEditing(item)
|
||||
setModalType(type)
|
||||
@@ -647,6 +712,7 @@ function ClubsPage() {
|
||||
if (!confirm('Antrag ablehnen?')) return
|
||||
try {
|
||||
await api.rejectClubJoinRequest(membersAdminClubId, req.id)
|
||||
notifyOrgInboxChanged()
|
||||
await reloadMembersAdmin()
|
||||
} catch (err) {
|
||||
alert(err.message || String(err))
|
||||
@@ -664,17 +730,41 @@ function ClubsPage() {
|
||||
|
||||
<div className="card">
|
||||
<h3 style={{ marginTop: 0 }}>Mitglieder</h3>
|
||||
{isPlatformAdmin ? (
|
||||
<p
|
||||
className="muted"
|
||||
style={{ fontSize: '0.85rem', marginTop: '-0.35rem', marginBottom: '0.85rem', lineHeight: 1.45 }}
|
||||
>
|
||||
Liste enthält <strong style={{ color: 'var(--text1)' }}>aktive und deaktivierte</strong> Vereinszugänge.
|
||||
Deaktiviert gilt pro Verein (ohne Kontosperre) — auch für Super-Admins ohne aktive Mitgliedschaft in diesem
|
||||
Verein kein Zugriff auf dessen Vereinsinhalte. Wiederherstellen über die Schaltflächen oder Mitglied
|
||||
bearbeiten.
|
||||
</p>
|
||||
) : (
|
||||
<p
|
||||
className="muted"
|
||||
style={{ fontSize: '0.85rem', marginTop: '-0.35rem', marginBottom: '0.85rem', lineHeight: 1.45 }}
|
||||
>
|
||||
Deaktivierte Vereinszugänge sind hervorgehoben —{' '}
|
||||
<strong>Anmeldung</strong> bleibt möglich, <strong>Vereinsinhalte</strong> dieser Zuordnung nicht.
|
||||
</p>
|
||||
)}
|
||||
{clubMembersAdmin.length === 0 ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Noch keine Mitglieder erfasst.</p>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: '0.65rem' }}>
|
||||
{clubMembersAdmin.map((m) => (
|
||||
{clubMembersAdmin.map((m) => {
|
||||
const memStatus = (m.status || 'active').toLowerCase()
|
||||
const inactiveRow = memStatus === 'inactive'
|
||||
const portalLabel = (m.portal_role || '').trim()
|
||||
return (
|
||||
<div
|
||||
key={m.membership_id}
|
||||
style={{
|
||||
padding: '0.65rem',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface2)',
|
||||
background: inactiveRow ? 'color-mix(in srgb, var(--warning, #884400) 12%, var(--surface2))' : 'var(--surface2)',
|
||||
border: inactiveRow ? '1px solid color-mix(in srgb, var(--warning, #d4a012) 40%, transparent)' : undefined,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
@@ -684,21 +774,77 @@ function ClubsPage() {
|
||||
<div>
|
||||
<strong>{m.name || m.email}</strong>
|
||||
<div style={{ fontSize: '0.8rem', color: 'var(--text2)' }}>
|
||||
{m.email} · #{m.profile_id} · {m.status}
|
||||
{m.email} · #{m.profile_id}
|
||||
{' · '}
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
Vereinszugang:{' '}
|
||||
<span style={{ color: inactiveRow ? 'var(--warning, #d4a012)' : 'inherit' }}>
|
||||
{inactiveRow ? 'deaktiviert' : 'aktiv'}
|
||||
</span>
|
||||
</span>
|
||||
{portalLabel ? (
|
||||
<span style={{ color: 'var(--text3)', marginLeft: '0.35rem' }}> · Portal: {portalLabel}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div style={{ fontSize: '0.8rem', marginTop: '0.25rem' }}>
|
||||
Rollen: {(m.roles || []).join(', ') || '—'}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setEditMemberModal(m)}
|
||||
>
|
||||
Bearbeiten
|
||||
</button>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem', alignItems: 'stretch' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setEditMemberModal(m)}>
|
||||
Mitglied bearbeiten
|
||||
</button>
|
||||
{m.profile_id !== user?.id ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={
|
||||
!isSuperAdmin &&
|
||||
!isPlatformAdmin &&
|
||||
isEscalatedPortalRole(m.portal_role)
|
||||
}
|
||||
title={
|
||||
!isSuperAdmin &&
|
||||
!isPlatformAdmin &&
|
||||
isEscalatedPortalRole(m.portal_role)
|
||||
? 'Für Portal-Administratoren nur mit Super-/Plattform-Administrator möglich'
|
||||
: undefined
|
||||
}
|
||||
onClick={() => {
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
setPwdModal({
|
||||
profileId: m.profile_id,
|
||||
label: m.name || m.email || `#${m.profile_id}`,
|
||||
})
|
||||
}}
|
||||
>
|
||||
Passwort / Link
|
||||
</button>
|
||||
) : null}
|
||||
{m.profile_id !== user?.id ? (
|
||||
inactiveRow ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => toggleMembersAdminClubAccess(m, true)}
|
||||
>
|
||||
Vereinszugang aktivieren
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => toggleMembersAdminClubAccess(m, false)}
|
||||
>
|
||||
Vereinszugang deaktivieren
|
||||
</button>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -1255,6 +1401,7 @@ function ClubsPage() {
|
||||
acceptJoinModal.id,
|
||||
acceptJoinModal.roles.length ? acceptJoinModal.roles : ['trainer']
|
||||
)
|
||||
notifyOrgInboxChanged()
|
||||
setAcceptJoinModal(null)
|
||||
await reloadMembersAdmin()
|
||||
await loadData()
|
||||
@@ -1307,7 +1454,7 @@ function ClubsPage() {
|
||||
{editMemberModal.name || editMemberModal.email} (#{editMemberModal.profile_id})
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Status</label>
|
||||
<label className="form-label">Vereinszugang</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={editMemberModal.status || 'active'}
|
||||
@@ -1315,10 +1462,13 @@ function ClubsPage() {
|
||||
setEditMemberModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
||||
}
|
||||
>
|
||||
<option value="active">aktiv</option>
|
||||
<option value="inactive">inaktiv</option>
|
||||
<option value="active">aktiv — sieht Vereinsinhalte</option>
|
||||
<option value="inactive">deaktiviert — weiter anmeldbar, keine Vereinsinhalte</option>
|
||||
</select>
|
||||
</div>
|
||||
<p className="muted" style={{ fontSize: '0.82rem', lineHeight: 1.45 }}>
|
||||
Deaktivierung gilt nur für diesen Verein; der Login-Account bleibt aktiv.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<span className="form-label">Rollen</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
||||
@@ -1394,6 +1544,93 @@ function ClubsPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pwdModal ? (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1250,
|
||||
padding: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: '1.5rem',
|
||||
maxWidth: '440px',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginTop: 0 }}>Passwort zurücksetzen</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>{pwdModal.label}</p>
|
||||
<p className="muted" style={{ fontSize: '0.82rem', marginBottom: '0.75rem' }}>
|
||||
Standard: Es wird ein sicherer Link per E-Mail verschickt (wie „Passwort vergessen“). Das bisherige Passwort
|
||||
bleibt gültig, bis die Person den Link nutzt und ein neues Passwort wählt.
|
||||
</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<button type="button" className="btn btn-primary" onClick={submitMembersPasswordEmail}>
|
||||
Reset-Link per E-Mail senden
|
||||
</button>
|
||||
</div>
|
||||
{isSuperAdmin ? (
|
||||
<>
|
||||
<hr style={{ margin: '1rem 0', borderColor: 'var(--border, #333)' }} />
|
||||
<p className="muted" style={{ fontSize: '0.82rem', marginBottom: '0.5rem' }}>
|
||||
Ausnahme: Passwort direkt setzen (nur bei Bedarf). Das bisherige Passwort ist danach ungültig.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Neues Passwort</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
autoComplete="new-password"
|
||||
value={pwdNew}
|
||||
onChange={(e) => setPwdNew(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Wiederholen</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-input"
|
||||
autoComplete="new-password"
|
||||
value={pwdNew2}
|
||||
onChange={(e) => setPwdNew2(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%' }}
|
||||
onClick={submitMembersPasswordDirect}
|
||||
>
|
||||
Passwort direkt setzen
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%' }}
|
||||
onClick={() => {
|
||||
setPwdModal(null)
|
||||
setPwdNew('')
|
||||
setPwdNew2('')
|
||||
}}
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import EmailVerificationBanner from '../components/EmailVerificationBanner'
|
||||
import DashboardTrainingVisibilityWidget from '../components/DashboardTrainingVisibilityWidget'
|
||||
import DashboardOrgInboxWidget from '../components/DashboardOrgInboxWidget'
|
||||
|
||||
function unitWhenLabel(u) {
|
||||
const d = u.planned_date ? String(u.planned_date).slice(0, 10) : ''
|
||||
@@ -183,6 +184,7 @@ function Dashboard() {
|
||||
|
||||
{user?.id ? (
|
||||
<>
|
||||
<DashboardOrgInboxWidget />
|
||||
<section className="dashboard-section" aria-labelledby="dash-phase0-title">
|
||||
<div className="dashboard-section__header">
|
||||
<div className="dashboard-section__headline">
|
||||
|
||||
@@ -1,57 +1,10 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { Link, useNavigate, useParams, useLocation } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
||||
import ExerciseRichTextBlock from '../components/ExerciseRichTextBlock'
|
||||
import ExerciseAttachmentMediaStrip from '../components/ExerciseAttachmentMediaStrip'
|
||||
import { formatSkillLevelSlug } from '../constants/skillLevels'
|
||||
|
||||
function HtmlBlock({ html, className = '' }) {
|
||||
if (!html || !String(html).trim()) return null
|
||||
const safe = sanitizeTrainerHtml(html)
|
||||
return (
|
||||
<div
|
||||
className={`rich-text-content ${className}`}
|
||||
dangerouslySetInnerHTML={{ __html: safe }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MediaBlock({ media, exerciseId }) {
|
||||
if (media.embed_url) {
|
||||
return (
|
||||
<div style={{ marginTop: '0.5rem' }}>
|
||||
<a href={media.embed_url} target="_blank" rel="noreferrer">
|
||||
{media.embed_url}
|
||||
</a>
|
||||
{media.embed_platform && (
|
||||
<span style={{ color: 'var(--text2)', marginLeft: '0.5rem', fontSize: '0.8rem' }}>
|
||||
({media.embed_platform})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const src = resolveExerciseMediaFileUrl(exerciseId, media)
|
||||
if (!src) return null
|
||||
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt={media.title || media.original_filename || ''}
|
||||
style={{ maxWidth: '100%', borderRadius: '8px', marginTop: '0.5rem' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
|
||||
return <video src={src} controls style={{ width: '100%', marginTop: '0.5rem', borderRadius: '8px' }} />
|
||||
}
|
||||
return (
|
||||
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.5rem' }}>
|
||||
{media.title || media.original_filename || 'Datei öffnen'}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
function TagRow({ exercise }) {
|
||||
const tags = []
|
||||
;(exercise.focus_areas || []).forEach((f) => {
|
||||
@@ -100,6 +53,7 @@ function metaParts(exercise) {
|
||||
function ExerciseDetailPage() {
|
||||
const { id } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [exercise, setExercise] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -151,27 +105,26 @@ function ExerciseDetailPage() {
|
||||
if (!exercise) return null
|
||||
|
||||
const meta = metaParts(exercise)
|
||||
const visibleMedia = (exercise.media || []).filter((m) => {
|
||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
||||
return lc !== 'trash_hidden'
|
||||
})
|
||||
const fromExerciseEdit = location.state?.fromExerciseEdit === true
|
||||
|
||||
return (
|
||||
<div className="exercise-detail-shell" style={{ padding: '12px 12px 24px' }}>
|
||||
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' }}>
|
||||
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/exercises')}>
|
||||
← Übersicht
|
||||
</button>
|
||||
<Link to={`/exercises/${exercise.id}/edit`} className="btn btn-primary">
|
||||
Bearbeiten
|
||||
</Link>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginLeft: 'auto' }}>
|
||||
<Link to={`/exercises/${exercise.id}/edit`} className="btn btn-primary">
|
||||
{fromExerciseEdit ? 'Zurück zur Bearbeitung' : 'Bearbeiten'}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card exercise-detail-section">
|
||||
<h1 style={{ margin: 0, fontSize: '1.35rem', lineHeight: 1.25 }}>{exercise.title}</h1>
|
||||
{exercise.summary && (
|
||||
<div style={{ marginTop: '10px', color: 'var(--text2)', fontSize: '15px' }}>
|
||||
<HtmlBlock html={exercise.summary} />
|
||||
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
|
||||
</div>
|
||||
)}
|
||||
<TagRow exercise={exercise} />
|
||||
@@ -186,7 +139,7 @@ function ExerciseDetailPage() {
|
||||
{exercise.goal && (
|
||||
<section className="card exercise-detail-section">
|
||||
<h2>Ziel</h2>
|
||||
<HtmlBlock html={exercise.goal} />
|
||||
<ExerciseRichTextBlock html={exercise.goal} exerciseId={exercise.id} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -204,39 +157,23 @@ function ExerciseDetailPage() {
|
||||
{exercise.preparation && (
|
||||
<section className="card exercise-detail-section">
|
||||
<h2>Vorbereitung</h2>
|
||||
<HtmlBlock html={exercise.preparation} />
|
||||
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={exercise.id} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{exercise.execution && (
|
||||
<section className="card exercise-detail-section">
|
||||
<h2>Ablauf</h2>
|
||||
<HtmlBlock html={exercise.execution} />
|
||||
<ExerciseRichTextBlock html={exercise.execution} exerciseId={exercise.id} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{visibleMedia.length > 0 && (
|
||||
<section className="card exercise-detail-section">
|
||||
<h2>Medien</h2>
|
||||
{visibleMedia.map((m) => (
|
||||
<div key={m.id} style={{ marginBottom: '1.25rem' }}>
|
||||
<strong style={{ fontSize: '15px' }}>{m.title || m.original_filename || m.media_type}</strong>
|
||||
{String(m.asset_lifecycle_state || 'active').toLowerCase() === 'trash_soft' && (
|
||||
<p style={{ fontSize: '12px', color: 'var(--danger)', margin: '6px 0 0' }}>
|
||||
Hinweis: Dieses Medium ist im Papierkorb und steht künftig nicht mehr zur Verfügung.
|
||||
</p>
|
||||
)}
|
||||
{m.description && <p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>{m.description}</p>}
|
||||
<MediaBlock media={m} exerciseId={exercise.id} />
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<ExerciseAttachmentMediaStrip exercise={exercise} exerciseId={exercise.id} />
|
||||
|
||||
{exercise.trainer_notes && (
|
||||
<section className="card exercise-detail-section">
|
||||
<h2>Hinweise für Trainer</h2>
|
||||
<HtmlBlock html={exercise.trainer_notes} />
|
||||
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={exercise.id} media={exercise.media} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -307,7 +244,11 @@ function ExerciseDetailPage() {
|
||||
{v.description && <p style={{ color: 'var(--text2)', marginTop: '4px' }}>{v.description}</p>}
|
||||
{v.execution_changes && (
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<HtmlBlock html={v.execution_changes} />
|
||||
<ExerciseRichTextBlock
|
||||
html={v.execution_changes}
|
||||
exerciseId={exercise.id}
|
||||
media={exercise.media}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,71 +4,14 @@ import api, { buildExerciseApiPayload } from '../utils/api'
|
||||
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
import RichTextEditor from '../components/RichTextEditor'
|
||||
import ExerciseProgressionGraphPanel from '../components/ExerciseProgressionGraphPanel'
|
||||
import ExerciseMediaThumbTile from '../components/ExerciseMediaThumbTile'
|
||||
import {
|
||||
SHINKAN_EXERCISE_MEDIA_DRAG_MIME,
|
||||
buildExerciseMediaDragPayload,
|
||||
} from '../utils/exerciseInlineMediaRefs'
|
||||
import { autoScrollForDragNearEdges } from '../utils/dragAutoScroll'
|
||||
import { SKILL_LEVEL_OPTIONS, normalizeSkillLevelSlug } from '../constants/skillLevels'
|
||||
|
||||
/** Kachelvorschau: Video nutzt ersten Frame (metadata), Bild = img. */
|
||||
function ExerciseMediaThumbTile({ exerciseId, media, onOpenPreview }) {
|
||||
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media) : null
|
||||
const commonStyle = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'cover',
|
||||
}
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
title="Vorschau"
|
||||
onClick={() => onOpenPreview(media)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
onOpenPreview(media)
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
width: 72,
|
||||
height: 72,
|
||||
flexShrink: 0,
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden',
|
||||
background: 'var(--surface2, rgba(127,127,127,0.12))',
|
||||
border: '1px solid var(--border)',
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{media.embed_url ? (
|
||||
<span style={{ fontSize: '11px', padding: '4px', color: 'var(--text2)', textAlign: 'center' }}>
|
||||
{media.embed_platform || 'Embed'}
|
||||
</span>
|
||||
) : (media.mime_type?.startsWith('image/') || media.media_type === 'image') && src ? (
|
||||
<img alt="" src={src} style={commonStyle} />
|
||||
) : (media.mime_type?.startsWith('video/') || media.media_type === 'video') && src ? (
|
||||
<video
|
||||
src={src}
|
||||
muted
|
||||
playsInline
|
||||
preload="metadata"
|
||||
style={{ ...commonStyle, pointerEvents: 'none' }}
|
||||
onLoadedMetadata={(e) => {
|
||||
try {
|
||||
const el = e.currentTarget
|
||||
const d = el.duration
|
||||
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span style={{ fontSize: '11px', color: 'var(--text2)' }}>Datei</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
const INTENSITY_OPTIONS = [
|
||||
{ value: '', label: '—' },
|
||||
@@ -154,7 +97,15 @@ function buildVariantPayloadFromRow(row) {
|
||||
}
|
||||
|
||||
/** Gemeinsame Felder für „Variante bearbeiten“ und „Neue Variante“. */
|
||||
function ExerciseVariantFields({ row, onPatch, prerequisiteOthers, rteMinHeight = '110px' }) {
|
||||
function ExerciseVariantFields({
|
||||
row,
|
||||
onPatch,
|
||||
prerequisiteOthers,
|
||||
rteMinHeight = '110px',
|
||||
inlineExerciseId,
|
||||
linkedExerciseMedia = [],
|
||||
onExerciseMediaListChanged,
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className="form-row">
|
||||
@@ -183,6 +134,9 @@ function ExerciseVariantFields({ row, onPatch, prerequisiteOthers, rteMinHeight
|
||||
onChange={(html) => onPatch({ execution_changes: html })}
|
||||
placeholder="Was unterscheidet diese Variante? (Listen über Symbolleiste)"
|
||||
minHeight={rteMinHeight}
|
||||
inlineExerciseId={inlineExerciseId}
|
||||
linkedExerciseMedia={linkedExerciseMedia}
|
||||
onExerciseMediaListChanged={onExerciseMediaListChanged}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
|
||||
@@ -406,6 +360,8 @@ function MultiAssocBlock({ title, rows, setRows, options, idKey, emptyLabel }) {
|
||||
function ExerciseFormPage() {
|
||||
const { id: routeId } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const exerciseId = routeId && !Number.isNaN(parseInt(routeId, 10)) ? parseInt(routeId, 10) : null
|
||||
const isEdit = exerciseId != null
|
||||
|
||||
@@ -418,6 +374,7 @@ function ExerciseFormPage() {
|
||||
const [mediaList, setMediaList] = useState([])
|
||||
const [loading, setLoading] = useState(!!isEdit)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [formDirty, setFormDirty] = useState(false)
|
||||
const [skillPick, setSkillPick] = useState('')
|
||||
const [variants, setVariants] = useState([])
|
||||
const [variantDraft, setVariantDraft] = useState(() => emptyVariantDraft())
|
||||
@@ -426,17 +383,10 @@ function ExerciseFormPage() {
|
||||
const [variantEditSelection, setVariantEditSelection] = useState(null)
|
||||
const variantsDetailsRef = useRef(null)
|
||||
|
||||
const [mediaFile, setMediaFile] = useState(null)
|
||||
const [mediaType, setMediaType] = useState('image')
|
||||
const [mediaTitle, setMediaTitle] = useState('')
|
||||
const [mediaContext, setMediaContext] = useState('ablauf')
|
||||
const [embedUrl, setEmbedUrl] = useState('')
|
||||
const [embedTitle, setEmbedTitle] = useState('')
|
||||
const [mediaFields, setMediaFields] = useState({})
|
||||
const [mediaSavingId, setMediaSavingId] = useState(null)
|
||||
const [archiveOpen, setArchiveOpen] = useState(false)
|
||||
const [archiveQ, setArchiveQ] = useState('')
|
||||
const [archiveCtx, setArchiveCtx] = useState('ablauf')
|
||||
const [archiveLoading, setArchiveLoading] = useState(false)
|
||||
const [archiveItems, setArchiveItems] = useState([])
|
||||
const [archiveError, setArchiveError] = useState(null)
|
||||
@@ -447,12 +397,32 @@ function ExerciseFormPage() {
|
||||
for (const m of mediaList) {
|
||||
next[m.id] = {
|
||||
title: m.title || '',
|
||||
context: m.context || 'ablauf',
|
||||
}
|
||||
}
|
||||
setMediaFields(next)
|
||||
}, [mediaList])
|
||||
|
||||
useEffect(() => {
|
||||
const onDragOverDoc = (e) => {
|
||||
const types = e.dataTransfer?.types ? Array.from(e.dataTransfer.types) : []
|
||||
if (!types.includes(SHINKAN_EXERCISE_MEDIA_DRAG_MIME)) return
|
||||
e.preventDefault()
|
||||
autoScrollForDragNearEdges(e)
|
||||
}
|
||||
document.addEventListener('dragover', onDragOverDoc)
|
||||
return () => document.removeEventListener('dragover', onDragOverDoc)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!formDirty) return undefined
|
||||
const warn = (ev) => {
|
||||
ev.preventDefault()
|
||||
ev.returnValue = ''
|
||||
}
|
||||
window.addEventListener('beforeunload', warn)
|
||||
return () => window.removeEventListener('beforeunload', warn)
|
||||
}, [formDirty])
|
||||
|
||||
useEffect(() => {
|
||||
if (!archiveOpen) return undefined
|
||||
let cancelled = false
|
||||
@@ -517,6 +487,7 @@ function ExerciseFormPage() {
|
||||
setVariants([])
|
||||
setVariantDraft(emptyVariantDraft())
|
||||
setVariantEditSelection(null)
|
||||
setFormDirty(false)
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
@@ -531,6 +502,7 @@ function ExerciseFormPage() {
|
||||
setVariants((exercise.variants || []).map(apiVariantToRow))
|
||||
setVariantDraft(emptyVariantDraft())
|
||||
setVariantEditSelection(null)
|
||||
setFormDirty(false)
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
alert(err.message || 'Übung nicht ladbar')
|
||||
@@ -560,6 +532,7 @@ function ExerciseFormPage() {
|
||||
}, [variantEditSelection])
|
||||
|
||||
const updateFormField = (field, value) => {
|
||||
setFormDirty(true)
|
||||
setFormData((prev) => ({ ...prev, [field]: value }))
|
||||
}
|
||||
|
||||
@@ -676,6 +649,33 @@ function ExerciseFormPage() {
|
||||
promote_attached_media_for_official: true,
|
||||
...(miss > 0 ? { default_official_media_copyright: String(defaultCopyright).trim() } : {}),
|
||||
})
|
||||
} else if (
|
||||
firstErr.status === 422 &&
|
||||
firstErr.code === 'CLUB_MEDIA_COPYRIGHT_REQUIRED' &&
|
||||
firstErr.payload?.media_assets
|
||||
) {
|
||||
const miss = firstErr.payload.media_assets.length
|
||||
const msg =
|
||||
`Vereinsöffentliche Übungen brauchen bei jeder verknüpften Datei einen Copyright-Vermerk (mind. 3 Zeichen). ` +
|
||||
`${miss} Datei(en) sind noch ohne ausreichenden Vermerk. ` +
|
||||
`Beim Speichern einen gemeinsamen Vermerk für diese Dateien setzen?`
|
||||
if (!window.confirm(msg)) throw firstErr
|
||||
const defaultCopyright = window.prompt(
|
||||
'Copyright-Vermerk für die betroffenen Dateien (mind. 3 Zeichen):',
|
||||
'© ',
|
||||
)
|
||||
if (!defaultCopyright || String(defaultCopyright).trim().length < 3) {
|
||||
alert('Mindestens 3 Zeichen für den Copyright-Vermerk.')
|
||||
throw firstErr
|
||||
}
|
||||
await saveOnce({
|
||||
default_club_media_copyright: String(defaultCopyright).trim(),
|
||||
})
|
||||
} else if (firstErr.status === 422 && firstErr.code === 'CLUB_MEDIA_LIFECYCLE') {
|
||||
alert(
|
||||
'Speichern nicht möglich: mindestens ein verknüpftes Medium ist nicht aktiv (Papierkorb). Bitte reaktivieren oder entfernen.',
|
||||
)
|
||||
throw firstErr
|
||||
} else {
|
||||
throw firstErr
|
||||
}
|
||||
@@ -683,6 +683,7 @@ function ExerciseFormPage() {
|
||||
const ex = await api.getExercise(exerciseId)
|
||||
setMediaList(ex.media || [])
|
||||
setVariants((ex.variants || []).map(apiVariantToRow))
|
||||
setFormDirty(false)
|
||||
alert('Gespeichert.')
|
||||
} else {
|
||||
const created = await api.createExercise(payload)
|
||||
@@ -706,7 +707,7 @@ function ExerciseFormPage() {
|
||||
try {
|
||||
await api.attachExerciseMediaFromAsset(exerciseId, {
|
||||
media_asset_id: assetId,
|
||||
context: archiveCtx,
|
||||
context: 'ablauf',
|
||||
title: '',
|
||||
description: '',
|
||||
is_primary: false,
|
||||
@@ -723,91 +724,11 @@ function ExerciseFormPage() {
|
||||
[mediaList],
|
||||
)
|
||||
|
||||
const handleUploadFile = async () => {
|
||||
if (!exerciseId || !mediaFile) {
|
||||
alert('Datei wählen')
|
||||
return
|
||||
}
|
||||
const fd = new FormData()
|
||||
fd.append('file', mediaFile)
|
||||
fd.append('media_type', mediaType)
|
||||
fd.append('title', mediaTitle)
|
||||
fd.append('description', '')
|
||||
fd.append('context', mediaContext)
|
||||
fd.append('is_primary', 'false')
|
||||
try {
|
||||
await api.uploadExerciseMedia(exerciseId, fd)
|
||||
setMediaFile(null)
|
||||
setMediaTitle('')
|
||||
await refreshMedia()
|
||||
} catch (err) {
|
||||
if (err.code === 'MEDIA_ASSET_IN_TRASH' && err.payload?.media_asset_id != null) {
|
||||
const aid = err.payload.media_asset_id
|
||||
const nameHint =
|
||||
(mediaFile && mediaFile.name) ||
|
||||
err.payload.original_filename ||
|
||||
'diese Datei'
|
||||
if (
|
||||
confirm(
|
||||
`Die hochgeladene Datei ist inhaltsgleich mit einem Archiv-Medium im Papierkorb (${nameHint}). ` +
|
||||
'Soll dieses Medium wieder aktiviert und an die Übung gehängt werden? (Es wird kein zweites Exemplar auf der Platte angelegt.)',
|
||||
)
|
||||
) {
|
||||
try {
|
||||
await api.postMediaAssetLifecycle(aid, 'reactivate')
|
||||
await api.attachExerciseMediaFromAsset(exerciseId, {
|
||||
media_asset_id: aid,
|
||||
title: mediaTitle || undefined,
|
||||
description: '',
|
||||
context: mediaContext,
|
||||
is_primary: false,
|
||||
})
|
||||
setMediaFile(null)
|
||||
setMediaTitle('')
|
||||
await refreshMedia()
|
||||
} catch (e2) {
|
||||
alert(e2.message || String(e2))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (err.code === 'MEDIA_ASSET_UNAVAILABLE') {
|
||||
alert(
|
||||
(err.message || 'Archiv-Konflikt') +
|
||||
' Bitte wenden Sie sich an einen Administrator oder wählen Sie eine andere Datei.',
|
||||
)
|
||||
return
|
||||
}
|
||||
alert('Upload: ' + (err.message || String(err)))
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddEmbed = async () => {
|
||||
if (!exerciseId || !embedUrl.trim()) {
|
||||
alert('Embed-URL eingeben')
|
||||
return
|
||||
}
|
||||
const fd = new FormData()
|
||||
fd.append('embed_url', embedUrl.trim())
|
||||
fd.append('media_type', 'video')
|
||||
fd.append('title', embedTitle)
|
||||
fd.append('description', '')
|
||||
fd.append('context', mediaContext)
|
||||
fd.append('is_primary', 'false')
|
||||
try {
|
||||
await api.uploadExerciseMedia(exerciseId, fd)
|
||||
setEmbedUrl('')
|
||||
setEmbedTitle('')
|
||||
await refreshMedia()
|
||||
} catch (err) {
|
||||
alert('Embed: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteMedia = async (mid) => {
|
||||
if (
|
||||
!confirm(
|
||||
'Dieses Medium aus der Übung entfernen? Nur die Verknüpfung wird gelöscht. Die Datei bleibt im Archiv, solange sie noch woanders genutzt wird.',
|
||||
'Dieses Medium aus der Übung entfernen? Nur die Verknüpfung wird gelöscht. Die Datei bleibt im Archiv, solange sie noch woanders genutzt wird.\n\n' +
|
||||
'Hinweis: Wenn dieser Eintrag noch als Platzhalter im Fließtext steht, zeigt die Vorschau [Medium nicht verfügbar] oder das Speichern der Übung schlägt fehl, bis der Platzhalter entfernt ist.',
|
||||
)
|
||||
) {
|
||||
return
|
||||
@@ -858,7 +779,6 @@ function ExerciseFormPage() {
|
||||
try {
|
||||
await api.updateExerciseMedia(exerciseId, mid, {
|
||||
title: fld.title.trim() || null,
|
||||
context: fld.context,
|
||||
})
|
||||
await refreshMedia()
|
||||
} catch (e) {
|
||||
@@ -875,6 +795,7 @@ function ExerciseFormPage() {
|
||||
}
|
||||
|
||||
const updateVariantField = (id, patch) => {
|
||||
setFormDirty(true)
|
||||
setVariants((prev) => prev.map((v) => (v.id === id ? { ...v, ...patch } : v)))
|
||||
}
|
||||
|
||||
@@ -978,7 +899,18 @@ function ExerciseFormPage() {
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ marginLeft: '8px' }}
|
||||
onClick={() => navigate(`/exercises/${exerciseId}`)}
|
||||
onClick={() => {
|
||||
if (
|
||||
formDirty &&
|
||||
!window.confirm(
|
||||
'Es gibt noch nicht über „Speichern“ gesicherte Änderungen (Texte, Zuordnungen, …).\n\n' +
|
||||
'Zur Ansicht wechseln und diese Änderungen verwerfen?',
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
navigate(`/exercises/${exerciseId}`, { state: { fromExerciseEdit: true } })
|
||||
}}
|
||||
>
|
||||
Ansehen
|
||||
</button>
|
||||
@@ -1008,6 +940,9 @@ function ExerciseFormPage() {
|
||||
onChange={(html) => updateFormField('summary', html)}
|
||||
placeholder="Kurzbeschreibung (optional)"
|
||||
minHeight="80px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1018,6 +953,9 @@ function ExerciseFormPage() {
|
||||
onChange={(html) => updateFormField('goal', html)}
|
||||
placeholder="Trainingsziel"
|
||||
minHeight="120px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1028,6 +966,9 @@ function ExerciseFormPage() {
|
||||
onChange={(html) => updateFormField('execution', html)}
|
||||
placeholder="Ablauf Schritt für Schritt"
|
||||
minHeight="180px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1038,6 +979,9 @@ function ExerciseFormPage() {
|
||||
onChange={(html) => updateFormField('preparation', html)}
|
||||
placeholder="Matten, Raum, …"
|
||||
minHeight="100px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1048,6 +992,9 @@ function ExerciseFormPage() {
|
||||
onChange={(html) => updateFormField('trainer_notes', html)}
|
||||
placeholder="Sicherheit, Varianten-Hinweise, …"
|
||||
minHeight="100px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1243,7 +1190,7 @@ function ExerciseFormPage() {
|
||||
>
|
||||
<option value="private">Privat</option>
|
||||
<option value="club">Verein</option>
|
||||
<option value="official">Offiziell</option>
|
||||
{isSuperadmin ? <option value="official">Offiziell</option> : null}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
@@ -1339,9 +1286,15 @@ function ExerciseFormPage() {
|
||||
<h3 style={{ marginTop: 0, fontSize: '1rem' }}>Neue Variante</h3>
|
||||
<ExerciseVariantFields
|
||||
row={variantDraft}
|
||||
onPatch={(patch) => setVariantDraft((d) => ({ ...d, ...patch }))}
|
||||
onPatch={(patch) => {
|
||||
setFormDirty(true)
|
||||
setVariantDraft((d) => ({ ...d, ...patch }))
|
||||
}}
|
||||
prerequisiteOthers={variants}
|
||||
rteMinHeight="110px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '10px' }} disabled={variantBusy}>
|
||||
{variantBusy ? 'Anlegen…' : 'Variante anlegen'}
|
||||
@@ -1408,6 +1361,9 @@ function ExerciseFormPage() {
|
||||
onPatch={(patch) => updateVariantField(selectedVariantForEdit.id, patch)}
|
||||
prerequisiteOthers={variants.filter((o) => o.id !== selectedVariantForEdit.id)}
|
||||
rteMinHeight="110px"
|
||||
inlineExerciseId={isEdit ? exerciseId : null}
|
||||
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||
onExerciseMediaListChanged={refreshMedia}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1436,8 +1392,13 @@ function ExerciseFormPage() {
|
||||
{isEdit && (
|
||||
<div className="card" style={{ marginTop: '16px' }}>
|
||||
<h2 style={{ marginTop: 0, fontSize: '1.1rem' }}>Medien</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '13px' }}>
|
||||
Datei oder Embed (YouTube, Vimeo, Instagram, TikTok). Max. 10 pro Übung.
|
||||
<p style={{ color: 'var(--text2)', fontSize: '13px', marginBottom: '6px' }}>
|
||||
Neue Uploads oder Embeds über die Textfeld-Symbolleiste („Medien im Text“ / „Embed im Text“). Hier
|
||||
verwaltest du Verknüpfungen — Kachel in ein Textfeld ziehen, um sie an der Cursorposition einzufügen
|
||||
(mittlere Darstellung).
|
||||
</p>
|
||||
<p style={{ color: 'var(--text3)', fontSize: '12px', marginTop: 0 }}>
|
||||
Max. 10 Medien pro Übung.
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
@@ -1455,184 +1416,125 @@ function ExerciseFormPage() {
|
||||
Medienbibliothek
|
||||
</Link>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gap: '12px', marginTop: '12px' }}>
|
||||
<div>
|
||||
<label className="form-label">Datei</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,video/*,application/pdf"
|
||||
onChange={(e) => setMediaFile(e.target.files?.[0] || null)}
|
||||
/>
|
||||
<div className="form-row" style={{ marginTop: '8px' }}>
|
||||
<select className="form-input" value={mediaType} onChange={(e) => setMediaType(e.target.value)}>
|
||||
<option value="image">Bild</option>
|
||||
<option value="video">Video</option>
|
||||
<option value="document">PDF</option>
|
||||
</select>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="Titel (optional)"
|
||||
value={mediaTitle}
|
||||
onChange={(e) => setMediaTitle(e.target.value)}
|
||||
style={{ marginTop: '8px' }}
|
||||
/>
|
||||
<select
|
||||
className="form-input"
|
||||
value={mediaContext}
|
||||
onChange={(e) => setMediaContext(e.target.value)}
|
||||
style={{ marginTop: '8px' }}
|
||||
>
|
||||
<option value="ablauf">Ablauf</option>
|
||||
<option value="detail">Detail</option>
|
||||
<option value="trainer_hint">Trainer-Hinweis</option>
|
||||
</select>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" style={{ marginTop: '8px' }} onClick={handleUploadFile}>
|
||||
Hochladen
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label">Embed-URL</label>
|
||||
<input
|
||||
type="url"
|
||||
className="form-input"
|
||||
placeholder="https://…"
|
||||
value={embedUrl}
|
||||
onChange={(e) => setEmbedUrl(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="Titel (optional)"
|
||||
value={embedTitle}
|
||||
onChange={(e) => setEmbedTitle(e.target.value)}
|
||||
style={{ marginTop: '8px' }}
|
||||
/>
|
||||
<button type="button" className="btn btn-secondary" style={{ marginTop: '8px' }} onClick={handleAddEmbed}>
|
||||
Embed hinzufügen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{mediaList.length > 0 && (
|
||||
<ul style={{ marginTop: '12px', paddingLeft: '0', listStyle: 'none' }}>
|
||||
{mediaList.map((m, idx) => (
|
||||
<li
|
||||
key={m.id}
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '10px',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid var(--border)',
|
||||
display: 'flex',
|
||||
gap: '12px',
|
||||
alignItems: 'flex-start',
|
||||
}}
|
||||
>
|
||||
<ExerciseMediaThumbTile exerciseId={exerciseId} media={m} onOpenPreview={setMediaPreview} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
#{idx + 1} · {m.media_type}
|
||||
{m.embed_platform ? ` · ${m.embed_platform}` : ''}
|
||||
</span>
|
||||
{mediaList.length > 1 && (
|
||||
<>
|
||||
<ul className="exercise-edit-media-strip">
|
||||
{mediaList.map((m, idx) => {
|
||||
const cap =
|
||||
(m.title || '').trim() ||
|
||||
(m.original_filename || '').trim() ||
|
||||
(m.embed_url ? String(m.embed_url).replace(/^https?:\/\//i, '').slice(0, 80) : '')
|
||||
const sub = [m.media_type, m.embed_platform].filter(Boolean).join(' · ') || 'Medium'
|
||||
const payloadCaption = (
|
||||
[m.title, m.original_filename].find((x) => typeof x === 'string' && x.trim()) || ''
|
||||
).trim()
|
||||
return (
|
||||
<li key={m.id} className="exercise-edit-media-strip__item">
|
||||
<div className="exercise-edit-media-strip__lead">
|
||||
{!m.embed_url ? (
|
||||
<ExerciseMediaThumbTile exerciseId={exerciseId} media={m} onOpenPreview={setMediaPreview} size={76} />
|
||||
) : (
|
||||
<div
|
||||
className="exercise-edit-media-strip__embed-badge exercise-edit-media-strip__embed-badge--solo"
|
||||
aria-hidden
|
||||
>
|
||||
{m.embed_platform || 'Embed'}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="exercise-edit-media-strip__handle"
|
||||
title="Mit Drag und Drop in ein Textfeld ziehen"
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
try {
|
||||
e.dataTransfer.setData(
|
||||
SHINKAN_EXERCISE_MEDIA_DRAG_MIME,
|
||||
buildExerciseMediaDragPayload(m.id, payloadCaption),
|
||||
)
|
||||
e.dataTransfer.effectAllowed = 'copy'
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}}
|
||||
>
|
||||
⣿<span className="exercise-edit-media-strip__handle-text"> Ziehen</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="exercise-edit-media-strip__body">
|
||||
<div className="exercise-edit-media-strip__headline">
|
||||
<span style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
#{m.id} · {sub}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ fontSize: '13px', color: 'var(--text2)', lineHeight: 1.35 }}>{cap || '—'}</div>
|
||||
<div className="exercise-edit-media-strip__toolbar">
|
||||
<input
|
||||
type="text"
|
||||
className="form-input exercise-edit-media-strip__title"
|
||||
placeholder="Titel (wird in der Vorschau und im Platzhalter genutzt)"
|
||||
value={(mediaFields[m.id] || {}).title ?? ''}
|
||||
onChange={(e) =>
|
||||
setMediaFields((prev) => ({
|
||||
...prev,
|
||||
[m.id]: {
|
||||
title: e.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="exercise-edit-media-strip__actions">
|
||||
{mediaList.length > 1 && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '4px 8px' }}
|
||||
disabled={idx === 0}
|
||||
onClick={() => moveMediaRow(idx, -1)}
|
||||
title="Nach oben"
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '4px 8px' }}
|
||||
disabled={idx >= mediaList.length - 1}
|
||||
onClick={() => moveMediaRow(idx, 1)}
|
||||
title="Nach unten"
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '2px 8px' }}
|
||||
disabled={idx === 0}
|
||||
onClick={() => moveMediaRow(idx, -1)}
|
||||
title="Nach oben"
|
||||
className="btn btn-primary"
|
||||
style={{ fontSize: '12px', padding: '4px 10px' }}
|
||||
disabled={mediaSavingId === m.id}
|
||||
onClick={() => saveMediaMeta(m.id)}
|
||||
>
|
||||
↑
|
||||
{mediaSavingId === m.id ? '…' : 'Speichern'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '2px 8px' }}
|
||||
disabled={idx >= mediaList.length - 1}
|
||||
onClick={() => moveMediaRow(idx, 1)}
|
||||
title="Nach unten"
|
||||
style={{ fontSize: '12px', padding: '4px 10px' }}
|
||||
onClick={() => handleDeleteMedia(m.id)}
|
||||
>
|
||||
↓
|
||||
Entfernen
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: '12px',
|
||||
color: 'var(--text2)',
|
||||
marginTop: '6px',
|
||||
wordBreak: 'break-word',
|
||||
lineHeight: 1.35,
|
||||
}}
|
||||
>
|
||||
{(m.original_filename || '').trim() ||
|
||||
(m.title || '').trim() ||
|
||||
(m.embed_url ? m.embed_url : '') ||
|
||||
'—'}
|
||||
</div>
|
||||
<div className="form-row" style={{ marginTop: '8px', display: 'grid', gap: '8px' }}>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="Titel"
|
||||
value={(mediaFields[m.id] || {}).title ?? ''}
|
||||
onChange={(e) =>
|
||||
setMediaFields((prev) => ({
|
||||
...prev,
|
||||
[m.id]: { ...(prev[m.id] || {}), title: e.target.value, context: (prev[m.id] || {}).context || 'ablauf' },
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<select
|
||||
className="form-input"
|
||||
value={(mediaFields[m.id] || {}).context || 'ablauf'}
|
||||
onChange={(e) =>
|
||||
setMediaFields((prev) => ({
|
||||
...prev,
|
||||
[m.id]: {
|
||||
...(prev[m.id] || {}),
|
||||
title: (prev[m.id] || {}).title ?? '',
|
||||
context: e.target.value,
|
||||
},
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="ablauf">Ablauf</option>
|
||||
<option value="detail">Detail</option>
|
||||
<option value="trainer_hint">Trainer-Hinweis</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
style={{ fontSize: '12px' }}
|
||||
disabled={mediaSavingId === m.id}
|
||||
onClick={() => saveMediaMeta(m.id)}
|
||||
>
|
||||
{mediaSavingId === m.id ? 'Speichern…' : 'Titel & Sektion speichern'}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{
|
||||
marginTop: '8px',
|
||||
fontSize: '12px',
|
||||
padding: '6px 12px',
|
||||
}}
|
||||
onClick={() => handleDeleteMedia(m.id)}
|
||||
>
|
||||
Aus Übung entfernen
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
<p style={{ color: 'var(--text3)', fontSize: '12px', marginTop: mediaList.length ? '12px' : 0 }}>
|
||||
Verknüpfungen bleiben nötig (u. a. Zugriff, Orphan-Hinweise): Im Fließtext verweist du gezielt über
|
||||
Platzhalter. Ohne Verknüpfung gäbe es keine exercise_media-ID zum Einbetten.
|
||||
</p>
|
||||
{archiveOpen && (
|
||||
<div
|
||||
role="dialog"
|
||||
@@ -1669,16 +1571,6 @@ function ExerciseFormPage() {
|
||||
onChange={(e) => setArchiveQ(e.target.value)}
|
||||
style={{ marginBottom: '8px' }}
|
||||
/>
|
||||
<select
|
||||
className="form-input"
|
||||
value={archiveCtx}
|
||||
onChange={(e) => setArchiveCtx(e.target.value)}
|
||||
style={{ marginBottom: '12px' }}
|
||||
>
|
||||
<option value="ablauf">Sektion: Ablauf</option>
|
||||
<option value="detail">Sektion: Detail</option>
|
||||
<option value="trainer_hint">Sektion: Trainer-Hinweis</option>
|
||||
</select>
|
||||
{archiveLoading && <p style={{ fontSize: '13px', color: 'var(--text3)' }}>Laden…</p>}
|
||||
{archiveError && <p style={{ fontSize: '13px', color: 'var(--danger)' }}>{archiveError}</p>}
|
||||
{!archiveLoading && !archiveError && archiveItems.length === 0 && (
|
||||
|
||||
@@ -14,11 +14,13 @@ import {
|
||||
} from 'lucide-react'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
||||
import MultiSelectCombo from '../components/MultiSelectCombo'
|
||||
import ExerciseFocusRulePicker from '../components/ExerciseFocusRulePicker'
|
||||
import CatalogRulePicker from '../components/CatalogRulePicker'
|
||||
import ExerciseProgressionGraphPanel from '../components/ExerciseProgressionGraphPanel'
|
||||
import ExerciseRichTextBlock from '../components/ExerciseRichTextBlock'
|
||||
import PageSectionNav from '../components/PageSectionNav'
|
||||
import {
|
||||
INITIAL_EXERCISE_LIST_FILTERS,
|
||||
@@ -27,7 +29,7 @@ import {
|
||||
splitMnCatalogRules,
|
||||
splitScalarCatalogRules,
|
||||
} from '../constants/exerciseListFilters'
|
||||
import { sanitizeExerciseRichText, coerceApiNameList } from '../utils/sanitizeHtml'
|
||||
import { coerceApiNameList } from '../utils/sanitizeHtml'
|
||||
import { canUserRequestExerciseDelete } from '../utils/exercisePermissions'
|
||||
|
||||
const PAGE_SIZE = 100
|
||||
@@ -152,6 +154,7 @@ function applyDashboardExerciseListUrl(mergedFromPrefs) {
|
||||
function ExercisesListPage() {
|
||||
const { user, checkAuth } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [mineOnly, setMineOnly] = useState(() => {
|
||||
try {
|
||||
@@ -506,7 +509,7 @@ function ExercisesListPage() {
|
||||
|
||||
const clubNameById = useMemo(() => {
|
||||
const m = {}
|
||||
for (const c of user?.clubs || []) {
|
||||
for (const c of activeClubMemberships(user?.clubs)) {
|
||||
if (c?.id != null) m[Number(c.id)] = c.name || `#${c.id}`
|
||||
}
|
||||
return m
|
||||
@@ -557,9 +560,9 @@ function ExercisesListPage() {
|
||||
{ id: 'private', label: 'Privat' },
|
||||
{ id: 'club', label: 'Verein' },
|
||||
]
|
||||
if (isPlatformAdmin) base.push({ id: 'official', label: 'Offiziell (global)' })
|
||||
if (isSuperadmin) base.push({ id: 'official', label: 'Offiziell (global)' })
|
||||
return base
|
||||
}, [isPlatformAdmin])
|
||||
}, [isSuperadmin])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -1204,7 +1207,7 @@ function ExercisesListPage() {
|
||||
onChange={(e) => setBulkClubSelect(e.target.value)}
|
||||
>
|
||||
<option value="">Aktiver Verein (Vereins-Umschalter / Header)</option>
|
||||
{(user?.clubs || []).map((c) => (
|
||||
{activeClubMemberships(user?.clubs).map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name || `#${c.id}`}
|
||||
</option>
|
||||
@@ -1379,9 +1382,6 @@ function ExercisesListPage() {
|
||||
const focusNames = exerciseFocusNames(exercise)
|
||||
const styleNames = coerceApiNameList(exercise.style_direction_names)
|
||||
const typeNames = coerceApiNameList(exercise.training_type_names)
|
||||
const summaryHtml = exercise.summary
|
||||
? sanitizeExerciseRichText(exercise.summary)
|
||||
: ''
|
||||
return (
|
||||
<div key={exercise.id} className={exerciseCardClassName(exercise, user?.id)}>
|
||||
<div className="exercise-card-layout exercise-card-layout--grow">
|
||||
@@ -1409,11 +1409,14 @@ function ExercisesListPage() {
|
||||
<span key={`tt:${name}`} className="exercise-tag exercise-tag--training">{name}</span>
|
||||
))}
|
||||
</div>
|
||||
{summaryHtml ? (
|
||||
<div
|
||||
className="exercise-card-summary exercise-card-summary--rich"
|
||||
dangerouslySetInnerHTML={{ __html: summaryHtml }}
|
||||
/>
|
||||
{exercise.summary && String(exercise.summary).trim() ? (
|
||||
<div className="exercise-card-summary exercise-card-summary--rich">
|
||||
<ExerciseRichTextBlock
|
||||
html={exercise.summary}
|
||||
exerciseId={exercise.id}
|
||||
media={exercise.media || []}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { notifyOrgInboxChanged, useOrgInbox } from '../context/OrgInboxContext'
|
||||
|
||||
const CLUB_ROLE_OPTIONS = [
|
||||
{ code: 'club_admin', label: 'Vereinsadmin' },
|
||||
{ code: 'trainer', label: 'Trainer' },
|
||||
{ code: 'division_lead', label: 'Spartenleitung' },
|
||||
{ code: 'content_editor', label: 'Inhalte bearbeiten' },
|
||||
]
|
||||
|
||||
function formatWhen(iso) {
|
||||
if (!iso) return ''
|
||||
const s = String(iso)
|
||||
const d = s.includes('T') ? s.split('T')[0] : s.slice(0, 10)
|
||||
const t = s.includes('T') ? s.split('T')[1] : ''
|
||||
const time = t ? t.slice(0, 5) : ''
|
||||
return time ? `${d} · ${time}` : d
|
||||
}
|
||||
|
||||
export default function InboxPage() {
|
||||
const { canAccessOrgInbox, refreshOrgInbox, inboxJoinRequests } = useOrgInbox()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [acceptModal, setAcceptModal] = useState(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!canAccessOrgInbox) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
try {
|
||||
await refreshOrgInbox()
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [canAccessOrgInbox, refreshOrgInbox])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
if (!canAccessOrgInbox) {
|
||||
return (
|
||||
<div className="app-page">
|
||||
<h1 className="page-title">Posteingang</h1>
|
||||
<p className="muted">Kein Zugriff. Nur Plattform-Admins und Vereinsadmins sehen den Posteingang.</p>
|
||||
<p>
|
||||
<Link to="/">Zur Übersicht</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page inbox-page">
|
||||
<div className="inbox-page__header">
|
||||
<div>
|
||||
<h1 className="page-title" style={{ marginBottom: '6px' }}>
|
||||
Posteingang
|
||||
</h1>
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
Offene Beitrittsanträge zu Vereinen, für die du zuständig bist.
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => load()} disabled={loading}>
|
||||
Aktualisieren
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div style={{ padding: '2rem', textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
) : inboxJoinRequests.length === 0 ? (
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<p style={{ margin: 0 }} className="muted">
|
||||
Keine offenen Beitrittsanträge.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="inbox-page__list">
|
||||
{inboxJoinRequests.map((req) => (
|
||||
<div key={`${req.club_id}-${req.id}`} className="card inbox-request-card">
|
||||
<div className="inbox-request-card__main">
|
||||
<div className="inbox-request-card__club">
|
||||
{req.club_name || 'Verein'}
|
||||
{req.club_abbreviation ? (
|
||||
<span className="muted" style={{ marginLeft: '0.35rem' }}>
|
||||
({req.club_abbreviation})
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<strong className="inbox-request-card__applicant">
|
||||
{req.applicant_name || req.applicant_email || 'Bewerber/in'}
|
||||
</strong>
|
||||
<div className="muted inbox-request-card__meta">
|
||||
{req.applicant_email} · Profil #{req.profile_id} · {formatWhen(req.created_at)}
|
||||
</div>
|
||||
{req.message ? <p className="inbox-request-card__message">{req.message}</p> : null}
|
||||
</div>
|
||||
<div className="inbox-request-card__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() =>
|
||||
setAcceptModal({
|
||||
id: req.id,
|
||||
club_id: req.club_id,
|
||||
label: req.applicant_name || req.applicant_email,
|
||||
roles: ['trainer'],
|
||||
})
|
||||
}
|
||||
>
|
||||
Annehmen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={async () => {
|
||||
if (!confirm('Antrag ablehnen?')) return
|
||||
try {
|
||||
await api.rejectClubJoinRequest(req.club_id, req.id)
|
||||
notifyOrgInboxChanged()
|
||||
await load()
|
||||
} catch (err) {
|
||||
alert(err.message || String(err))
|
||||
}
|
||||
}}
|
||||
>
|
||||
Ablehnen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{acceptModal && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1100,
|
||||
padding: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: '1.5rem',
|
||||
maxWidth: '480px',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginTop: 0 }}>Antrag annehmen</h2>
|
||||
<p style={{ color: 'var(--text2)' }}>{acceptModal.label}</p>
|
||||
<div className="form-row">
|
||||
<span className="form-label">Rollen bei Aufnahme</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
||||
{CLUB_ROLE_OPTIONS.map((opt) => (
|
||||
<label key={opt.code} style={{ display: 'flex', alignItems: 'center', gap: '0.35rem' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={acceptModal.roles.includes(opt.code)}
|
||||
onChange={() => {
|
||||
setAcceptModal((prev) => {
|
||||
if (!prev) return prev
|
||||
const set = new Set(prev.roles)
|
||||
if (set.has(opt.code)) set.delete(opt.code)
|
||||
else set.add(opt.code)
|
||||
const roles = Array.from(set)
|
||||
return { ...prev, roles: roles.length ? roles : ['trainer'] }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
{opt.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await api.acceptClubJoinRequest(
|
||||
acceptModal.club_id,
|
||||
acceptModal.id,
|
||||
acceptModal.roles.length ? acceptModal.roles : ['trainer']
|
||||
)
|
||||
setAcceptModal(null)
|
||||
notifyOrgInboxChanged()
|
||||
await load()
|
||||
} catch (err) {
|
||||
alert(err.message || String(err))
|
||||
}
|
||||
}}
|
||||
>
|
||||
Aufnehmen
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setAcceptModal(null)}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, useCallback, useRef } from 'react'
|
||||
import { useEffect, useState, useCallback, useRef, useMemo } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
LayoutGrid,
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||
|
||||
const LC_OPTIONS = [
|
||||
@@ -234,6 +234,12 @@ export default function MediaLibraryPage() {
|
||||
const { user } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const hasClubOrgAdmin = activeClubMemberships(user?.clubs).some((c) => (c.roles || []).includes('club_admin'))
|
||||
|
||||
const archiveVisOptions = useMemo(
|
||||
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
||||
[isSuperadmin],
|
||||
)
|
||||
|
||||
const [lifecycle, setLifecycle] = useState('active')
|
||||
const [q, setQ] = useState('')
|
||||
@@ -265,6 +271,25 @@ export default function MediaLibraryPage() {
|
||||
const mediaListFetchSeqRef = useRef(0)
|
||||
const gridTopAnchorRef = useRef(null)
|
||||
|
||||
const modalVisibilityOptions = useMemo(() => {
|
||||
if (!modalDraft) return archiveVisOptions
|
||||
const o = [...archiveVisOptions]
|
||||
if (!o.some((x) => x.value === modalDraft.visibility)) {
|
||||
o.push({
|
||||
value: modalDraft.visibility,
|
||||
label: visibilityUiLabel(modalDraft.visibility),
|
||||
})
|
||||
}
|
||||
return o
|
||||
}, [archiveVisOptions, modalDraft])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return
|
||||
const cid = user?.effective_club_id ?? user?.active_club_id
|
||||
if (cid == null || cid === '') return
|
||||
setUploadClubId(String(cid))
|
||||
}, [isSuperadmin, user?.effective_club_id, user?.active_club_id])
|
||||
|
||||
const loadClubs = useCallback(async () => {
|
||||
try {
|
||||
const c = await api.listClubs()
|
||||
@@ -374,7 +399,7 @@ export default function MediaLibraryPage() {
|
||||
}
|
||||
if (p.change_visibility) {
|
||||
body.visibility = modalDraft.visibility
|
||||
if (modalDraft.visibility === 'club') {
|
||||
if (modalDraft.visibility === 'club' || (modalDraft.visibility === 'private' && isPlatformAdmin)) {
|
||||
const cid = Number(modalDraft.club_id)
|
||||
if (!cid) {
|
||||
alert('Bitte einen Verein wählen.')
|
||||
@@ -421,7 +446,7 @@ export default function MediaLibraryPage() {
|
||||
}
|
||||
if (bulkApplyVis) {
|
||||
body.visibility = bulkVis
|
||||
if (bulkVis === 'club') {
|
||||
if (bulkVis === 'club' || (bulkVis === 'private' && isPlatformAdmin)) {
|
||||
const cid = Number(bulkClubId)
|
||||
if (!cid) {
|
||||
alert('Bitte einen Verein wählen.')
|
||||
@@ -482,12 +507,18 @@ export default function MediaLibraryPage() {
|
||||
window.alert('Bitte einen Verein für die Sichtbarkeit „Verein“ wählen.')
|
||||
return
|
||||
}
|
||||
if (uploadVis === 'private' && isPlatformAdmin && !Number(uploadClubId)) {
|
||||
window.alert('Als Plattform-Admin: Bitte den Zielverein für private Archiv-Uploads wählen (club_id).')
|
||||
return
|
||||
}
|
||||
setUploadBusy(true)
|
||||
setUploadSummary('')
|
||||
try {
|
||||
const res = await api.bulkUploadMediaAssets(list, {
|
||||
visibility: uploadVis,
|
||||
...(uploadVis === 'club' ? { club_id: Number(uploadClubId) } : {}),
|
||||
...((uploadVis === 'club' || (uploadVis === 'private' && isPlatformAdmin)) && Number(uploadClubId)
|
||||
? { club_id: Number(uploadClubId) }
|
||||
: {}),
|
||||
})
|
||||
setUploadSummary(
|
||||
`Archiv-Upload: neu ${res.created_count}, bereits vorhanden ${res.duplicate_count}, fehlgeschlagen ${res.failed_count}. Liste aktualisiert.`,
|
||||
@@ -508,21 +539,23 @@ export default function MediaLibraryPage() {
|
||||
|
||||
return (
|
||||
<div className="app-page media-library">
|
||||
{isPlatformAdmin ? <AdminPageNav /> : null}
|
||||
|
||||
<div className="media-library__container">
|
||||
<header className="media-library__hero">
|
||||
<div className="media-library__hero-row">
|
||||
<h1 className="media-library__title">Medienbibliothek</h1>
|
||||
<div className="media-library__hero-links">
|
||||
<Link to="/">Übersicht</Link>
|
||||
<Link to="/exercises">Übungen</Link>
|
||||
{isPlatformAdmin ? <Link to="/admin/hierarchy">Admin</Link> : null}
|
||||
{isSuperadmin ? <Link to="/admin">Globale Administration</Link> : null}
|
||||
{hasClubOrgAdmin ? <Link to="/clubs">Vereine & Mitglieder</Link> : null}
|
||||
</div>
|
||||
</div>
|
||||
<p className="media-library__intro">
|
||||
Veröffentlichte Medien (Verein/Plattform) und eigene Uploads. Suche durchsucht Bezeichner,
|
||||
technischen Speicherpfad, Copyright-Text und Schlagwörter. Vorschau: Vorschaubild antippen.
|
||||
Bearbeiten über das Menü — Bulk in der unteren Leiste.
|
||||
Offizielle und vereinsfreigegebene Medien sind für alle passenden Nutzer sichtbar. Eigene private Medien
|
||||
kannst du bearbeiten, veröffentlichen oder in den Papierkorb legen; im Papierkorb siehst du als Standardnutzer
|
||||
nur deine eigenen privaten Objekte, als Vereinsadmin zusätzlich den Vereins-Papierkorb. Vereins-Rollen können
|
||||
Vereins-Medien verwalten, aber nicht bis „Offiziell“ anheben — das bleibt dem Superadmin vorbehalten.
|
||||
Plattform-Admins geben beim privaten Upload den Zielverein an (club_id).
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -647,13 +680,13 @@ export default function MediaLibraryPage() {
|
||||
}}
|
||||
aria-label="Sichtbarkeit für neuen Upload"
|
||||
>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{archiveVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
Upload: {o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{uploadVis === 'club' ? (
|
||||
{uploadVis === 'club' || (uploadVis === 'private' && isPlatformAdmin) ? (
|
||||
<select
|
||||
className="form-input"
|
||||
value={uploadClubId}
|
||||
@@ -969,13 +1002,13 @@ export default function MediaLibraryPage() {
|
||||
{bulkApplyVis ? (
|
||||
<>
|
||||
<select className="form-input" value={bulkVis} onChange={(e) => setBulkVis(e.target.value)}>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{archiveVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{bulkVis === 'club' ? (
|
||||
{bulkVis === 'club' || (bulkVis === 'private' && isPlatformAdmin) ? (
|
||||
<select className="form-input" value={bulkClubId} onChange={(e) => setBulkClubId(e.target.value)}>
|
||||
<option value="">— Verein —</option>
|
||||
{clubs.map((c) => (
|
||||
@@ -1025,13 +1058,20 @@ export default function MediaLibraryPage() {
|
||||
<div className="media-library__overlay" role="dialog" aria-modal="true" aria-labelledby="edit-media-title">
|
||||
<div className="media-library__modal">
|
||||
<div className="media-library__modal-head">
|
||||
<h2 id="edit-media-title">Medium #{modal.id}</h2>
|
||||
<h2 id="edit-media-title">
|
||||
Medium #{modal.id}
|
||||
{(modal.visibility || '').toLowerCase() === 'official' && !isSuperadmin
|
||||
? ' · Nur Lesen'
|
||||
: ''}
|
||||
</h2>
|
||||
<button type="button" className="media-library__icon-btn" onClick={closeModal} aria-label="Schließen">
|
||||
<X size={22} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="media-library__modal-body">
|
||||
{(viewer?.show_club_meta || viewer?.show_uploader_meta) && (
|
||||
{(viewer?.show_club_meta ||
|
||||
viewer?.show_uploader_meta ||
|
||||
(modal.visibility || '').toLowerCase() === 'official') && (
|
||||
<div className="media-library__meta-block">
|
||||
{viewer?.show_club_meta ? (
|
||||
<div>
|
||||
@@ -1078,6 +1118,18 @@ export default function MediaLibraryPage() {
|
||||
placeholder="z. B. Technik, Wurf"
|
||||
/>
|
||||
</>
|
||||
) : (modal.visibility || '').toLowerCase() === 'official' ? (
|
||||
<>
|
||||
<p className="media-library__hint">
|
||||
Offizielle Medien sind für alle sichtbar. Bearbeiten, Sichtbarkeit und Löschung nur als Superadmin.
|
||||
</p>
|
||||
<label className="form-label">Bezeichnung</label>
|
||||
<input className="form-input" readOnly value={modalDraft.display_name} />
|
||||
<label className="form-label">Copyright</label>
|
||||
<textarea className="form-input" readOnly rows={3} value={modalDraft.copyright_notice} />
|
||||
<label className="form-label">Schlagwörter</label>
|
||||
<input className="form-input" readOnly value={modalDraft.tags_input} />
|
||||
</>
|
||||
) : (
|
||||
<p className="media-library__hint">Keine Berechtigung für Metadaten — nur Verwaltende dieser Stufe.</p>
|
||||
)}
|
||||
@@ -1090,13 +1142,13 @@ export default function MediaLibraryPage() {
|
||||
value={modalDraft.visibility}
|
||||
onChange={(e) => setModalDraft((d) => ({ ...d, visibility: e.target.value }))}
|
||||
>
|
||||
{VIS_OPTIONS.map((o) => (
|
||||
{modalVisibilityOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{modalDraft.visibility === 'club' ? (
|
||||
{modalDraft.visibility === 'club' || (modalDraft.visibility === 'private' && isPlatformAdmin) ? (
|
||||
<>
|
||||
<label className="form-label">Verein</label>
|
||||
<select
|
||||
@@ -1131,9 +1183,11 @@ export default function MediaLibraryPage() {
|
||||
</div>
|
||||
|
||||
<div className="media-library__modal-actions">
|
||||
<button type="button" className="btn btn-secondary" disabled={busy} onClick={saveModal}>
|
||||
Speichern
|
||||
</button>
|
||||
{modal.permissions?.edit_metadata ? (
|
||||
<button type="button" className="btn btn-secondary" disabled={busy} onClick={saveModal}>
|
||||
Speichern
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="media-library__lc-block">
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'
|
||||
import { Link, useSearchParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { activeClubMemberships } from '../utils/activeClub'
|
||||
import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
||||
@@ -284,13 +285,13 @@ function TrainingPlanningPage() {
|
||||
const r = (user?.role || '').toLowerCase()
|
||||
if (r === 'admin' || r === 'superadmin') return true
|
||||
if (selectedGroupClubIdMemo == null || !Number.isFinite(selectedGroupClubIdMemo)) return false
|
||||
const row = (user?.clubs || []).find((c) => Number(c.id) === selectedGroupClubIdMemo)
|
||||
const row = activeClubMemberships(user?.clubs).find((c) => Number(c.id) === selectedGroupClubIdMemo)
|
||||
return Array.isArray(row?.roles) && row.roles.includes('club_admin')
|
||||
}, [user?.role, user?.clubs, selectedGroupClubIdMemo])
|
||||
|
||||
const clubAdminClubIdSet = useMemo(() => {
|
||||
const ids = []
|
||||
for (const c of user?.clubs || []) {
|
||||
for (const c of activeClubMemberships(user?.clubs)) {
|
||||
if (Array.isArray(c.roles) && c.roles.includes('club_admin')) {
|
||||
const id = Number(c.id)
|
||||
if (Number.isFinite(id)) ids.push(id)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ACTIVE_CLUB_STORAGE_KEY } from './api'
|
||||
|
||||
/** Nur Mitgliedschaften mit aktivem Vereinszugang (Backend: club_members.status). */
|
||||
export function activeClubMemberships(clubs) {
|
||||
return (clubs || []).filter(
|
||||
(c) => (c.membership_status || 'active').toString().trim().toLowerCase() === 'active'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Einheitliche Anzeige des aktiven Vereins: Abgleich mit effective_club_id, active_club_id,
|
||||
* LocalStorage (Request-Header-Quelle), sonst erster **aktiver** Verein der Liste.
|
||||
*/
|
||||
export function getResolvedActiveClubIdForUi(user) {
|
||||
const clubs = activeClubMemberships(user?.clubs)
|
||||
if (!clubs.length) return null
|
||||
|
||||
const idInClubs = (id) =>
|
||||
id != null &&
|
||||
id !== '' &&
|
||||
clubs.some((c) => Number(c.id) === Number(id))
|
||||
|
||||
const eff = user?.effective_club_id
|
||||
if (idInClubs(eff)) return Number(eff)
|
||||
|
||||
const ac = user?.active_club_id
|
||||
if (idInClubs(ac)) return Number(ac)
|
||||
|
||||
try {
|
||||
const ls = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
if (ls && /^\d+$/.test(ls.trim()) && clubs.some((c) => String(c.id) === ls.trim())) {
|
||||
return Number(ls.trim())
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
return Number(clubs[0].id)
|
||||
}
|
||||
@@ -139,6 +139,21 @@ export async function updateProfile(profileId, data) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Passwort anderer Konten: Standard leerer Body → E-Mail mit Reset-Link (wie Passwort vergessen).
|
||||
* Nur Super-Admins dürfen `newPassword` setzen (direktes Überschreiben des Passwort-Hashes).
|
||||
*/
|
||||
export async function managementPasswordReset(profileId, newPassword = null) {
|
||||
const body = {}
|
||||
if (newPassword != null && String(newPassword).trim() !== '') {
|
||||
body.new_password = newPassword
|
||||
}
|
||||
return request(`/api/profiles/${profileId}/management-password-reset`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function changePassword(newPassword) {
|
||||
return request('/api/auth/pin', {
|
||||
method: 'PUT',
|
||||
@@ -264,6 +279,11 @@ export async function rejectClubJoinRequest(clubId, requestId) {
|
||||
})
|
||||
}
|
||||
|
||||
/** Aggregierter Posteingang: offene Beitrittsanträge für Vereins-/Plattform-Admins. */
|
||||
export async function getInboxJoinRequests() {
|
||||
return request('/api/me/inbox/join-requests')
|
||||
}
|
||||
|
||||
export async function listDivisions(clubId) {
|
||||
const query = clubId ? `?club_id=${clubId}` : ''
|
||||
return request(`/api/divisions${query}`)
|
||||
@@ -472,8 +492,14 @@ export async function uploadExerciseMedia(exerciseId, formData) {
|
||||
body: formData,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({ detail: 'Unknown error' }))
|
||||
const d = err.detail
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const d = parsed?.detail
|
||||
if (
|
||||
response.status === 409 &&
|
||||
d &&
|
||||
@@ -489,6 +515,14 @@ export async function uploadExerciseMedia(exerciseId, formData) {
|
||||
e.payload = d
|
||||
throw e
|
||||
}
|
||||
if (response.status === 413) {
|
||||
const nginx = (text || '').toLowerCase().includes('nginx')
|
||||
throw new Error(
|
||||
nginx
|
||||
? 'Die Anfrage ist zu groß (413). Häufig: nginx „client_max_body_size“ — z. B. große/r mehrere Videos oder Bulk-Upload. Dateien kleiner aufteilen oder Server-Limit erhöhen (Frontend-Image Neu bauen).'
|
||||
: 'Die Anfrage ist zu groß (413). Dateigröße oder Server-Limit prüfen.',
|
||||
)
|
||||
}
|
||||
const msg =
|
||||
typeof d === 'string'
|
||||
? d
|
||||
@@ -496,7 +530,9 @@ export async function uploadExerciseMedia(exerciseId, formData) {
|
||||
? d.message
|
||||
: d != null
|
||||
? JSON.stringify(d)
|
||||
: `HTTP ${response.status}`
|
||||
: text && text.length < 400 && !/^\s*</.test(text)
|
||||
? `HTTP ${response.status}: ${text.trim()}`
|
||||
: `HTTP ${response.status}`
|
||||
throw new Error(msg)
|
||||
}
|
||||
return response.json()
|
||||
@@ -1287,6 +1323,7 @@ export const api = {
|
||||
listProfiles,
|
||||
listAdminUsers,
|
||||
updateProfile,
|
||||
managementPasswordReset,
|
||||
changePassword,
|
||||
verifyEmail,
|
||||
resendVerification,
|
||||
@@ -1310,6 +1347,7 @@ export const api = {
|
||||
listClubJoinRequests,
|
||||
acceptClubJoinRequest,
|
||||
rejectClubJoinRequest,
|
||||
getInboxJoinRequests,
|
||||
listDivisions,
|
||||
createDivision,
|
||||
updateDivision,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Während eines Drags automatischen Bildlauf auslösen (Viewport + scrollbare Bereiche unter dem Cursor).
|
||||
* @param {DragEvent} e
|
||||
* @param {{ edgePx?: number, scrollStep?: number }} [opts]
|
||||
*/
|
||||
export function autoScrollForDragNearEdges(e, opts = {}) {
|
||||
const edge = opts.edgePx ?? 80
|
||||
const step = opts.scrollStep ?? Math.max(24, Math.round(window.innerHeight * 0.05))
|
||||
const { clientX, clientY } = e
|
||||
|
||||
const vh = window.innerHeight || 0
|
||||
const vw = window.innerWidth || 0
|
||||
|
||||
let sy =
|
||||
clientY < edge ? -step : vh > 0 && clientY > vh - edge ? step : 0
|
||||
let sx =
|
||||
clientX < edge ? -step : vw > 0 && clientX > vw - edge ? step : 0
|
||||
|
||||
if (sy !== 0) window.scrollBy(0, sy)
|
||||
if (sx !== 0) window.scrollBy(sx, 0)
|
||||
|
||||
/** @type {HTMLElement|null} */
|
||||
let top = /** @type {HTMLElement|null} */ (document.elementFromPoint(clientX, clientY))
|
||||
|
||||
/** @type {Set<HTMLElement>} */
|
||||
const done = new Set()
|
||||
|
||||
/** @type {HTMLElement|null} */
|
||||
let walk = top
|
||||
const innerEdge = Math.min(edge, 40)
|
||||
|
||||
while (walk && walk !== document.body) {
|
||||
if (!(walk instanceof HTMLElement)) break
|
||||
|
||||
const cs = window.getComputedStyle(walk)
|
||||
const canY =
|
||||
walk.scrollHeight - walk.clientHeight > 6 &&
|
||||
(cs.overflowY === 'auto' || cs.overflowY === 'scroll')
|
||||
const canX =
|
||||
walk.scrollWidth - walk.clientWidth > 6 &&
|
||||
(cs.overflowX === 'auto' || cs.overflowX === 'scroll')
|
||||
|
||||
if ((canY || canX) && !done.has(walk)) {
|
||||
done.add(walk)
|
||||
const rect = walk.getBoundingClientRect()
|
||||
|
||||
const relY = clientY - rect.top
|
||||
const relX = clientX - rect.left
|
||||
|
||||
if (canY) {
|
||||
if (relY < innerEdge && walk.scrollTop > 0) walk.scrollTop -= step
|
||||
else if (rect.height - relY < innerEdge && walk.scrollTop < walk.scrollHeight - walk.clientHeight) {
|
||||
walk.scrollTop += step
|
||||
}
|
||||
}
|
||||
if (canX) {
|
||||
if (relX < innerEdge && walk.scrollLeft > 0) walk.scrollLeft -= step
|
||||
else if (rect.width - relX < innerEdge && walk.scrollLeft < walk.scrollWidth - walk.clientWidth) {
|
||||
walk.scrollLeft += step
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk = walk.parentElement
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* §11 Inline-Medien: aus HTML / Übungsobjekt referenzierte exercise_media-IDs sammeln.
|
||||
*/
|
||||
|
||||
const DATA_ATTR_RE = /data-shinkan-exercise-media\s*=\s*["']?(\d+)/gi
|
||||
|
||||
export const SHINKAN_EXERCISE_MEDIA_DRAG_MIME = 'application/x-shinkan-exercise-media'
|
||||
|
||||
/**
|
||||
* @param {string|null|undefined} html
|
||||
* @returns {Set<number>}
|
||||
*/
|
||||
export function collectInlineExerciseMediaIdsFromHtml(html) {
|
||||
const ids = new Set()
|
||||
if (!html || typeof html !== 'string') return ids
|
||||
let m
|
||||
const re = new RegExp(DATA_ATTR_RE.source, 'gi')
|
||||
while ((m = re.exec(html)) !== null) {
|
||||
const n = parseInt(m[1], 10)
|
||||
if (Number.isFinite(n) && n > 0) ids.add(n)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
const EXERCISE_RTF_FIELDS = ['summary', 'goal', 'execution', 'preparation', 'trainer_notes']
|
||||
|
||||
/**
|
||||
* HTML-Schnipsel aus Übung + Varianten-Fließtext für Inline-Scan.
|
||||
* @param {object|null|undefined} exercise
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function gatherExerciseHtmlSlicesForInlineScan(exercise) {
|
||||
if (!exercise || typeof exercise !== 'object') return []
|
||||
const slices = []
|
||||
for (const f of EXERCISE_RTF_FIELDS) {
|
||||
const html = exercise[f]
|
||||
if (typeof html === 'string' && html.trim()) slices.push(html)
|
||||
}
|
||||
for (const v of exercise.variants || []) {
|
||||
const ec = v?.execution_changes
|
||||
if (typeof ec === 'string' && ec.trim()) slices.push(ec)
|
||||
}
|
||||
return slices
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle im Fließtext eingebetteten exercise_media-IDs (Übung + Varianten).
|
||||
* @param {object|null|undefined} exercise
|
||||
* @returns {Set<number>}
|
||||
*/
|
||||
export function collectInlineExerciseMediaIdsFromExercise(exercise) {
|
||||
const ids = new Set()
|
||||
for (const html of gatherExerciseHtmlSlicesForInlineScan(exercise)) {
|
||||
collectInlineExerciseMediaIdsFromHtml(html).forEach((id) => ids.add(id))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} exerciseMediaId
|
||||
* @param {string} [caption]
|
||||
*/
|
||||
export function buildExerciseMediaDragPayload(exerciseMediaId, caption = '') {
|
||||
return JSON.stringify({
|
||||
exerciseMediaId: Number(exerciseMediaId),
|
||||
caption: typeof caption === 'string' ? caption : '',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} raw
|
||||
* @returns {{ exerciseMediaId: number, caption: string }|null}
|
||||
*/
|
||||
export function parseExerciseMediaDragPayload(raw) {
|
||||
if (!raw || typeof raw !== 'string') return null
|
||||
try {
|
||||
const o = JSON.parse(raw)
|
||||
const id = Number(o.exerciseMediaId)
|
||||
if (!Number.isFinite(id) || id < 1) return null
|
||||
const caption = typeof o.caption === 'string' ? o.caption : ''
|
||||
return { exerciseMediaId: id, caption }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { activeClubMemberships } from './activeClub'
|
||||
|
||||
function userIsClubAdminForClub(user, clubId) {
|
||||
if (clubId == null || user == null) return false
|
||||
const cid = Number(clubId)
|
||||
const row = (user.clubs || []).find((c) => Number(c.id) === cid)
|
||||
const row = activeClubMemberships(user.clubs).find((c) => Number(c.id) === cid)
|
||||
return Array.isArray(row?.roles) && row.roles.includes('club_admin')
|
||||
}
|
||||
|
||||
function userHasAnyClubAdminRole(user) {
|
||||
return (user?.clubs || []).some((c) => Array.isArray(c.roles) && c.roles.includes('club_admin'))
|
||||
return activeClubMemberships(user?.clubs).some((c) => Array.isArray(c.roles) && c.roles.includes('club_admin'))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Sanitizer für Übungs-Rich-HTML inkl. §11 Platzhalter (span data-shinkan-exercise-media).
|
||||
* Restriktiver als sanitizeTrainerHtml: Allowlist für XSS-Minimierung.
|
||||
*/
|
||||
|
||||
import { sanitizeInlineMediaCaption } from './inlineMediaCaption'
|
||||
|
||||
const ALLOWED_BLOCK = new Set(['p', 'div', 'br', 'ul', 'ol', 'li', 'h3'])
|
||||
const ALLOWED_INLINE = new Set(['b', 'strong', 'i', 'em', 'u', 'span', 'a'])
|
||||
|
||||
function isHttpsUrl(val) {
|
||||
if (!val || typeof val !== 'string') return false
|
||||
const s = val.trim()
|
||||
return s.startsWith('http://') || s.startsWith('https://')
|
||||
}
|
||||
|
||||
/** Nur für unsere Embed-Markierung: erlaubt data-attribut und optionale Marker-Klasse + Größe. */
|
||||
const _SIZE_OK = new Set(['small', 'medium', 'full'])
|
||||
function isInlineExerciseMediaPlaceholderSpan(el) {
|
||||
if (!el?.getAttribute || el.tagName.toLowerCase() !== 'span') return false
|
||||
const raw = el.getAttribute('data-shinkan-exercise-media')
|
||||
if (!raw || !String(raw).trim().match(/^\d+$/)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function sanitizeAttributes(el, tagLower) {
|
||||
if (tagLower === 'a') {
|
||||
const href = el.getAttribute('href')
|
||||
if (href && isHttpsUrl(href)) {
|
||||
const out = document.createElement('a')
|
||||
out.setAttribute('href', href.trim())
|
||||
return out.attributes
|
||||
}
|
||||
return []
|
||||
}
|
||||
if (tagLower === 'span' && isInlineExerciseMediaPlaceholderSpan(el)) {
|
||||
const out = document.createElement('span')
|
||||
out.setAttribute('data-shinkan-exercise-media', el.getAttribute('data-shinkan-exercise-media').trim())
|
||||
const sz = (el.getAttribute('data-shinkan-exercise-media-size') || '').trim().toLowerCase()
|
||||
if (sz && _SIZE_OK.has(sz)) {
|
||||
out.setAttribute('data-shinkan-exercise-media-size', sz)
|
||||
}
|
||||
const capRaw = el.getAttribute('data-shinkan-exercise-media-caption')
|
||||
if (capRaw != null && String(capRaw).trim()) {
|
||||
const cap = sanitizeInlineMediaCaption(String(capRaw))
|
||||
if (cap) out.setAttribute('data-shinkan-exercise-media-caption', cap)
|
||||
}
|
||||
const cls = (el.getAttribute('class') || '').trim().split(/\s+/).filter(Boolean)
|
||||
const keep = cls.filter((c) => c === 'shinkan-inline-media')
|
||||
if (keep.length) out.setAttribute('class', keep.join(' '))
|
||||
return out.attributes
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function cloneAsAllowed(tagLower, el) {
|
||||
const fresh = document.createElement(tagLower)
|
||||
const attrs = sanitizeAttributes(el, tagLower)
|
||||
for (const a of attrs) {
|
||||
fresh.setAttribute(a.name, a.value)
|
||||
}
|
||||
return fresh
|
||||
}
|
||||
|
||||
function cleanTree(parent) {
|
||||
const nodes = Array.from(parent.childNodes)
|
||||
for (const node of nodes) {
|
||||
if (node.nodeType === Node.TEXT_NODE) continue
|
||||
if (node.nodeType === Node.COMMENT_NODE) {
|
||||
parent.removeChild(node)
|
||||
continue
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) {
|
||||
parent.removeChild(node)
|
||||
continue
|
||||
}
|
||||
const tag = node.tagName.toLowerCase()
|
||||
if (tag === 'script' || tag === 'iframe' || tag === 'object' || tag === 'embed') {
|
||||
parent.removeChild(node)
|
||||
continue
|
||||
}
|
||||
if (ALLOWED_BLOCK.has(tag) || ALLOWED_INLINE.has(tag)) {
|
||||
const repl = cloneAsAllowed(tag, node)
|
||||
while (node.firstChild) {
|
||||
repl.appendChild(node.firstChild)
|
||||
}
|
||||
cleanTree(repl)
|
||||
parent.replaceChild(repl, node)
|
||||
continue
|
||||
}
|
||||
while (node.firstChild) {
|
||||
parent.insertBefore(node.firstChild, node)
|
||||
}
|
||||
parent.removeChild(node)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|null|undefined} html
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sanitizeExerciseRichDisplayHtml(html) {
|
||||
if (html == null || typeof html !== 'string') return ''
|
||||
const trimmed = html.trim()
|
||||
if (!trimmed) return ''
|
||||
|
||||
const tpl = document.createElement('template')
|
||||
tpl.innerHTML = trimmed
|
||||
cleanTree(tpl.content)
|
||||
return tpl.innerHTML
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const MAX_CAPTION = 120
|
||||
|
||||
/**
|
||||
* Für data-shinkan-exercise-media-caption: kurz, ohne Anführungszeichen/HTML.
|
||||
* @param {string|null|undefined} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sanitizeInlineMediaCaption(raw) {
|
||||
if (raw == null || typeof raw !== 'string') return ''
|
||||
let s = raw
|
||||
.replace(/[\u0000-\u001F\u007F]/g, ' ')
|
||||
.replace(/["'`<>]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
if (s.length > MAX_CAPTION) s = s.slice(0, MAX_CAPTION)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Portal-/Plattformrollen auf Profil-Ebene mit besonderem Schutz (Passwort-/Rechte-Angriffsfläche). */
|
||||
export function isEscalatedPortalRole(role) {
|
||||
const r = (role || 'user').toLowerCase()
|
||||
return r === 'admin' || r === 'superadmin'
|
||||
}
|
||||
Reference in new issue
Block a user