34 Commits
Author SHA1 Message Date
Lars d82b805ffa Merge pull request 'feat(exercises): update to version 0.8.64 and enhance inline media functionality' (#25) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 31s
Reviewed-on: #25
2026-05-08 13:28:30 +02:00
Lars bab9b178a4 feat(exercises): update to version 0.8.64 and enhance inline media functionality
Deploy Development / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 14s
Test Suite / playwright-tests (pull_request) Successful in 22s
- Incremented application version to 0.8.64 and updated changelog with new features.
- Implemented inline media support in Rich Text Editor, allowing for drag-and-drop functionality and auto-scrolling.
- Enhanced media handling with a modal picker for media insertion, size selection, and improved user experience.
- Updated documentation to reflect changes in media handling and inline media specifications.
- Adjusted various API specifications to support new inline media features.
2026-05-08 13:27:15 +02:00
Lars c8c40474d1 Merge pull request 'Inline Medien' (#24) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #24
2026-05-08 12:39:27 +02:00
Lars 5cf775c920 feat(exercises): bump version to 0.8.64 and enhance media handling
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 7s
Test Suite / playwright-tests (pull_request) Successful in 23s
- Incremented application version to 0.8.64 and updated changelog with new features.
- Improved media handling in the Rich Text Editor with auto-scrolling during drag-and-drop.
- Added new CSS styles for video thumbnails and enhanced layout for media items.
- Removed deprecated `ExerciseAttachmentMediaStrip` from the ExerciseFullContent component.
- Updated ExerciseFormPage to manage form dirty state and prevent data loss on navigation.
2026-05-08 12:35:28 +02:00
Lars 337f29401b feat(exercises): update inline media functionality and version bump to 0.8.63
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 30s
- Incremented application version to 0.8.63 and updated changelog with new features.
- Enhanced inline media handling in the Rich Text Editor, including support for captions.
- Introduced new CSS styles for improved media display and layout in the editor.
- Replaced `ExerciseMediaEmbed` with `ExerciseAttachmentMediaStrip` for better media management in exercise content.
2026-05-08 12:20:24 +02:00
Lars 311a106d93 feat(exercises): enhance inline media functionality and update styles
Deploy Development / deploy (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 27s
- Updated inline media markup to include a new data attribute for media size.
- Enhanced the Rich Text Editor to support media size selection when inserting inline media.
- Improved CSS styles for inline media display, accommodating different sizes (small, medium, full).
- Bumped version to 0.8.62 and updated changelog to reflect these changes.
2026-05-08 12:00:02 +02:00
Lars 979e328cef chore(release): bump version to 0.8.61 and update changelog
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
- Updated application version to 0.8.61.
- Added changelog entry for version 0.8.61, detailing the new inline help feature for the "Bild/Video im Text" functionality, including a visible 📎-chip in the editor and prompts for failed insertions.
2026-05-08 11:51:28 +02:00
Lars cc51b0f08f feat(exercises): implement inline media support in exercise content
Deploy Development / deploy (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 24s
- Added functionality for inline media references in exercise text using `{{exerciseMedia:id}}` syntax, which normalizes to a canonical `<span>` element.
- Updated the frontend to utilize `ExerciseRichTextBlock` for rendering exercise content, allowing for embedded media display.
- Enhanced the Rich Text Editor to support inserting inline media placeholders.
- Version bump to 0.8.60 to reflect these changes in media handling and exercise content management.
2026-05-08 11:44:29 +02:00
Lars f035b5bb0b Merge pull request 'MediaPfad extern, Upload Manager Bug Fixes' (#23) from develop into main
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Deploy Production / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 25s
Reviewed-on: #23
2026-05-08 11:17:12 +02:00
Lars f745e5d082 feat(nginx): add media location handling with Content-Security-Policy
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (pull_request) Successful in 24s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (pull_request) Successful in 22s
- Implemented specific location blocks for `/media` and `/media/` to serve the React media library correctly.
- Added Content-Security-Policy headers to enhance security for media resources.
- Ensured proper handling of requests to prevent 404 errors on media reloads.
2026-05-08 11:15:19 +02:00
LarsandCursor b6de1f15ea feat(media): implement centralized media archive and inline media linking
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
- Introduced a centralized media archive (`/media`) with lifecycle management, including soft delete and recovery options.
- Enhanced media upload functionality to support multiple files and automatic type inference.
- Updated documentation to reflect the new media architecture and inline media linking specifications.
- Version bump to 0.8.59 to accommodate changes in media handling and database schema.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:56:43 +02:00
Lars 3ff47779e0 feat(tenant_context): enhance effective_club_id resolution for platform admins without header
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 31s
- Updated resolve_tenant_context to use stored active_club_id if the club exists when no header is provided.
- Adjusted comments for clarity regarding platform admin behavior.
- Added unit tests to verify new behavior for platform admins in test_access_layer.py.

version bump to 1.0.5 for tenant_context module.
2026-05-08 10:45:58 +02:00
LarsandCursor d3055f6f2f Medien: offizielle Assets nur Superadmin verwaltbar; Lesemodus; Upload-Verein vorausfüllen
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 28s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:35:28 +02:00
LarsandCursor f354bd9f77 Governance: official nur Superadmin; Privat-Archiv Verein wählbar; Club-Übung Copyright; gleiche Medienordner
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 47s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:20:41 +02:00
LarsandCursor 01636b5baf Medien: Vereinsordner aus Namen statt library/club/c{id}
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Successful in 24s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:06:05 +02:00
LarsandCursor 3e4fa0dc39 Medien: library-Pfade nach Medientyp (image/video/pdf/other) unterteilen
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:03:00 +02:00
LarsandCursor 8d85649cf8 refactor(media): Vereinsflache Ablage; private als u{profile} unter Verein
- club: library/club/c{id}/{sha} (kein shared/)
- private: library/club/c{id}/u{profile}/{sha} statt …/private/
- Dedupe private: sha + club_id + uploaded_by_profile_id
- version 0.8.54

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:00:37 +02:00
LarsandCursor 3f0d02edab fix(media): Vereinsordner für private/shared; kein library/private mehr
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Successful in 23s
- library/club/c{id}/private/* und …/shared/* (club visibility)
- Private Archiv-Upload: effective_club_id oder club_id Form; Plattform braucht Header
- media_assets.club_id bei private gesetzt; Dedupe pro Verein
- Übungs-Upload: dedupe_club für private aus exercise.club_id oder Mandant
- PATCH: club_id für private erhalten; Relocate inkl. private
- version 0.8.53

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:58:28 +02:00
LarsandCursor 4fb77d6927 feat(media): library/* Speicherpfade nach Sichtbarkeit und Verein
Deploy Development / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
- media_storage.library_storage_key + relocate_local_media_file
- Übungs- und Archiv-Upload nutzen library/private|club/c*|official
- PATCH/Bulk-Patch: bei visibility/club_id Datei umziehen, storage_key + exercise_media.file_path
- pytest: test_library_storage_key; Mocks angepasst
- version 0.8.52 / media_assets 1.7.0 / exercises 2.17.0

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:47:16 +02:00
Lars 696cb09bf4 Merge pull request 'Medienmanager update 1' (#22) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #22
2026-05-07 16:30:20 +02:00
Lars 33fedd5ec6 Merge pull request 'Medienmanager und Sicherheitsupdate' (#21) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 24s
Reviewed-on: #21
2026-05-07 16:00:18 +02:00
Lars c8a08f8a94 Merge pull request 'pre-Prod Alpha' (#18) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #18
2026-05-07 10:37:21 +02:00
Lars d04ebee1f6 Merge pull request 'UX - Filter' (#12) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 28s
Reviewed-on: #12
2026-05-06 21:25:56 +02:00
Lars 0c1fbab0ef Merge pull request 'Mandantenfähigkeit V1.1' (#11) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 11s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 22s
Reviewed-on: #11
2026-05-05 23:11:49 +02:00
Lars a7d68c0646 Merge pull request 'Mandantenfähigkeit V1' (#10) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 46s
Reviewed-on: #10
2026-05-05 22:34:25 +02:00
Lars a34dc19f5d Merge pull request 'Trainingsplanung und Rahmenplanung' (#9) from develop into main
Deploy Production / deploy (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 58s
Reviewed-on: #9
2026-05-05 16:05:01 +02:00
Lars 9227b98431 Merge pull request 'feat: enhance MediaWiki integration and error handling in SMW client' (#8) from develop into main
Deploy Production / deploy (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 52s
Reviewed-on: #8
2026-04-29 13:56:58 +02:00
Lars 390b0ecb73 Merge pull request 'chore: clean up docker-compose files and enhance SQL migration for skills' (#7) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 40s
Reviewed-on: #7
2026-04-29 13:43:57 +02:00
Lars 7e7adfab54 Merge pull request 'bug fixes' (#6) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 1m29s
Reviewed-on: #6
2026-04-29 13:37:21 +02:00
Lars bce235b9f6 Merge pull request 'feat: enhance Playwright configuration and CI workflow for E2E testing' (#5) from develop into main
Deploy Production / deploy (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 4s
Reviewed-on: #5
2026-04-29 12:37:28 +02:00
Lars 5334836207 Merge pull request 'feat: enhance database migration handling and health check endpoint' (#4) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m55s
Reviewed-on: #4
2026-04-29 12:31:03 +02:00
Lars 38d78abc3b Merge pull request 'bug fix' (#3) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m59s
Reviewed-on: #3
2026-04-29 11:54:17 +02:00
Lars a143532486 Merge pull request 'Version 0.1' (#2) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m53s
Reviewed-on: #2
2026-04-29 11:20:41 +02:00
Lars 2f54fef88e Merge pull request 'feat: update docker-compose and Nginx configuration for improved service dependencies and API routing' (#1) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m56s
Reviewed-on: #1
2026-04-29 08:52:11 +02:00
57 changed files with 3605 additions and 776 deletions

No files matched your search

+25 -24
View File
@@ -1,29 +1,29 @@
# Shinkan Jinkendo - Projekt-Status # Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-07 **Stand:** 2026-05-08
**Version (Code):** 0.8.48 (`backend/version.py`, APP_VERSION) **Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260507045` (u. a. `media_assets`, `platform_media_storage`) **DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
**Branch:** develop **Branch:** develop
--- ---
## Executive Summary ## Executive Summary
**Aktueller Meilenstein (Medien):** **Medienbibliothek `/media`** ergänzt den Archiv-Picker: **Lifecycle-Filter** (aktiv / Papierkorb / ausgeblendet), **Copyright bearbeiten** (`PATCH`), **Vorschau** inkl. Papierkorb bei Verwaltungsrecht; API-Liste `copyright_notice`; zuvor **§4.2 Promotion official** (Übung + Medien). **Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge), plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop mit Auto-Scroll, Vorschau-/Rückweg-UX). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**. **Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) **Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
**Nächste Schritte — Medien & Archiv** (neu priorisiert, Stand 2026-05-07): **Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47). 1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`): Filter, Copyright, Lifecycle-Aktionen; Ausbau: Sichtbarkeit bearbeiten, Bulk, Quotas. 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; optional Retention-Job-Dry-Run dokumentieren. 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) — bewusst **nach** Promotion/Copyright und tragfähigem Archiv-Workflow. 5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
**Inline:** Leitplanken in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; kein Big-Bang vor stabiler Archiv-/Governance-Basis. **Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
--- ---
@@ -50,7 +50,7 @@
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 | | **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 | | **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 | | **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
| **040–045** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets`, Plattform-Speicherpfad** | ✅ | 🔲 | | **040–046** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets` (046 z. B. Tags/GIN), Plattform-Speicherpfad** | ✅ Dev | 🔲 Prod |
--- ---
@@ -103,10 +103,11 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
### 🔲 In Arbeit / Backlog ### 🔲 In Arbeit / Backlog
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (Release 0.8.42 ff.) - [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (0.8.42 ff.)
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` (Spec §4.2) — 0.8.47 - [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
- [x] **Medien:** Medienbibliothek `/media` (Lifecycle-Filter, Copyright PATCH, Vorschau); Ausbau Manager/Bulk/S3 — Roadmap - [x] **Medien:** Medienbibliothek `/media` (Filter, Tags, Copyright, Bulk-Lifecycle/PATCH, Lesemodus für eingeschränkte Rollen bei `official`)
- [ ] **Medien:** Inline im Fließtext — nach Spec §11, nach Promotion/Archiv-Reife - [x] **Medien:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen - [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
- [ ] Responsive Design / Dark Mode / PWA - [ ] Responsive Design / Dark Mode / PWA
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus - [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
@@ -137,7 +138,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
### Dev ### Dev
Branch `develop`; Migrations bis mindestens **045** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`. Branch `develop`; Migrations bis mindestens **046** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
### Prod ### Prod
@@ -149,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-05 | ✅ Aktualisiert (u. a. 036–037) | | Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-08 | ✅ Aktualisiert (§12 Medien inkl. Inline 0.8.60–0.8.64) |
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint | | 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-05 | ✅ Aktualisiert (037) | | Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-05 | ✅ Aktualisiert | | Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-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-04-27 | ✅ Aktualisiert (Limits) | | 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 | ✅ §11 Inline-Plan, Drift-Tab | | 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-Meilenstein aktualisiert | | Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
--- ---
@@ -170,4 +171,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
--- ---
**Letzte Aktualisierung:** 2026-05-07 **Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
+12 -2
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo - Fachliches Domänenmodell # Shinkan Jinkendo - Fachliches Domänenmodell
**Version:** 0.4.3 **Version:** 0.4.4
**Stand:** 2026-05-05 (Migration **036–037:** Rahmen nur Bibliothek; Slot‑Inhalt über Blueprint‑`training_units` + Sektionen/Items wie Planung — siehe `TRAINING_FRAMEWORK_SPEC.md` §2) **Stand:** 2026-05-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
--- ---
@@ -476,6 +476,16 @@ skill_level_definitions (
--- ---
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
- **Geplant:** **Inline-Verweise** in Fließtextfeldern auf dieselbe Verknüpfung (`exercise_media.id`) — **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
---
## Methodenbezug (§11.5) ## Methodenbezug (§11.5)
**Prinzip:** Genau EINE Hauptmethode, optional weitere Nebenmethoden. **Prinzip:** Genau EINE Hauptmethode, optional weitere Nebenmethoden.
@@ -5,9 +5,10 @@ Ausführliche fachliche Inhalte:
| Dokument | Inhalt | | Dokument | Inhalt |
|----------|--------| |----------|--------|
| [shinkan_anforderungsdokument_entwurf.md](./shinkan_anforderungsdokument_entwurf.md) | Gesamtentwurf Anforderungen | | [shinkan_anforderungsdokument_entwurf.md](./shinkan_anforderungsdokument_entwurf.md) | Gesamtentwurf Anforderungen |
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (Abschnitt 11.2) | | [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (§11.2), **Medien-Archiv** (Abschnitt 2026-05) |
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **geplante Inline-Medien §11** |
| [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan | | [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan |
**Lieferstand & Umsetzung (Stand Code):** siehe [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md) und [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md). **Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) §12, Repo-Root **`docs/HANDOVER.md`**.
`CLAUDE.md` (Repo-Root) verweist hierher als Einstieg. `CLAUDE.md` (Repo-Root) verweist hierher als Einstieg.
@@ -1,9 +1,9 @@
# Gelieferte Features & technische Basis (Q2 2026) # Gelieferte Features & technische Basis (Q2 2026)
**Stand:** 2026-05-05 **Stand:** 2026-05-08
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.10**, **DB_SCHEMA_VERSION 20260505037** **Referenz:** `backend/version.py` — **APP_VERSION 0.8.64**, **DB_SCHEMA_VERSION** siehe dort
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`. Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
--- ---
@@ -17,7 +17,7 @@ Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren**
| **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL | | **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL |
| **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** | | **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** |
| **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` | | **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` |
| **037** | **`training_units.framework_slot_id`**, strukturierter Ablauf wie Planung; Entfall **`training_framework_slot_exercises`**; **`origin_framework_slot_id`** | | **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
--- ---
@@ -79,7 +79,7 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`) ## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`)
- **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante. - **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante.
- **Medien** wie zuvor (Formularteil). - **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung. - Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen). Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
@@ -123,16 +123,44 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
--- ---
## 12. Nächste sinnvolle Schritte (nicht Lieferstand) ## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
### 12.1 Datenbank & Router
- **`media_assets`**, **`platform_media_storage`**, **`exercise_media.media_asset_id`** (Dedupe `sha256` + Sichtbarkeit + `club_id` je nach Policy).
- Router **`media_assets.py`**: Listen, PATCH, Lifecycle, Dateiauslieferung, Bulk; Integration in **`exercises.py`** (Upload, `from-asset`, Promotion/Copyright-Regeln bei `official` / Vereinsübungen).
### 12.2 Funktional (Ist)
- Zentrale **Medienbibliothek** Frontend **`/media`**: Filter (Lifecycle, Medientyp, Verein für Admins), Suche, Tags, Copyright bearbeiten (rollengerecht), Kacheln/Liste, Nutzungs-Hinweise (Übungen/Planung wo implementiert).
- **Papierkorb** mehrstufig (`trash_soft` / `trash_hidden`), Recovery, Superadmin-Purge; strukturierte Fehlercodes bei Governance (u. a. Übung **`CLUB_MEDIA_*`**).
- **Speicher:** Pfadkonvention **`library/{vereinssegment}/…`** mit Medienkind-Unterordnern; Umzug bei Sichtbarkeits-/Vereinsänderung; effektives Wurzelverzeichnis `MEDIA_ROOT` + Superadmin-`local_relative_root`.
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
- Platzhalter-Syntax: `{{exerciseMedia:id}}` (normalisiert auf `data-shinkan-exercise-media`), Validierung gegen `exercise_media` der aktuellen Übung.
- Zentraler Anzeigepfad über `ExerciseRichTextBlock` inkl. Sanitize und Lifecycle-Hinweisen.
- RTE-Workflow: Modal „Medien im Text“ (Mediathek + Upload), separates „Embed im Text“-Modal, Größenwahl (`small|medium|full`) und sprechende Platzhalter-Captions.
- Bearbeiten: kompakte Medien-Kacheln + Drag&Drop in Textfelder; Auto-Scroll beim Drag aktiv.
- UX-Schutz: Warnung bei Wechsel „Ansehen“ mit ungespeicherten Änderungen; Detailseite bietet Rückweg zur Bearbeitung.
---
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später). - Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden). - Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht. - Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema). - Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
--- ---
## 13. Verweise ## 14. Verweise
| Thema | Dokument | | Thema | Dokument |
|--------|----------| |--------|----------|
@@ -140,5 +168,6 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
| API Übungen | `technical/EXERCISES_API_SPEC.md` | | API Übungen | `technical/EXERCISES_API_SPEC.md` |
| Domänenmodell | `functional/DOMAIN_MODEL.md` | | Domänenmodell | `functional/DOMAIN_MODEL.md` |
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` | | Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
| Upload formal | `technical/MEDIA_UPLOAD_SPEC.md` | | Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
| Projektstatus-Kachel | `../PROJECT_STATUS.md` | | Projektstatus-Kachel | `../PROJECT_STATUS.md` |
+8 -7
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Datenbank-Schema (Technisch) # Shinkan Jinkendo - Datenbank-Schema (Technisch)
**Version:** 0.5.2 **Version:** 0.5.3
**Stand:** 2026-05-05 **Stand:** 2026-05-07
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints in `training_units`; Entfall `training_framework_slot_exercises`) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`). **Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints) und für Medien-Archiv bis **045+** (`media_assets`, …) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`) und **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
--- ---
@@ -47,8 +47,7 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
| **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ | | **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ |
| **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ | | **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ |
| **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ | | **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ |
| **040–046** | **2026-05** | **Mitgliedschaft/Anträge, Übungs-Governance-Erweiterungen, `media_assets`, `platform_media_storage`, `exercise_media.media_asset_id`, Tags/GIN u. a.** — exakte Nummern: `backend/migrations/`; fachliche Norm Medien: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** | ✅ je Umgebung |
---
## Migration 022: Skills Schema Complete (BREAKING CHANGE) ## Migration 022: Skills Schema Complete (BREAKING CHANGE)
@@ -267,9 +266,11 @@ exercise_skills (
UNIQUE (exercise_id, skill_id) -- Migration 020 UNIQUE (exercise_id, skill_id) -- Migration 020
) )
-- Varianten & Medien -- Varianten & Medien (028+ Embed/Datei; 045+ optional media_asset_id → media_assets)
exercise_variants (id, exercise_id, name, description, ...) exercise_variants (id, exercise_id, name, description, ...)
exercise_media (id, exercise_id, type, url, title, description, ...) exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
platform_media_storage (id, local_relative_root, …)
``` ```
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**) ### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
+12 -8
View File
@@ -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 (§11 Inline-Plan ergänzt) **Stand:** 2026-05-08 (Ist-Changelog Medien bis 0.8.64; §11 Inline umgesetzt und erweitert)
**ersetzt/ergänzt:** operatives Upload-Format/Größen siehe weiterhin `MEDIA_UPLOAD_SPEC.md` **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,26 +186,33 @@ Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **globa
| Datum | Änderung | | Datum | Änderung |
|-------|----------| |-------|----------|
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung mit Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. | | 2026-05-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-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Zeitpunkt der Umsetzung; Drift-Vermeidung ohne jetzigen Vollbau. | | 2026-05-08 | **0.8.63:** Inline-Medien-Picker als Modal (Mediathek/Upload + separates Embed-Modal), Größenwahl `small|medium|full`, Platzhalter-Caption (`data-shinkan-exercise-media-caption`), Wiederverwendung bereits verknüpfter Assets im Picker, kompakter Medienbereich mit Drag&Drop in Textfelder. |
| 2026-05-08 | **0.8.60 §11:** Inline in Übungstexten (`{{exerciseMedia:id}}` / `data-shinkan-exercise-media`); Server-Normalisierung + Validierung; Client-Sanitize und zentraler Block-Renderer (`ExerciseRichTextBlock`); CREATE ohne bestehende `exercise_media` lehnt Platzhalter ab. |
| 2026-05-07 | **0.8.59:** Dokumentation — Aktiver Verein (Profil/Header/`effective_club_id`) für Plattform-Admin und UI-Dropdown synchron; kein fachliches Archiv-Schema-Change. |
| 2026-05-07 | **0.8.58:** Medien **`official`:** Lifecycle schwerpunktmäßig **Superadmin** (nicht Plattform-Admin); Bearbeitungsdialog Bibliothek für andere Rollen **Lesemodus**; Superadmin-Upload: Vereinskontext folgt aktiv gesetztem Verein / `effective_club_id`. |
| 2026-05-07 | **0.8.47–0.8.57 (Auszug):** Übung **`official`** nur Superadmin; Vereinsübungen mit File-Assets: **Copyright-Pflicht**; Speicherpfade **`library/`** mit Vereinsordner (Name+c{id}), Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeit; Bibliothek-GET mit Filtern/Tags/Nutzungs-Anzeige; Bulk-Lifecycle/PATCH; Lesemodus/Kacheln; Konflikt **409** bei Upload-Dedupe vs. Papierkorb + UI-Reaktivierung. |
| 2026-05-07 | **0.8.42–0.8.43:** Papierkorb-Lifecycle API, Retention-Skript; **`POST …/exercises/{id}/media/from-asset`**; Übungs-UI Archiv verknüpfen / Vorschau. |
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Umsetzung **nach** tragfähigem Archiv — siehe **`docs/HANDOVER.md`** §5. |
| 2026-05-07 | **Medienmanager (Basis):** `GET /api/media-assets?lifecycle=…`, `copyright_notice` in Response; `PATCH` Copyright; `GET …/file` für Papierkorb-Zeilen bei Verwaltungsrecht; UI-Route `/media` (Medienbibliothek). | | 2026-05-07 | **Medienmanager (Basis):** `GET /api/media-assets?lifecycle=…`, `copyright_notice` in Response; `PATCH` Copyright; `GET …/file` für Papierkorb-Zeilen bei Verwaltungsrecht; UI-Route `/media` (Medienbibliothek). |
--- ---
## 11. Inline-Medien im Fließtext (Planung, Leitplanken) ## 11. Inline-Medien im Fließtext (Umsetzung & Leitplanken)
**Status:** nicht implementiert; verbindlich nur als **Richtschnur**, damit später **kein Big-Bang-Refactor** nötig ist. **Status:** Frontend-Renderer und API-Validierung/Normalisierung umgesetzt (App ≥ 0.8.60); verbindliche Leitplanken unten.
### 11.1 Ziel ### 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
@@ -214,14 +221,15 @@ 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. **Vorher:** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Basis-Papierkorb (§5) – jeweils stabil. 1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
2. **Danach:** Inline implementieren, sobald Trainer-Feedback oder Content-Menge den Bedarf **konkret** bestätigt (typisch nach 1–2 Beta-Zyklen). 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. **Nicht nötig:** vorher kompletten Block-Editor einführen; **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)
+3 -5
View File
@@ -1,10 +1,8 @@
# Media Upload & Embed Specification # Media Upload & Embed Specification
**Version:** 1.1 **Version:** 1.2
**Datum:** 2026-04-27 **Datum:** 2026-05-07
**Status:** DRAFT - Awaiting Review **Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
**Autor:** Claude Code
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
> **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:** > **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:**
> Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung). > Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung).
@@ -1,11 +1,14 @@
# Session Handover (Verweis) # Session Handover (Verweis)
**Dieses Dokument ist veraltet.** Der aktuelle Entwicklungsstand und die Handover-Basis stehen hier: **Aktuelle Handover-Basis (Stand Implementierung + Medien):**
👉 **`docs/HANDOVER.md`** (Projektroot: `c:\Dev\shinkan-jinkendo\docs\HANDOVER.md`) 👉 **`docs/HANDOVER.md`** (Projektroot)
Dort: Fähigkeits-/Reifegrad-Stand (Bindings, Resolve, Export/Import, Matrix-Stack), Verweise auf `.claude/docs` für Anforderungen, und **nächste Priorität Übungen (UI/CRUD/Medien)**. Dort: **Medien-Archiv/Medienbibliothek (Ist)**, **geplante Inline-Medienverlinkung (§11 Spec)**, Reifegrad/Matrix, Rahmenprogramm, nächste sinnvolle Arbeitspakete für neue Sessions.
**Projektstatus-Kachel:** `.claude/docs/PROJECT_STATUS.md`
**Medien Single Source of Truth:** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
--- ---
*Historischer Inhalt aus April 2026 wurde durch `docs/HANDOVER.md` ersetzt.* *Die historische „Übungen Lücke“-Fassung (2026-04) ist überholt; Medien-UI und Archiv sind seit 0.8.41+ weitgehend umgesetzt — Details `docs/HANDOVER.md` §4.*
+2 -1
View File
@@ -58,7 +58,8 @@ return {"message": "Fehler", "success": False}
### 1.4 Mandanten & Zugriffsschicht (Shinkan / ACCESS_LAYER) ### 1.4 Mandanten & Zugriffsschicht (Shinkan / ACCESS_LAYER)
**Verbindlicher Rahmen:** `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` **Verbindlicher Rahmen:** `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` **Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher, geplante Inline-Verlinkung §11):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
**Session-Handover (Ist + nächste Schritte):** `docs/HANDOVER.md`
**Fortlaufendes Inventar:** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` **Fortlaufendes Inventar:** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
**Definition of Done für neue oder geänderte geschützte APIs**, sobald Daten **Verein**, **Sichtbarkeit** oder **mandantenbezogene Listen** betreffen: **Definition of Done für neue oder geänderte geschützte APIs**, sobald Daten **Verein**, **Sichtbarkeit** oder **mandantenbezogene Listen** betreffen:
+2 -1
View File
@@ -10,7 +10,8 @@
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus) 1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt) 2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
3. Spez-Index: **`.claude/docs/README.md`** 3. Spez-Index: **`.claude/docs/README.md`**
4. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf) 4. **Session-Handover (aktuelle Prioritäten, Medien-Ist):** **`docs/HANDOVER.md`**
5. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
--- ---
+2
View File
@@ -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
+6 -4
View File
@@ -11,7 +11,8 @@
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` | > | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` | > | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` | > | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
> | Medien-Archiv, Lifecycle, Promotion | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | > | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
## Projekt-Übersicht ## Projekt-Übersicht
@@ -57,7 +58,7 @@ backend/
└── routers/ # Router-Module └── routers/ # Router-Module
auth · profiles · clubs · groups · skills · methods auth · profiles · clubs · groups · skills · methods
exercises · exercise_progression_graphs · training_units · training_programs exercises · exercise_progression_graphs · training_units · training_programs
planning · import_wiki · admin · membership planning · import_wiki · admin · membership · media_assets
frontend/src/ frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation ├── App.jsx # Root, Auth-Gates, Navigation
@@ -82,10 +83,11 @@ frontend/src/
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`. **Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**; Kern: Übungen, Varianten, Medien, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md` und `TRAINING_FRAMEWORK_SPEC.md` §2. Kurz (Stand 2026-05-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)
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`. - 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`. - 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
@@ -106,7 +108,7 @@ Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**
- `exercises` - Übungen (Kernobjekt) - `exercises` - Übungen (Kernobjekt)
- `exercise_variants` - Übungsvarianten - `exercise_variants` - Übungsvarianten
- `exercise_skills` - M:N Übung ↔ Fähigkeit - `exercise_skills` - M:N Übung ↔ Fähigkeit
- `exercise_media` - Medien (Bilder, Videos); 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**)
+1
View File
@@ -13,6 +13,7 @@ Shinkan ist eine moderne Web- und Mobile-App für Kampfsport-Trainer und Vereine
- **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten - **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen - **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten - **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
- **Medien:** Zentrale **Medienbibliothek** (`/media`), Archiv mit Lifecycle/Papierkorb, Verknüpfung in Übungen — Norm: `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` · Einstieg: `docs/HANDOVER.md`
## Nicht in Shinkan ## Nicht in Shinkan
+3 -3
View File
@@ -157,13 +157,13 @@ def assert_valid_governance_visibility(
visibility: str, visibility: str,
club_id: Optional[int], club_id: Optional[int],
) -> None: ) -> None:
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Plattform-Admin.""" """Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Superadmin."""
if visibility not in _GOVERNANCE_VISIBILITY: if visibility not in _GOVERNANCE_VISIBILITY:
raise HTTPException(status_code=400, detail="Ungültige visibility") raise HTTPException(status_code=400, detail="Ungültige visibility")
if visibility == "official" and not is_platform_admin(role): if visibility == "official" and not is_superadmin(role):
raise HTTPException( raise HTTPException(
status_code=403, status_code=403,
detail="Nur Plattform-Admins dürfen offizielle Inhalte setzen", detail="Nur Superadmins dürfen offizielle Inhalte setzen",
) )
if visibility == "club": if visibility == "club":
if club_id is None: if club_id is None:
+101
View File
@@ -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),
},
)
+17 -8
View File
@@ -27,20 +27,26 @@ HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS",
def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None: def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None:
""" """
Papierkorb Stufe 2 / Recovery / Reaktivierung — nicht für trash_soft (siehe assert_can_trash_soft). Papierkorb Stufe 2 / Recovery / Reaktivierung — nicht für trash_soft (siehe assert_can_trash_soft).
§5.2: official nur Plattform-Admin; club Vereinsorga; privat nur Uploader. §5.2: official nur Superadmin; club Vereinsorga; privat nur Uploader (Plattform-Admin sonst wie bisher).
""" """
profile_id = tenant.profile_id profile_id = tenant.profile_id
role = (tenant.global_role or "").strip().lower() role = (tenant.global_role or "").strip().lower()
vis = (asset.get("visibility") or "private").strip().lower()
if vis == "official":
if not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Offizielle Medien dürfen nur von Superadmins geändert oder gelöscht werden",
)
return
if is_platform_admin(role): if is_platform_admin(role):
return return
vis = (asset.get("visibility") or "private").strip().lower()
uid = asset.get("uploaded_by_profile_id") uid = asset.get("uploaded_by_profile_id")
if vis == "private": if vis == "private":
if uid is not None and int(uid) == int(profile_id): if uid is not None and int(uid) == int(profile_id):
return return
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium") raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
if vis == "official":
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
if vis == "club": if vis == "club":
cid = asset.get("club_id") cid = asset.get("club_id")
if cid is None: if cid is None:
@@ -54,15 +60,20 @@ def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict)
def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None: def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
""" """
Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads. Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads.
Vereinsmedien: Vereinsorga; official: Plattform-Admin; Superadmin: immer. Vereinsmedien: Vereinsorga; official: nur Superadmin; Plattform-Admin: sonst wie Verein/privat.
""" """
role_raw = tenant.global_role role_raw = tenant.global_role
role = (role_raw or "").strip().lower() role = (role_raw or "").strip().lower()
if is_superadmin(role): if is_superadmin(role):
return return
vis = (asset.get("visibility") or "private").strip().lower()
if vis == "official":
raise HTTPException(
status_code=403,
detail="Offizielle Medien dürfen nur von Superadmins in den Papierkorb gelegt werden",
)
if is_platform_admin(role): if is_platform_admin(role):
return return
vis = (asset.get("visibility") or "private").strip().lower()
uid = asset.get("uploaded_by_profile_id") uid = asset.get("uploaded_by_profile_id")
cid = asset.get("club_id") cid = asset.get("club_id")
pid = int(tenant.profile_id) pid = int(tenant.profile_id)
@@ -80,8 +91,6 @@ def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
status_code=403, status_code=403,
detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen", detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen",
) )
if vis == "official":
raise HTTPException(status_code=403, detail="Nur Plattform-Admin")
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium") raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
+172
View File
@@ -3,9 +3,23 @@ from __future__ import annotations
import os import os
import re import re
import shutil
import unicodedata
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
_CLUB_SLUG_TRANS = str.maketrans(
{
"ä": "ae",
"ö": "oe",
"ü": "ue",
"ß": "ss",
"Ä": "ae",
"Ö": "oe",
"Ü": "ue",
}
)
def _default_media_root() -> Path: def _default_media_root() -> Path:
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))) return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
@@ -44,6 +58,70 @@ def get_effective_media_root(cur: Any) -> Path:
return (base / rel).resolve() return (base / rel).resolve()
def library_media_kind_dir(mime_type: Optional[str], ext: str) -> str:
"""
Unterordner unter library/* — an API-Filter media_kind angelehnt (image/video/pdf/other).
Bei fehlendem MIME wird anhand der Dateiendung geraten (letzte Instanz: other).
"""
m = (mime_type or "").strip().lower()
x = (ext or "").strip().lower()
if x and not x.startswith("."):
x = "." + x
if m.startswith("image/"):
return "image"
if m.startswith("video/"):
return "video"
if m == "application/pdf" or (m and "pdf" in m):
return "pdf"
if x in (
".jpg",
".jpeg",
".png",
".gif",
".webp",
".heic",
".heif",
".bmp",
".svg",
".avif",
):
return "image"
if x in (".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"):
return "video"
if x == ".pdf":
return "pdf"
return "other"
def library_club_path_segment(club_id: int, club_name: Optional[str]) -> str:
"""
Ein Verzeichnissegment pro Verein: aus Anzeigenamen abgeleitet + „-c{id}“ für Eindeutigkeit
(Umbenennung, Kollisionen nach Slugify). Nur [a-z0-9-], keine Pfad-Sonderzeichen.
Fehlt der Name / Slug leer → „verein-c{id}“.
"""
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
raw = unicodedata.normalize("NFKC", (club_name or "").strip()).translate(_CLUB_SLUG_TRANS).lower()
raw = re.sub(r"[^a-z0-9]+", "-", raw)
raw = raw.strip("-")
if len(raw) > 48:
raw = raw[:48].rstrip("-")
if not raw:
base = f"verein-c{cid}"
else:
base = f"{raw}-c{cid}"
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", base):
raise ValueError("Ungültiger abgeleiteter Vereins-Ordnername")
return base
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]: def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal.""" """Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
key = (storage_key or "").strip().replace("\\", "/").lstrip("/") key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
@@ -55,3 +133,97 @@ def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
except ValueError: except ValueError:
return None return None
return p return p
def library_storage_key(
visibility: str,
club_id: Optional[int],
sha256_hex: str,
ext: str,
*,
uploader_profile_id: Optional[int] = None,
mime_type: Optional[str] = None,
club_name: Optional[str] = None,
) -> str:
"""
Relativer Speicherpfad unter MEDIA_ROOT für lokale media_assets.
- official → library/official/{kind}/{sha256}{ext}
- club (vereinsgeteilt) → library/{vereins-segment}/{kind}/{sha256}{ext}
- private → dieselbe Ordnerlogik wie Verein: library/{vereins-segment}/{kind}/{sha}.u{profile}{ext}
Dateiname bei private: „{sha}.u{profile_id}{ext}“ (nicht Unterordner u{…}), damit Ordnerstruktur wie bei „Verein“.
Vereins-Segment: aus club_name abgeleitet + „-c{club_id}“ — siehe library_club_path_segment.
kind ∈ {image, video, pdf, other} — siehe library_media_kind_dir.
Kein Ordnername „private“ auf der Platte. Private Dateien unterscheiden sich nur im Dateinamen (.u{Profil} vor Endung).
"""
vis = (visibility or "private").strip().lower()
if vis not in ("private", "club", "official"):
raise ValueError(f"Ungültige Sichtbarkeit für Speicherpfad: {visibility!r}")
sha = (sha256_hex or "").strip().lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
raise ValueError("sha256_hex muss 64 Hex-Zeichen sein")
e = (ext or "").strip()
if not e:
e = ".bin"
if not e.startswith("."):
e = "." + e
if ".." in e or "/" in e or "\\" in e or "\x00" in e:
raise ValueError("Ungültige Dateiendung")
kind = library_media_kind_dir(mime_type, e)
e = e[:16]
club_blob = f"{kind}/{sha}{e}"
if vis == "official":
return f"library/official/{club_blob}"
if club_id is None:
raise ValueError("Verein (club_id) ist für diese Sichtbarkeit auf der Platte erforderlich")
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
club_seg = library_club_path_segment(cid, club_name)
if vis == "club":
return f"library/{club_seg}/{club_blob}"
if uploader_profile_id is None:
raise ValueError("uploader_profile_id ist für private Archiv-Medien erforderlich")
up = int(uploader_profile_id)
if up < 1:
raise ValueError("uploader_profile_id muss positiv sein")
priv_name = f"{sha}.u{up}{e}"
return f"library/{club_seg}/{kind}/{priv_name}"
def relocate_local_media_file(media_root: Path, old_storage_key: str, new_storage_key: str) -> None:
"""
Physisches Verschieben bei geändertem library_*-Pfad (z. B. nach PATCH visibility/club_id).
- Kein Op, wenn Quelle fehlt aber Ziel bereits existiert (idempotent).
- Erwartet storage_backend=local; Aufrufer prüft das.
"""
if (old_storage_key or "").replace("\\", "/").lstrip("/") == (new_storage_key or "").replace(
"\\", "/"
).lstrip("/"):
return
old_p = path_under_media_root(media_root, old_storage_key)
new_p = path_under_media_root(media_root, new_storage_key)
if old_p is None or new_p is None:
raise ValueError("Ungültiger Speicherpfad (Path-Traversal)")
if new_p.is_file():
if not old_p.is_file():
return
if old_p.resolve() == new_p.resolve():
return
raise FileExistsError(f"Zieldatei existiert bereits: {new_storage_key}")
if not old_p.is_file():
raise FileNotFoundError(f"Medien-Quelldatei nicht gefunden: {old_storage_key}")
new_p.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(old_p), str(new_p))
+56 -25
View File
@@ -19,6 +19,26 @@ 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
# ── List Clubs ──────────────────────────────────────────────────────── # ── List Clubs ────────────────────────────────────────────────────────
@router.get("/clubs") @router.get("/clubs")
def list_clubs( def list_clubs(
@@ -581,9 +601,16 @@ 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_raw = data.get("co_trainer_ids")
co_trainer_ids = [] if co_raw is None else co_raw
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
@@ -610,19 +637,19 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
) 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_trainer_ids,
data.get("status", "active"), data.get("status") or "active",
), ),
) )
@@ -662,6 +689,10 @@ 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_upd = data.get("co_trainer_ids")
if co_upd is None:
co_upd = []
cur.execute( cur.execute(
""" """
UPDATE training_groups SET UPDATE training_groups SET
@@ -682,17 +713,17 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
""", """,
( (
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_upd,
data.get("status"), data.get("status") or "active",
group_id, group_id,
), ),
) )
+204 -19
View File
@@ -28,7 +28,14 @@ from club_tenancy import (
library_content_visible_to_profile, library_content_visible_to_profile,
) )
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, 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__)
@@ -642,6 +649,72 @@ def apply_official_exercise_media_rules(
) )
def apply_club_exercise_media_copyright_rules(cur, exercise_id: int, next_visibility: str) -> None:
"""
Vereins-sichtbare Übung: angehängte Archiv-Dateien müssen aktiv sein und einen Copyright-Vermerk haben
(wie bei offiziellen Übungen, ohne Sichtbarkeits-Promotion der Assets).
"""
nv = (next_visibility or "private").strip().lower()
if nv != "club":
return
rows = _fetch_exercise_linked_file_assets(cur, exercise_id)
if not rows:
return
blocking_lc: List[Dict[str, Any]] = []
missing_cr: List[Dict[str, Any]] = []
for r in rows:
aid = int(r["id"])
lc = (r.get("lifecycle_state") or "").strip().lower()
cr = _normalize_media_copyright_notice(r.get("copyright_notice"))
if lc != "active":
blocking_lc.append(
{
"media_asset_id": aid,
"lifecycle_state": lc,
"visibility": (r.get("visibility") or "").strip().lower(),
"original_filename": r.get("original_filename"),
}
)
continue
if len(cr) < _MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN:
missing_cr.append(
{
"media_asset_id": aid,
"original_filename": r.get("original_filename"),
}
)
if blocking_lc:
raise HTTPException(
status_code=422,
detail={
"code": "CLUB_MEDIA_LIFECYCLE",
"message": (
"Nicht aktive Archiv-Medien dürfen nicht an einer vereinsöffentlichen Übung hängen "
"(Papierkorb/Recovery zuerst)."
),
"media_assets": blocking_lc,
},
)
if missing_cr:
raise HTTPException(
status_code=422,
detail={
"code": "CLUB_MEDIA_COPYRIGHT_REQUIRED",
"message": (
f"Für vereinsöffentliche Übungen ist ein Copyright-Vermerk pro Datei erforderlich "
f"(mind. {_MIN_OFFICIAL_MEDIA_COPYRIGHT_LEN} Zeichen)."
),
"media_assets": missing_cr,
},
)
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"):
return None return None
@@ -1247,6 +1320,23 @@ def bulk_patch_exercises_metadata(
failed.append(entry) failed.append(entry)
continue continue
if (next_vis or "").strip().lower() == "club":
try:
apply_club_exercise_media_copyright_rules(cur, ex_id, next_vis)
except HTTPException as he:
d = he.detail
entry: Dict[str, Any] = {"id": ex_id}
if isinstance(d, dict):
entry["detail"] = str(d.get("message") or d.get("code") or "Vereins-Medien-Validierung fehlgeschlagen")
if "code" in d:
entry["code"] = d["code"]
if "media_assets" in d:
entry["media_assets"] = d["media_assets"]
else:
entry["detail"] = _fail_msg(he)
failed.append(entry)
continue
sets: List[str] = [] sets: List[str] = []
vals: List[Any] = [] vals: List[Any] = []
if patch_visibility: if patch_visibility:
@@ -1729,6 +1819,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(
@@ -1757,13 +1857,13 @@ def create_exercise(
) )
row = cur.fetchone() row = cur.fetchone()
exercise_id = row['id'] if isinstance(row, dict) else row[0] exercise_id = row['id'] if isinstance(row, dict) else row[0]
data = body.dict()
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
if (body.visibility or "").strip().lower() == "club":
apply_club_exercise_media_copyright_rules(cur, exercise_id, "club")
conn.commit() conn.commit()
# M:N Relations zuweisen
data = body.dict()
assign_exercise_relations(cur, conn, exercise_id, data)
# Vollständiges Objekt zurückgeben
exercise = enrich_exercise_detail(exercise_id, cur) exercise = enrich_exercise_detail(exercise_id, cur)
return exercise return exercise
@@ -1785,16 +1885,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:
@@ -1805,6 +1914,23 @@ def update_exercise(
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)
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:
v_raw = str(data["visibility"]).strip().lower() v_raw = str(data["visibility"]).strip().lower()
@@ -1866,6 +1992,11 @@ def update_exercise(
cur.execute(query, params) cur.execute(query, params)
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False) assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
try:
apply_club_exercise_media_copyright_rules(cur, exercise_id, next_vis)
except HTTPException:
conn.rollback()
raise
conn.commit() conn.commit()
exercise = enrich_exercise_detail(exercise_id, cur) exercise = enrich_exercise_detail(exercise_id, cur)
@@ -1976,7 +2107,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(
@@ -2030,7 +2165,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:
@@ -2397,13 +2538,41 @@ async def upload_exercise_media(
media_root = get_effective_media_root(cur) media_root = get_effective_media_root(cur)
full_sha = hashlib.sha256(raw).hexdigest() full_sha = hashlib.sha256(raw).hexdigest()
cur.execute( if ex_vis == "official":
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets dedupe_club: Optional[int] = None
WHERE sha256 = %s AND lower(trim(visibility)) = %s elif ex_vis == "private":
AND (club_id IS NOT DISTINCT FROM %s) dedupe_club = int(ex_club) if ex_club is not None else tenant.effective_club_id
LIMIT 1""", if dedupe_club is None:
(full_sha, ex_vis, ex_club), raise HTTPException(
) status_code=400,
detail=(
"Private Übungsmedien werden pro Verein gespeichert. Bitte der Übung einen Verein zuordnen "
"oder einen aktiven Verein wählen (X-Active-Club-Id)."
),
)
dedupe_club = int(dedupe_club)
else:
if ex_club is None:
raise HTTPException(status_code=400, detail="Vereinsübung ohne club_id")
dedupe_club = int(ex_club)
if ex_vis == "private":
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = 'private'
AND (club_id IS NOT DISTINCT FROM %s)
AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, dedupe_club, profile_id),
)
else:
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = %s
AND (club_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, ex_vis, dedupe_club),
)
existing_asset = cur.fetchone() existing_asset = cur.fetchone()
if existing_asset: if existing_asset:
@@ -2490,7 +2659,23 @@ async def upload_exercise_media(
}, },
) )
else: else:
storage_key = f"exercises/{full_sha}{ext}" club_nm = ""
if dedupe_club is not None:
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(dedupe_club),))
cnr = cur.fetchone()
club_nm = str(r2d(cnr).get("name") or "") if cnr else ""
try:
storage_key = library_storage_key(
ex_vis,
dedupe_club if ex_vis != "official" else None,
full_sha,
ext,
uploader_profile_id=profile_id if ex_vis == "private" else None,
mime_type=mime,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
dest_path = path_under_media_root(media_root, storage_key) dest_path = path_under_media_root(media_root, storage_key)
if dest_path is None: if dest_path is None:
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad") raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
@@ -2510,7 +2695,7 @@ async def upload_exercise_media(
full_sha, full_sha,
file.filename, file.filename,
ex_vis, ex_vis,
ex_club, dedupe_club,
profile_id, profile_id,
storage_key, storage_key,
), ),
+203 -37
View File
@@ -10,6 +10,7 @@ from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Reques
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
from club_tenancy import ( from club_tenancy import (
assert_club_member,
assert_valid_governance_visibility, assert_valid_governance_visibility,
club_ids_for_profile_with_roles, club_ids_for_profile_with_roles,
is_platform_admin, is_platform_admin,
@@ -33,7 +34,7 @@ from media_lifecycle import (
transition_to_trash_hidden, transition_to_trash_hidden,
transition_to_trash_soft, transition_to_trash_soft,
) )
from media_storage import get_effective_media_root, path_under_media_root from media_storage import get_effective_media_root, library_storage_key, path_under_media_root, relocate_local_media_file
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
@@ -293,17 +294,89 @@ def _fetch_filter_uploaders(cur: Any, is_adm: bool, profile_id: int) -> list[dic
def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict: def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict:
"""Nach visibility-Wechsel club_id konsistent setzen (official/private → NULL).""" """
Nach visibility-Wechsel club_id konsistent setzen.
official → club_id NULL. private/club: club_id aus Patch oder bisheriger Zeile beibehalten
(private nutzt club_id für Vereinsordner auf der Platte).
"""
eff = dict(patch_fields) eff = dict(patch_fields)
if eff.get("visibility") is not None: if eff.get("visibility") is not None:
v = str(eff["visibility"]).strip().lower() v = str(eff["visibility"]).strip().lower()
if v in ("official", "private"): if v == "official":
eff["club_id"] = None eff["club_id"] = None
elif v == "club" and "club_id" not in eff: elif v == "club" and "club_id" not in eff:
eff["club_id"] = asset.get("club_id") eff["club_id"] = asset.get("club_id")
elif v == "private" and "club_id" not in eff:
eff["club_id"] = asset.get("club_id")
return eff return eff
def _club_display_name_for_storage(cur: Any, club_id: int) -> str:
"""Anzeigename für library_club_path_segment; leer wenn Verein fehlt."""
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(club_id),))
row = cur.fetchone()
if not row:
return ""
return str(r2d(row).get("name") or "")
def _relocate_asset_file_if_governance_changed(
cur: Any,
media_root: Path,
asset_id: int,
asset: dict,
next_vis: str,
next_club_id: Optional[int],
) -> Optional[str]:
"""
Passt bei local-Assets den Dateipfad an, wenn sich Sichtbarkeit/Verein ändert.
Aktualisiert exercise_media.file_path. Gibt neuen storage_key oder None zurück.
"""
if (asset.get("storage_backend") or "local") != "local":
return None
old_key = (asset.get("storage_key") or "").strip()
sha = (asset.get("sha256") or "").strip().lower()
if not old_key or len(sha) != 64:
return None
ext = Path(old_key.replace("\\", "/")).suffix or ".bin"
try:
up = asset.get("uploaded_by_profile_id")
up_i = int(up) if up is not None else None
club_nm: Optional[str] = None
if next_vis in ("club", "private") and next_club_id is not None:
club_nm = _club_display_name_for_storage(cur, next_club_id)
new_key = library_storage_key(
next_vis,
next_club_id if next_vis != "official" else None,
sha,
ext,
uploader_profile_id=up_i if next_vis == "private" else None,
mime_type=str(asset.get("mime_type") or "") or None,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
old_norm = old_key.replace("\\", "/").lstrip("/")
if new_key == old_norm:
return None
try:
relocate_local_media_file(media_root, old_key, new_key)
except FileNotFoundError as e:
raise HTTPException(status_code=500, detail=f"Mediendatei fehlt auf der Platte: {e}") from e
except FileExistsError as e:
raise HTTPException(status_code=409, detail=str(e)) from e
except (ValueError, OSError) as e:
raise HTTPException(status_code=500, detail=str(e)) from e
db_path = f"/media/{new_key}"
cur.execute(
"UPDATE exercise_media SET file_path = %s WHERE media_asset_id = %s",
(db_path, asset_id),
)
return new_key
def _lifecycle_where_sql(lifecycle: str) -> str: def _lifecycle_where_sql(lifecycle: str) -> str:
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:
@@ -354,25 +427,25 @@ def _item_permissions(row: dict, tenant: TenantContext, admin_club_ids: set[int]
is_owner = uid is not None and int(uid) == pid is_owner = uid is not None and int(uid) == pid
club_mgr = plat or (cid is not None and int(cid) in admin_club_ids) club_mgr = plat or (cid is not None and int(cid) in admin_club_ids)
edit_metadata = ( if vis == "official":
sup edit_metadata = sup
or (vis == "official" and plat) trash_soft = lc == "active" and sup
or (vis == "club" and club_mgr) can_manage_adv = sup
or (vis == "private" and is_owner) else:
) edit_metadata = (
sup
trash_soft = lc == "active" and ( or (vis == "club" and club_mgr)
sup or plat or (vis == "private" and is_owner) or (vis == "club" and club_mgr) or (vis == "private" and is_owner)
) )
if vis == "official" and not (sup or plat): trash_soft = lc == "active" and (
trash_soft = False sup or plat or (vis == "private" and is_owner) or (vis == "club" and club_mgr)
)
can_manage_adv = ( can_manage_adv = (
sup sup
or plat or plat
or (vis == "private" and is_owner) or (vis == "private" and is_owner)
or (vis == "club" and club_mgr) or (vis == "club" and club_mgr)
) )
trash_hidden = lc in ("active", "trash_soft") and can_manage_adv trash_hidden = lc in ("active", "trash_soft") and can_manage_adv
recover_from_hidden = lc == "trash_hidden" and can_manage_adv recover_from_hidden = lc == "trash_hidden" and can_manage_adv
@@ -474,8 +547,32 @@ def _ingest_library_media_file(
if club_id_form is None: if club_id_form is None:
raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“") raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“")
next_cid = int(club_id_form) next_cid = int(club_id_form)
elif vis == "private":
if club_id_form is not None:
next_cid = int(club_id_form)
elif is_platform_admin(role):
raise HTTPException(
status_code=400,
detail=(
"Private Archiv-Uploads als Plattform-Admin: bitte den Zielverein wählen und "
"club_id im Formular setzen (nicht vom allgemeinen Kontext ableiten)."
),
)
else:
cid = tenant.effective_club_id
next_cid = int(cid) if cid is not None else None
if next_cid is None:
raise HTTPException(
status_code=400,
detail=(
"Private Medien werden pro Verein abgelegt. Bitte aktiven Verein setzen "
"(Header X-Active-Club-Id) oder club_id im Formular übergeben — auch für Plattform-Admins."
),
)
if not is_platform_admin(role):
assert_club_member(cur, profile_id, next_cid)
assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid) assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid if vis == "club" else None)
max_b = _upload_limit_bytes(tenant) max_b = _upload_limit_bytes(tenant)
if len(raw) > max_b: if len(raw) > max_b:
@@ -490,13 +587,23 @@ def _ingest_library_media_file(
raise HTTPException(status_code=400, detail=str(e)) from e raise HTTPException(status_code=400, detail=str(e)) from e
full_sha = hashlib.sha256(raw).hexdigest() full_sha = hashlib.sha256(raw).hexdigest()
cur.execute( if vis == "private":
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets cur.execute(
WHERE sha256 = %s AND lower(trim(visibility)) = %s """SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
AND (club_id IS NOT DISTINCT FROM %s) WHERE sha256 = %s AND lower(trim(visibility)) = %s
LIMIT 1""", AND (club_id IS NOT DISTINCT FROM %s)
(full_sha, vis, next_cid), AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
) LIMIT 1""",
(full_sha, vis, next_cid, profile_id),
)
else:
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = %s
AND (club_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, vis, next_cid),
)
existing_asset = cur.fetchone() existing_asset = cur.fetchone()
if existing_asset: if existing_asset:
@@ -537,8 +644,23 @@ def _ingest_library_media_file(
elif not ext and mime == "video/quicktime": elif not ext and mime == "video/quicktime":
ext = ".mov" ext = ".mov"
club_nm = ""
if next_cid is not None:
club_nm = _club_display_name_for_storage(cur, next_cid)
media_root = get_effective_media_root(cur) media_root = get_effective_media_root(cur)
storage_key = f"exercises/{full_sha}{ext}" try:
storage_key = library_storage_key(
vis,
next_cid,
full_sha,
ext,
uploader_profile_id=profile_id if vis == "private" else None,
mime_type=mime,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
dest_path = path_under_media_root(media_root, storage_key) dest_path = path_under_media_root(media_root, storage_key)
if dest_path is None: if dest_path is None:
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad") raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
@@ -915,7 +1037,7 @@ def bulk_media_patch(
try: try:
cur.execute( cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state, """SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
copyright_notice, original_filename copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
FROM media_assets WHERE id = %s""", FROM media_assets WHERE id = %s""",
(asset_id,), (asset_id,),
) )
@@ -937,7 +1059,7 @@ def bulk_media_patch(
eff = _effective_media_patch_fields(patch_fields, asset) eff = _effective_media_patch_fields(patch_fields, asset)
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower() next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id") next_cid = eff.get("club_id", asset.get("club_id"))
if "visibility" in patch_fields or "club_id" in patch_fields: if "visibility" in patch_fields or "club_id" in patch_fields:
assert_valid_governance_visibility( assert_valid_governance_visibility(
cur, cur,
@@ -946,6 +1068,26 @@ def bulk_media_patch(
next_vis, next_vis,
int(next_cid) if next_cid is not None else None, int(next_cid) if next_cid is not None else None,
) )
if next_vis in ("private", "club") and next_cid is None:
failed.append(
{
"id": asset_id,
"detail": (
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner)."
),
}
)
continue
new_sk: Optional[str] = None
if "visibility" in patch_fields or "club_id" in patch_fields:
next_club_param: Optional[int] = None
if next_vis in ("club", "private"):
next_club_param = int(next_cid) if next_cid is not None else None
media_root = get_effective_media_root(cur)
new_sk = _relocate_asset_file_if_governance_changed(
cur, media_root, asset_id, asset, next_vis, next_club_param
)
sets: list[str] = [] sets: list[str] = []
vals: list[Any] = [] vals: list[Any] = []
@@ -962,7 +1104,10 @@ def bulk_media_patch(
sets.append("visibility = %s") sets.append("visibility = %s")
vals.append(str(eff.get("visibility", asset["visibility"])).strip()) vals.append(str(eff.get("visibility", asset["visibility"])).strip())
sets.append("club_id = %s") sets.append("club_id = %s")
vals.append(eff.get("club_id")) vals.append(next_cid)
if new_sk:
sets.append("storage_key = %s")
vals.append(new_sk)
if not sets: if not sets:
failed.append({"id": asset_id, "detail": "Nichts zu aktualisieren"}) failed.append({"id": asset_id, "detail": "Nichts zu aktualisieren"})
continue continue
@@ -996,7 +1141,7 @@ def patch_media_asset(
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute( cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state, """SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
copyright_notice, original_filename copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
FROM media_assets WHERE id = %s""", FROM media_assets WHERE id = %s""",
(asset_id,), (asset_id,),
) )
@@ -1014,7 +1159,7 @@ def patch_media_asset(
eff = _effective_media_patch_fields(data, asset) eff = _effective_media_patch_fields(data, asset)
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower() next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id") next_cid = eff.get("club_id", asset.get("club_id"))
if "visibility" in data or "club_id" in data: if "visibility" in data or "club_id" in data:
assert_valid_governance_visibility( assert_valid_governance_visibility(
cur, cur,
@@ -1023,6 +1168,24 @@ def patch_media_asset(
next_vis, next_vis,
int(next_cid) if next_cid is not None else None, int(next_cid) if next_cid is not None else None,
) )
if next_vis in ("private", "club") and next_cid is None:
raise HTTPException(
status_code=400,
detail=(
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner). "
"Bitte im PATCH setzen, z. B. bei Wechsel von „offiziell“ zu „privat“."
),
)
new_sk: Optional[str] = None
if "visibility" in data or "club_id" in data:
next_club_param: Optional[int] = None
if next_vis in ("club", "private"):
next_club_param = int(next_cid) if next_cid is not None else None
media_root = get_effective_media_root(cur)
new_sk = _relocate_asset_file_if_governance_changed(
cur, media_root, asset_id, asset, next_vis, next_club_param
)
sets: list[str] = [] sets: list[str] = []
vals: list[Any] = [] vals: list[Any] = []
@@ -1039,7 +1202,10 @@ def patch_media_asset(
sets.append("visibility = %s") sets.append("visibility = %s")
vals.append(str(eff.get("visibility", asset["visibility"])).strip()) vals.append(str(eff.get("visibility", asset["visibility"])).strip())
sets.append("club_id = %s") sets.append("club_id = %s")
vals.append(eff.get("club_id")) vals.append(next_cid)
if new_sk:
sets.append("storage_key = %s")
vals.append(new_sk)
if sets: if sets:
sets.append("updated_at = NOW()") sets.append("updated_at = NOW()")
vals.append(asset_id) vals.append(asset_id)
+8 -2
View File
@@ -80,7 +80,7 @@ def library_content_visibility_sql(
class TenantContext: class TenantContext:
profile_id: int profile_id: int
global_role: str global_role: str
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header oft None # Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header: Profil-Verein wenn existent
effective_club_id: Optional[int] effective_club_id: Optional[int]
club_ids: frozenset[int] club_ids: frozenset[int]
memberships: List[Dict[str, Any]] memberships: List[Dict[str, Any]]
@@ -100,7 +100,8 @@ def resolve_tenant_context(
Mitgliedschaften: wenn nicht übergeben, wird aus der DB geladen (aktive Mitgliedschaften). Mitgliedschaften: wenn nicht übergeben, wird aus der DB geladen (aktive Mitgliedschaften).
Auflösung effective_club_id: Auflösung effective_club_id:
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → None. - Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
active_club_id falls der Verein existiert, sonst None.
- Sonst: gültiger Header zwingend Mitgliedschaft — bei ``reject`` sonst 403, bei ``ignore`` wie ohne Header. - Sonst: gültiger Header zwingend Mitgliedschaft — bei ``reject`` sonst 403, bei ``ignore`` wie ohne Header.
Ohne gültigen Header: gespeichertes active_club_id wenn Mitglied; sonst einziger Verein; Ohne gültigen Header: gespeichertes active_club_id wenn Mitglied; sonst einziger Verein;
bei mehreren ohne gültige Vorgabe → min(club_ids) (Fallback). bei mehreren ohne gültige Vorgabe → min(club_ids) (Fallback).
@@ -118,6 +119,11 @@ def resolve_tenant_context(
if not _club_exists(cur, header_cid): if not _club_exists(cur, header_cid):
raise HTTPException(status_code=400, detail="Verein nicht gefunden") raise HTTPException(status_code=400, detail="Verein nicht gefunden")
effective = header_cid effective = header_cid
elif (
stored_active_club_id is not None
and _club_exists(cur, stored_active_club_id)
):
effective = stored_active_club_id
else: else:
effective = None effective = None
return TenantContext( return TenantContext(
+52 -1
View File
@@ -2,7 +2,7 @@
import pytest import pytest
from fastapi import HTTPException from fastapi import HTTPException
from tenant_context import library_content_visibility_sql, parse_active_club_header from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
def test_library_visibility_sql_platform_admin_no_filter(): def test_library_visibility_sql_platform_admin_no_filter():
@@ -74,3 +74,54 @@ def test_parse_active_club_header_non_positive():
with pytest.raises(HTTPException) as exc: with pytest.raises(HTTPException) as exc:
parse_active_club_header("0") parse_active_club_header("0")
assert exc.value.status_code == 400 assert exc.value.status_code == 400
def test_resolve_platform_admin_uses_stored_club_without_header(monkeypatch):
"""Ohne X-Active-Club-Id: effective wie gespeichertes Profil (Sync mit Dropdown/DB)."""
cur = object()
def fake_exists(c, cid):
return cid == 99
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="admin",
header_raw=None,
memberships=[{"id": 10}],
stored_active_club_id=99,
)
assert ctx.effective_club_id == 99
def test_resolve_platform_admin_header_overrides_stored(monkeypatch):
cur = object()
def fake_exists(c, cid):
return cid in (5, 99)
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="superadmin",
header_raw="5",
memberships=[{"id": 10}],
stored_active_club_id=99,
)
assert ctx.effective_club_id == 5
def test_resolve_platform_admin_no_header_stored_invalid(monkeypatch):
cur = object()
monkeypatch.setattr("tenant_context._club_exists", lambda c, cid: False)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="admin",
header_raw=None,
memberships=[{"id": 1}],
stored_active_club_id=123,
)
assert ctx.effective_club_id is None
@@ -0,0 +1,62 @@
"""Vereins-Übung: Copyright-Pflicht für angehängte Archiv-Dateien."""
from __future__ import annotations
import pytest
from fastapi import HTTPException
import routers.exercises as exercises_mod
from routers.exercises import apply_club_exercise_media_copyright_rules
def test_apply_club_exercise_media_copyright_skips_non_club() -> None:
apply_club_exercise_media_copyright_rules(object(), 1, "private")
def test_apply_club_exercise_media_copyright_missing_copyright() -> None:
orig = exercises_mod._fetch_exercise_linked_file_assets
def mock_fetch(_cur, eid: int):
assert eid == 42
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "",
"original_filename": "x.jpg",
}
]
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
try:
with pytest.raises(HTTPException) as ei:
apply_club_exercise_media_copyright_rules(object(), 42, "club")
assert ei.value.status_code == 422
d = ei.value.detail
assert isinstance(d, dict)
assert d.get("code") == "CLUB_MEDIA_COPYRIGHT_REQUIRED"
finally:
exercises_mod._fetch_exercise_linked_file_assets = orig
def test_apply_club_exercise_media_copyright_ok() -> None:
orig = exercises_mod._fetch_exercise_linked_file_assets
def mock_fetch(_cur, _eid: int):
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "© Verein 2026",
"original_filename": "x.jpg",
}
]
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
try:
apply_club_exercise_media_copyright_rules(object(), 42, "club")
finally:
exercises_mod._fetch_exercise_linked_file_assets = orig
@@ -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"
+44
View File
@@ -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]
+107
View File
@@ -0,0 +1,107 @@
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
from __future__ import annotations
import pytest
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
_HEX64 = "a" * 64
def test_library_media_kind_dir_mime_overrides_ext() -> None:
assert library_media_kind_dir("image/png", ".bin") == "image"
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
def test_library_club_path_segment_slug_and_fallback() -> None:
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
assert library_club_path_segment(3, None) == "verein-c3"
assert library_club_path_segment(3, " ") == "verein-c3"
assert library_club_path_segment(12, "東道場") == "verein-c12"
def test_library_club_path_segment_long_name_truncated() -> None:
long = "a" * 80
seg = library_club_path_segment(5, long)
assert seg == "a" * 48 + "-c5"
def test_library_storage_key_private_is_uploader_under_club() -> None:
assert (
library_storage_key(
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
)
== f"library/ost-dojo-muenchen-c7/image/{_HEX64}.u99.jpg"
)
def test_library_storage_key_club_flat_under_club() -> None:
assert (
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
== f"library/demo-verein-c42/image/{_HEX64}.png"
)
def test_library_storage_key_official() -> None:
assert (
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
== f"library/official/video/{_HEX64}.mp4"
)
def test_library_storage_key_normalizes_visibility() -> None:
assert (
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
)
def test_library_storage_key_other_bin() -> None:
assert (
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
== f"library/official/other/{_HEX64}.bin"
)
def test_library_storage_key_private_requires_uploader() -> None:
with pytest.raises(ValueError, match="uploader_profile_id"):
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
def test_library_storage_key_private_requires_club() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
def test_library_storage_key_club_requires_id() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_club_id_positive() -> None:
with pytest.raises(ValueError, match="positiv"):
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_visibility() -> None:
with pytest.raises(ValueError, match="Sichtbarkeit"):
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_sha() -> None:
with pytest.raises(ValueError, match="64"):
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
def test_library_storage_key_extension() -> None:
with pytest.raises(ValueError):
library_storage_key(
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
)
def test_library_storage_key_private_no_club_name_fallback() -> None:
assert (
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
== f"library/verein-c2/image/{_HEX64}.u3.jpg"
)
+10 -5
View File
@@ -15,6 +15,11 @@ from auth import require_auth
from main import app from main import app
from tenant_context import TenantContext, get_tenant_context from tenant_context import TenantContext, get_tenant_context
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
_SK_PRIV_C = f"library/verein-c1/video/{'c' * 64}.u1.mp4"
@pytest.fixture @pytest.fixture
def client() -> TestClient: def client() -> TestClient:
@@ -136,7 +141,7 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
"club_id": None, "club_id": None,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "active", "lifecycle_state": "active",
"storage_key": "exercises/x.jpg", "storage_key": _SK_OFF_A,
}, },
{"id": 1}, {"id": 1},
] ]
@@ -175,7 +180,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
"id": 99, "id": 99,
"exercise_id": 3, "exercise_id": 3,
"media_type": "image", "media_type": "image",
"file_path": "/media/exercises/h.jpg", "file_path": f"/media/{_SK_OFF_B}",
"file_size": 10, "file_size": 10,
"mime_type": "image/jpeg", "mime_type": "image/jpeg",
"original_filename": "h.jpg", "original_filename": "h.jpg",
@@ -202,7 +207,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
"club_id": None, "club_id": None,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "active", "lifecycle_state": "active",
"storage_key": "exercises/h.jpg", "storage_key": _SK_OFF_B,
}, },
None, None,
inserted, inserted,
@@ -326,10 +331,10 @@ def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
{ {
"id": 5, "id": 5,
"visibility": "private", "visibility": "private",
"club_id": None, "club_id": 1,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "trash_soft", "lifecycle_state": "trash_soft",
"storage_key": "exercises/a.mp4", "storage_key": _SK_PRIV_C,
"storage_backend": "local", "storage_backend": "local",
"trash_soft_at": None, "trash_soft_at": None,
"trash_hidden_at": None, "trash_hidden_at": None,
+102 -6
View File
@@ -1,23 +1,23 @@
# Shinkan Jinkendo Version Information # Shinkan Jinkendo Version Information
APP_VERSION = "0.8.51" APP_VERSION = "0.8.64"
BUILD_DATE = "2026-05-07" BUILD_DATE = "2026-05-08"
DB_SCHEMA_VERSION = "20260507046" DB_SCHEMA_VERSION = "20260508049"
MODULE_VERSIONS = { MODULE_VERSIONS = {
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute) "auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json() "profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
"tenant_context": "1.0.4", # pytest: Unit test_access_layer.py + optional Integration test_access_layer_integration (PostgreSQL) "tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext "clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
"club_memberships": "1.0.1", # Depends(get_tenant_context) "club_memberships": "1.0.1", # Depends(get_tenant_context)
"club_join_requests": "1.0.1", # Depends(get_tenant_context) "club_join_requests": "1.0.1", # Depends(get_tenant_context)
"admin_users": "1.0.0", # GET /api/admin/users "admin_users": "1.0.0", # GET /api/admin/users
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT) "platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
"media_assets": "1.5.1", # usage: training_unit_exercises optional (Schema ohne planning-Tabelle) "media_assets": "1.12.1", # official: nur Superadmin Lifecycle/PATCH; UI Lesemodus; Superadmin Upload-Verein = aktiv
"groups": "0.1.0", "groups": "0.1.0",
"skills": "0.1.0", "skills": "0.1.0",
"methods": "0.1.0", "methods": "0.1.0",
"exercises": "2.16.0", # §4.2 official: angehängte media_assets + Copyright (PUT + bulk-metadata) "exercises": "2.19.0", # Inline-Medien §11: Fließtext-Platzhalter exercise_media.id, Normalisierung/Validierung; CREATE ohne Platzhalter
"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,102 @@ MODULE_VERSIONS = {
} }
CHANGELOG = [ CHANGELOG = [
{
"version": "0.8.64",
"date": "2026-05-08",
"changes": [
"Übung bearbeiten: Auto-Scroll beim Drag von Medien zu Textfeldern; Medien-Kacheln mehrspaltig; Sektion/Ablauf-Zuordnung an Medien entfernt (nur noch Titel bearbeiten); Picker: Video-Vorschau-Frame; Katalogvorschau ohne Anhangs-Medienliste; Ansehen mit Speichern-Hinweis + Zurück zur Bearbeitung von der Ansicht",
],
},
{
"version": "0.8.63",
"date": "2026-05-08",
"changes": [
"RTE/Übung Medien: Picker-Thumbnails; Dateiauswahl-Anzeige; bereits verknüpfte Archive-Medien ins Fließtext einfügen; Platzhalter-Caption data-shinkan-exercise-media-caption + Caret nach ZWSP; Lesemodus: Medienliste nur für nicht eingebettete Anhänge; bearbeiten: kompakte Kacheln mit Drag-and-Drop in Textfelder, Upload unter Medien entfällt",
],
},
{
"version": "0.8.62",
"date": "2026-05-08",
"changes": [
"RTE Inline-Medien: Modals Mediathek+Hochladen + „Embed im Text“; Darstellungsgröße small|medium|full (data-shinkan-exercise-media-size); Lesemodus begrenzt Bild/Video-Breite",
],
},
{
"version": "0.8.61",
"date": "2026-05-08",
"changes": [
"RTE „Bild/Video im Text“: eingebaute Hilfe (Caret + insertHTML/Fallback); sichtbarer 📎-Chip im Editor; Hinweis bei fehlgeschlagener Einfügung/Prompt-ID",
],
},
{
"version": "0.8.60",
"date": "2026-05-08",
"changes": [
"Inline-Medien im Übungs-Fließtext (MEDIA_SPEC §11): {{exerciseMedia:id}} → kanonisches span; nur exercise_media dieser Übung; create ohne Platzhalter",
"Frontend: ExerciseRichTextBlock mit Allowlist-Sanitize + Embed; Toolbar „Bild/Video im Text“ im RichTextEditor wenn Medien an der Übung; Detail/Katalog/Liste konsistent",
],
},
{
"version": "0.8.59",
"date": "2026-05-07",
"changes": [
"Aktiver Verein: Backend resolve_tenant_context für Plattform-Admin ohne X-Active-Club-Id nutzt gespeichertes active_club_id wenn der Verein existiert (kein effective=null nach hartem Reload mehr)",
"Frontend: Nach Vereinswechsel Profil neu laden; Dropdown-Wert aus effective_club_id / active_club_id / LocalStorage abgestimmt (getResolvedActiveClubIdForUi)",
],
},
{
"version": "0.8.58",
"date": "2026-05-07",
"changes": [
"Medienbibliothek offiziell: Ändern/Lifecycle nur Superadmin (nicht Plattform-Admin); Bearbeiten-Dialog für andere nur Lesemodus; Superadmin: Vereinsauswahl beim Archiv-Upload folgt aktiv/gesetzt effective_club_id",
],
},
{
"version": "0.8.57",
"date": "2026-05-07",
"changes": [
"Governance: visibility=official nur noch Superadmin (nicht Plattform-Admin)",
"Medienarchiv: private Uploads als Plattform-Admin erfordern explizites club_id; gleiche Ordnerstruktur wie „Verein“, private Kopien mit .u{Profil} vor Dateiendung",
"Übung visibility=Verein: angebundene Archiv-Dateien müssen aktiv sein und Copyright (≥3 Zeichen) haben; UI- und API-Fehlercodes CLUB_MEDIA_*",
"Frontend: „Offiziell“ nur Superadmin (Bibliothek, Übungsformular, Bulk-Sichtbarkeit, Progressionsgraphen)",
],
},
{
"version": "0.8.56",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Vereinsmedien unter library/{aus Name abgeleitet}-c{club_id}/ statt festem library/club/c{id}/; Sonderzeichen/Umlaute zu sicheren Ordnernamen; fehlender Name → verein-c{id}; Governance-Umzug liest aktuellen Vereinsnamen aus DB",
],
},
{
"version": "0.8.55",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Speicherpfad library/* mit Medientyp-Unterordnern (image, video, pdf, other) vor SHA-Dateinamen; Umzug bei Governance-PATCH nutzt mime_type aus DB",
],
},
{
"version": "0.8.54",
"date": "2026-05-08",
"changes": [
"Medienpfade: vereinsgeteilt (club) direkt unter library/club/c{id}/; private unter library/club/c{id}/u{profile}/ (kein Ordner „private“/„shared“); Dedupe private inkl. uploaded_by_profile_id",
],
},
{
"version": "0.8.53",
"date": "2026-05-08",
"changes": [
"Medienablage vereinsbezogen: private → library/club/c{id}/private, Vereinssichtbarkeit → …/shared, official unverändert; private Archiv-Upload: club_id oder X-Active-Club-Id; DB club_id bei private gesetzt; PATCH/Bulk: club_id für private nicht mehr blind auf NULL",
],
},
{
"version": "0.8.52",
"date": "2026-05-08",
"changes": [
"Neue lokale media_assets: hierarchische library/* Pfade; Dedupe nach sha+visibility+club_id; bei PATCH/Bulk-Patch Sichtbarkeit/Verein: Datei umziehen, exercise_media.file_path aktualisieren (Details siehe 0.8.53)",
],
},
{ {
"version": "0.8.51", "version": "0.8.51",
"date": "2026-05-07", "date": "2026-05-07",
+2
View File
@@ -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:
+75 -34
View File
@@ -1,9 +1,9 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover # Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-05-05 **Stand:** 2026-05-07
**App-Version / DB-Schema:** siehe `backend/version.py` **App-Version / DB-Schema:** App **0.8.59**, DB-Schema siehe `backend/version.py` (`DB_SCHEMA_VERSION`)
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand** und **nächste Baustellen**. Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
### Produktion: `relation … does not exist` (z. B. `skill_main_categories`) ### Produktion: `relation … does not exist` (z. B. `skill_main_categories`)
@@ -21,11 +21,17 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Thema | Pfad | | Thema | Pfad |
|--------|------| |--------|------|
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` | | Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
| Projekt-Status (Skills, Wiki, Stats) | `.claude/docs/PROJECT_STATUS.md` | | **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
| Übungen: API, DB, Architektur, Routing | `.claude/docs/technical/EXERCISES_API_SPEC.md`, `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_FRONTEND_ROUTING.md` | | Übungen: API, DB, Architektur, Routing | `.claude/docs/technical/EXERCISES_API_SPEC.md`, `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_FRONTEND_ROUTING.md` |
| Media / Upload | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` | | Media / Upload-Limits / Embed | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
| MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` | | MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
| Rahmenprogramm · Planung (`training_units` Blueprints), Progressionsgraph | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md`; Überblick DB → `.claude/docs/technical/DATABASE_SCHEMA.md`; Domäne → `.claude/docs/functional/DOMAIN_MODEL.md` | | Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
--- ---
@@ -36,73 +42,108 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **`maturity_models`**, **`model_levels`**, **`model_skills`**, **`model_skill_levels`**: Matrix-Inhalt pro Modell. - **`maturity_models`**, **`model_levels`**, **`model_skills`**, **`model_skill_levels`**: Matrix-Inhalt pro Modell.
- **Kontext am Modell (Legacy, M:N):** `maturity_model_focus_areas`, `maturity_model_style_directions`, `maturity_model_target_groups` (Migration 025). - **Kontext am Modell (Legacy, M:N):** `maturity_model_focus_areas`, `maturity_model_style_directions`, `maturity_model_target_groups` (Migration 025).
- **Hierarchische Kontext-Zuordnung (Resolve):** `maturity_model_context_bindings` mit optional `style_direction_id`, `training_type_id` (Migration 026, 027). - **Hierarchische Kontext-Zuordnung (Resolve):** `maturity_model_context_bindings` mit optional `style_direction_id`, `training_type_id` (Migration 026, 027).
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes). - **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
### 2.2 Resolve-Logik (Backend) ### 2.2 Resolve-Logik (Backend)
- **`GET /api/maturity-models/resolve`**: Bindings zum Fokus, die zur Anfrage passen; Merge nach Spezifität (weniger spezifisch zuerst); spezifischere Zeilen überschreiben Zelltexte. - **`GET /api/maturity-models/resolve`**: Bindings zum Fokus, die zur Anfrage passen; Merge nach Spezifität (weniger spezifisch zuerst); spezifischere Zeilen überschreiben Zelltexte.
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard (z. B. Fokus+Trainingsstil gilt für alle Stilrichtungen, aber nur für diesen Trainingsstil). - **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard.
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert. Sonst bei fehlendem Treffer **`null`** (kein stilles Legacy mit falschem Trainingsstil). - **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert.
### 2.3 Export / Import (einzelnes Modell & aufgelöst) ### 2.3 Export / Import (einzelnes Modell & aufgelöst)
- **`GET /api/maturity-models/{id}/export`**: `shinkan.maturity_model.v1` inkl. `context_bindings_for_model` (IDs). - **`GET /api/maturity-models/{id}/export`**: `shinkan.maturity_model.v1` inkl. `context_bindings_for_model` (IDs).
- **`GET /api/maturity-models/export-resolved`**: `shinkan.maturity_matrix_resolved.v1` (Query: `focus_area_id`, optional `style_direction_id`, `training_type_id`). - **`GET /api/maturity-models/export-resolved`**: `shinkan.maturity_matrix_resolved.v1` (Query: `focus_area_id`, optional `style_direction_id`, `training_type_id`).
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings` (nur bei `maturity_model.v1`). - **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings`.
### 2.4 Komplett-Stack Test → Prod ### 2.4 Komplett-Stack Test → Prod
- **`GET /api/admin/matrix-stack/export`**: `shinkan.matrix_stack.v1` – Katalog (`skill_main_categories`, `skill_categories`, `skills`, `skill_level_definitions`) + alle Reifegradmodelle + Bindings mit **Namen** (Fokus/Stil/Trainingsstil). - **`GET /api/admin/matrix-stack/export`**, **`POST /api/admin/matrix-stack/import`** — siehe `matrix_stack_bundle.py`.
- **`POST /api/admin/matrix-stack/import`**: Upsert Katalog per Slug; Skills per Kategorie+Name; Modelle neu anlegen; Bindings per Katalognamen. Optional **`replace_all_maturity_models`** + **`confirm_replace_all: "DELETE_MATURITY_STACK"`** (nur Superadmin).
- Router: `backend/routers/matrix_stack_bundle.py`, in `main.py` registriert.
### 2.5 Frontend (Admin) ### 2.5 Frontend (Admin)
- **`frontend/src/pages/AdminMaturityModelsPage.jsx`**: Tabs u. a. Katalog, Modelle, Kontext-Zuordnung, **Matrix-Ansicht und Export**. - **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
- **`MaturityModelBindingsAdmin.jsx`**: Bindings CRUD, Erklärung Merge/Legacy.
- **`MaturityMatrixToolsAdmin.jsx`**: Kontext auflösen, hierarchische Matrix-Ansicht, Export einzelnes Modell / aufgelöst, Einzelmodell-Import; **Komplett-Stack** mit eigenem Export-Button und **eigenem Dateifeld für Stack-Import** (`POST /api/admin/matrix-stack/import`).
- **`frontend/src/utils/api.js`**: u. a. `exportMatrixStackBundle`, `importMatrixStackBundle`, Reifegrad-APIs.
--- ---
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz) ## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
- **Migration 036:** Rahmenkopf nur Bibliothek (Kontext: Fokusbereich, Stilrichtung; M:N Trainingsarten/Zielgruppen); keine `plan_mode`/keine Kopf‑`group_id`. - **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
- **Migration 037:** Pro Rahmen‑Slot eine **`training_units`‑Zeile mit `framework_slot_id`**; strukturierter Ablauf wie echte Einheiten (`training_unit_sections` / `training_unit_section_items`). Tabelle **`training_framework_slot_exercises`** entfällt. - **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
- **API:** Rahmen unter **`/api/training-framework-programs`** (Slots liefern u. a. **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`**); Kalenderliste **`GET /api/training-units`** ohne Blueprints; Übernahme **`POST /api/training-units/from-framework-slot`**.
- **Code:** `backend/routers/training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**; **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
--- ---
## 4. Stand: Übungen (Lücke für nächste Session) ## 4. Stand: Medien-Management (Ist, 2026-05-07)
**Ist (laut Projektdoku und aktuellem Produktziel):** **Datenmodell (Kurz):**
- Backend: Übungen-CRUD, M:N, Suche, Blöcke, Medien-Struktur u. a. sind in `PROJECT_STATUS.md` als umgesetzt geführt; viele Übungen stammen aus **MediaWiki-Import** (Wiki-Tracking-Tabellen). - **`media_assets`:** Physische oder logische Archiv-Datei (u. a. `sha256`, `visibility`, `club_id`, `lifecycle_state`, `copyright_notice`, Speicherpfad/`storage_key`, `tags` ab passender Migration).
- **Soll / Nutzerfeedback:** In der Praxis fehlt oder ist unzureichend: **stabile Liste**, **gerenderte Detailansicht**, **Bearbeiten/Anlegen**, **Medien zuweisen/Upload** – konkrete Fehler (404, leere Liste, falsche Route) sind vor Ort zu verifizieren. - **`exercise_media`:** optional **`media_asset_id`**; weiterhin Embeds ohne Asset; Kontext/Sortierung/Titel wie bisher.
- **`platform_media_storage`:** Superadmin — relativer Unterpfad unter `MEDIA_ROOT`.
**Nächste Session sollte:** **API (Auszug):**
1. Aktuelle Routen und Seiten prüfen (`App.jsx`, `EXERCISES_FRONTEND_ROUTING.md`). - **`GET /api/media-assets`**, Filter (Lifecycle, `media_kind`, Verein, Suche, Tags), Berechtigungen pro Zeile.
2. `GET /api/exercises` (Filter, Auth) und eine Beispiel-Übung gegen die Dev-DB testen. - **`PATCH /api/media-assets/{id}`** / Bulk-PATCH, **Lifecycle** (`POST …/lifecycle`, Bulk).
3. UI schrittweise: Liste → Detail → Formular → Medien (an Specs in `.claude/docs/technical/` ausrichten). - **`GET …/media-assets/{id}/file`** (inkl. Kontext `ssetoken` wo vorgesehen).
- **`POST /api/exercises/{id}/media/from-asset`:** bestehendes Asset verknüpfen.
- Übungs-Uploads erzeugen/verknüpfen **`media_assets`**; Governance wie **`library_content_*`** / TenantContext.
**Frontend:**
- Route **`/media`** (Medienbibliothek): Kacheln/Liste, Filter, Copyright, Lifecycle-Actions (Rollen gemäß Spec; **`official`:** bearbeiten/Lifecycle im Wesentlichen **Superadmin**, andere Rollen **Lesemodus** im Bearbeiten-Dialog).
- Übungsformular: Archiv-Picker, Vorschau, Reaktivierung bei Dedupe-Konflikt (Papierkorb).
**Speicher & Pfade:**
- Struktur unter **`library/`** mit Vereinssegment (aus Vereinsname abgeleitet + `c{id}`), Unterordner nach Medienkind (`image`/`video`/`pdf`/`other`), Dateiname z. B. SHA-basiert — Details und Drift-Vermeidung in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
**Governance & Mandant:**
- **`visibility=official`** für Übungen: nur **Superadmin**; Medien **`official`:** Lifecycle/PATCH schwerpunktmäßig Superadmin (Plattform-Admin nicht gleich Superadmin).
- **Aktiver Verein:** `profiles.active_club_id`, Header **`X-Active-Club-Id`**, Response **`effective_club_id`** — nach **0.8.59** konsistent inkl. Plattform-Admin beim Reload (Backend **`tenant_context`**, Frontend **`getResolvedActiveClubIdForUi`** + Profil-Refresh nach Vereinswechsel).
--- ---
## 5. Technische Referenz (kurz) ## 5. Geplant: Inline-Medienverlinkung (nicht umgesetzt)
**Ziel:** Mediendarstellung **innerhalb** von Fließtext-Feldern (Ablauf, Ziele, Trainerhinweise), konsistent mit derselben **`exercise_media`‑** bzw. Asset-Governance wie die Medienliste.
**Norm:** **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — u. a.:
- Verweis auf **`exercise_media.id`** (oder kanonisch übersetzte Markup-Syntax), **keine** zweite Sichtbarkeitslogik.
- **Ein** zentraler Render-/Sanitize-Pfad für Übungstexte; keine verstreuten „roh `dangerouslySetInnerHTML`“-Pfade.
- XSS/CSP: nur Allowlist-HTML und kontrollierte Player-Komponenten.
**Reihenfolge:** Archiv & aktuelle Governance gelten als Basis; Inline ist die **nächste** inhaltliche Ausbaustufe für Medien (siehe **`PROJECT_STATUS.md`** Nächste Schritte).
---
## 6. Nächste Session — sinnvolle Arbeitspakete
1. **Inline §11:** Syntax festlegen (z. B. `{{exerciseMedia:id}}` → kanonisches HTML), Server normalisieren bei Speichern, einen **`renderExerciseRichText()`**-Pfad im Frontend.
2. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
3. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
4. **S3/Adapter:** Speicher-Abstraktion §7 — wenn Produkt es verlangt.
5. **Rahmen/UI:** Kalender „aus Rahmen übernehmen“ weiter anbinden (parallel, unabhängig von Medien).
---
## 7. Technische Referenz (kurz)
| Bereich | Einstieg | | Bereich | Einstieg |
|---------|----------| |---------|----------|
| Backend API | `backend/main.py`; Router u. a. **`training_framework_programs.py`**, **`training_planning.py`**, `maturity_models.py`, `matrix_stack_bundle.py`, `exercises.py`, `catalogs.py`, `skills.py` | | Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Migrationen | `backend/migrations/` (u. a. 024–027 Reifegrad/Bindings; **035–037** Rahmenprogramm / Slot‑Blueprint) | | Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
| Frontend API | `frontend/src/utils/api.js` | | Frontend API | `frontend/src/utils/api.js` |
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
| Version / Changelog | `backend/version.py` | | Version / Changelog | `backend/version.py` |
--- ---
## 6. Veraltete Hinweise ## 8. Veraltete Hinweise
Die Datei `.claude/docs/working/HANDOVER_NEXT_SESSION.md` (2026-04-22) ist **historisch**; für den aktuellen Stand gilt **`docs/HANDOVER.md`**. `.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
--- ---
+14 -3
View File
@@ -13,9 +13,20 @@ server {
# — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat. # — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat.
resolver 127.0.0.11 valid=10s ipv6=off; resolver 127.0.0.11 valid=10s ipv6=off;
# Uploads (Übungsmedien) und API erreichen Clients unter derselben Host-URL wie die SPA — # Uploads (Übungsmedien, Medienarchiv-Bulk) — Limit muss >= größte Einzeldatei und
# dafür muss Nginx zur FastAPI-Instanz im Compose-Netz weiterleiten. # bei multipart ggf. Summe mehrerer Dateien sein (Backend praxis: bis 1024 MB Admin).
client_max_body_size 64m; client_max_body_size 1024m;
# Medienbibliothek (React /media) — vor location ^~ /media/: sonst liefert ein Reload
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
location = /media {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
try_files /index.html =404;
}
location = /media/ {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
try_files /index.html =404;
}
location ^~ /api/ { location ^~ /api/ {
set $docker_backend_svc backend; set $docker_backend_svc backend;
+270 -1
View File
@@ -3895,7 +3895,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 +3944,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;
@@ -1,4 +1,5 @@
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
import { 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.
@@ -9,10 +10,7 @@ export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
const clubs = user?.clubs || [] const clubs = user?.clubs || []
if (clubs.length <= 1) return null if (clubs.length <= 1) return null
const selectClubId = const selectClubId = getResolvedActiveClubIdForUi(user)
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
? user.active_club_id
: clubs[0]?.id
const isMobile = variant === 'mobile' const isMobile = variant === 'mobile'
@@ -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>
)
}
+8 -16
View File
@@ -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} />
</> </>
)} )}
</> </>
@@ -5,6 +5,7 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react' import React, { useCallback, useEffect, 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 { useAuth } from '../context/AuthContext'
import ExercisePickerModal from './ExercisePickerModal' import ExercisePickerModal from './ExercisePickerModal'
const VIS_OPTIONS = [ const VIS_OPTIONS = [
@@ -99,6 +100,13 @@ export default function ExerciseProgressionGraphPanel({
anchorExerciseId = null, anchorExerciseId = null,
anchorTitle = null, anchorTitle = null,
}) { }) {
const { user } = useAuth()
const isSuperadmin = user?.role === 'superadmin'
const filteredGraphVisOptions = useMemo(
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
[isSuperadmin],
)
const [graphs, setGraphs] = useState([]) const [graphs, setGraphs] = useState([])
const [selectedGraphId, setSelectedGraphId] = useState(null) const [selectedGraphId, setSelectedGraphId] = useState(null)
const [edges, setEdges] = useState([]) const [edges, setEdges] = useState([])
@@ -566,7 +574,7 @@ export default function ExerciseProgressionGraphPanel({
value={newGraphVisibility} value={newGraphVisibility}
onChange={(e) => setNewGraphVisibility(e.target.value)} onChange={(e) => setNewGraphVisibility(e.target.value)}
> >
{VIS_OPTIONS.map((o) => ( {filteredGraphVisOptions.map((o) => (
<option key={o.value} value={o.value}> <option key={o.value} value={o.value}>
{o.label} {o.label}
</option> </option>
@@ -599,7 +607,7 @@ export default function ExerciseProgressionGraphPanel({
<div className="form-row"> <div className="form-row">
<label className="form-label">Sichtbarkeit</label> <label className="form-label">Sichtbarkeit</label>
<select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}> <select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}>
{VIS_OPTIONS.map((o) => ( {filteredGraphVisOptions.map((o) => (
<option key={o.value} value={o.value}> <option key={o.value} value={o.value}>
{o.label} {o.label}
</option> </option>
@@ -0,0 +1,107 @@
import React, { useMemo } from 'react'
import { sanitizeExerciseRichDisplayHtml } from '../utils/exerciseRichTextSanitize'
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
function isTrashHidden(m) {
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
}
function buildVisibleMediaMap(mediaList) {
const map = new Map()
for (const m of mediaList || []) {
if (!m || m.id == null || isTrashHidden(m)) continue
map.set(Number(m.id), m)
}
return map
}
function domToReactNodes(node, exerciseId, mediaById, path) {
if (node.nodeType === Node.TEXT_NODE) {
const t = node.textContent
return t ? t : null
}
if (node.nodeType !== Node.ELEMENT_NODE) return null
const el = node
const tag = el.tagName.toLowerCase()
const key = path.join('.')
if (tag === 'span' && el.getAttribute('data-shinkan-exercise-media')) {
const raw = el.getAttribute('data-shinkan-exercise-media')
const mid = parseInt(raw, 10)
if (!Number.isFinite(mid) || mid < 1) {
return (
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
[Ungültiger Medienverweis]
</span>
)
}
const media = mediaById.get(mid)
if (!media) {
return (
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
[Medium nicht verfügbar]
</span>
)
}
const rawSize = (el.getAttribute('data-shinkan-exercise-media-size') || 'medium').toLowerCase().trim()
const layoutSize = rawSize === 'small' || rawSize === 'full' ? rawSize : 'medium'
const wrapClass =
layoutSize === 'small'
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--sm'
: layoutSize === 'full'
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--full'
: 'shinkan-inline-media-wrap shinkan-inline-media-wrap--md'
const lc = String(media.asset_lifecycle_state || 'active').toLowerCase()
return (
<span key={key} className={wrapClass} style={{ display: 'inline-block', verticalAlign: 'top' }}>
{lc === 'trash_soft' && (
<span style={{ fontSize: '0.75rem', color: 'var(--danger)', display: 'block', marginBottom: '4px' }}>
Dieses Medium ist im Papierkorb.
</span>
)}
<ExerciseMediaEmbed exerciseId={exerciseId} media={media} layoutSize={layoutSize} />
</span>
)
}
const children = []
const childNodes = Array.from(el.childNodes)
childNodes.forEach((ch, i) => {
const sub = domToReactNodes(ch, exerciseId, mediaById, [...path, String(i)])
if (sub != null && sub !== false) children.push(sub)
})
const props = { key }
if (tag === 'a' && el.getAttribute('href')) {
props.href = el.getAttribute('href')
props.target = '_blank'
props.rel = 'noreferrer'
}
return React.createElement(tag, props, children.length ? children : null)
}
/**
* Zentraler Anzeige-Pfad für Übungs-Rich-Text inkl. §11 Inline-Medien.
* @param {{ html?: string|null, exerciseId?: number|null, media?: object[]|null, className?: string }} props
*/
export default function ExerciseRichTextBlock({ html, exerciseId, media, className = '' }) {
const safe = useMemo(() => sanitizeExerciseRichDisplayHtml(html), [html])
const mediaById = useMemo(() => buildVisibleMediaMap(media), [media])
const body = useMemo(() => {
if (!safe.trim()) return null
const tpl = document.createElement('template')
tpl.innerHTML = safe
const nodes = []
Array.from(tpl.content.childNodes).forEach((ch, i) => {
const r = domToReactNodes(ch, exerciseId, mediaById, [String(i)])
if (r != null) nodes.push(r)
})
return nodes
}, [safe, exerciseId, mediaById])
if (!body || body.length === 0) return null
return <div className={`rich-text-content ${className}`.trim()}>{body}</div>
}
+2 -4
View File
@@ -1,5 +1,6 @@
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'
function Navigation() { function Navigation() {
const location = useLocation() const location = useLocation()
@@ -7,10 +8,7 @@ function Navigation() {
const { user, logout, setActiveClub } = useAuth() const { user, logout, setActiveClub } = useAuth()
const clubs = user?.clubs || [] const clubs = user?.clubs || []
const selectClubId = const selectClubId = getResolvedActiveClubIdForUi(user)
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
? user.active_club_id
: clubs[0]?.id
const handleLogout = async () => { const handleLogout = async () => {
await logout() await logout()
+305 -2
View File
@@ -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, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
}
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>
) )
} }
@@ -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
}
+15 -1
View File
@@ -64,11 +64,25 @@ export function AuthProvider({ children }) {
const uid = userRef.current?.id const uid = userRef.current?.id
if (!Number.isFinite(cid) || cid < 1 || !uid) return if (!Number.isFinite(cid) || cid < 1 || !uid) return
localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(cid)) localStorage.setItem(ACTIVE_CLUB_STORAGE_KEY, String(cid))
setUser((prev) => (prev?.id ? { ...prev, active_club_id: cid } : prev)) setUser((prev) =>
prev?.id
? { ...prev, active_club_id: cid, effective_club_id: cid }
: prev
)
try { try {
await api.updateProfile(uid, { active_club_id: cid }) await api.updateProfile(uid, { active_club_id: cid })
const profile = await api.getCurrentProfile()
syncStoredActiveClub(profile)
setUser(profile)
} catch (e) { } catch (e) {
console.error(e) console.error(e)
try {
const profile = await api.getCurrentProfile()
syncStoredActiveClub(profile)
setUser(profile)
} catch {
/* ignore */
}
} }
}, []) }, [])
+22 -81
View File
@@ -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>
+217 -338
View File
@@ -4,71 +4,14 @@ 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'
/** 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: '—' },
@@ -154,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">
@@ -183,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' }}>
@@ -406,6 +360,8 @@ function MultiAssocBlock({ title, rows, setRows, options, idKey, emptyLabel }) {
function ExerciseFormPage() { function ExerciseFormPage() {
const { id: routeId } = useParams() const { id: routeId } = useParams()
const navigate = useNavigate() const navigate = useNavigate()
const { user } = useAuth()
const isSuperadmin = user?.role === 'superadmin'
const exerciseId = routeId && !Number.isNaN(parseInt(routeId, 10)) ? parseInt(routeId, 10) : null const exerciseId = routeId && !Number.isNaN(parseInt(routeId, 10)) ? parseInt(routeId, 10) : null
const isEdit = exerciseId != null const isEdit = exerciseId != null
@@ -418,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())
@@ -426,17 +383,10 @@ function ExerciseFormPage() {
const [variantEditSelection, setVariantEditSelection] = useState(null) const [variantEditSelection, setVariantEditSelection] = useState(null)
const variantsDetailsRef = useRef(null) const variantsDetailsRef = useRef(null)
const [mediaFile, setMediaFile] = useState(null)
const [mediaType, setMediaType] = useState('image')
const [mediaTitle, setMediaTitle] = useState('')
const [mediaContext, setMediaContext] = useState('ablauf')
const [embedUrl, setEmbedUrl] = useState('')
const [embedTitle, setEmbedTitle] = useState('')
const [mediaFields, setMediaFields] = useState({}) const [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)
@@ -447,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
@@ -517,6 +487,7 @@ function ExerciseFormPage() {
setVariants([]) setVariants([])
setVariantDraft(emptyVariantDraft()) setVariantDraft(emptyVariantDraft())
setVariantEditSelection(null) setVariantEditSelection(null)
setFormDirty(false)
setLoading(false) setLoading(false)
return return
} }
@@ -531,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')
@@ -560,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 }))
} }
@@ -676,6 +649,20 @@ function ExerciseFormPage() {
promote_attached_media_for_official: true, promote_attached_media_for_official: true,
...(miss > 0 ? { default_official_media_copyright: String(defaultCopyright).trim() } : {}), ...(miss > 0 ? { default_official_media_copyright: String(defaultCopyright).trim() } : {}),
}) })
} else if (
firstErr.status === 422 &&
firstErr.code === 'CLUB_MEDIA_COPYRIGHT_REQUIRED' &&
firstErr.payload?.media_assets
) {
alert(
'Vereinsöffentliche Übungen brauchen bei jeder verknüpften Datei einen Copyright-Vermerk (mind. 3 Zeichen). Bitte in der Medienbibliothek oder den Mediendetails nachtragen.',
)
throw firstErr
} else if (firstErr.status === 422 && firstErr.code === 'CLUB_MEDIA_LIFECYCLE') {
alert(
'Speichern nicht möglich: mindestens ein verknüpftes Medium ist nicht aktiv (Papierkorb). Bitte reaktivieren oder entfernen.',
)
throw firstErr
} else { } else {
throw firstErr throw firstErr
} }
@@ -683,6 +670,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)
@@ -706,7 +694,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,
@@ -723,91 +711,11 @@ function ExerciseFormPage() {
[mediaList], [mediaList],
) )
const handleUploadFile = async () => {
if (!exerciseId || !mediaFile) {
alert('Datei wählen')
return
}
const fd = new FormData()
fd.append('file', mediaFile)
fd.append('media_type', mediaType)
fd.append('title', mediaTitle)
fd.append('description', '')
fd.append('context', mediaContext)
fd.append('is_primary', 'false')
try {
await api.uploadExerciseMedia(exerciseId, fd)
setMediaFile(null)
setMediaTitle('')
await refreshMedia()
} catch (err) {
if (err.code === 'MEDIA_ASSET_IN_TRASH' && err.payload?.media_asset_id != null) {
const aid = err.payload.media_asset_id
const nameHint =
(mediaFile && mediaFile.name) ||
err.payload.original_filename ||
'diese Datei'
if (
confirm(
`Die hochgeladene Datei ist inhaltsgleich mit einem Archiv-Medium im Papierkorb (${nameHint}). ` +
'Soll dieses Medium wieder aktiviert und an die Übung gehängt werden? (Es wird kein zweites Exemplar auf der Platte angelegt.)',
)
) {
try {
await api.postMediaAssetLifecycle(aid, 'reactivate')
await api.attachExerciseMediaFromAsset(exerciseId, {
media_asset_id: aid,
title: mediaTitle || undefined,
description: '',
context: mediaContext,
is_primary: false,
})
setMediaFile(null)
setMediaTitle('')
await refreshMedia()
} catch (e2) {
alert(e2.message || String(e2))
}
}
return
}
if (err.code === 'MEDIA_ASSET_UNAVAILABLE') {
alert(
(err.message || 'Archiv-Konflikt') +
' Bitte wenden Sie sich an einen Administrator oder wählen Sie eine andere Datei.',
)
return
}
alert('Upload: ' + (err.message || String(err)))
}
}
const handleAddEmbed = async () => {
if (!exerciseId || !embedUrl.trim()) {
alert('Embed-URL eingeben')
return
}
const fd = new FormData()
fd.append('embed_url', embedUrl.trim())
fd.append('media_type', 'video')
fd.append('title', embedTitle)
fd.append('description', '')
fd.append('context', mediaContext)
fd.append('is_primary', 'false')
try {
await api.uploadExerciseMedia(exerciseId, fd)
setEmbedUrl('')
setEmbedTitle('')
await refreshMedia()
} catch (err) {
alert('Embed: ' + err.message)
}
}
const handleDeleteMedia = async (mid) => { 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
@@ -858,7 +766,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) {
@@ -875,6 +782,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)))
} }
@@ -978,7 +886,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>
@@ -1008,6 +927,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>
@@ -1018,6 +940,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>
@@ -1028,6 +953,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>
@@ -1038,6 +966,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>
@@ -1048,6 +979,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>
@@ -1243,7 +1177,7 @@ function ExerciseFormPage() {
> >
<option value="private">Privat</option> <option value="private">Privat</option>
<option value="club">Verein</option> <option value="club">Verein</option>
<option value="official">Offiziell</option> {isSuperadmin ? <option value="official">Offiziell</option> : null}
</select> </select>
</div> </div>
<div className="form-row"> <div className="form-row">
@@ -1339,9 +1273,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'}
@@ -1408,6 +1348,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>
)} )}
@@ -1436,8 +1379,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={{
@@ -1455,184 +1403,125 @@ function ExerciseFormPage() {
Medienbibliothek Medienbibliothek
</Link> </Link>
</div> </div>
<div style={{ display: 'grid', gap: '12px', marginTop: '12px' }}>
<div>
<label className="form-label">Datei</label>
<input
type="file"
accept="image/*,video/*,application/pdf"
onChange={(e) => setMediaFile(e.target.files?.[0] || null)}
/>
<div className="form-row" style={{ marginTop: '8px' }}>
<select className="form-input" value={mediaType} onChange={(e) => setMediaType(e.target.value)}>
<option value="image">Bild</option>
<option value="video">Video</option>
<option value="document">PDF</option>
</select>
<input
type="text"
className="form-input"
placeholder="Titel (optional)"
value={mediaTitle}
onChange={(e) => setMediaTitle(e.target.value)}
style={{ marginTop: '8px' }}
/>
<select
className="form-input"
value={mediaContext}
onChange={(e) => setMediaContext(e.target.value)}
style={{ marginTop: '8px' }}
>
<option value="ablauf">Ablauf</option>
<option value="detail">Detail</option>
<option value="trainer_hint">Trainer-Hinweis</option>
</select>
</div>
<button type="button" className="btn btn-secondary" style={{ marginTop: '8px' }} onClick={handleUploadFile}>
Hochladen
</button>
</div>
<div>
<label className="form-label">Embed-URL</label>
<input
type="url"
className="form-input"
placeholder="https://…"
value={embedUrl}
onChange={(e) => setEmbedUrl(e.target.value)}
/>
<input
type="text"
className="form-input"
placeholder="Titel (optional)"
value={embedTitle}
onChange={(e) => setEmbedTitle(e.target.value)}
style={{ marginTop: '8px' }}
/>
<button type="button" className="btn btn-secondary" style={{ marginTop: '8px' }} onClick={handleAddEmbed}>
Embed hinzufügen
</button>
</div>
</div>
{mediaList.length > 0 && ( {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"
@@ -1669,16 +1558,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 && (
+13 -11
View File
@@ -19,6 +19,7 @@ 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 +28,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
@@ -152,6 +153,7 @@ function applyDashboardExerciseListUrl(mergedFromPrefs) {
function ExercisesListPage() { function ExercisesListPage() {
const { user, checkAuth } = useAuth() const { user, checkAuth } = useAuth()
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin' const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
const isSuperadmin = user?.role === 'superadmin'
const [mineOnly, setMineOnly] = useState(() => { const [mineOnly, setMineOnly] = useState(() => {
try { try {
@@ -557,9 +559,9 @@ function ExercisesListPage() {
{ id: 'private', label: 'Privat' }, { id: 'private', label: 'Privat' },
{ id: 'club', label: 'Verein' }, { id: 'club', label: 'Verein' },
] ]
if (isPlatformAdmin) base.push({ id: 'official', label: 'Offiziell (global)' }) if (isSuperadmin) base.push({ id: 'official', label: 'Offiziell (global)' })
return base return base
}, [isPlatformAdmin]) }, [isSuperadmin])
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
@@ -1379,9 +1381,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">
@@ -1409,11 +1408,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>
+69 -17
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useCallback, useRef } from 'react' import { useEffect, useState, useCallback, useRef, useMemo } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { import {
LayoutGrid, LayoutGrid,
@@ -235,6 +235,11 @@ export default function MediaLibraryPage() {
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 archiveVisOptions = useMemo(
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
[isSuperadmin],
)
const [lifecycle, setLifecycle] = useState('active') const [lifecycle, setLifecycle] = useState('active')
const [q, setQ] = useState('') const [q, setQ] = useState('')
const [items, setItems] = useState([]) const [items, setItems] = useState([])
@@ -265,6 +270,25 @@ export default function MediaLibraryPage() {
const mediaListFetchSeqRef = useRef(0) const mediaListFetchSeqRef = useRef(0)
const gridTopAnchorRef = useRef(null) const gridTopAnchorRef = useRef(null)
const modalVisibilityOptions = useMemo(() => {
if (!modalDraft) return archiveVisOptions
const o = [...archiveVisOptions]
if (!o.some((x) => x.value === modalDraft.visibility)) {
o.push({
value: modalDraft.visibility,
label: visibilityUiLabel(modalDraft.visibility),
})
}
return o
}, [archiveVisOptions, modalDraft])
useEffect(() => {
if (!isSuperadmin) return
const cid = user?.effective_club_id ?? user?.active_club_id
if (cid == null || cid === '') return
setUploadClubId(String(cid))
}, [isSuperadmin, user?.effective_club_id, user?.active_club_id])
const loadClubs = useCallback(async () => { const loadClubs = useCallback(async () => {
try { try {
const c = await api.listClubs() const c = await api.listClubs()
@@ -374,7 +398,7 @@ export default function MediaLibraryPage() {
} }
if (p.change_visibility) { if (p.change_visibility) {
body.visibility = modalDraft.visibility body.visibility = modalDraft.visibility
if (modalDraft.visibility === 'club') { if (modalDraft.visibility === 'club' || (modalDraft.visibility === 'private' && isPlatformAdmin)) {
const cid = Number(modalDraft.club_id) const cid = Number(modalDraft.club_id)
if (!cid) { if (!cid) {
alert('Bitte einen Verein wählen.') alert('Bitte einen Verein wählen.')
@@ -421,7 +445,7 @@ export default function MediaLibraryPage() {
} }
if (bulkApplyVis) { if (bulkApplyVis) {
body.visibility = bulkVis body.visibility = bulkVis
if (bulkVis === 'club') { if (bulkVis === 'club' || (bulkVis === 'private' && isPlatformAdmin)) {
const cid = Number(bulkClubId) const cid = Number(bulkClubId)
if (!cid) { if (!cid) {
alert('Bitte einen Verein wählen.') alert('Bitte einen Verein wählen.')
@@ -482,12 +506,18 @@ export default function MediaLibraryPage() {
window.alert('Bitte einen Verein für die Sichtbarkeit „Verein“ wählen.') window.alert('Bitte einen Verein für die Sichtbarkeit „Verein“ wählen.')
return return
} }
if (uploadVis === 'private' && isPlatformAdmin && !Number(uploadClubId)) {
window.alert('Als Plattform-Admin: Bitte den Zielverein für private Archiv-Uploads wählen (club_id).')
return
}
setUploadBusy(true) setUploadBusy(true)
setUploadSummary('') setUploadSummary('')
try { try {
const res = await api.bulkUploadMediaAssets(list, { const res = await api.bulkUploadMediaAssets(list, {
visibility: uploadVis, visibility: uploadVis,
...(uploadVis === 'club' ? { club_id: Number(uploadClubId) } : {}), ...((uploadVis === 'club' || (uploadVis === 'private' && isPlatformAdmin)) && Number(uploadClubId)
? { club_id: Number(uploadClubId) }
: {}),
}) })
setUploadSummary( setUploadSummary(
`Archiv-Upload: neu ${res.created_count}, bereits vorhanden ${res.duplicate_count}, fehlgeschlagen ${res.failed_count}. Liste aktualisiert.`, `Archiv-Upload: neu ${res.created_count}, bereits vorhanden ${res.duplicate_count}, fehlgeschlagen ${res.failed_count}. Liste aktualisiert.`,
@@ -520,8 +550,9 @@ export default function MediaLibraryPage() {
</div> </div>
</div> </div>
<p className="media-library__intro"> <p className="media-library__intro">
Veröffentlichte Medien (Verein/Plattform) und eigene Uploads. Suche durchsucht Bezeichner, Veröffentlichte Medien (Verein/Plattform) und eigene Uploads — „Privat“ steuert nur, wer das Asset in der
technischen Speicherpfad, Copyright-Text und Schlagwörter. Vorschau: Vorschaubild antippen. Datenbank sieht; der Ablageordner folgt dem gewählten Verein wie bei „Verein“. Plattform-Admins wählen den
Zielverein bei privatem Archiv-Upload aktiv. Suche durchsucht Bezeichner, Speicherpfad, Copyright und Tags.
Bearbeiten über das Menü — Bulk in der unteren Leiste. Bearbeiten über das Menü — Bulk in der unteren Leiste.
</p> </p>
</header> </header>
@@ -647,13 +678,13 @@ export default function MediaLibraryPage() {
}} }}
aria-label="Sichtbarkeit für neuen Upload" aria-label="Sichtbarkeit für neuen Upload"
> >
{VIS_OPTIONS.map((o) => ( {archiveVisOptions.map((o) => (
<option key={o.value} value={o.value}> <option key={o.value} value={o.value}>
Upload: {o.label} Upload: {o.label}
</option> </option>
))} ))}
</select> </select>
{uploadVis === 'club' ? ( {uploadVis === 'club' || (uploadVis === 'private' && isPlatformAdmin) ? (
<select <select
className="form-input" className="form-input"
value={uploadClubId} value={uploadClubId}
@@ -969,13 +1000,13 @@ export default function MediaLibraryPage() {
{bulkApplyVis ? ( {bulkApplyVis ? (
<> <>
<select className="form-input" value={bulkVis} onChange={(e) => setBulkVis(e.target.value)}> <select className="form-input" value={bulkVis} onChange={(e) => setBulkVis(e.target.value)}>
{VIS_OPTIONS.map((o) => ( {archiveVisOptions.map((o) => (
<option key={o.value} value={o.value}> <option key={o.value} value={o.value}>
{o.label} {o.label}
</option> </option>
))} ))}
</select> </select>
{bulkVis === 'club' ? ( {bulkVis === 'club' || (bulkVis === 'private' && isPlatformAdmin) ? (
<select className="form-input" value={bulkClubId} onChange={(e) => setBulkClubId(e.target.value)}> <select className="form-input" value={bulkClubId} onChange={(e) => setBulkClubId(e.target.value)}>
<option value="">— Verein —</option> <option value="">— Verein —</option>
{clubs.map((c) => ( {clubs.map((c) => (
@@ -1025,13 +1056,20 @@ export default function MediaLibraryPage() {
<div className="media-library__overlay" role="dialog" aria-modal="true" aria-labelledby="edit-media-title"> <div className="media-library__overlay" role="dialog" aria-modal="true" aria-labelledby="edit-media-title">
<div className="media-library__modal"> <div className="media-library__modal">
<div className="media-library__modal-head"> <div className="media-library__modal-head">
<h2 id="edit-media-title">Medium #{modal.id}</h2> <h2 id="edit-media-title">
Medium #{modal.id}
{(modal.visibility || '').toLowerCase() === 'official' && !isSuperadmin
? ' · Nur Lesen'
: ''}
</h2>
<button type="button" className="media-library__icon-btn" onClick={closeModal} aria-label="Schließen"> <button type="button" className="media-library__icon-btn" onClick={closeModal} aria-label="Schließen">
<X size={22} /> <X size={22} />
</button> </button>
</div> </div>
<div className="media-library__modal-body"> <div className="media-library__modal-body">
{(viewer?.show_club_meta || viewer?.show_uploader_meta) && ( {(viewer?.show_club_meta ||
viewer?.show_uploader_meta ||
(modal.visibility || '').toLowerCase() === 'official') && (
<div className="media-library__meta-block"> <div className="media-library__meta-block">
{viewer?.show_club_meta ? ( {viewer?.show_club_meta ? (
<div> <div>
@@ -1078,6 +1116,18 @@ export default function MediaLibraryPage() {
placeholder="z. B. Technik, Wurf" placeholder="z. B. Technik, Wurf"
/> />
</> </>
) : (modal.visibility || '').toLowerCase() === 'official' ? (
<>
<p className="media-library__hint">
Offizielle Medien sind für alle sichtbar. Bearbeiten, Sichtbarkeit und Löschung nur als Superadmin.
</p>
<label className="form-label">Bezeichnung</label>
<input className="form-input" readOnly value={modalDraft.display_name} />
<label className="form-label">Copyright</label>
<textarea className="form-input" readOnly rows={3} value={modalDraft.copyright_notice} />
<label className="form-label">Schlagwörter</label>
<input className="form-input" readOnly value={modalDraft.tags_input} />
</>
) : ( ) : (
<p className="media-library__hint">Keine Berechtigung für Metadaten — nur Verwaltende dieser Stufe.</p> <p className="media-library__hint">Keine Berechtigung für Metadaten — nur Verwaltende dieser Stufe.</p>
)} )}
@@ -1090,13 +1140,13 @@ export default function MediaLibraryPage() {
value={modalDraft.visibility} value={modalDraft.visibility}
onChange={(e) => setModalDraft((d) => ({ ...d, visibility: e.target.value }))} onChange={(e) => setModalDraft((d) => ({ ...d, visibility: e.target.value }))}
> >
{VIS_OPTIONS.map((o) => ( {modalVisibilityOptions.map((o) => (
<option key={o.value} value={o.value}> <option key={o.value} value={o.value}>
{o.label} {o.label}
</option> </option>
))} ))}
</select> </select>
{modalDraft.visibility === 'club' ? ( {modalDraft.visibility === 'club' || (modalDraft.visibility === 'private' && isPlatformAdmin) ? (
<> <>
<label className="form-label">Verein</label> <label className="form-label">Verein</label>
<select <select
@@ -1131,9 +1181,11 @@ export default function MediaLibraryPage() {
</div> </div>
<div className="media-library__modal-actions"> <div className="media-library__modal-actions">
<button type="button" className="btn btn-secondary" disabled={busy} onClick={saveModal}> {modal.permissions?.edit_metadata ? (
Speichern <button type="button" className="btn btn-secondary" disabled={busy} onClick={saveModal}>
</button> Speichern
</button>
) : null}
</div> </div>
<div className="media-library__lc-block"> <div className="media-library__lc-block">
+32
View File
@@ -0,0 +1,32 @@
import { ACTIVE_CLUB_STORAGE_KEY } from './api'
/**
* Einheitliche Anzeige des aktiven Vereins: Abgleich mit effective_club_id, active_club_id,
* LocalStorage (Request-Header-Quelle), sonst erster Verein der Liste.
*/
export function getResolvedActiveClubIdForUi(user) {
const clubs = user?.clubs || []
if (!clubs.length) return null
const idInClubs = (id) =>
id != null &&
id !== '' &&
clubs.some((c) => Number(c.id) === Number(id))
const eff = user?.effective_club_id
if (idInClubs(eff)) return Number(eff)
const ac = user?.active_club_id
if (idInClubs(ac)) return Number(ac)
try {
const ls = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
if (ls && /^\d+$/.test(ls.trim()) && clubs.some((c) => String(c.id) === ls.trim())) {
return Number(ls.trim())
}
} catch {
/* ignore */
}
return Number(clubs[0].id)
}
+19 -3
View File
@@ -472,8 +472,14 @@ export async function uploadExerciseMedia(exerciseId, formData) {
body: formData, body: formData,
}) })
if (!response.ok) { if (!response.ok) {
const err = await response.json().catch(() => ({ detail: 'Unknown error' })) const text = await response.text()
const d = err.detail let parsed = null
try {
parsed = text ? JSON.parse(text) : null
} catch {
parsed = null
}
const d = parsed?.detail
if ( if (
response.status === 409 && response.status === 409 &&
d && d &&
@@ -489,6 +495,14 @@ export async function uploadExerciseMedia(exerciseId, formData) {
e.payload = d e.payload = d
throw e throw e
} }
if (response.status === 413) {
const nginx = (text || '').toLowerCase().includes('nginx')
throw new Error(
nginx
? 'Die Anfrage ist zu groß (413). Häufig: nginx „client_max_body_size“ — z. B. große/r mehrere Videos oder Bulk-Upload. Dateien kleiner aufteilen oder Server-Limit erhöhen (Frontend-Image Neu bauen).'
: 'Die Anfrage ist zu groß (413). Dateigröße oder Server-Limit prüfen.',
)
}
const msg = const msg =
typeof d === 'string' typeof d === 'string'
? d ? d
@@ -496,7 +510,9 @@ export async function uploadExerciseMedia(exerciseId, formData) {
? d.message ? d.message
: d != null : d != null
? JSON.stringify(d) ? JSON.stringify(d)
: `HTTP ${response.status}` : text && text.length < 400 && !/^\s*</.test(text)
? `HTTP ${response.status}: ${text.trim()}`
: `HTTP ${response.status}`
throw new Error(msg) throw new Error(msg)
} }
return response.json() return response.json()
+66
View File
@@ -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
}
}
@@ -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
}
+17
View File
@@ -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
}