Compare commits
21
Commits
f035b5bb0b
...
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 |
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
# Shinkan Jinkendo - Projekt-Status
|
# Shinkan Jinkendo - Projekt-Status
|
||||||
|
|
||||||
**Stand:** 2026-05-07
|
**Stand:** 2026-05-08
|
||||||
**Version (Code):** 0.8.59 (`backend/version.py`, APP_VERSION)
|
**Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
|
||||||
**DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
|
**DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||||
**Branch:** develop
|
**Branch:** develop
|
||||||
|
|
||||||
@@ -9,21 +9,21 @@
|
|||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
|
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (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`**.
|
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||||
|
|
||||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, Planung)
|
**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** (Stand 2026-05-07, für **neue Session**):
|
**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).
|
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
|
||||||
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
|
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.
|
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.
|
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
|
||||||
5. **Inline-Medien im Fließtext** (Spec **§11**) — nächste inhaltliche Ausbaustufe: Platzhalter-Syntax, ein zentraler Renderer, keine zweite Governance; Archiv-Basis ist gelegt.
|
5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
|
||||||
|
|
||||||
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung bewusst nach stabiler Archiv-/Governance-Basis.
|
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -107,7 +107,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
|||||||
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
|
- [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:** 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:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
|
||||||
- [ ] **Medien:** Inline im Fließtext — Spec §11 (nächste Session / Backlog)
|
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
|
||||||
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
|
||||||
- [ ] Responsive Design / Dark Mode / PWA
|
- [ ] Responsive Design / Dark Mode / PWA
|
||||||
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
|
||||||
@@ -150,17 +150,17 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
| Dokument | Pfad | Stand | Status |
|
| Dokument | Pfad | Stand | Status |
|
||||||
|----------|------|-------|--------|
|
|----------|------|-------|--------|
|
||||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-07 | ✅ Aktualisiert (§12 Medien 0.8.41–0.8.59) |
|
| 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 |
|
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
|
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
|
||||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-07 | ✅ Abschnitt Medien-Archiv |
|
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-07 | ✅ Abschnitt Medien-Archiv |
|
||||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-30 | ✅ Ergänzt Progressions-API |
|
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
||||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
||||||
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
||||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
| 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-07 | ✅ Ist-Changelog + §11 Inline geplant |
|
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-07 | ✅ Medien + Tenant-Dropdown |
|
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -171,4 +171,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Letzte Aktualisierung:** 2026-05-07 (Medien-Doku abgestimmt, §12 FEATURES, Handover)
|
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Shinkan Jinkendo - Fachliches Domänenmodell
|
# Shinkan Jinkendo - Fachliches Domänenmodell
|
||||||
|
|
||||||
**Version:** 0.4.4
|
**Version:** 0.4.4
|
||||||
**Stand:** 2026-05-07 (Medien-Archiv **`media_assets`** / Bibliothek **`/media`** im Ist; **Inline-Medien** Fließtext geplant — `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11)
|
**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
|
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Gelieferte Features & technische Basis (Q2 2026)
|
# Gelieferte Features & technische Basis (Q2 2026)
|
||||||
|
|
||||||
**Stand:** 2026-05-07
|
**Stand:** 2026-05-08
|
||||||
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.59**, **DB_SCHEMA_VERSION** siehe dort
|
**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**. **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/`.
|
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/`.
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.59**)
|
## 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:
|
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
||||||
|
|
||||||
@@ -140,9 +140,13 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
|||||||
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
|
- **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`).
|
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
|
||||||
|
|
||||||
### 12.3 Geplant (nicht geliefert)
|
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
|
||||||
|
|
||||||
- **Inline-Medien** in Fließtextfeldern gemäß **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — Verweis auf `exercise_media.id`, zentraler Renderer; siehe **`docs/HANDOVER.md` §5**.
|
- 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -152,7 +156,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
|||||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||||
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
|
||||||
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
|
||||||
- **Medien:** Inline Fließtext §11; Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7).
|
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
# Exercises API Specification
|
# Exercises API Specification
|
||||||
|
|
||||||
**Version:** 1.4
|
**Version:** 1.5
|
||||||
**Datum:** 2026-04-30
|
**Datum:** 2026-05-08
|
||||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||||
**Autor:** Claude Code
|
**Autor:** Claude Code
|
||||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||||
|
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
|
||||||
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
||||||
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
||||||
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||||
@@ -336,6 +337,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
|||||||
### `PUT /exercises/{id}`
|
### `PUT /exercises/{id}`
|
||||||
|
|
||||||
**Request Body:** Same as POST (all fields optional except id)
|
**Request Body:** Same as POST (all fields optional except id)
|
||||||
|
**Inline-Hinweis:** Rich-Text-Felder (`summary`, `goal`, `execution`, `preparation`, `trainer_notes` sowie `execution_changes` bei Varianten) unterstützen Platzhalter `{{exerciseMedia:id}}`, die serverseitig auf kanonisches Span-Markup normalisiert werden. Beim erstmaligen Anlegen ohne vorhandene `exercise_media` wird dies mit 400 abgelehnt.
|
||||||
|
|
||||||
**Response:** `200 OK` (full exercise object)
|
**Response:** `200 OK` (full exercise object)
|
||||||
|
|
||||||
@@ -459,7 +461,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
|||||||
- `media_type` (enum, required) - `image | video | document | sketch`
|
- `media_type` (enum, required) - `image | video | document | sketch`
|
||||||
- `title` (string, optional)
|
- `title` (string, optional)
|
||||||
- `description` (string, optional)
|
- `description` (string, optional)
|
||||||
- `context` (enum, optional) - `ablauf | detail | trainer_hint`
|
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
|
||||||
|
|
||||||
**Entweder `file` ODER `embed_url` (nicht beides).**
|
**Entweder `file` ODER `embed_url` (nicht beides).**
|
||||||
|
|
||||||
@@ -505,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
|||||||
{
|
{
|
||||||
"title": "Neuer Titel",
|
"title": "Neuer Titel",
|
||||||
"description": "Neue Beschreibung",
|
"description": "Neue Beschreibung",
|
||||||
"is_primary": true,
|
"is_primary": true
|
||||||
"context": "detail"
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`context` bleibt backendseitig kompatibel, wird in aktuellen Bearbeitungsflüssen jedoch nicht mehr aktiv zur UI-Zuordnung verwendet (Inline-Platzhalter priorisiert).
|
||||||
|
|
||||||
**Response:** `200 OK` (media object)
|
**Response:** `200 OK` (media object)
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -893,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
|
|||||||
- File size: max 50MB
|
- File size: max 50MB
|
||||||
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
|
||||||
- Embed platforms: `youtube, instagram, vimeo`
|
- Embed platforms: `youtube, instagram, vimeo`
|
||||||
|
- Inline-Rich-Text: `{{exerciseMedia:id}}` bzw. `data-shinkan-exercise-media="<id>"`; optional `data-shinkan-exercise-media-size="small|medium|full"` für Layout.
|
||||||
|
|
||||||
### Exercise Block
|
### Exercise Block
|
||||||
- `name`: 3-200 chars
|
- `name`: 3-200 chars
|
||||||
@@ -947,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Version:** 1.0
|
**Version:** 1.5
|
||||||
**Letzte Änderung:** 2026-04-24
|
**Letzte Änderung:** 2026-05-08
|
||||||
**Status:** DRAFT - Awaiting Review
|
**Status:** Living Spec
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
|
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
|
||||||
|
|
||||||
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
|
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
|
||||||
**Stand:** 2026-05-07 (Ist-Changelog Medien bis 0.8.59; §11 Inline geplant)
|
**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`
|
**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.
|
**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,6 +186,9 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
|||||||
|
|
||||||
| Datum | Änderung |
|
| Datum | Änderung |
|
||||||
|-------|----------|
|
|-------|----------|
|
||||||
|
| 2026-05-08 | **0.8.64:** Bearbeiten-UX erweitert: Drag&Drop mit Auto-Scroll in Richtung Rich-Text, Medienliste in Kachel-Grid, Warnhinweis vor Wechsel „Ansehen“ bei ungespeicherten Änderungen + Rückweg „Zurück zur Bearbeitung“, Katalogvorschau ohne separaten Anhangs-Medienstreifen. |
|
||||||
|
| 2026-05-08 | **0.8.63:** Inline-Medien-Picker als Modal (Mediathek/Upload + separates Embed-Modal), Größenwahl `small|medium|full`, Platzhalter-Caption (`data-shinkan-exercise-media-caption`), Wiederverwendung bereits verknüpfter Assets im Picker, kompakter Medienbereich mit Drag&Drop in Textfelder. |
|
||||||
|
| 2026-05-08 | **0.8.60 §11:** Inline in Übungstexten (`{{exerciseMedia:id}}` / `data-shinkan-exercise-media`); Server-Normalisierung + Validierung; Client-Sanitize und zentraler Block-Renderer (`ExerciseRichTextBlock`); CREATE ohne bestehende `exercise_media` lehnt Platzhalter ab. |
|
||||||
| 2026-05-07 | **0.8.59:** Dokumentation — Aktiver Verein (Profil/Header/`effective_club_id`) für Plattform-Admin und UI-Dropdown synchron; kein fachliches Archiv-Schema-Change. |
|
| 2026-05-07 | **0.8.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.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.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. |
|
||||||
@@ -196,20 +199,20 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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
|
### 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`.
|
- 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).
|
- **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.
|
- **Kanonisches Markup nach Speichern:** `<span data-shinkan-exercise-media="<numerische exercise_media.id>" class="shinkan-inline-media"></span>`.
|
||||||
`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.
|
- **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.
|
||||||
- **Final festlegen** beim Start der Implementierung (ein Format, nicht mehrere parallele).
|
- **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
|
### 11.3 Rendering & Sicherheit
|
||||||
|
|
||||||
@@ -218,13 +221,14 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
|
|||||||
|
|
||||||
### 11.4 Koexistenz mit Sektions-Medien
|
### 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.
|
- Import/Wiki: vor großen Content-Migrationen **Syntax festlegen**, damit nicht irreversibel „falsches“ HTML importiert wird.
|
||||||
|
|
||||||
### 11.5 Wann umsetzen (Reihenfolge)
|
### 11.5 Wann umsetzen (Reihenfolge)
|
||||||
|
|
||||||
1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
|
1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
|
||||||
2. **Als Nächstes (geplant):** Inline implementieren gemäß §11.1–11.4 — Trainer-Feedback/Content-Menge kann Priorität schärfen; technische Leitplanken hier sind verbindlich.
|
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.
|
3. **Editor:** kein Zwang zum vollen Block-Editor vorab; **Platzhalter im bestehenden RTE** ist der vorgesehene schlanke Einstieg.
|
||||||
|
|
||||||
### 11.6 Refactor-Vermeidung (jetzt schon)
|
### 11.6 Refactor-Vermeidung (jetzt schon)
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ ENVIRONMENT=production
|
|||||||
|
|
||||||
# Medien (Docker Compose): SHINKAN_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
|
# 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).
|
# 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
|
SHINKAN_MEDIA_HOST=/shinkan-media
|
||||||
MEDIA_ROOT=/app/media
|
MEDIA_ROOT=/app/media
|
||||||
|
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ frontend/src/
|
|||||||
|
|
||||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||||
|
|
||||||
Kurz (Stand 2026-05-07): App **0.8.59**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, 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 **Inline geplant**).
|
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)
|
### Log (Auszug)
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ Kurz (Stand 2026-05-07): App **0.8.59**, DB‑Schema‑Version siehe **`backend/
|
|||||||
- `exercises` - Übungen (Kernobjekt)
|
- `exercises` - Übungen (Kernobjekt)
|
||||||
- `exercise_variants` - Übungsvarianten
|
- `exercise_variants` - Übungsvarianten
|
||||||
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
- `exercise_skills` - M:N Übung ↔ Fähigkeit
|
||||||
- `exercise_media` - Medien (Bilder, Videos); 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:**
|
**Trainingsplanung / Rahmen:**
|
||||||
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
|
||||||
|
|||||||
+45
-20
@@ -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:
|
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):
|
if is_platform_admin(global_role):
|
||||||
return True
|
return True
|
||||||
return has_club_role(
|
return has_club_role(
|
||||||
@@ -198,25 +203,45 @@ def exercise_visible_to_profile(
|
|||||||
created_by: Optional[int],
|
created_by: Optional[int],
|
||||||
global_role: Optional[str],
|
global_role: Optional[str],
|
||||||
) -> bool:
|
) -> 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
|
return True
|
||||||
if visibility == "official":
|
if created_by is not None and int(created_by) == pid:
|
||||||
return True
|
return True
|
||||||
if created_by is not None and created_by == profile_id:
|
if vis == "private":
|
||||||
return True
|
return plat
|
||||||
if visibility == "private":
|
if vis != "club":
|
||||||
return False
|
return False
|
||||||
if visibility == "club":
|
if exercise_club_id is None:
|
||||||
if exercise_club_id is None:
|
return False
|
||||||
return False
|
try:
|
||||||
cur.execute(
|
ecid = int(exercise_club_id)
|
||||||
"""
|
except (TypeError, ValueError):
|
||||||
SELECT 1 FROM club_members
|
return False
|
||||||
WHERE profile_id = %s AND club_id = %s AND status = 'active'
|
cur.execute(
|
||||||
LIMIT 1
|
"""
|
||||||
""",
|
SELECT cm.status
|
||||||
(profile_id, exercise_club_id),
|
FROM club_members cm
|
||||||
)
|
WHERE cm.profile_id = %s AND cm.club_id = %s
|
||||||
return cur.fetchone() is not None
|
LIMIT 1
|
||||||
return False
|
""",
|
||||||
|
(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),
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -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 db import get_db, get_cursor
|
||||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
||||||
|
from password_reset_mail import (
|
||||||
|
insert_password_reset_session,
|
||||||
|
password_reset_email_body,
|
||||||
|
revoke_pending_password_resets_for_profile,
|
||||||
|
)
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
@@ -116,28 +121,14 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
|
|||||||
if not prof:
|
if not prof:
|
||||||
# Don't reveal if email exists
|
# Don't reveal if email exists
|
||||||
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||||
|
revoke_pending_password_resets_for_profile(cur, prof["id"])
|
||||||
|
raw_token = insert_password_reset_session(cur, prof["id"])
|
||||||
|
|
||||||
# Generate reset token
|
reset_body = password_reset_email_body(
|
||||||
token = secrets.token_urlsafe(32)
|
recipient_name=prof.get("name"),
|
||||||
expires = datetime.now() + timedelta(hours=1)
|
token=raw_token,
|
||||||
|
intro="Du hast einen Passwort-Reset angefordert.",
|
||||||
# Store in sessions table (reuse mechanism)
|
)
|
||||||
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
|
||||||
(f"reset_{token}", prof['id'], expires.isoformat()))
|
|
||||||
|
|
||||||
app_base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
|
|
||||||
reset_body = f"""Hallo {prof['name']},
|
|
||||||
|
|
||||||
Du hast einen Passwort-Reset angefordert.
|
|
||||||
|
|
||||||
Reset-Link: {app_base}/reset-password?token={token}
|
|
||||||
|
|
||||||
Der Link ist 1 Stunde gültig.
|
|
||||||
|
|
||||||
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
|
|
||||||
|
|
||||||
Dein Shinkan Jinkendo Team
|
|
||||||
"""
|
|
||||||
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
|
||||||
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optional
|
|||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel, Field
|
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 db import get_db, get_cursor, r2d
|
||||||
from tenant_context import TenantContext, get_tenant_context
|
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)
|
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")
|
@router.get("/me/club-join-requests")
|
||||||
def get_my_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
def get_my_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
pid = tenant.profile_id
|
pid = tenant.profile_id
|
||||||
|
|||||||
@@ -50,6 +50,44 @@ def _club_exists(cur, club_id: int) -> bool:
|
|||||||
return cur.fetchone() is not None
|
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):
|
class ClubMemberUpsert(BaseModel):
|
||||||
profile_id: int = Field(..., ge=1)
|
profile_id: int = Field(..., ge=1)
|
||||||
roles: List[str] = Field(default_factory=list, description="Mindestens eine Vereinsrolle")
|
roles: List[str] = Field(default_factory=list, description="Mindestens eine Vereinsrolle")
|
||||||
@@ -77,7 +115,8 @@ def list_club_members(
|
|||||||
cur.execute(
|
cur.execute(
|
||||||
f"""
|
f"""
|
||||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
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(
|
COALESCE(
|
||||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||||
ARRAY[]::varchar[]
|
ARRAY[]::varchar[]
|
||||||
@@ -86,7 +125,7 @@ def list_club_members(
|
|||||||
INNER JOIN profiles p ON p.id = cm.profile_id
|
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
WHERE cm.club_id = %s {status_clause}
|
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
|
ORDER BY p.name NULLS LAST, p.email
|
||||||
""",
|
""",
|
||||||
(club_id,),
|
(club_id,),
|
||||||
@@ -153,7 +192,8 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
|
|||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
|
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(
|
COALESCE(
|
||||||
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
|
||||||
ARRAY[]::varchar[]
|
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
|
INNER JOIN profiles p ON p.id = cm.profile_id
|
||||||
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
|
||||||
WHERE cm.club_id = %s AND cm.profile_id = %s
|
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),
|
(club_id, profile_id),
|
||||||
)
|
)
|
||||||
@@ -217,21 +257,50 @@ def update_club_member(
|
|||||||
if body.roles is None and body.status is None:
|
if body.roles is None and body.status is None:
|
||||||
return _one_member(cur, club_id, profile_id)
|
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:
|
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(
|
cur.execute(
|
||||||
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
|
"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:
|
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,))
|
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(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO club_member_roles (club_member_id, role_code)
|
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")
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
||||||
_assert_manage(cur, tenant, club_id)
|
_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(
|
cur.execute(
|
||||||
"DELETE FROM club_members WHERE club_id = %s AND profile_id = %s RETURNING id",
|
"DELETE FROM club_members WHERE club_id = %s AND profile_id = %s RETURNING id",
|
||||||
(club_id, profile_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 typing import Any, List, Optional
|
||||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||||
|
from psycopg2.extras import Json
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from tenant_context import TenantContext, get_tenant_context
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
@@ -19,6 +20,53 @@ from club_tenancy import (
|
|||||||
router = APIRouter(prefix="/api", tags=["clubs"])
|
router = APIRouter(prefix="/api", tags=["clubs"])
|
||||||
|
|
||||||
|
|
||||||
|
def _blank_to_none(value: Any) -> Any:
|
||||||
|
"""Frontend sendet häufig '' für optionale Felder — ungültig für PostgreSQL TIME/INTEGER."""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, str) and value.strip() == "":
|
||||||
|
return None
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_int(value: Any) -> Optional[int]:
|
||||||
|
v = _blank_to_none(value)
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
i = int(v)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return i if i > 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_co_trainer_ids(val: Any) -> List[int]:
|
||||||
|
"""Listen von Profil-IDs für JSONB; ungültige Einträge werden verworfen."""
|
||||||
|
if val is None:
|
||||||
|
raw: List[Any] = []
|
||||||
|
elif isinstance(val, list):
|
||||||
|
raw = val
|
||||||
|
else:
|
||||||
|
raw = []
|
||||||
|
out: List[int] = []
|
||||||
|
seen = set()
|
||||||
|
for x in raw:
|
||||||
|
try:
|
||||||
|
i = int(x)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if i <= 0 or i in seen:
|
||||||
|
continue
|
||||||
|
seen.add(i)
|
||||||
|
out.append(i)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _co_trainer_ids_jsonb(val: Any) -> Json:
|
||||||
|
"""psycopg2: reine list/dict für JSONB → ProgrammingError ohne Json()."""
|
||||||
|
return Json(_normalize_co_trainer_ids(val))
|
||||||
|
|
||||||
|
|
||||||
# ── List Clubs ────────────────────────────────────────────────────────
|
# ── List Clubs ────────────────────────────────────────────────────────
|
||||||
@router.get("/clubs")
|
@router.get("/clubs")
|
||||||
def list_clubs(
|
def list_clubs(
|
||||||
@@ -581,9 +629,15 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
|||||||
if not club_id or not name:
|
if not club_id or not name:
|
||||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||||
|
|
||||||
trainer_id = data.get("trainer_id")
|
raw_tid = data.get("trainer_id")
|
||||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
if role in ("trainer", "user"):
|
||||||
trainer_id = profile_id
|
parsed_tid = _optional_int(raw_tid)
|
||||||
|
trainer_id = parsed_tid if parsed_tid is not None else profile_id
|
||||||
|
else:
|
||||||
|
trainer_id = _optional_int(raw_tid)
|
||||||
|
|
||||||
|
division_id = _optional_int(data.get("division_id"))
|
||||||
|
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
@@ -606,23 +660,23 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
|
|||||||
) VALUES (
|
) VALUES (
|
||||||
%s, %s, %s, %s, %s, %s,
|
%s, %s, %s, %s, %s, %s,
|
||||||
%s, %s, %s, %s,
|
%s, %s, %s, %s,
|
||||||
%s, %s, %s
|
%s, %s::jsonb, %s
|
||||||
) RETURNING id
|
) RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
club_id,
|
int(club_id),
|
||||||
data.get("division_id"),
|
division_id,
|
||||||
name,
|
name,
|
||||||
data.get("focus"),
|
_blank_to_none(data.get("focus")),
|
||||||
data.get("level"),
|
_blank_to_none(data.get("level")),
|
||||||
data.get("age_group"),
|
_blank_to_none(data.get("age_group")),
|
||||||
data.get("weekday"),
|
_blank_to_none(data.get("weekday")),
|
||||||
data.get("time_start"),
|
_blank_to_none(data.get("time_start")),
|
||||||
data.get("time_end"),
|
_blank_to_none(data.get("time_end")),
|
||||||
data.get("location"),
|
_blank_to_none(data.get("location")),
|
||||||
trainer_id,
|
trainer_id,
|
||||||
data.get("co_trainer_ids"),
|
co_json,
|
||||||
data.get("status", "active"),
|
data.get("status") or "active",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -662,6 +716,8 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
|||||||
if not allowed:
|
if not allowed:
|
||||||
raise HTTPException(403, "Keine Berechtigung")
|
raise HTTPException(403, "Keine Berechtigung")
|
||||||
|
|
||||||
|
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE training_groups SET
|
UPDATE training_groups SET
|
||||||
@@ -675,24 +731,24 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
|
|||||||
time_end = %s,
|
time_end = %s,
|
||||||
location = %s,
|
location = %s,
|
||||||
trainer_id = %s,
|
trainer_id = %s,
|
||||||
co_trainer_ids = %s,
|
co_trainer_ids = %s::jsonb,
|
||||||
status = %s,
|
status = %s,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
data.get("name"),
|
data.get("name"),
|
||||||
data.get("division_id"),
|
_optional_int(data.get("division_id")),
|
||||||
data.get("focus"),
|
_blank_to_none(data.get("focus")),
|
||||||
data.get("level"),
|
_blank_to_none(data.get("level")),
|
||||||
data.get("age_group"),
|
_blank_to_none(data.get("age_group")),
|
||||||
data.get("weekday"),
|
_blank_to_none(data.get("weekday")),
|
||||||
data.get("time_start"),
|
_blank_to_none(data.get("time_start")),
|
||||||
data.get("time_end"),
|
_blank_to_none(data.get("time_end")),
|
||||||
data.get("location"),
|
_blank_to_none(data.get("location")),
|
||||||
data.get("trainer_id"),
|
_optional_int(data.get("trainer_id")),
|
||||||
data.get("co_trainer_ids"),
|
co_json,
|
||||||
data.get("status"),
|
data.get("status") or "active",
|
||||||
group_id,
|
group_id,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -206,32 +206,22 @@ def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context))
|
|||||||
role = tenant.global_role
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
if is_platform_admin(role):
|
vis_sql, vis_params = library_content_visibility_sql(
|
||||||
cur.execute(
|
alias="g",
|
||||||
"""
|
profile_id=profile_id,
|
||||||
SELECT g.*,
|
role=role,
|
||||||
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
effective_club_id=tenant.effective_club_id,
|
||||||
FROM exercise_progression_graphs g
|
)
|
||||||
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
cur.execute(
|
||||||
"""
|
f"""
|
||||||
)
|
SELECT g.*,
|
||||||
else:
|
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
|
||||||
vis_sql, vis_params = library_content_visibility_sql(
|
FROM exercise_progression_graphs g
|
||||||
alias="g",
|
WHERE ({vis_sql})
|
||||||
profile_id=profile_id,
|
ORDER BY g.updated_at DESC NULLS LAST, g.name
|
||||||
role=role,
|
""",
|
||||||
effective_club_id=tenant.effective_club_id,
|
vis_params,
|
||||||
)
|
)
|
||||||
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()]
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+151
-17
@@ -29,6 +29,13 @@ from club_tenancy import (
|
|||||||
)
|
)
|
||||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
|
from media_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__)
|
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)
|
# §4.2: Übung → official — angehängte Datei-Assets anheben + Copyright (nur mit expliziter Bestätigung)
|
||||||
promote_attached_media_for_official: Optional[bool] = None
|
promote_attached_media_for_official: Optional[bool] = None
|
||||||
default_official_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
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")
|
@model_validator(mode="after")
|
||||||
def normalize_goal_execution(self):
|
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)
|
target_group_ids: Optional[list[int]] = Field(default=None, max_length=_MAX_BULK_RELATION_IDS_PER_KIND)
|
||||||
promote_attached_media_for_official: bool = False
|
promote_attached_media_for_official: bool = False
|
||||||
default_official_media_copyright: Optional[str] = Field(default=None, max_length=2000)
|
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")
|
@model_validator(mode="after")
|
||||||
def at_least_one_patch_field(self):
|
def at_least_one_patch_field(self):
|
||||||
@@ -642,10 +652,19 @@ def apply_official_exercise_media_rules(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def apply_club_exercise_media_copyright_rules(cur, exercise_id: int, next_visibility: str) -> None:
|
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
|
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).
|
(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()
|
nv = (next_visibility or "private").strip().lower()
|
||||||
if nv != "club":
|
if nv != "club":
|
||||||
@@ -694,7 +713,11 @@ def apply_club_exercise_media_copyright_rules(cur, exercise_id: int, next_visibi
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
if missing_cr:
|
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(
|
raise HTTPException(
|
||||||
status_code=422,
|
status_code=422,
|
||||||
detail={
|
detail={
|
||||||
@@ -707,6 +730,61 @@ def apply_club_exercise_media_copyright_rules(cur, exercise_id: int, next_visibi
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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]:
|
def _abs_media_path(file_path_db: str, media_root: Path) -> Optional[Path]:
|
||||||
if not file_path_db or file_path_db.startswith("http"):
|
if not file_path_db or file_path_db.startswith("http"):
|
||||||
@@ -1315,7 +1393,12 @@ def bulk_patch_exercises_metadata(
|
|||||||
|
|
||||||
if (next_vis or "").strip().lower() == "club":
|
if (next_vis or "").strip().lower() == "club":
|
||||||
try:
|
try:
|
||||||
apply_club_exercise_media_copyright_rules(cur, ex_id, next_vis)
|
apply_club_exercise_media_copyright_rules(
|
||||||
|
cur,
|
||||||
|
ex_id,
|
||||||
|
next_vis,
|
||||||
|
default_club_media_copyright=body.default_club_media_copyright,
|
||||||
|
)
|
||||||
except HTTPException as he:
|
except HTTPException as he:
|
||||||
d = he.detail
|
d = he.detail
|
||||||
entry: Dict[str, Any] = {"id": ex_id}
|
entry: Dict[str, Any] = {"id": ex_id}
|
||||||
@@ -1459,15 +1542,14 @@ def list_exercises(
|
|||||||
params = []
|
params = []
|
||||||
|
|
||||||
role = tenant.global_role
|
role = tenant.global_role
|
||||||
if not is_platform_admin(role):
|
vis_sql, vis_params = library_content_visibility_sql(
|
||||||
vis_sql, vis_params = library_content_visibility_sql(
|
alias="e",
|
||||||
alias="e",
|
profile_id=profile_id,
|
||||||
profile_id=profile_id,
|
role=role,
|
||||||
role=role,
|
effective_club_id=tenant.effective_club_id,
|
||||||
effective_club_id=tenant.effective_club_id,
|
)
|
||||||
)
|
where.append(vis_sql)
|
||||||
where.append(vis_sql)
|
params.extend(vis_params)
|
||||||
params.extend(vis_params)
|
|
||||||
|
|
||||||
if created_by_me:
|
if created_by_me:
|
||||||
where.append("e.created_by = %s")
|
where.append("e.created_by = %s")
|
||||||
@@ -1812,6 +1894,16 @@ def create_exercise(
|
|||||||
if body.visibility == "club" and club_id is None:
|
if body.visibility == "club" and club_id is None:
|
||||||
club_id = tenant.effective_club_id
|
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:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
assert_valid_governance_visibility(
|
assert_valid_governance_visibility(
|
||||||
@@ -1868,16 +1960,25 @@ def update_exercise(
|
|||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
cur.execute(
|
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,),
|
(exercise_id,),
|
||||||
)
|
)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
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)
|
_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_vis = (rd.get("visibility") or "private").strip().lower()
|
||||||
ex_cid = rd.get("club_id")
|
ex_cid = rd.get("club_id")
|
||||||
if ex_cid is not None:
|
if ex_cid is not None:
|
||||||
@@ -1887,6 +1988,24 @@ def update_exercise(
|
|||||||
raw_promo = data.pop("promote_attached_media_for_official", None)
|
raw_promo = data.pop("promote_attached_media_for_official", None)
|
||||||
promote_media_flag = raw_promo is True
|
promote_media_flag = raw_promo is True
|
||||||
default_official_copy = data.pop("default_official_media_copyright", None)
|
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
|
next_vis = ex_vis
|
||||||
if "visibility" in data and data["visibility"] is not None:
|
if "visibility" in data and data["visibility"] is not None:
|
||||||
@@ -1950,7 +2069,12 @@ def update_exercise(
|
|||||||
|
|
||||||
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
|
||||||
try:
|
try:
|
||||||
apply_club_exercise_media_copyright_rules(cur, exercise_id, next_vis)
|
apply_club_exercise_media_copyright_rules(
|
||||||
|
cur,
|
||||||
|
exercise_id,
|
||||||
|
next_vis,
|
||||||
|
default_club_media_copyright=default_club_copy,
|
||||||
|
)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
raise
|
raise
|
||||||
@@ -2064,7 +2188,11 @@ def create_exercise_variant(
|
|||||||
seq = cur.fetchone()["n"]
|
seq = cur.fetchone()["n"]
|
||||||
|
|
||||||
desc = (body.description or "").strip() or None
|
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
|
diff = (body.difficulty_adjustment or "").strip() or None
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
@@ -2118,7 +2246,13 @@ def update_exercise_variant(
|
|||||||
if "description" in data:
|
if "description" in data:
|
||||||
old["description"] = (data["description"] or "").strip() or None
|
old["description"] = (data["description"] or "").strip() or None
|
||||||
if "execution_changes" in data:
|
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:
|
if "duration_min" in data:
|
||||||
old["duration_min"] = data["duration_min"]
|
old["duration_min"] = data["duration_min"]
|
||||||
if "duration_max" in data:
|
if "duration_max" in data:
|
||||||
|
|||||||
+105
-26
@@ -377,17 +377,111 @@ def _relocate_asset_file_if_governance_changed(
|
|||||||
return new_key
|
return new_key
|
||||||
|
|
||||||
|
|
||||||
def _lifecycle_where_sql(lifecycle: str) -> str:
|
|
||||||
|
|
||||||
|
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()
|
lc = (lifecycle or "active").strip().lower()
|
||||||
if lc not in _LIFECYCLE_LIST_FILTERS:
|
if lc not in _LIFECYCLE_LIST_FILTERS:
|
||||||
raise HTTPException(status_code=400, detail="Ungültiger lifecycle-Filter")
|
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":
|
if lc == "active":
|
||||||
return "ma.lifecycle_state = 'active'"
|
return active_block, active_params
|
||||||
if lc == "trash_soft":
|
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":
|
if lc == "trash_hidden":
|
||||||
return "ma.lifecycle_state = 'trash_hidden'"
|
return (
|
||||||
return "ma.lifecycle_state IN ('active', 'trash_soft', 'trash_hidden')"
|
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]:
|
def _fetch_asset_file_row(cur: Any, asset_id: int) -> Optional[dict]:
|
||||||
@@ -789,7 +883,6 @@ def list_media_assets(
|
|||||||
limit: int = Query(30, ge=1, le=100),
|
limit: int = Query(30, ge=1, le=100),
|
||||||
offset: int = Query(0, ge=0),
|
offset: int = Query(0, ge=0),
|
||||||
):
|
):
|
||||||
lc_where = _lifecycle_where_sql(lifecycle)
|
|
||||||
mk = (media_kind or "all").strip().lower()
|
mk = (media_kind or "all").strip().lower()
|
||||||
if mk not in _MEDIA_KIND_FILTERS:
|
if mk not in _MEDIA_KIND_FILTERS:
|
||||||
raise HTTPException(status_code=400, detail="Ungültiger media_kind")
|
raise HTTPException(status_code=400, detail="Ungültiger media_kind")
|
||||||
@@ -831,6 +924,9 @@ def list_media_assets(
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
admin_club_ids = club_ids_for_profile_with_roles(cur, profile_id, "club_admin")
|
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)
|
show_uploader = sup or is_adm or bool(admin_club_ids)
|
||||||
if uploaded_by is not None and not show_uploader:
|
if uploaded_by is not None and not show_uploader:
|
||||||
raise HTTPException(status_code=403, detail="Uploader-Filter nicht erlaubt")
|
raise HTTPException(status_code=403, detail="Uploader-Filter nicht erlaubt")
|
||||||
@@ -863,7 +959,7 @@ def list_media_assets(
|
|||||||
)
|
)
|
||||||
|
|
||||||
params: list[Any] = (
|
params: list[Any] = (
|
||||||
[is_adm, profile_id, profile_id]
|
vis_params
|
||||||
+ club_sql_params
|
+ club_sql_params
|
||||||
+ uploaded_params
|
+ uploaded_params
|
||||||
+ search_params
|
+ search_params
|
||||||
@@ -880,24 +976,7 @@ def list_media_assets(
|
|||||||
FROM media_assets ma
|
FROM media_assets ma
|
||||||
LEFT JOIN profiles pr ON pr.id = ma.uploaded_by_profile_id
|
LEFT JOIN profiles pr ON pr.id = ma.uploaded_by_profile_id
|
||||||
LEFT JOIN clubs cl ON cl.id = ma.club_id
|
LEFT JOIN clubs cl ON cl.id = ma.club_id
|
||||||
WHERE {lc_where}
|
WHERE {vis_main_sql}
|
||||||
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'
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
{club_sql}
|
{club_sql}
|
||||||
{uploaded_sql}
|
{uploaded_sql}
|
||||||
{media_kind_sql}
|
{media_kind_sql}
|
||||||
@@ -907,7 +986,7 @@ def list_media_assets(
|
|||||||
params,
|
params,
|
||||||
)
|
)
|
||||||
rows = [r2d(r) for r in cur.fetchall()]
|
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]
|
asset_ids = [int(r["id"]) for r in rows]
|
||||||
usage_map = _usage_for_media_assets(cur, asset_ids)
|
usage_map = _usage_for_media_assets(cur, asset_ids)
|
||||||
for r in rows:
|
for r in rows:
|
||||||
|
|||||||
+131
-3
@@ -11,15 +11,81 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
|||||||
|
|
||||||
from psycopg2.extras import Json
|
from psycopg2.extras import Json
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from auth import require_auth, hash_pin
|
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 tenant_context import resolve_tenant_context, TenantContext, get_tenant_context
|
||||||
from models import ProfileCreate, ProfileUpdate
|
from models import ProfileCreate, ProfileUpdate
|
||||||
|
|
||||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||||
|
|
||||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
_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 ──────────────────────────────────────────────────────
|
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||||
@@ -28,7 +94,7 @@ def get_current_profile(
|
|||||||
session=Depends(require_auth),
|
session=Depends(require_auth),
|
||||||
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
|
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"]
|
profile_id = session["profile_id"]
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
@@ -38,7 +104,7 @@ def get_current_profile(
|
|||||||
raise HTTPException(404, "Profil nicht gefunden")
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
data = r2d(row)
|
data = r2d(row)
|
||||||
data.pop("pin_hash", None)
|
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
|
data["clubs"] = clubs
|
||||||
ac_raw = data.get("active_club_id")
|
ac_raw = data.get("active_club_id")
|
||||||
stored_ac = int(ac_raw) if ac_raw is not None and ac_raw != "" else None
|
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
|
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}")
|
@router.get("/profiles/{pid}")
|
||||||
def get_profile(pid: str, session=Depends(require_auth)):
|
def get_profile(pid: str, session=Depends(require_auth)):
|
||||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
"""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 focus_areas fa ON fa.id = fp.focus_area_id
|
||||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||||
"""
|
"""
|
||||||
if is_platform_admin(role):
|
vis_clause, vis_params = library_content_visibility_sql(
|
||||||
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
|
alias="fp",
|
||||||
else:
|
profile_id=profile_id,
|
||||||
vis_clause, vis_params = library_content_visibility_sql(
|
role=role,
|
||||||
alias="fp",
|
effective_club_id=tenant.effective_club_id,
|
||||||
profile_id=profile_id,
|
)
|
||||||
role=role,
|
cur.execute(
|
||||||
effective_club_id=tenant.effective_club_id,
|
base_sel
|
||||||
)
|
+ f""" WHERE ({vis_clause})
|
||||||
cur.execute(
|
|
||||||
base_sel
|
|
||||||
+ f""" WHERE ({vis_clause})
|
|
||||||
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
|
||||||
vis_params,
|
vis_params,
|
||||||
)
|
)
|
||||||
return [r2d(r) for r in cur.fetchall()]
|
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
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
if is_platform_admin(role):
|
vis_clause, vis_params = library_content_visibility_sql(
|
||||||
cur.execute(
|
alias="t",
|
||||||
"""
|
profile_id=profile_id,
|
||||||
SELECT t.*,
|
role=role,
|
||||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
effective_club_id=tenant.effective_club_id,
|
||||||
AS sections_count
|
)
|
||||||
FROM training_plan_templates t
|
cur.execute(
|
||||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
f"""
|
||||||
"""
|
|
||||||
)
|
|
||||||
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"""
|
|
||||||
SELECT t.*,
|
SELECT t.*,
|
||||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||||
AS sections_count
|
AS sections_count
|
||||||
@@ -922,8 +911,8 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
|||||||
WHERE ({vis_clause})
|
WHERE ({vis_clause})
|
||||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||||
""",
|
""",
|
||||||
vis_params,
|
vis_params,
|
||||||
)
|
)
|
||||||
return [r2d(r) for r in cur.fetchall()]
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+52
-17
@@ -21,6 +21,22 @@ def _club_exists(cur, club_id: int) -> bool:
|
|||||||
return cur.fetchone() is not None
|
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]:
|
def parse_active_club_header(raw: Optional[str]) -> Optional[int]:
|
||||||
"""Parst X-Active-Club-Id; leer → None. Ungültig → HTTP 400."""
|
"""Parst X-Active-Club-Id; leer → None. Ungültig → HTTP 400."""
|
||||||
if raw is None:
|
if raw is None:
|
||||||
@@ -45,21 +61,36 @@ def library_content_visibility_sql(
|
|||||||
effective_club_id: Optional[int],
|
effective_club_id: Optional[int],
|
||||||
) -> tuple[str, List[Any]]:
|
) -> tuple[str, List[Any]]:
|
||||||
"""
|
"""
|
||||||
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme):
|
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).
|
- official immer
|
||||||
Ohne effective_club_id: kein club-Zweig (nur official + private).
|
- 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):
|
plat = is_platform_admin(role)
|
||||||
return "TRUE", []
|
parts: List[str] = [f"{alias}.visibility = 'official'"]
|
||||||
|
params: List[Any] = []
|
||||||
|
|
||||||
parts: List[str] = [
|
if plat:
|
||||||
f"{alias}.visibility = 'official'",
|
parts.append(f"({alias}.visibility = 'private')")
|
||||||
f"({alias}.visibility = 'private' AND {alias}.created_by = %s)",
|
else:
|
||||||
]
|
parts.append(f"({alias}.visibility = 'private' AND {alias}.created_by = %s)")
|
||||||
params: List[Any] = [profile_id]
|
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(
|
parts.append(
|
||||||
f"""(
|
f"""(
|
||||||
{alias}.visibility = 'club'
|
{alias}.visibility = 'club'
|
||||||
@@ -97,7 +128,9 @@ def resolve_tenant_context(
|
|||||||
invalid_header_policy: str = "reject",
|
invalid_header_policy: str = "reject",
|
||||||
) -> TenantContext:
|
) -> 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:
|
Auflösung effective_club_id:
|
||||||
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
|
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
|
||||||
@@ -110,9 +143,11 @@ def resolve_tenant_context(
|
|||||||
header_cid = parse_active_club_header(header_raw)
|
header_cid = parse_active_club_header(header_raw)
|
||||||
|
|
||||||
if memberships is None:
|
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 is_platform_admin(role_lc):
|
||||||
if header_cid is not None:
|
if header_cid is not None:
|
||||||
@@ -131,7 +166,7 @@ def resolve_tenant_context(
|
|||||||
global_role=role_lc,
|
global_role=role_lc,
|
||||||
effective_club_id=effective,
|
effective_club_id=effective,
|
||||||
club_ids=club_ids,
|
club_ids=club_ids,
|
||||||
memberships=memberships,
|
memberships=membership_rows,
|
||||||
)
|
)
|
||||||
|
|
||||||
chosen_header = header_cid
|
chosen_header = header_cid
|
||||||
@@ -159,7 +194,7 @@ def resolve_tenant_context(
|
|||||||
global_role=role_lc,
|
global_role=role_lc,
|
||||||
effective_club_id=effective,
|
effective_club_id=effective,
|
||||||
club_ids=club_ids,
|
club_ids=club_ids,
|
||||||
memberships=memberships,
|
memberships=membership_rows,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,26 +5,27 @@ from fastapi import HTTPException
|
|||||||
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
|
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(
|
sql, params = library_content_visibility_sql(
|
||||||
alias="e",
|
alias="e",
|
||||||
profile_id=1,
|
profile_id=1,
|
||||||
role="admin",
|
role="admin",
|
||||||
effective_club_id=None,
|
effective_club_id=None,
|
||||||
)
|
)
|
||||||
assert sql == "TRUE"
|
assert "e.visibility = 'official'" in sql
|
||||||
assert params == []
|
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(
|
sql, params = library_content_visibility_sql(
|
||||||
alias="fp",
|
alias="fp",
|
||||||
profile_id=2,
|
profile_id=2,
|
||||||
role="superadmin",
|
role="superadmin",
|
||||||
effective_club_id=100,
|
effective_club_id=100,
|
||||||
)
|
)
|
||||||
assert sql == "TRUE"
|
assert "club_members" in sql
|
||||||
assert params == []
|
assert params == [2, 2]
|
||||||
|
|
||||||
|
|
||||||
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
|
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
|
||||||
@@ -125,3 +126,37 @@ def test_resolve_platform_admin_no_header_stored_invalid(monkeypatch):
|
|||||||
stored_active_club_id=123,
|
stored_active_club_id=123,
|
||||||
)
|
)
|
||||||
assert ctx.effective_club_id is None
|
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
|
||||||
@@ -60,3 +60,49 @@ def test_apply_club_exercise_media_copyright_ok() -> None:
|
|||||||
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
apply_club_exercise_media_copyright_rules(object(), 42, "club")
|
||||||
finally:
|
finally:
|
||||||
exercises_mod._fetch_exercise_linked_file_assets = orig
|
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]
|
||||||
+46
-3
@@ -1,7 +1,7 @@
|
|||||||
# Shinkan Jinkendo Version Information
|
# Shinkan Jinkendo Version Information
|
||||||
|
|
||||||
APP_VERSION = "0.8.59"
|
APP_VERSION = "0.8.65"
|
||||||
BUILD_DATE = "2026-05-07"
|
BUILD_DATE = "2026-05-08"
|
||||||
DB_SCHEMA_VERSION = "20260508049"
|
DB_SCHEMA_VERSION = "20260508049"
|
||||||
|
|
||||||
MODULE_VERSIONS = {
|
MODULE_VERSIONS = {
|
||||||
@@ -17,7 +17,7 @@ MODULE_VERSIONS = {
|
|||||||
"groups": "0.1.0",
|
"groups": "0.1.0",
|
||||||
"skills": "0.1.0",
|
"skills": "0.1.0",
|
||||||
"methods": "0.1.0",
|
"methods": "0.1.0",
|
||||||
"exercises": "2.18.0", # Vereins-Übung: Copyright-Pflicht File-Assets; official nur Superadmin (Governance)
|
"exercises": "2.19.1", # Verein: PUT default_club_media_copyright + Prompt beim Speichern (fehlende File-Asset-Copyrights)
|
||||||
"training_units": "0.2.0",
|
"training_units": "0.2.0",
|
||||||
"training_programs": "0.1.0",
|
"training_programs": "0.1.0",
|
||||||
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||||
@@ -29,6 +29,49 @@ MODULE_VERSIONS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
CHANGELOG = [
|
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",
|
"version": "0.8.59",
|
||||||
"date": "2026-05-07",
|
"date": "2026-05-07",
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ services:
|
|||||||
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
|
||||||
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
|
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
|
||||||
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
|
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:
|
volumes:
|
||||||
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
+66
-13
@@ -9,6 +9,7 @@ import {
|
|||||||
Outlet,
|
Outlet,
|
||||||
} from 'react-router-dom'
|
} from 'react-router-dom'
|
||||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||||
|
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
||||||
import DesktopSidebar from './components/DesktopSidebar'
|
import DesktopSidebar from './components/DesktopSidebar'
|
||||||
import { getMainNavItems } from './config/appNav'
|
import { getMainNavItems } from './config/appNav'
|
||||||
import LoginPage from './pages/LoginPage'
|
import LoginPage from './pages/LoginPage'
|
||||||
@@ -20,6 +21,7 @@ import ExercisesListPage from './pages/ExercisesListPage'
|
|||||||
import ExerciseDetailPage from './pages/ExerciseDetailPage'
|
import ExerciseDetailPage from './pages/ExerciseDetailPage'
|
||||||
import ExerciseFormPage from './pages/ExerciseFormPage'
|
import ExerciseFormPage from './pages/ExerciseFormPage'
|
||||||
import ClubsPage from './pages/ClubsPage'
|
import ClubsPage from './pages/ClubsPage'
|
||||||
|
import InboxPage from './pages/InboxPage'
|
||||||
import SkillsPage from './pages/SkillsPage'
|
import SkillsPage from './pages/SkillsPage'
|
||||||
import TrainingPlanningPage from './pages/TrainingPlanningPage'
|
import TrainingPlanningPage from './pages/TrainingPlanningPage'
|
||||||
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
|
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
|
||||||
@@ -32,13 +34,22 @@ import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
|
|||||||
import TrainerContextsPage from './pages/TrainerContextsPage'
|
import TrainerContextsPage from './pages/TrainerContextsPage'
|
||||||
import MediaWikiImportPage from './pages/MediaWikiImportPage'
|
import MediaWikiImportPage from './pages/MediaWikiImportPage'
|
||||||
import AdminUsersPage from './pages/AdminUsersPage'
|
import AdminUsersPage from './pages/AdminUsersPage'
|
||||||
|
import AdminHomeRedirect from './components/AdminHomeRedirect'
|
||||||
|
import PlatformAdminRoute from './components/PlatformAdminRoute'
|
||||||
import MediaLibraryPage from './pages/MediaLibraryPage'
|
import MediaLibraryPage from './pages/MediaLibraryPage'
|
||||||
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
|
||||||
|
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
|
||||||
import './app.css'
|
import './app.css'
|
||||||
|
|
||||||
|
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||||
|
function computeShowAdminNav(currentUser) {
|
||||||
|
return currentUser?.role === 'superadmin'
|
||||||
|
}
|
||||||
|
|
||||||
// Bottom Navigation (Mobile)
|
// Bottom Navigation (Mobile)
|
||||||
function Nav({ isAdmin }) {
|
function Nav({ showAdminNav }) {
|
||||||
const items = getMainNavItems(isAdmin)
|
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||||
|
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||||
const loc = useLocation()
|
const loc = useLocation()
|
||||||
|
|
||||||
const navItemActive = (pathname, item, routerIsActive) => {
|
const navItemActive = (pathname, item, routerIsActive) => {
|
||||||
@@ -58,6 +69,11 @@ function Nav({ isAdmin }) {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<item.Icon size={26} strokeWidth={2} />
|
<item.Icon size={26} strokeWidth={2} />
|
||||||
|
{item.to === '/inbox' && inboxCount > 0 ? (
|
||||||
|
<span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
|
||||||
|
{inboxCount > 99 ? '99+' : inboxCount}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
<span>{item.shortLabel || item.label}</span>
|
<span>{item.shortLabel || item.label}</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
))}
|
))}
|
||||||
@@ -95,11 +111,11 @@ function ProtectedLayout() {
|
|||||||
return <Navigate to="/login" replace />
|
return <Navigate to="/login" replace />
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
const showAdminNav = computeShowAdminNav(user)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<OrgInboxProvider user={user}>
|
||||||
<DesktopSidebar isAdmin={isAdmin} user={user} onLogout={handleLogout} />
|
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<div className="app-shell__column">
|
<div className="app-shell__column">
|
||||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||||
@@ -109,12 +125,13 @@ function ProtectedLayout() {
|
|||||||
<ActiveClubSwitcher variant="mobile" />
|
<ActiveClubSwitcher variant="mobile" />
|
||||||
</div>
|
</div>
|
||||||
<div className="app-main">
|
<div className="app-main">
|
||||||
|
<InactiveMembershipBanner />
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</div>
|
</div>
|
||||||
<Nav isAdmin={isAdmin} />
|
<Nav showAdminNav={showAdminNav} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</OrgInboxProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,6 +184,7 @@ function AppRoutes() {
|
|||||||
<Route path=":id" element={<ExerciseDetailPage />} />
|
<Route path=":id" element={<ExerciseDetailPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="clubs" element={<ClubsPage />} />
|
<Route path="clubs" element={<ClubsPage />} />
|
||||||
|
<Route path="inbox" element={<InboxPage />} />
|
||||||
<Route path="skills" element={<SkillsPage />} />
|
<Route path="skills" element={<SkillsPage />} />
|
||||||
<Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
|
<Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
|
||||||
<Route path="planning/framework-programs/:id" 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/coach" element={<TrainingCoachPage />} />
|
||||||
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
|
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
|
||||||
<Route path="planning" element={<TrainingPlanningPage />} />
|
<Route path="planning" element={<TrainingPlanningPage />} />
|
||||||
<Route path="admin" element={<Navigate to="/admin/hierarchy" replace />} />
|
<Route path="admin" element={<AdminHomeRedirect />} />
|
||||||
<Route path="admin/users" element={<AdminUsersPage />} />
|
<Route
|
||||||
<Route path="admin/hierarchy" element={<AdminHierarchyPage />} />
|
path="admin/users"
|
||||||
<Route path="admin/maturity-models" element={<AdminMaturityModelsPage />} />
|
element={
|
||||||
<Route path="admin/catalogs" element={<AdminCatalogsPage />} />
|
<PlatformAdminRoute>
|
||||||
<Route path="admin/mediawiki-import" element={<MediaWikiImportPage />} />
|
<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 path="trainer-contexts" element={<TrainerContextsPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
|
|||||||
+424
-1
@@ -198,6 +198,7 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
|
|||||||
min-width: 68px;
|
min-width: 68px;
|
||||||
max-width: 108px;
|
max-width: 108px;
|
||||||
min-height: 48px;
|
min-height: 48px;
|
||||||
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -3895,7 +3896,30 @@ a.analysis-split__nav-item {
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
resize: vertical;
|
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 ul,
|
||||||
.rich-text-editor ol {
|
.rich-text-editor ol {
|
||||||
margin: 0.35rem 0;
|
margin: 0.35rem 0;
|
||||||
@@ -3921,6 +3945,252 @@ a.analysis-split__nav-item {
|
|||||||
pointer-events: none;
|
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 {
|
.rich-text-content {
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
line-height: 1.55;
|
line-height: 1.55;
|
||||||
@@ -6107,3 +6377,156 @@ a.analysis-split__nav-item {
|
|||||||
.media-library__preview-fallback .btn {
|
.media-library__preview-fallback .btn {
|
||||||
margin-top: 12px;
|
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,5 +1,5 @@
|
|||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
import { getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
import { activeClubMemberships, getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
|
* Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
|
||||||
@@ -7,7 +7,7 @@ import { getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
|||||||
*/
|
*/
|
||||||
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
|
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
|
||||||
const { user, setActiveClub } = useAuth()
|
const { user, setActiveClub } = useAuth()
|
||||||
const clubs = user?.clubs || []
|
const clubs = activeClubMemberships(user?.clubs)
|
||||||
if (clubs.length <= 1) return null
|
if (clubs.length <= 1) return null
|
||||||
|
|
||||||
const selectClubId = getResolvedActiveClubIdForUi(user)
|
const selectClubId = getResolvedActiveClubIdForUi(user)
|
||||||
|
|||||||
@@ -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 { 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)
|
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||||
* Wechselt zwischen verschiedenen Admin-Seiten
|
|
||||||
*/
|
*/
|
||||||
export default function AdminPageNav() {
|
export default function AdminPageNav() {
|
||||||
const pages = [
|
const pages = [
|
||||||
@@ -11,8 +10,7 @@ export default function AdminPageNav() {
|
|||||||
{ to: '/admin/users', label: 'Nutzer', icon: Users },
|
{ to: '/admin/users', label: 'Nutzer', icon: Users },
|
||||||
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
|
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
|
||||||
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
|
{ 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 (
|
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 { NavLink, useLocation } from 'react-router-dom'
|
||||||
import { LogOut } from 'lucide-react'
|
import { LogOut } from 'lucide-react'
|
||||||
import { getMainNavItems } from '../config/appNav'
|
import { getMainNavItems } from '../config/appNav'
|
||||||
|
import { useOrgInbox } from '../context/OrgInboxContext'
|
||||||
import ActiveClubSwitcher from './ActiveClubSwitcher'
|
import ActiveClubSwitcher from './ActiveClubSwitcher'
|
||||||
|
|
||||||
function sidebarLinkActive(pathname, item, routerIsActive) {
|
function sidebarLinkActive(pathname, item, routerIsActive) {
|
||||||
@@ -12,12 +13,13 @@ function sidebarLinkActive(pathname, item, routerIsActive) {
|
|||||||
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
|
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
|
||||||
*/
|
*/
|
||||||
export default function DesktopSidebar({
|
export default function DesktopSidebar({
|
||||||
isAdmin,
|
showAdminNav,
|
||||||
user,
|
user,
|
||||||
onLogout
|
onLogout
|
||||||
}) {
|
}) {
|
||||||
const loc = useLocation()
|
const loc = useLocation()
|
||||||
const items = getMainNavItems(isAdmin)
|
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
|
||||||
|
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
|
||||||
const tier = user?.tier || ''
|
const tier = user?.tier || ''
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -42,6 +44,11 @@ export default function DesktopSidebar({
|
|||||||
>
|
>
|
||||||
<item.Icon size={20} strokeWidth={2} />
|
<item.Icon size={20} strokeWidth={2} />
|
||||||
<span>{item.label}</span>
|
<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>
|
</NavLink>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</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 React from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||||
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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function TagRow({ exercise }) {
|
function TagRow({ exercise }) {
|
||||||
const tags = []
|
const tags = []
|
||||||
@@ -112,11 +67,8 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
|||||||
}
|
}
|
||||||
if (!exercise) return null
|
if (!exercise) return null
|
||||||
|
|
||||||
|
const resolvedId = exercise.id ?? exerciseId
|
||||||
const meta = metaParts(exercise)
|
const meta = metaParts(exercise)
|
||||||
const visibleMedia = (exercise.media || []).filter((m) => {
|
|
||||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
|
||||||
return lc !== 'trash_hidden'
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="exercise-coach-catalog" style={{ fontSize: '0.93rem', lineHeight: 1.5 }}>
|
<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' }}>
|
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px', letterSpacing: '0.04em' }}>
|
||||||
Kurzbeschreibung
|
Kurzbeschreibung
|
||||||
</h3>
|
</h3>
|
||||||
<HtmlBlock html={exercise.summary} />
|
<ExerciseRichTextBlock html={exercise.summary} exerciseId={resolvedId} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
{exercise.goal && (
|
{exercise.goal && (
|
||||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ziel</h3>
|
<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>
|
</section>
|
||||||
)}
|
)}
|
||||||
{(exercise.equipment || []).length > 0 && (
|
{(exercise.equipment || []).length > 0 && (
|
||||||
@@ -156,32 +108,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
|
|||||||
{exercise.preparation && (
|
{exercise.preparation && (
|
||||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Vorbereitung</h3>
|
<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>
|
</section>
|
||||||
)}
|
)}
|
||||||
{exercise.execution && (
|
{exercise.execution && (
|
||||||
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
|
||||||
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ablauf</h3>
|
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ablauf</h3>
|
||||||
<HtmlBlock html={exercise.execution} />
|
<ExerciseRichTextBlock html={exercise.execution} exerciseId={resolvedId} media={exercise.media} />
|
||||||
</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>
|
|
||||||
))}
|
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
{exercise.trainer_notes && (
|
{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' }}>
|
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||||
Hinweise Trainer (Katalog)
|
Hinweise Trainer (Katalog)
|
||||||
</h3>
|
</h3>
|
||||||
<HtmlBlock html={exercise.trainer_notes} />
|
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={resolvedId} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
{exerciseId != null && (
|
{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 React, { useEffect, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||||
|
|
||||||
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 TagMini({ exercise }) {
|
function TagMini({ exercise }) {
|
||||||
const parts = []
|
const parts = []
|
||||||
@@ -129,7 +121,7 @@ export default function ExercisePeekModal({
|
|||||||
</div>
|
</div>
|
||||||
{variant.description ? (
|
{variant.description ? (
|
||||||
<div style={{ marginTop: 8, fontSize: '0.9rem', color: 'var(--text2)' }}>
|
<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>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{variant.execution_changes ? (
|
{variant.execution_changes ? (
|
||||||
@@ -137,14 +129,14 @@ export default function ExercisePeekModal({
|
|||||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>
|
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>
|
||||||
Durchführung (Variante)
|
Durchführung (Variante)
|
||||||
</h4>
|
</h4>
|
||||||
<HtmlBlock html={variant.execution_changes} />
|
<ExerciseRichTextBlock html={variant.execution_changes} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{exercise.summary && (
|
{exercise.summary && (
|
||||||
<div style={{ fontSize: '0.95rem', color: 'var(--text2)' }}>
|
<div style={{ fontSize: '0.95rem', color: 'var(--text2)' }}>
|
||||||
<HtmlBlock html={exercise.summary} />
|
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<TagMini exercise={exercise} />
|
<TagMini exercise={exercise} />
|
||||||
@@ -154,25 +146,25 @@ export default function ExercisePeekModal({
|
|||||||
{exercise.goal && (
|
{exercise.goal && (
|
||||||
<>
|
<>
|
||||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>Ziel</h4>
|
<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 && (
|
{exercise.preparation && (
|
||||||
<>
|
<>
|
||||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Vorbereitung</h4>
|
<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 && (
|
{exercise.execution && (
|
||||||
<>
|
<>
|
||||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Ablauf</h4>
|
<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 && (
|
{exercise.trainer_notes && (
|
||||||
<>
|
<>
|
||||||
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Trainer-Hinweise</h4>
|
<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} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -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,13 +1,13 @@
|
|||||||
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
import { getResolvedActiveClubIdForUi } from '../utils/activeClub'
|
import { getResolvedActiveClubIdForUi, activeClubMemberships } from '../utils/activeClub'
|
||||||
|
|
||||||
function Navigation() {
|
function Navigation() {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { user, logout, setActiveClub } = useAuth()
|
const { user, logout, setActiveClub } = useAuth()
|
||||||
|
|
||||||
const clubs = user?.clubs || []
|
const clubs = activeClubMemberships(user?.clubs)
|
||||||
const selectClubId = getResolvedActiveClubIdForUi(user)
|
const selectClubId = getResolvedActiveClubIdForUi(user)
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
|
|||||||
@@ -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 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) {
|
function exec(cmd, value = null) {
|
||||||
try {
|
try {
|
||||||
@@ -45,12 +53,140 @@ function normalText() {
|
|||||||
formatBlock('p')
|
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 ref = useRef(null)
|
||||||
|
const pendingRangeRef = useRef(null)
|
||||||
const [focused, setFocused] = useState(false)
|
const [focused, setFocused] = useState(false)
|
||||||
|
const [fileModalOpen, setFileModalOpen] = useState(false)
|
||||||
|
const [embedModalOpen, setEmbedModalOpen] = useState(false)
|
||||||
|
|
||||||
|
const showInlineToolbar = inlineExerciseId != null && Number(inlineExerciseId) > 0
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = ref.current
|
const el = ref.current
|
||||||
@@ -66,6 +202,129 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
|
|||||||
onChange(ref.current.innerHTML)
|
onChange(ref.current.innerHTML)
|
||||||
}, [onChange])
|
}, [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) => {
|
const run = (fn) => (e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
e.stopPropagation()
|
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}>
|
<button type="button" className="rte-btn" title="Link einfügen" onMouseDown={onLink}>
|
||||||
Link
|
Link
|
||||||
</button>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="rte-btn"
|
className="rte-btn"
|
||||||
@@ -158,7 +437,31 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
|
|||||||
sync()
|
sync()
|
||||||
}}
|
}}
|
||||||
onInput={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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { useCallback, useMemo, useState } from 'react'
|
import React, { useCallback, useMemo, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
|
|
||||||
const VIS_LABELS = {
|
const VIS_LABELS = {
|
||||||
private: 'Privat',
|
private: 'Privat',
|
||||||
@@ -48,7 +49,7 @@ function userMayPromote(user, targetClubId, createdBy) {
|
|||||||
const role = String(user.role || '').toLowerCase()
|
const role = String(user.role || '').toLowerCase()
|
||||||
if (role === 'admin' || role === 'superadmin') return true
|
if (role === 'admin' || role === 'superadmin') return true
|
||||||
if (createdBy != null && Number(createdBy) === Number(user.id)) 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
|
if (!row || !Array.isArray(row.roles)) return false
|
||||||
return row.roles.includes('club_admin')
|
return row.roles.includes('club_admin')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ import {
|
|||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
BookOpen,
|
BookOpen,
|
||||||
Calendar,
|
Calendar,
|
||||||
|
Images,
|
||||||
Building2,
|
Building2,
|
||||||
Settings,
|
Settings,
|
||||||
Shield,
|
Shield,
|
||||||
Target
|
Inbox
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -15,30 +16,35 @@ import {
|
|||||||
* @typedef {{ to: string, label: string, shortLabel?: string, end?: boolean, Icon: import('react').ForwardRefExoticComponent }} AppNavItem
|
* @typedef {{ to: string, label: string, shortLabel?: string, end?: boolean, Icon: import('react').ForwardRefExoticComponent }} AppNavItem
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** @returns {Omit<AppNavItem, 'Icon'>[]} */
|
/** @param {{ showInbox?: boolean }} opts */
|
||||||
function baseItems() {
|
function baseItems(opts = {}) {
|
||||||
return [
|
const showInbox = !!opts.showInbox
|
||||||
|
const items = [
|
||||||
{ to: '/', label: 'Übersicht', end: true },
|
{ to: '/', label: 'Übersicht', end: true },
|
||||||
|
...(showInbox ? [{ to: '/inbox', label: 'Posteingang', shortLabel: 'Post' }] : []),
|
||||||
{ to: '/exercises', label: 'Übungen', shortLabel: 'Übungen' },
|
{ to: '/exercises', label: 'Übungen', shortLabel: 'Übungen' },
|
||||||
{ to: '/planning', label: 'Planung' },
|
{ to: '/planning', label: 'Planung' },
|
||||||
|
{ to: '/media', label: 'Medien', shortLabel: 'Medien' },
|
||||||
{ to: '/clubs', label: 'Vereine' },
|
{ to: '/clubs', label: 'Vereine' },
|
||||||
{ to: '/trainer-contexts', label: 'Meine Bereiche', shortLabel: 'Bereiche' },
|
|
||||||
{ to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' }
|
{ to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' }
|
||||||
]
|
]
|
||||||
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {boolean} isAdmin */
|
/** @param {boolean} isAdmin @param {{ showInbox?: boolean }} opts */
|
||||||
export function getMainNavItems(isAdmin) {
|
export function getMainNavItems(isAdmin, opts = {}) {
|
||||||
|
const showInbox = !!opts.showInbox
|
||||||
const icons = [
|
const icons = [
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
|
...(showInbox ? [Inbox] : []),
|
||||||
BookOpen,
|
BookOpen,
|
||||||
Calendar,
|
Calendar,
|
||||||
|
Images,
|
||||||
Building2,
|
Building2,
|
||||||
Target,
|
Settings,
|
||||||
Settings
|
|
||||||
]
|
]
|
||||||
|
|
||||||
const raw = baseItems().map((item, i) => ({
|
const raw = baseItems(opts).map((item, i) => ({
|
||||||
...item,
|
...item,
|
||||||
Icon: icons[i]
|
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 { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import api, { ACTIVE_CLUB_STORAGE_KEY } from '../utils/api'
|
import api, { ACTIVE_CLUB_STORAGE_KEY } from '../utils/api'
|
||||||
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
|
|
||||||
const AuthContext = createContext(null)
|
const AuthContext = createContext(null)
|
||||||
|
|
||||||
function syncStoredActiveClub(profile) {
|
function syncStoredActiveClub(profile) {
|
||||||
const clubs = profile?.clubs || []
|
const clubs = activeClubMemberships(profile?.clubs)
|
||||||
const ids = new Set(clubs.map((c) => String(c.id)))
|
const ids = new Set(clubs.map((c) => String(c.id)))
|
||||||
const eff = profile?.effective_club_id
|
const eff = profile?.effective_club_id
|
||||||
if (eff != null && eff !== '' && ids.has(String(eff))) {
|
if (eff != null && eff !== '' && ids.has(String(eff))) {
|
||||||
@@ -24,6 +25,12 @@ function syncStoredActiveClub(profile) {
|
|||||||
}
|
}
|
||||||
if (clubs.length >= 1) {
|
if (clubs.length >= 1) {
|
||||||
localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(clubs[0].id))
|
localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(clubs[0].id))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||||
|
} 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 }}>
|
<span style={{ lineHeight: 1.45 }}>
|
||||||
{user?.clubs?.length ? (
|
{user?.clubs?.length ? (
|
||||||
<>
|
<>
|
||||||
{user.clubs.map((c) => (
|
{user.clubs.map((c) => {
|
||||||
<div key={c.id}>
|
const mem = (c.membership_status || 'active').toString().trim().toLowerCase()
|
||||||
<strong style={{ color: 'var(--text1)' }}>{c.name}</strong>
|
const inactive = mem === 'inactive'
|
||||||
{': '}
|
return (
|
||||||
{(c.roles || []).length ? (c.roles || []).join(', ') : '—'}
|
<div key={c.id}>
|
||||||
</div>
|
<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 { Navigate } from 'react-router-dom'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
@@ -11,24 +11,37 @@ const CLUB_ROLE_OPTIONS = [
|
|||||||
{ code: 'content_editor', label: 'Inhalte bearbeiten' },
|
{ code: 'content_editor', label: 'Inhalte bearbeiten' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const TIER_OPTIONS = ['free', 'premium', 'pro', 'enterprise']
|
const PORTAL_ROLE_LABEL = {
|
||||||
|
|
||||||
const ROLE_LABEL = {
|
|
||||||
user: 'Nutzer',
|
user: 'Nutzer',
|
||||||
trainer: 'Trainer',
|
trainer: 'Portal-Trainer',
|
||||||
admin: 'Portal-Admin',
|
admin: 'Portal-Administrator',
|
||||||
superadmin: 'Super-Admin',
|
superadmin: 'Super-Administrator',
|
||||||
}
|
}
|
||||||
|
|
||||||
function AdminUsersPage() {
|
function portalRoleSelectOptions(viewerIsSuperadmin, currentRole) {
|
||||||
const { user } = useAuth()
|
const base = [
|
||||||
const isSuper = user?.role === 'superadmin'
|
{ value: 'user', label: PORTAL_ROLE_LABEL.user },
|
||||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
{ value: 'trainer', label: `${PORTAL_ROLE_LABEL.trainer} (Legacy)` },
|
||||||
const portalRoleChoices = isSuper
|
{ value: 'admin', label: PORTAL_ROLE_LABEL.admin },
|
||||||
? ['user', 'trainer', 'admin', 'superadmin']
|
]
|
||||||
: ['user', 'trainer', '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 [clubs, setClubs] = useState([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
@@ -36,43 +49,48 @@ function AdminUsersPage() {
|
|||||||
const [assignModal, setAssignModal] = useState(null)
|
const [assignModal, setAssignModal] = useState(null)
|
||||||
const [assignRoles, setAssignRoles] = useState(['trainer'])
|
const [assignRoles, setAssignRoles] = useState(['trainer'])
|
||||||
const [clubEditModal, setClubEditModal] = useState(null)
|
const [clubEditModal, setClubEditModal] = useState(null)
|
||||||
|
const [pwdModal, setPwdModal] = useState(null)
|
||||||
|
const [pwdNew, setPwdNew] = useState('')
|
||||||
|
const [pwdNew2, setPwdNew2] = useState('')
|
||||||
|
|
||||||
const load = async () => {
|
const loadPlatform = useCallback(async () => {
|
||||||
setError('')
|
const [u, c] = await Promise.all([api.listAdminUsers(), api.listClubs()])
|
||||||
try {
|
setPlatformUsers(Array.isArray(u) ? u : [])
|
||||||
const [u, c] = await Promise.all([api.listAdminUsers(), api.listClubs()])
|
setClubs(Array.isArray(c) ? c : [])
|
||||||
setUsers(u)
|
const d = {}
|
||||||
setClubs(c)
|
for (const row of u || []) {
|
||||||
const d = {}
|
d[row.id] = { role: (row.role || 'user').toLowerCase() }
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
setPortalDraft(d)
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isPlatformAdmin) return
|
if (!isSuperadminViewer) return
|
||||||
load()
|
let cancelled = false
|
||||||
}, [isPlatformAdmin])
|
;(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) {
|
if (!isSuperadminViewer) return <Navigate to="/" replace />
|
||||||
return <Navigate to="/" replace />
|
|
||||||
}
|
|
||||||
|
|
||||||
const savePortal = async (profileId) => {
|
const savePortal = async (profileId) => {
|
||||||
const dr = portalDraft[profileId]
|
const dr = portalDraft[profileId]
|
||||||
if (!dr) return
|
if (!dr) return
|
||||||
try {
|
try {
|
||||||
await api.updateProfile(profileId, { role: dr.role, tier: dr.tier })
|
await api.updateProfile(profileId, { role: dr.role })
|
||||||
await load()
|
await loadPlatform()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert(e.message || String(e))
|
alert(e.message || String(e))
|
||||||
}
|
}
|
||||||
@@ -90,7 +108,7 @@ function AdminUsersPage() {
|
|||||||
await api.addClubMember(clubId, { profile_id: profileId, roles: assignRoles })
|
await api.addClubMember(clubId, { profile_id: profileId, roles: assignRoles })
|
||||||
setAssignModal(null)
|
setAssignModal(null)
|
||||||
setAssignRoles(['trainer'])
|
setAssignRoles(['trainer'])
|
||||||
await load()
|
await loadPlatform()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert(e.message || String(e))
|
alert(e.message || String(e))
|
||||||
}
|
}
|
||||||
@@ -102,7 +120,7 @@ function AdminUsersPage() {
|
|||||||
try {
|
try {
|
||||||
await api.updateClubMember(clubId, profileId, { roles, status })
|
await api.updateClubMember(clubId, profileId, { roles, status })
|
||||||
setClubEditModal(null)
|
setClubEditModal(null)
|
||||||
await load()
|
await loadPlatform()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert(e.message || String(e))
|
alert(e.message || String(e))
|
||||||
}
|
}
|
||||||
@@ -114,7 +132,46 @@ function AdminUsersPage() {
|
|||||||
try {
|
try {
|
||||||
await api.removeClubMember(clubEditModal.clubId, clubEditModal.profileId)
|
await api.removeClubMember(clubEditModal.clubId, clubEditModal.profileId)
|
||||||
setClubEditModal(null)
|
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) {
|
} catch (e) {
|
||||||
alert(e.message || String(e))
|
alert(e.message || String(e))
|
||||||
}
|
}
|
||||||
@@ -123,12 +180,45 @@ function AdminUsersPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="app-page">
|
<div className="app-page">
|
||||||
<AdminPageNav />
|
<AdminPageNav />
|
||||||
<h1 style={{ marginTop: 0 }}>Portal-Nutzer & Vereine</h1>
|
|
||||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '1.25rem' }}>
|
<h1 style={{ marginTop: 0 }}>Globale Nutzer & Portal-Rollen</h1>
|
||||||
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 style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '0.75rem' }}>
|
||||||
</p>
|
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 ? (
|
{loading ? (
|
||||||
<p style={{ color: 'var(--text2)' }}>Laden…</p>
|
<p style={{ color: 'var(--text2)' }}>Laden…</p>
|
||||||
@@ -138,140 +228,156 @@ function AdminUsersPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div style={{ display: 'grid', gap: '1rem' }}>
|
<div style={{ display: 'grid', gap: '1rem' }}>
|
||||||
{users.map((row) => {
|
{platformUsers.map((row) => {
|
||||||
const tierValue = portalDraft[row.id]?.tier ?? row.tier ?? 'free'
|
const portalRoleChoices = portalRoleSelectOptions(isSuperadminViewer, row.role)
|
||||||
const tierChoices = [...TIER_OPTIONS]
|
|
||||||
if (tierValue && !tierChoices.includes(tierValue)) tierChoices.unshift(tierValue)
|
|
||||||
return (
|
return (
|
||||||
<div key={row.id} className="card">
|
<div key={row.id} className="card">
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.75rem' }}>
|
<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>
|
<div>
|
||||||
<label className="form-label" style={{ fontSize: '0.75rem' }}>
|
<strong style={{ fontSize: '1.05rem' }}>
|
||||||
Portal-Rolle
|
{row.name || '—'} <span style={{ color: 'var(--text2)', fontWeight: 400 }}>#{row.id}</span>
|
||||||
</label>
|
</strong>
|
||||||
<select
|
<div style={{ fontSize: '0.875rem', color: 'var(--text2)' }}>{row.email || '—'}</div>
|
||||||
className="form-input"
|
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginTop: '0.35rem' }}>
|
||||||
style={{ minWidth: '140px' }}
|
Verifiziert: {row.email_verified ? 'ja' : 'nein'}
|
||||||
value={(portalDraft[row.id]?.role || row.role || 'user').toLowerCase()}
|
</div>
|
||||||
onChange={(e) =>
|
</div>
|
||||||
setPortalDraft((prev) => ({
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'flex-end' }}>
|
||||||
...prev,
|
<div>
|
||||||
[row.id]: { ...prev[row.id], role: e.target.value, tier: prev[row.id]?.tier ?? row.tier },
|
<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) => (
|
Passwort / Link
|
||||||
<option key={r} value={r}>
|
</button>
|
||||||
{ROLE_LABEL[r] || r}
|
<button type="button" className="btn btn-secondary" onClick={() => savePortal(row.id)}>
|
||||||
</option>
|
Portal speichern
|
||||||
))}
|
</button>
|
||||||
</select>
|
<button
|
||||||
</div>
|
type="button"
|
||||||
<div>
|
className="btn btn-primary"
|
||||||
<label className="form-label" style={{ fontSize: '0.75rem' }}>
|
disabled={!clubs.length}
|
||||||
Tier
|
title={!clubs.length ? 'Zuerst einen Verein anlegen' : undefined}
|
||||||
</label>
|
onClick={() => {
|
||||||
<select
|
if (!clubs.length) return
|
||||||
className="form-input"
|
setAssignRoles(['trainer'])
|
||||||
style={{ minWidth: '120px' }}
|
setAssignModal({
|
||||||
value={tierValue}
|
profileId: row.id,
|
||||||
onChange={(e) =>
|
profileLabel: row.name || row.email || `#${row.id}`,
|
||||||
setPortalDraft((prev) => ({
|
clubId: clubs[0]?.id ?? '',
|
||||||
...prev,
|
})
|
||||||
[row.id]: {
|
}}
|
||||||
...prev[row.id],
|
|
||||||
tier: e.target.value,
|
|
||||||
role: prev[row.id]?.role ?? row.role,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{tierChoices.map((t) => (
|
Verein zuweisen
|
||||||
<option key={t} value={t}>
|
</button>
|
||||||
{t}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
</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>
|
|
||||||
|
|
||||||
<div style={{ marginTop: '1rem', paddingTop: '0.75rem', borderTop: '1px solid var(--border)' }}>
|
<div style={{ marginTop: '1rem', paddingTop: '0.75rem', borderTop: '1px solid var(--border)' }}>
|
||||||
<strong style={{ fontSize: '0.85rem' }}>Vereinsmitgliedschaften</strong>
|
<strong style={{ fontSize: '0.85rem' }}>Vereinsmitgliedschaften</strong>
|
||||||
{!row.clubs?.length ? (
|
{!row.clubs?.length ? (
|
||||||
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', margin: '0.35rem 0 0' }}>
|
<p style={{ color: 'var(--text2)', fontSize: '0.875rem', margin: '0.35rem 0 0' }}>
|
||||||
Keine Zuordnung.
|
Keine Zuordnung.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem', fontSize: '0.9rem' }}>
|
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem', fontSize: '0.9rem' }}>
|
||||||
{row.clubs.map((c) => (
|
{(row.clubs || []).map((c) => (
|
||||||
<li key={c.id} style={{ marginBottom: '0.35rem' }}>
|
<li key={c.id} style={{ marginBottom: '0.35rem' }}>
|
||||||
<strong>{c.name}</strong>
|
<strong>{c.name}</strong>
|
||||||
{c.abbreviation ? ` (${c.abbreviation})` : ''} —{' '}
|
{c.abbreviation ? ` (${c.abbreviation})` : ''} —{' '}
|
||||||
{(c.roles || []).join(', ') || '—'}
|
{(c.roles || []).join(', ') || '—'}
|
||||||
{c.membership_status === 'inactive' ? (
|
{c.membership_status === 'inactive' ? (
|
||||||
<span style={{ color: 'var(--text3)', fontSize: '0.8rem' }}> (inaktiv)</span>
|
<span style={{ color: 'var(--warning, #d4a012)', fontSize: '0.8rem', fontWeight: 600 }}>
|
||||||
) : null}{' '}
|
{' '}
|
||||||
<button
|
(Vereinszugang deaktiviert)
|
||||||
type="button"
|
</span>
|
||||||
style={{
|
) : null}{' '}
|
||||||
marginLeft: '0.35rem',
|
<button
|
||||||
fontSize: '0.75rem',
|
type="button"
|
||||||
padding: '0.12rem 0.45rem',
|
style={{
|
||||||
borderRadius: '6px',
|
marginLeft: '0.35rem',
|
||||||
border: '1px solid var(--border)',
|
fontSize: '0.75rem',
|
||||||
background: 'var(--surface2)',
|
padding: '0.12rem 0.45rem',
|
||||||
cursor: 'pointer',
|
borderRadius: '6px',
|
||||||
}}
|
border: '1px solid var(--border)',
|
||||||
onClick={() =>
|
background: 'var(--surface2)',
|
||||||
setClubEditModal({
|
cursor: 'pointer',
|
||||||
clubId: c.id,
|
}}
|
||||||
clubName: c.name,
|
onClick={() =>
|
||||||
profileId: row.id,
|
setClubEditModal({
|
||||||
profileLabel: row.name || row.email,
|
clubId: c.id,
|
||||||
roles: [...(c.roles || [])],
|
clubName: c.name,
|
||||||
status: (c.membership_status || 'active').toLowerCase(),
|
profileId: row.id,
|
||||||
})
|
profileLabel: row.name || row.email,
|
||||||
}
|
roles: [...(c.roles || [])],
|
||||||
>
|
status: (c.membership_status || 'active').toLowerCase(),
|
||||||
bearbeiten
|
})
|
||||||
</button>
|
}
|
||||||
</li>
|
>
|
||||||
))}
|
bearbeiten
|
||||||
</ul>
|
</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>
|
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
@@ -346,11 +452,7 @@ function AdminUsersPage() {
|
|||||||
<button type="button" className="btn btn-primary" style={{ flex: 1 }} onClick={submitAssignClub}>
|
<button type="button" className="btn btn-primary" style={{ flex: 1 }} onClick={submitAssignClub}>
|
||||||
Zuweisen
|
Zuweisen
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button type="button" className="btn btn-secondary" onClick={() => setAssignModal(null)}>
|
||||||
type="button"
|
|
||||||
className="btn btn-secondary"
|
|
||||||
onClick={() => setAssignModal(null)}
|
|
||||||
>
|
|
||||||
Abbrechen
|
Abbrechen
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -384,8 +486,11 @@ function AdminUsersPage() {
|
|||||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>
|
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>
|
||||||
{clubEditModal.profileLabel} → {clubEditModal.clubName}
|
{clubEditModal.profileLabel} → {clubEditModal.clubName}
|
||||||
</p>
|
</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">
|
<div className="form-row">
|
||||||
<label className="form-label">Status</label>
|
<label className="form-label">Vereinszugang</label>
|
||||||
<select
|
<select
|
||||||
className="form-input"
|
className="form-input"
|
||||||
value={clubEditModal.status}
|
value={clubEditModal.status}
|
||||||
@@ -393,8 +498,8 @@ function AdminUsersPage() {
|
|||||||
setClubEditModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
setClubEditModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<option value="active">aktiv</option>
|
<option value="active">aktiv — sieht Vereinsinhalte</option>
|
||||||
<option value="inactive">inaktiv</option>
|
<option value="inactive">deaktiviert — kein Zugriff auf Vereinsinhalte</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div className="form-row">
|
<div className="form-row">
|
||||||
@@ -441,8 +546,86 @@ function AdminUsersPage() {
|
|||||||
</div>
|
</div>
|
||||||
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AdminUsersPage
|
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
import React, { useState, useEffect, useMemo } from 'react'
|
import React, { useState, useEffect, useMemo } from 'react'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
|
import { notifyOrgInboxChanged } from '../context/OrgInboxContext'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
|
import { isEscalatedPortalRole } from '../utils/portalRoles'
|
||||||
import PageSectionNav from '../components/PageSectionNav'
|
import PageSectionNav from '../components/PageSectionNav'
|
||||||
|
|
||||||
const CLUB_ROLE_OPTIONS = [
|
const CLUB_ROLE_OPTIONS = [
|
||||||
@@ -33,6 +36,9 @@ function ClubsPage() {
|
|||||||
|
|
||||||
const [editMemberModal, setEditMemberModal] = useState(null)
|
const [editMemberModal, setEditMemberModal] = useState(null)
|
||||||
const [acceptJoinModal, setAcceptJoinModal] = useState(null)
|
const [acceptJoinModal, setAcceptJoinModal] = useState(null)
|
||||||
|
const [pwdModal, setPwdModal] = useState(null)
|
||||||
|
const [pwdNew, setPwdNew] = useState('')
|
||||||
|
const [pwdNew2, setPwdNew2] = useState('')
|
||||||
|
|
||||||
// Form state
|
// Form state
|
||||||
const [formData, setFormData] = useState({})
|
const [formData, setFormData] = useState({})
|
||||||
@@ -40,7 +46,7 @@ function ClubsPage() {
|
|||||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||||
const isSuperAdmin = user?.role === 'superadmin'
|
const isSuperAdmin = user?.role === 'superadmin'
|
||||||
const clubAdminClubIds = new Set(
|
const clubAdminClubIds = new Set(
|
||||||
(user?.clubs || [])
|
activeClubMemberships(user?.clubs)
|
||||||
.filter((c) => (c.roles || []).includes('club_admin'))
|
.filter((c) => (c.roles || []).includes('club_admin'))
|
||||||
.map((c) => c.id)
|
.map((c) => c.id)
|
||||||
)
|
)
|
||||||
@@ -48,7 +54,7 @@ function ClubsPage() {
|
|||||||
const canCreateClub = isPlatformAdmin
|
const canCreateClub = isPlatformAdmin
|
||||||
const canManageOrgSomewhere = isPlatformAdmin || clubAdminClubIds.size > 0
|
const canManageOrgSomewhere = isPlatformAdmin || clubAdminClubIds.size > 0
|
||||||
const canCreateTrainingGroup =
|
const canCreateTrainingGroup =
|
||||||
isPlatformAdmin || (Array.isArray(user?.clubs) && user.clubs.length > 0)
|
isPlatformAdmin || activeClubMemberships(user?.clubs).length > 0
|
||||||
|
|
||||||
const canEditGroup = (g) =>
|
const canEditGroup = (g) =>
|
||||||
isPlatformAdmin ||
|
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) => {
|
const handleEdit = (item, type) => {
|
||||||
setEditing(item)
|
setEditing(item)
|
||||||
setModalType(type)
|
setModalType(type)
|
||||||
@@ -647,6 +712,7 @@ function ClubsPage() {
|
|||||||
if (!confirm('Antrag ablehnen?')) return
|
if (!confirm('Antrag ablehnen?')) return
|
||||||
try {
|
try {
|
||||||
await api.rejectClubJoinRequest(membersAdminClubId, req.id)
|
await api.rejectClubJoinRequest(membersAdminClubId, req.id)
|
||||||
|
notifyOrgInboxChanged()
|
||||||
await reloadMembersAdmin()
|
await reloadMembersAdmin()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert(err.message || String(err))
|
alert(err.message || String(err))
|
||||||
@@ -664,17 +730,41 @@ function ClubsPage() {
|
|||||||
|
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<h3 style={{ marginTop: 0 }}>Mitglieder</h3>
|
<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 ? (
|
{clubMembersAdmin.length === 0 ? (
|
||||||
<p style={{ color: 'var(--text2)' }}>Noch keine Mitglieder erfasst.</p>
|
<p style={{ color: 'var(--text2)' }}>Noch keine Mitglieder erfasst.</p>
|
||||||
) : (
|
) : (
|
||||||
<div style={{ display: 'grid', gap: '0.65rem' }}>
|
<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
|
<div
|
||||||
key={m.membership_id}
|
key={m.membership_id}
|
||||||
style={{
|
style={{
|
||||||
padding: '0.65rem',
|
padding: '0.65rem',
|
||||||
borderRadius: '8px',
|
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',
|
display: 'flex',
|
||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
flexWrap: 'wrap',
|
flexWrap: 'wrap',
|
||||||
@@ -684,21 +774,77 @@ function ClubsPage() {
|
|||||||
<div>
|
<div>
|
||||||
<strong>{m.name || m.email}</strong>
|
<strong>{m.name || m.email}</strong>
|
||||||
<div style={{ fontSize: '0.8rem', color: 'var(--text2)' }}>
|
<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>
|
||||||
<div style={{ fontSize: '0.8rem', marginTop: '0.25rem' }}>
|
<div style={{ fontSize: '0.8rem', marginTop: '0.25rem' }}>
|
||||||
Rollen: {(m.roles || []).join(', ') || '—'}
|
Rollen: {(m.roles || []).join(', ') || '—'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem', alignItems: 'stretch' }}>
|
||||||
type="button"
|
<button type="button" className="btn btn-secondary" onClick={() => setEditMemberModal(m)}>
|
||||||
className="btn btn-secondary"
|
Mitglied bearbeiten
|
||||||
onClick={() => setEditMemberModal(m)}
|
</button>
|
||||||
>
|
{m.profile_id !== user?.id ? (
|
||||||
Bearbeiten
|
<button
|
||||||
</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>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -1255,6 +1401,7 @@ function ClubsPage() {
|
|||||||
acceptJoinModal.id,
|
acceptJoinModal.id,
|
||||||
acceptJoinModal.roles.length ? acceptJoinModal.roles : ['trainer']
|
acceptJoinModal.roles.length ? acceptJoinModal.roles : ['trainer']
|
||||||
)
|
)
|
||||||
|
notifyOrgInboxChanged()
|
||||||
setAcceptJoinModal(null)
|
setAcceptJoinModal(null)
|
||||||
await reloadMembersAdmin()
|
await reloadMembersAdmin()
|
||||||
await loadData()
|
await loadData()
|
||||||
@@ -1307,7 +1454,7 @@ function ClubsPage() {
|
|||||||
{editMemberModal.name || editMemberModal.email} (#{editMemberModal.profile_id})
|
{editMemberModal.name || editMemberModal.email} (#{editMemberModal.profile_id})
|
||||||
</p>
|
</p>
|
||||||
<div className="form-row">
|
<div className="form-row">
|
||||||
<label className="form-label">Status</label>
|
<label className="form-label">Vereinszugang</label>
|
||||||
<select
|
<select
|
||||||
className="form-input"
|
className="form-input"
|
||||||
value={editMemberModal.status || 'active'}
|
value={editMemberModal.status || 'active'}
|
||||||
@@ -1315,10 +1462,13 @@ function ClubsPage() {
|
|||||||
setEditMemberModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
setEditMemberModal((prev) => (prev ? { ...prev, status: e.target.value } : prev))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<option value="active">aktiv</option>
|
<option value="active">aktiv — sieht Vereinsinhalte</option>
|
||||||
<option value="inactive">inaktiv</option>
|
<option value="inactive">deaktiviert — weiter anmeldbar, keine Vereinsinhalte</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</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">
|
<div className="form-row">
|
||||||
<span className="form-label">Rollen</span>
|
<span className="form-label">Rollen</span>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
||||||
@@ -1394,6 +1544,93 @@ function ClubsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useAuth } from '../context/AuthContext'
|
|||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import EmailVerificationBanner from '../components/EmailVerificationBanner'
|
import EmailVerificationBanner from '../components/EmailVerificationBanner'
|
||||||
import DashboardTrainingVisibilityWidget from '../components/DashboardTrainingVisibilityWidget'
|
import DashboardTrainingVisibilityWidget from '../components/DashboardTrainingVisibilityWidget'
|
||||||
|
import DashboardOrgInboxWidget from '../components/DashboardOrgInboxWidget'
|
||||||
|
|
||||||
function unitWhenLabel(u) {
|
function unitWhenLabel(u) {
|
||||||
const d = u.planned_date ? String(u.planned_date).slice(0, 10) : ''
|
const d = u.planned_date ? String(u.planned_date).slice(0, 10) : ''
|
||||||
@@ -183,6 +184,7 @@ function Dashboard() {
|
|||||||
|
|
||||||
{user?.id ? (
|
{user?.id ? (
|
||||||
<>
|
<>
|
||||||
|
<DashboardOrgInboxWidget />
|
||||||
<section className="dashboard-section" aria-labelledby="dash-phase0-title">
|
<section className="dashboard-section" aria-labelledby="dash-phase0-title">
|
||||||
<div className="dashboard-section__header">
|
<div className="dashboard-section__header">
|
||||||
<div className="dashboard-section__headline">
|
<div className="dashboard-section__headline">
|
||||||
|
|||||||
@@ -1,57 +1,10 @@
|
|||||||
import React, { useEffect, useState } from 'react'
|
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 api from '../utils/api'
|
||||||
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
|
import ExerciseRichTextBlock from '../components/ExerciseRichTextBlock'
|
||||||
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
|
import ExerciseAttachmentMediaStrip from '../components/ExerciseAttachmentMediaStrip'
|
||||||
import { formatSkillLevelSlug } from '../constants/skillLevels'
|
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 }) {
|
function TagRow({ exercise }) {
|
||||||
const tags = []
|
const tags = []
|
||||||
;(exercise.focus_areas || []).forEach((f) => {
|
;(exercise.focus_areas || []).forEach((f) => {
|
||||||
@@ -100,6 +53,7 @@ function metaParts(exercise) {
|
|||||||
function ExerciseDetailPage() {
|
function ExerciseDetailPage() {
|
||||||
const { id } = useParams()
|
const { id } = useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const location = useLocation()
|
||||||
const [exercise, setExercise] = useState(null)
|
const [exercise, setExercise] = useState(null)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
@@ -151,27 +105,26 @@ function ExerciseDetailPage() {
|
|||||||
if (!exercise) return null
|
if (!exercise) return null
|
||||||
|
|
||||||
const meta = metaParts(exercise)
|
const meta = metaParts(exercise)
|
||||||
const visibleMedia = (exercise.media || []).filter((m) => {
|
const fromExerciseEdit = location.state?.fromExerciseEdit === true
|
||||||
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
|
|
||||||
return lc !== 'trash_hidden'
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="exercise-detail-shell" style={{ padding: '12px 12px 24px' }}>
|
<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')}>
|
<button type="button" className="btn btn-secondary" onClick={() => navigate('/exercises')}>
|
||||||
← Übersicht
|
← Übersicht
|
||||||
</button>
|
</button>
|
||||||
<Link to={`/exercises/${exercise.id}/edit`} className="btn btn-primary">
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginLeft: 'auto' }}>
|
||||||
Bearbeiten
|
<Link to={`/exercises/${exercise.id}/edit`} className="btn btn-primary">
|
||||||
</Link>
|
{fromExerciseEdit ? 'Zurück zur Bearbeitung' : 'Bearbeiten'}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card exercise-detail-section">
|
<div className="card exercise-detail-section">
|
||||||
<h1 style={{ margin: 0, fontSize: '1.35rem', lineHeight: 1.25 }}>{exercise.title}</h1>
|
<h1 style={{ margin: 0, fontSize: '1.35rem', lineHeight: 1.25 }}>{exercise.title}</h1>
|
||||||
{exercise.summary && (
|
{exercise.summary && (
|
||||||
<div style={{ marginTop: '10px', color: 'var(--text2)', fontSize: '15px' }}>
|
<div style={{ marginTop: '10px', color: 'var(--text2)', fontSize: '15px' }}>
|
||||||
<HtmlBlock html={exercise.summary} />
|
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<TagRow exercise={exercise} />
|
<TagRow exercise={exercise} />
|
||||||
@@ -186,7 +139,7 @@ function ExerciseDetailPage() {
|
|||||||
{exercise.goal && (
|
{exercise.goal && (
|
||||||
<section className="card exercise-detail-section">
|
<section className="card exercise-detail-section">
|
||||||
<h2>Ziel</h2>
|
<h2>Ziel</h2>
|
||||||
<HtmlBlock html={exercise.goal} />
|
<ExerciseRichTextBlock html={exercise.goal} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -204,39 +157,23 @@ function ExerciseDetailPage() {
|
|||||||
{exercise.preparation && (
|
{exercise.preparation && (
|
||||||
<section className="card exercise-detail-section">
|
<section className="card exercise-detail-section">
|
||||||
<h2>Vorbereitung</h2>
|
<h2>Vorbereitung</h2>
|
||||||
<HtmlBlock html={exercise.preparation} />
|
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{exercise.execution && (
|
{exercise.execution && (
|
||||||
<section className="card exercise-detail-section">
|
<section className="card exercise-detail-section">
|
||||||
<h2>Ablauf</h2>
|
<h2>Ablauf</h2>
|
||||||
<HtmlBlock html={exercise.execution} />
|
<ExerciseRichTextBlock html={exercise.execution} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{visibleMedia.length > 0 && (
|
<ExerciseAttachmentMediaStrip exercise={exercise} exerciseId={exercise.id} />
|
||||||
<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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{exercise.trainer_notes && (
|
{exercise.trainer_notes && (
|
||||||
<section className="card exercise-detail-section">
|
<section className="card exercise-detail-section">
|
||||||
<h2>Hinweise für Trainer</h2>
|
<h2>Hinweise für Trainer</h2>
|
||||||
<HtmlBlock html={exercise.trainer_notes} />
|
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={exercise.id} media={exercise.media} />
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -307,7 +244,11 @@ function ExerciseDetailPage() {
|
|||||||
{v.description && <p style={{ color: 'var(--text2)', marginTop: '4px' }}>{v.description}</p>}
|
{v.description && <p style={{ color: 'var(--text2)', marginTop: '4px' }}>{v.description}</p>}
|
||||||
{v.execution_changes && (
|
{v.execution_changes && (
|
||||||
<div style={{ marginTop: '8px' }}>
|
<div style={{ marginTop: '8px' }}>
|
||||||
<HtmlBlock html={v.execution_changes} />
|
<ExerciseRichTextBlock
|
||||||
|
html={v.execution_changes}
|
||||||
|
exerciseId={exercise.id}
|
||||||
|
media={exercise.media}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,87 +4,15 @@ import api, { buildExerciseApiPayload } from '../utils/api'
|
|||||||
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
import { resolveExerciseMediaFileUrl, resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||||
import RichTextEditor from '../components/RichTextEditor'
|
import RichTextEditor from '../components/RichTextEditor'
|
||||||
import ExerciseProgressionGraphPanel from '../components/ExerciseProgressionGraphPanel'
|
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'
|
import { SKILL_LEVEL_OPTIONS, normalizeSkillLevelSlug } from '../constants/skillLevels'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
|
|
||||||
/** MIME/Dateiname → Übungs-media_type; null → Dropdown-Fallback. */
|
|
||||||
function inferExerciseMediaType(file) {
|
|
||||||
if (!file) return null
|
|
||||||
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 null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const INTENSITY_OPTIONS = [
|
const INTENSITY_OPTIONS = [
|
||||||
{ value: '', label: '—' },
|
{ value: '', label: '—' },
|
||||||
{ value: 'niedrig', label: 'niedrig' },
|
{ value: 'niedrig', label: 'niedrig' },
|
||||||
@@ -169,7 +97,15 @@ function buildVariantPayloadFromRow(row) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Gemeinsame Felder für „Variante bearbeiten“ und „Neue Variante“. */
|
/** 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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="form-row">
|
<div className="form-row">
|
||||||
@@ -198,6 +134,9 @@ function ExerciseVariantFields({ row, onPatch, prerequisiteOthers, rteMinHeight
|
|||||||
onChange={(html) => onPatch({ execution_changes: html })}
|
onChange={(html) => onPatch({ execution_changes: html })}
|
||||||
placeholder="Was unterscheidet diese Variante? (Listen über Symbolleiste)"
|
placeholder="Was unterscheidet diese Variante? (Listen über Symbolleiste)"
|
||||||
minHeight={rteMinHeight}
|
minHeight={rteMinHeight}
|
||||||
|
inlineExerciseId={inlineExerciseId}
|
||||||
|
linkedExerciseMedia={linkedExerciseMedia}
|
||||||
|
onExerciseMediaListChanged={onExerciseMediaListChanged}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
|
||||||
@@ -435,6 +374,7 @@ function ExerciseFormPage() {
|
|||||||
const [mediaList, setMediaList] = useState([])
|
const [mediaList, setMediaList] = useState([])
|
||||||
const [loading, setLoading] = useState(!!isEdit)
|
const [loading, setLoading] = useState(!!isEdit)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [formDirty, setFormDirty] = useState(false)
|
||||||
const [skillPick, setSkillPick] = useState('')
|
const [skillPick, setSkillPick] = useState('')
|
||||||
const [variants, setVariants] = useState([])
|
const [variants, setVariants] = useState([])
|
||||||
const [variantDraft, setVariantDraft] = useState(() => emptyVariantDraft())
|
const [variantDraft, setVariantDraft] = useState(() => emptyVariantDraft())
|
||||||
@@ -443,17 +383,10 @@ function ExerciseFormPage() {
|
|||||||
const [variantEditSelection, setVariantEditSelection] = useState(null)
|
const [variantEditSelection, setVariantEditSelection] = useState(null)
|
||||||
const variantsDetailsRef = useRef(null)
|
const variantsDetailsRef = useRef(null)
|
||||||
|
|
||||||
const [mediaFiles, setMediaFiles] = useState([])
|
|
||||||
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 [mediaFields, setMediaFields] = useState({})
|
||||||
const [mediaSavingId, setMediaSavingId] = useState(null)
|
const [mediaSavingId, setMediaSavingId] = useState(null)
|
||||||
const [archiveOpen, setArchiveOpen] = useState(false)
|
const [archiveOpen, setArchiveOpen] = useState(false)
|
||||||
const [archiveQ, setArchiveQ] = useState('')
|
const [archiveQ, setArchiveQ] = useState('')
|
||||||
const [archiveCtx, setArchiveCtx] = useState('ablauf')
|
|
||||||
const [archiveLoading, setArchiveLoading] = useState(false)
|
const [archiveLoading, setArchiveLoading] = useState(false)
|
||||||
const [archiveItems, setArchiveItems] = useState([])
|
const [archiveItems, setArchiveItems] = useState([])
|
||||||
const [archiveError, setArchiveError] = useState(null)
|
const [archiveError, setArchiveError] = useState(null)
|
||||||
@@ -464,12 +397,32 @@ function ExerciseFormPage() {
|
|||||||
for (const m of mediaList) {
|
for (const m of mediaList) {
|
||||||
next[m.id] = {
|
next[m.id] = {
|
||||||
title: m.title || '',
|
title: m.title || '',
|
||||||
context: m.context || 'ablauf',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setMediaFields(next)
|
setMediaFields(next)
|
||||||
}, [mediaList])
|
}, [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(() => {
|
useEffect(() => {
|
||||||
if (!archiveOpen) return undefined
|
if (!archiveOpen) return undefined
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
@@ -534,6 +487,7 @@ function ExerciseFormPage() {
|
|||||||
setVariants([])
|
setVariants([])
|
||||||
setVariantDraft(emptyVariantDraft())
|
setVariantDraft(emptyVariantDraft())
|
||||||
setVariantEditSelection(null)
|
setVariantEditSelection(null)
|
||||||
|
setFormDirty(false)
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -548,6 +502,7 @@ function ExerciseFormPage() {
|
|||||||
setVariants((exercise.variants || []).map(apiVariantToRow))
|
setVariants((exercise.variants || []).map(apiVariantToRow))
|
||||||
setVariantDraft(emptyVariantDraft())
|
setVariantDraft(emptyVariantDraft())
|
||||||
setVariantEditSelection(null)
|
setVariantEditSelection(null)
|
||||||
|
setFormDirty(false)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
alert(err.message || 'Übung nicht ladbar')
|
alert(err.message || 'Übung nicht ladbar')
|
||||||
@@ -577,6 +532,7 @@ function ExerciseFormPage() {
|
|||||||
}, [variantEditSelection])
|
}, [variantEditSelection])
|
||||||
|
|
||||||
const updateFormField = (field, value) => {
|
const updateFormField = (field, value) => {
|
||||||
|
setFormDirty(true)
|
||||||
setFormData((prev) => ({ ...prev, [field]: value }))
|
setFormData((prev) => ({ ...prev, [field]: value }))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -698,10 +654,23 @@ function ExerciseFormPage() {
|
|||||||
firstErr.code === 'CLUB_MEDIA_COPYRIGHT_REQUIRED' &&
|
firstErr.code === 'CLUB_MEDIA_COPYRIGHT_REQUIRED' &&
|
||||||
firstErr.payload?.media_assets
|
firstErr.payload?.media_assets
|
||||||
) {
|
) {
|
||||||
alert(
|
const miss = firstErr.payload.media_assets.length
|
||||||
'Vereinsöffentliche Übungen brauchen bei jeder verknüpften Datei einen Copyright-Vermerk (mind. 3 Zeichen). Bitte in der Medienbibliothek oder den Mediendetails nachtragen.',
|
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):',
|
||||||
|
'© ',
|
||||||
)
|
)
|
||||||
throw firstErr
|
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') {
|
} else if (firstErr.status === 422 && firstErr.code === 'CLUB_MEDIA_LIFECYCLE') {
|
||||||
alert(
|
alert(
|
||||||
'Speichern nicht möglich: mindestens ein verknüpftes Medium ist nicht aktiv (Papierkorb). Bitte reaktivieren oder entfernen.',
|
'Speichern nicht möglich: mindestens ein verknüpftes Medium ist nicht aktiv (Papierkorb). Bitte reaktivieren oder entfernen.',
|
||||||
@@ -714,6 +683,7 @@ function ExerciseFormPage() {
|
|||||||
const ex = await api.getExercise(exerciseId)
|
const ex = await api.getExercise(exerciseId)
|
||||||
setMediaList(ex.media || [])
|
setMediaList(ex.media || [])
|
||||||
setVariants((ex.variants || []).map(apiVariantToRow))
|
setVariants((ex.variants || []).map(apiVariantToRow))
|
||||||
|
setFormDirty(false)
|
||||||
alert('Gespeichert.')
|
alert('Gespeichert.')
|
||||||
} else {
|
} else {
|
||||||
const created = await api.createExercise(payload)
|
const created = await api.createExercise(payload)
|
||||||
@@ -737,7 +707,7 @@ function ExerciseFormPage() {
|
|||||||
try {
|
try {
|
||||||
await api.attachExerciseMediaFromAsset(exerciseId, {
|
await api.attachExerciseMediaFromAsset(exerciseId, {
|
||||||
media_asset_id: assetId,
|
media_asset_id: assetId,
|
||||||
context: archiveCtx,
|
context: 'ablauf',
|
||||||
title: '',
|
title: '',
|
||||||
description: '',
|
description: '',
|
||||||
is_primary: false,
|
is_primary: false,
|
||||||
@@ -754,92 +724,11 @@ function ExerciseFormPage() {
|
|||||||
[mediaList],
|
[mediaList],
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleUploadFile = async () => {
|
|
||||||
if (!exerciseId || mediaFiles.length === 0) {
|
|
||||||
alert('Datei(en) wählen')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const files = [...mediaFiles]
|
|
||||||
for (const file of files) {
|
|
||||||
const inferred = inferExerciseMediaType(file) || mediaType
|
|
||||||
const fd = new FormData()
|
|
||||||
fd.append('file', file)
|
|
||||||
fd.append('media_type', inferred)
|
|
||||||
fd.append('title', mediaTitle)
|
|
||||||
fd.append('description', '')
|
|
||||||
fd.append('context', mediaContext)
|
|
||||||
fd.append('is_primary', 'false')
|
|
||||||
try {
|
|
||||||
await api.uploadExerciseMedia(exerciseId, fd)
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code === 'MEDIA_ASSET_IN_TRASH' && err.payload?.media_asset_id != null) {
|
|
||||||
const aid = err.payload.media_asset_id
|
|
||||||
const nameHint = file?.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,
|
|
||||||
})
|
|
||||||
} catch (e2) {
|
|
||||||
alert(e2.message || String(e2))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else 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
|
|
||||||
} else {
|
|
||||||
alert(`Upload (${file.name}): ${err.message || String(err)}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setMediaFiles([])
|
|
||||||
setMediaTitle('')
|
|
||||||
await refreshMedia()
|
|
||||||
}
|
|
||||||
|
|
||||||
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) => {
|
const handleDeleteMedia = async (mid) => {
|
||||||
if (
|
if (
|
||||||
!confirm(
|
!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
|
return
|
||||||
@@ -890,7 +779,6 @@ function ExerciseFormPage() {
|
|||||||
try {
|
try {
|
||||||
await api.updateExerciseMedia(exerciseId, mid, {
|
await api.updateExerciseMedia(exerciseId, mid, {
|
||||||
title: fld.title.trim() || null,
|
title: fld.title.trim() || null,
|
||||||
context: fld.context,
|
|
||||||
})
|
})
|
||||||
await refreshMedia()
|
await refreshMedia()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -907,6 +795,7 @@ function ExerciseFormPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateVariantField = (id, patch) => {
|
const updateVariantField = (id, patch) => {
|
||||||
|
setFormDirty(true)
|
||||||
setVariants((prev) => prev.map((v) => (v.id === id ? { ...v, ...patch } : v)))
|
setVariants((prev) => prev.map((v) => (v.id === id ? { ...v, ...patch } : v)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1010,7 +899,18 @@ function ExerciseFormPage() {
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
style={{ marginLeft: '8px' }}
|
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
|
Ansehen
|
||||||
</button>
|
</button>
|
||||||
@@ -1040,6 +940,9 @@ function ExerciseFormPage() {
|
|||||||
onChange={(html) => updateFormField('summary', html)}
|
onChange={(html) => updateFormField('summary', html)}
|
||||||
placeholder="Kurzbeschreibung (optional)"
|
placeholder="Kurzbeschreibung (optional)"
|
||||||
minHeight="80px"
|
minHeight="80px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1050,6 +953,9 @@ function ExerciseFormPage() {
|
|||||||
onChange={(html) => updateFormField('goal', html)}
|
onChange={(html) => updateFormField('goal', html)}
|
||||||
placeholder="Trainingsziel"
|
placeholder="Trainingsziel"
|
||||||
minHeight="120px"
|
minHeight="120px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1060,6 +966,9 @@ function ExerciseFormPage() {
|
|||||||
onChange={(html) => updateFormField('execution', html)}
|
onChange={(html) => updateFormField('execution', html)}
|
||||||
placeholder="Ablauf Schritt für Schritt"
|
placeholder="Ablauf Schritt für Schritt"
|
||||||
minHeight="180px"
|
minHeight="180px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1070,6 +979,9 @@ function ExerciseFormPage() {
|
|||||||
onChange={(html) => updateFormField('preparation', html)}
|
onChange={(html) => updateFormField('preparation', html)}
|
||||||
placeholder="Matten, Raum, …"
|
placeholder="Matten, Raum, …"
|
||||||
minHeight="100px"
|
minHeight="100px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1080,6 +992,9 @@ function ExerciseFormPage() {
|
|||||||
onChange={(html) => updateFormField('trainer_notes', html)}
|
onChange={(html) => updateFormField('trainer_notes', html)}
|
||||||
placeholder="Sicherheit, Varianten-Hinweise, …"
|
placeholder="Sicherheit, Varianten-Hinweise, …"
|
||||||
minHeight="100px"
|
minHeight="100px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1371,9 +1286,15 @@ function ExerciseFormPage() {
|
|||||||
<h3 style={{ marginTop: 0, fontSize: '1rem' }}>Neue Variante</h3>
|
<h3 style={{ marginTop: 0, fontSize: '1rem' }}>Neue Variante</h3>
|
||||||
<ExerciseVariantFields
|
<ExerciseVariantFields
|
||||||
row={variantDraft}
|
row={variantDraft}
|
||||||
onPatch={(patch) => setVariantDraft((d) => ({ ...d, ...patch }))}
|
onPatch={(patch) => {
|
||||||
|
setFormDirty(true)
|
||||||
|
setVariantDraft((d) => ({ ...d, ...patch }))
|
||||||
|
}}
|
||||||
prerequisiteOthers={variants}
|
prerequisiteOthers={variants}
|
||||||
rteMinHeight="110px"
|
rteMinHeight="110px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '10px' }} disabled={variantBusy}>
|
<button type="submit" className="btn btn-primary" style={{ marginTop: '10px' }} disabled={variantBusy}>
|
||||||
{variantBusy ? 'Anlegen…' : 'Variante anlegen'}
|
{variantBusy ? 'Anlegen…' : 'Variante anlegen'}
|
||||||
@@ -1440,6 +1361,9 @@ function ExerciseFormPage() {
|
|||||||
onPatch={(patch) => updateVariantField(selectedVariantForEdit.id, patch)}
|
onPatch={(patch) => updateVariantField(selectedVariantForEdit.id, patch)}
|
||||||
prerequisiteOthers={variants.filter((o) => o.id !== selectedVariantForEdit.id)}
|
prerequisiteOthers={variants.filter((o) => o.id !== selectedVariantForEdit.id)}
|
||||||
rteMinHeight="110px"
|
rteMinHeight="110px"
|
||||||
|
inlineExerciseId={isEdit ? exerciseId : null}
|
||||||
|
linkedExerciseMedia={isEdit ? mediaList : []}
|
||||||
|
onExerciseMediaListChanged={refreshMedia}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -1468,8 +1392,13 @@ function ExerciseFormPage() {
|
|||||||
{isEdit && (
|
{isEdit && (
|
||||||
<div className="card" style={{ marginTop: '16px' }}>
|
<div className="card" style={{ marginTop: '16px' }}>
|
||||||
<h2 style={{ marginTop: 0, fontSize: '1.1rem' }}>Medien</h2>
|
<h2 style={{ marginTop: 0, fontSize: '1.1rem' }}>Medien</h2>
|
||||||
<p style={{ color: 'var(--text2)', fontSize: '13px' }}>
|
<p style={{ color: 'var(--text2)', fontSize: '13px', marginBottom: '6px' }}>
|
||||||
Datei oder Embed (YouTube, Vimeo, Instagram, TikTok). Max. 10 pro Übung.
|
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>
|
</p>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -1487,193 +1416,125 @@ function ExerciseFormPage() {
|
|||||||
Medienbibliothek
|
Medienbibliothek
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ display: 'grid', gap: '12px', marginTop: '12px' }}>
|
|
||||||
<div>
|
|
||||||
<label className="form-label">Dateien</label>
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
multiple
|
|
||||||
accept="image/*,video/*,application/pdf"
|
|
||||||
onChange={(e) => {
|
|
||||||
setMediaFiles(Array.from(e.target.files || []))
|
|
||||||
e.target.value = ''
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{mediaFiles.length > 0 && (
|
|
||||||
<div style={{ fontSize: '0.875rem', color: 'var(--text2)', marginTop: '6px' }}>
|
|
||||||
{mediaFiles.length} Datei(en): {mediaFiles.map((f) => f.name).join(', ')}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="form-row" style={{ marginTop: '8px' }}>
|
|
||||||
<select className="form-input" value={mediaType} onChange={(e) => setMediaType(e.target.value)}>
|
|
||||||
<option value="image">Typ-Fallback: Bild</option>
|
|
||||||
<option value="video">Typ-Fallback: Video</option>
|
|
||||||
<option value="document">Typ-Fallback: 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 && (
|
{mediaList.length > 0 && (
|
||||||
<ul style={{ marginTop: '12px', paddingLeft: '0', listStyle: 'none' }}>
|
<ul className="exercise-edit-media-strip">
|
||||||
{mediaList.map((m, idx) => (
|
{mediaList.map((m, idx) => {
|
||||||
<li
|
const cap =
|
||||||
key={m.id}
|
(m.title || '').trim() ||
|
||||||
className="card"
|
(m.original_filename || '').trim() ||
|
||||||
style={{
|
(m.embed_url ? String(m.embed_url).replace(/^https?:\/\//i, '').slice(0, 80) : '')
|
||||||
marginBottom: '10px',
|
const sub = [m.media_type, m.embed_platform].filter(Boolean).join(' · ') || 'Medium'
|
||||||
padding: '10px 12px',
|
const payloadCaption = (
|
||||||
border: '1px solid var(--border)',
|
[m.title, m.original_filename].find((x) => typeof x === 'string' && x.trim()) || ''
|
||||||
display: 'flex',
|
).trim()
|
||||||
gap: '12px',
|
return (
|
||||||
alignItems: 'flex-start',
|
<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} />
|
<ExerciseMediaThumbTile exerciseId={exerciseId} media={m} onOpenPreview={setMediaPreview} size={76} />
|
||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
) : (
|
||||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'center' }}>
|
<div
|
||||||
<span style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
className="exercise-edit-media-strip__embed-badge exercise-edit-media-strip__embed-badge--solo"
|
||||||
#{idx + 1} · {m.media_type}
|
aria-hidden
|
||||||
{m.embed_platform ? ` · ${m.embed_platform}` : ''}
|
>
|
||||||
</span>
|
{m.embed_platform || 'Embed'}
|
||||||
{mediaList.length > 1 && (
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-primary"
|
||||||
style={{ fontSize: '11px', padding: '2px 8px' }}
|
style={{ fontSize: '12px', padding: '4px 10px' }}
|
||||||
disabled={idx === 0}
|
disabled={mediaSavingId === m.id}
|
||||||
onClick={() => moveMediaRow(idx, -1)}
|
onClick={() => saveMediaMeta(m.id)}
|
||||||
title="Nach oben"
|
|
||||||
>
|
>
|
||||||
↑
|
{mediaSavingId === m.id ? '…' : 'Speichern'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
style={{ fontSize: '11px', padding: '2px 8px' }}
|
style={{ fontSize: '12px', padding: '4px 10px' }}
|
||||||
disabled={idx >= mediaList.length - 1}
|
onClick={() => handleDeleteMedia(m.id)}
|
||||||
onClick={() => moveMediaRow(idx, 1)}
|
|
||||||
title="Nach unten"
|
|
||||||
>
|
>
|
||||||
↓
|
Entfernen
|
||||||
</button>
|
</button>
|
||||||
</>
|
</div>
|
||||||
)}
|
</div>
|
||||||
</div>
|
</li>
|
||||||
<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>
|
|
||||||
))}
|
|
||||||
</ul>
|
</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 && (
|
{archiveOpen && (
|
||||||
<div
|
<div
|
||||||
role="dialog"
|
role="dialog"
|
||||||
@@ -1710,16 +1571,6 @@ function ExerciseFormPage() {
|
|||||||
onChange={(e) => setArchiveQ(e.target.value)}
|
onChange={(e) => setArchiveQ(e.target.value)}
|
||||||
style={{ marginBottom: '8px' }}
|
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>}
|
{archiveLoading && <p style={{ fontSize: '13px', color: 'var(--text3)' }}>Laden…</p>}
|
||||||
{archiveError && <p style={{ fontSize: '13px', color: 'var(--danger)' }}>{archiveError}</p>}
|
{archiveError && <p style={{ fontSize: '13px', color: 'var(--danger)' }}>{archiveError}</p>}
|
||||||
{!archiveLoading && !archiveError && archiveItems.length === 0 && (
|
{!archiveLoading && !archiveError && archiveItems.length === 0 && (
|
||||||
|
|||||||
@@ -14,11 +14,13 @@ import {
|
|||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
||||||
import MultiSelectCombo from '../components/MultiSelectCombo'
|
import MultiSelectCombo from '../components/MultiSelectCombo'
|
||||||
import ExerciseFocusRulePicker from '../components/ExerciseFocusRulePicker'
|
import ExerciseFocusRulePicker from '../components/ExerciseFocusRulePicker'
|
||||||
import CatalogRulePicker from '../components/CatalogRulePicker'
|
import CatalogRulePicker from '../components/CatalogRulePicker'
|
||||||
import ExerciseProgressionGraphPanel from '../components/ExerciseProgressionGraphPanel'
|
import ExerciseProgressionGraphPanel from '../components/ExerciseProgressionGraphPanel'
|
||||||
|
import ExerciseRichTextBlock from '../components/ExerciseRichTextBlock'
|
||||||
import PageSectionNav from '../components/PageSectionNav'
|
import PageSectionNav from '../components/PageSectionNav'
|
||||||
import {
|
import {
|
||||||
INITIAL_EXERCISE_LIST_FILTERS,
|
INITIAL_EXERCISE_LIST_FILTERS,
|
||||||
@@ -27,7 +29,7 @@ import {
|
|||||||
splitMnCatalogRules,
|
splitMnCatalogRules,
|
||||||
splitScalarCatalogRules,
|
splitScalarCatalogRules,
|
||||||
} from '../constants/exerciseListFilters'
|
} from '../constants/exerciseListFilters'
|
||||||
import { sanitizeExerciseRichText, coerceApiNameList } from '../utils/sanitizeHtml'
|
import { coerceApiNameList } from '../utils/sanitizeHtml'
|
||||||
import { canUserRequestExerciseDelete } from '../utils/exercisePermissions'
|
import { canUserRequestExerciseDelete } from '../utils/exercisePermissions'
|
||||||
|
|
||||||
const PAGE_SIZE = 100
|
const PAGE_SIZE = 100
|
||||||
@@ -507,7 +509,7 @@ function ExercisesListPage() {
|
|||||||
|
|
||||||
const clubNameById = useMemo(() => {
|
const clubNameById = useMemo(() => {
|
||||||
const m = {}
|
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}`
|
if (c?.id != null) m[Number(c.id)] = c.name || `#${c.id}`
|
||||||
}
|
}
|
||||||
return m
|
return m
|
||||||
@@ -1205,7 +1207,7 @@ function ExercisesListPage() {
|
|||||||
onChange={(e) => setBulkClubSelect(e.target.value)}
|
onChange={(e) => setBulkClubSelect(e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="">Aktiver Verein (Vereins-Umschalter / Header)</option>
|
<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)}>
|
<option key={c.id} value={String(c.id)}>
|
||||||
{c.name || `#${c.id}`}
|
{c.name || `#${c.id}`}
|
||||||
</option>
|
</option>
|
||||||
@@ -1380,9 +1382,6 @@ function ExercisesListPage() {
|
|||||||
const focusNames = exerciseFocusNames(exercise)
|
const focusNames = exerciseFocusNames(exercise)
|
||||||
const styleNames = coerceApiNameList(exercise.style_direction_names)
|
const styleNames = coerceApiNameList(exercise.style_direction_names)
|
||||||
const typeNames = coerceApiNameList(exercise.training_type_names)
|
const typeNames = coerceApiNameList(exercise.training_type_names)
|
||||||
const summaryHtml = exercise.summary
|
|
||||||
? sanitizeExerciseRichText(exercise.summary)
|
|
||||||
: ''
|
|
||||||
return (
|
return (
|
||||||
<div key={exercise.id} className={exerciseCardClassName(exercise, user?.id)}>
|
<div key={exercise.id} className={exerciseCardClassName(exercise, user?.id)}>
|
||||||
<div className="exercise-card-layout exercise-card-layout--grow">
|
<div className="exercise-card-layout exercise-card-layout--grow">
|
||||||
@@ -1410,11 +1409,14 @@ function ExercisesListPage() {
|
|||||||
<span key={`tt:${name}`} className="exercise-tag exercise-tag--training">{name}</span>
|
<span key={`tt:${name}`} className="exercise-tag exercise-tag--training">{name}</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{summaryHtml ? (
|
{exercise.summary && String(exercise.summary).trim() ? (
|
||||||
<div
|
<div className="exercise-card-summary exercise-card-summary--rich">
|
||||||
className="exercise-card-summary exercise-card-summary--rich"
|
<ExerciseRichTextBlock
|
||||||
dangerouslySetInnerHTML={{ __html: summaryHtml }}
|
html={exercise.summary}
|
||||||
/>
|
exerciseId={exercise.id}
|
||||||
|
media={exercise.media || []}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import AdminPageNav from '../components/AdminPageNav'
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
|
||||||
|
|
||||||
const LC_OPTIONS = [
|
const LC_OPTIONS = [
|
||||||
@@ -234,6 +234,7 @@ export default function MediaLibraryPage() {
|
|||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||||
const isSuperadmin = user?.role === 'superadmin'
|
const isSuperadmin = user?.role === 'superadmin'
|
||||||
|
const hasClubOrgAdmin = activeClubMemberships(user?.clubs).some((c) => (c.roles || []).includes('club_admin'))
|
||||||
|
|
||||||
const archiveVisOptions = useMemo(
|
const archiveVisOptions = useMemo(
|
||||||
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
||||||
@@ -538,22 +539,23 @@ export default function MediaLibraryPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-page media-library">
|
<div className="app-page media-library">
|
||||||
{isPlatformAdmin ? <AdminPageNav /> : null}
|
|
||||||
|
|
||||||
<div className="media-library__container">
|
<div className="media-library__container">
|
||||||
<header className="media-library__hero">
|
<header className="media-library__hero">
|
||||||
<div className="media-library__hero-row">
|
<div className="media-library__hero-row">
|
||||||
<h1 className="media-library__title">Medienbibliothek</h1>
|
<h1 className="media-library__title">Medienbibliothek</h1>
|
||||||
<div className="media-library__hero-links">
|
<div className="media-library__hero-links">
|
||||||
|
<Link to="/">Übersicht</Link>
|
||||||
<Link to="/exercises">Übungen</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>
|
||||||
</div>
|
</div>
|
||||||
<p className="media-library__intro">
|
<p className="media-library__intro">
|
||||||
Veröffentlichte Medien (Verein/Plattform) und eigene Uploads — „Privat“ steuert nur, wer das Asset in der
|
Offizielle und vereinsfreigegebene Medien sind für alle passenden Nutzer sichtbar. Eigene private Medien
|
||||||
Datenbank sieht; der Ablageordner folgt dem gewählten Verein wie bei „Verein“. Plattform-Admins wählen den
|
kannst du bearbeiten, veröffentlichen oder in den Papierkorb legen; im Papierkorb siehst du als Standardnutzer
|
||||||
Zielverein bei privatem Archiv-Upload aktiv. Suche durchsucht Bezeichner, Speicherpfad, Copyright und Tags.
|
nur deine eigenen privaten Objekte, als Vereinsadmin zusätzlich den Vereins-Papierkorb. Vereins-Rollen können
|
||||||
Bearbeiten über das Menü — Bulk in der unteren Leiste.
|
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>
|
</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'
|
|||||||
import { Link, useSearchParams } from 'react-router-dom'
|
import { Link, useSearchParams } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
|
import { activeClubMemberships } from '../utils/activeClub'
|
||||||
import ExercisePickerModal from '../components/ExercisePickerModal'
|
import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||||
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
||||||
@@ -284,13 +285,13 @@ function TrainingPlanningPage() {
|
|||||||
const r = (user?.role || '').toLowerCase()
|
const r = (user?.role || '').toLowerCase()
|
||||||
if (r === 'admin' || r === 'superadmin') return true
|
if (r === 'admin' || r === 'superadmin') return true
|
||||||
if (selectedGroupClubIdMemo == null || !Number.isFinite(selectedGroupClubIdMemo)) return false
|
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')
|
return Array.isArray(row?.roles) && row.roles.includes('club_admin')
|
||||||
}, [user?.role, user?.clubs, selectedGroupClubIdMemo])
|
}, [user?.role, user?.clubs, selectedGroupClubIdMemo])
|
||||||
|
|
||||||
const clubAdminClubIdSet = useMemo(() => {
|
const clubAdminClubIdSet = useMemo(() => {
|
||||||
const ids = []
|
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')) {
|
if (Array.isArray(c.roles) && c.roles.includes('club_admin')) {
|
||||||
const id = Number(c.id)
|
const id = Number(c.id)
|
||||||
if (Number.isFinite(id)) ids.push(id)
|
if (Number.isFinite(id)) ids.push(id)
|
||||||
|
|||||||
@@ -1,11 +1,18 @@
|
|||||||
import { ACTIVE_CLUB_STORAGE_KEY } from './api'
|
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,
|
* Einheitliche Anzeige des aktiven Vereins: Abgleich mit effective_club_id, active_club_id,
|
||||||
* LocalStorage (Request-Header-Quelle), sonst erster Verein der Liste.
|
* LocalStorage (Request-Header-Quelle), sonst erster **aktiver** Verein der Liste.
|
||||||
*/
|
*/
|
||||||
export function getResolvedActiveClubIdForUi(user) {
|
export function getResolvedActiveClubIdForUi(user) {
|
||||||
const clubs = user?.clubs || []
|
const clubs = activeClubMemberships(user?.clubs)
|
||||||
if (!clubs.length) return null
|
if (!clubs.length) return null
|
||||||
|
|
||||||
const idInClubs = (id) =>
|
const idInClubs = (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) {
|
export async function changePassword(newPassword) {
|
||||||
return request('/api/auth/pin', {
|
return request('/api/auth/pin', {
|
||||||
method: 'PUT',
|
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) {
|
export async function listDivisions(clubId) {
|
||||||
const query = clubId ? `?club_id=${clubId}` : ''
|
const query = clubId ? `?club_id=${clubId}` : ''
|
||||||
return request(`/api/divisions${query}`)
|
return request(`/api/divisions${query}`)
|
||||||
@@ -1303,6 +1323,7 @@ export const api = {
|
|||||||
listProfiles,
|
listProfiles,
|
||||||
listAdminUsers,
|
listAdminUsers,
|
||||||
updateProfile,
|
updateProfile,
|
||||||
|
managementPasswordReset,
|
||||||
changePassword,
|
changePassword,
|
||||||
verifyEmail,
|
verifyEmail,
|
||||||
resendVerification,
|
resendVerification,
|
||||||
@@ -1326,6 +1347,7 @@ export const api = {
|
|||||||
listClubJoinRequests,
|
listClubJoinRequests,
|
||||||
acceptClubJoinRequest,
|
acceptClubJoinRequest,
|
||||||
rejectClubJoinRequest,
|
rejectClubJoinRequest,
|
||||||
|
getInboxJoinRequests,
|
||||||
listDivisions,
|
listDivisions,
|
||||||
createDivision,
|
createDivision,
|
||||||
updateDivision,
|
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) {
|
function userIsClubAdminForClub(user, clubId) {
|
||||||
if (clubId == null || user == null) return false
|
if (clubId == null || user == null) return false
|
||||||
const cid = Number(clubId)
|
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')
|
return Array.isArray(row?.roles) && row.roles.includes('club_admin')
|
||||||
}
|
}
|
||||||
|
|
||||||
function userHasAnyClubAdminRole(user) {
|
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