Compare commits
158
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a1b85cd865 | ||
|
|
7245bbb1da | ||
|
|
5f67c01cef | ||
|
|
4720d70af0 | ||
|
|
13a1d3a060 | ||
|
|
7f62b6ceee | ||
|
|
9b3f594007 | ||
|
|
5d308b20ba | ||
|
|
1d698e4b0a | ||
|
|
57c464c9f6 | ||
|
|
a7a428745f | ||
|
|
2d187447bb | ||
|
|
2de4c0b7c9 | ||
|
|
34966b9e84 | ||
|
|
9a0cf7f823 | ||
|
|
78c6c51520 | ||
|
|
5200895a73 | ||
|
|
8f8bdf6d8b | ||
|
|
f67bf280c3 | ||
|
|
732b322c52 | ||
|
|
d42eb3ac52 | ||
|
|
e382b6ed35 | ||
|
|
a4548f5587 | ||
|
|
9d122d4808 | ||
|
|
9c3494a7ea | ||
|
|
9353909fda | ||
|
|
5a8a212f40 | ||
|
|
f9df2d31db | ||
|
|
ab612a5335 | ||
|
|
b2f77ca627 | ||
|
|
39b1fd04f0 | ||
|
|
9020e5eb16 | ||
|
|
46feb4c867 | ||
|
|
3067b2e6a8 | ||
|
|
1e2fdeeb0f | ||
|
|
728b37ad5f | ||
|
|
8afdd811db | ||
|
|
4588ef4c7e | ||
|
|
6e6270b717 | ||
|
|
14b005e9b8 | ||
|
|
ef4dd93324 | ||
|
|
7450c269a5 | ||
|
|
e50c18f92e | ||
|
|
d19a1061d8 | ||
|
|
99a5fccaa5 | ||
|
|
cb868373f4 | ||
|
|
472cf1afdb | ||
|
|
0cb0e81d27 | ||
|
|
6a9351874f | ||
|
|
734d943d73 | ||
|
|
16eaf839e7 | ||
|
|
295c7e7efc | ||
|
|
c9175bd2fd | ||
|
|
f15aa7c415 | ||
|
|
1684892bcb | ||
|
|
4fee5a2b47 | ||
|
|
82705f0c3e | ||
|
|
a51f794945 | ||
|
|
7693139242 | ||
|
|
55d87d8d17 | ||
|
|
623af621b4 | ||
|
|
949a77fe38 | ||
|
|
0275f76432 | ||
|
|
bc1790bd82 | ||
|
|
b35a5ae216 | ||
|
|
8c07cf36ee | ||
|
|
7d2661a8e8 | ||
|
|
0fdee610ed | ||
|
|
f1c470a8a3 | ||
|
|
736656bde8 | ||
|
|
e441f59bff | ||
|
|
c3eb5a62c4 | ||
|
|
79e748b470 | ||
|
|
88c4201f80 | ||
|
|
6e1cc62065 | ||
|
|
76cc81a385 | ||
|
|
bd9cfaa6e4 | ||
|
|
a4f11a8225 | ||
|
|
5e5350d5ac | ||
|
|
73ac2218c7 | ||
|
|
352237bbb9 | ||
|
|
4cf7133bce | ||
|
|
c182ced7cd | ||
|
|
5338871f36 | ||
|
|
3005f1cb3e | ||
|
|
72e8f31cff | ||
|
|
73975d3402 | ||
|
|
4902771772 | ||
|
|
c2efbee4ee | ||
|
|
514b64682c | ||
|
|
a0a0be8bef | ||
|
|
613fedfaff | ||
|
|
2e761161ef | ||
|
|
0a203aaf75 | ||
|
|
f50e9db523 | ||
|
|
749c185e3d | ||
|
|
214f90d39b | ||
|
|
0d34c0a73d | ||
|
|
ae51d201bc | ||
|
|
220a16429c | ||
|
|
e759076a6c | ||
|
|
8175e239b4 | ||
|
|
8f5af49a6f | ||
|
|
e7dc6a6cd3 | ||
|
|
e09a2284e9 | ||
|
|
b0faa4bfab | ||
|
|
a1a3f2e0a1 | ||
|
|
45bc049c0d | ||
|
|
e4e362b0a9 | ||
|
|
300d916fad | ||
|
|
1631bd2e02 | ||
|
|
639392e133 | ||
|
|
2e105a99b8 | ||
|
|
4235246cd7 | ||
|
|
57a8957c93 | ||
|
|
d153a22545 | ||
|
|
930a786315 | ||
|
|
9da29a2231 | ||
|
|
b06d026dd0 | ||
|
|
32ba008660 | ||
|
|
657fcc241a | ||
|
|
c69edc6952 | ||
|
|
789b640ad0 | ||
|
|
14cf8a1a53 | ||
|
|
ea4c1f87f6 | ||
|
|
2fa1db55fd | ||
|
|
75ddd06d6a | ||
|
|
597486bef1 | ||
|
|
ebad8025f4 | ||
|
|
c7650cac2f | ||
|
|
4b2848c7c3 | ||
|
|
255fa45e90 | ||
|
|
7043addd15 | ||
|
|
81d1e9bdfd | ||
|
|
3214055531 | ||
|
|
4c974620d8 | ||
|
|
3134160003 | ||
|
|
b19940c997 | ||
|
|
dbc9057601 | ||
|
|
6136813f60 | ||
|
|
d82b805ffa | ||
|
|
c8c40474d1 | ||
|
|
f035b5bb0b | ||
|
|
696cb09bf4 | ||
|
|
33fedd5ec6 | ||
|
|
c8a08f8a94 | ||
|
|
d04ebee1f6 | ||
|
|
0c1fbab0ef | ||
|
|
a7d68c0646 | ||
|
|
a34dc19f5d | ||
|
|
9227b98431 | ||
|
|
390b0ecb73 | ||
|
|
7e7adfab54 | ||
|
|
bce235b9f6 | ||
|
|
5334836207 | ||
|
|
38d78abc3b | ||
|
|
a143532486 | ||
|
|
2f54fef88e |
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo - Projekt-Status
|
||||
|
||||
**Stand:** 2026-05-12
|
||||
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||
**Stand:** 2026-05-14
|
||||
**Version (Code):** 0.8.140 (`backend/version.py`, APP_VERSION)
|
||||
**DB-Schema-Version:** `20260515063` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||
**Branch:** develop
|
||||
|
||||
---
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
||||
|
||||
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||
|
||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
||||
|
||||
@@ -36,7 +36,8 @@
|
||||
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
||||
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
|
||||
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
|
||||
4. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
|
||||
4. **Breakout / Coaching (Arbeitspaket):** Backend-Konsistenz `phases`↔`sections`, Run-UI vs. Spec (Stream-Tabs), Vorlagen phasenfähig, E2E-Smoke — siehe **`docs/HANDOVER.md`** (Tabelle „Coaching & Breakout“).
|
||||
5. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -92,6 +93,8 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
|
||||
- [x] **Trainingsrahmenprogramm Bibliothek** (Ziele, Slots, Kontext) + **Slot‑Blueprints** in `training_units` (036–037)
|
||||
- [x] **Materialisierung** aus Rahmen‑Slot (`POST …/training-units/from-framework-slot`; UI‑Anbindung optional)
|
||||
- [x] **Phasenmodell & parallele Streams** pro Einheit (Migration **063**): `training_unit_phases`, `training_unit_parallel_streams`; GET mit **`phases`** + flachen **`sections`**; PUT mit **`phases`** (App **0.8.137–0.8.140**)
|
||||
- [x] **Coaching-Modus** für Breakout: Timeline mit Split-Wahl, Rejoin vor Ganzgruppe/nächstem Split, Nachbereitung speichern → Plan & Ablauf (`TrainingCoachPage`, `trainingPlanUtils.js`)
|
||||
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
|
||||
|
||||
**MediaWiki Import:**
|
||||
@@ -101,6 +104,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
**Skills-System:**
|
||||
|
||||
- [x] Hierarchisches Schema, Fokusbereich-Zuordnung, Exercise-Skill mit Levels
|
||||
- [x] **Gewichtetes Fähigkeiten-Profil (Phase 3):** Module, Rahmenprogramme, Regressionspfade; Peer-Kontext getrennt; Listen-Filter + Discovery — **`technical/SKILL_SCORING_SPEC.md`**
|
||||
|
||||
**Admin-UI:**
|
||||
|
||||
@@ -155,18 +159,19 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
| Dokument | Pfad | Stand | Status |
|
||||
|----------|------|-------|--------|
|
||||
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-12 | neu, Ist-Überblick |
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-12 | Verweis Version siehe `version.py` |
|
||||
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-14 | Phasen/Coach/Rejoin |
|
||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-14 | §11a Breakout |
|
||||
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
|
||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
|
||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-14 | Parallele Streams Ist 063 |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
||||
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
|
||||
| Parallele Streams (Fach/Technik) | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | 2026-05-14 | Ist-Stand P1 teils |
|
||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-14 | Keyset, KPIs, Breakout/Coach Kurzverweis |
|
||||
|
||||
---
|
||||
|
||||
@@ -177,4 +182,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-12 (Version 0.8.96, Executive Summary P-13/P-01, `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
**Letzte Aktualisierung:** 2026-05-14 (Version 0.8.140, DB 063, Handover Coaching/Breakout)
|
||||
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo - Fachliches Domänenmodell
|
||||
|
||||
**Version:** 0.4.5
|
||||
**Stand:** 2026-05-12 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
**Version:** 0.4.6
|
||||
**Stand:** 2026-05-14 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
||||
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
|
||||
|
||||
---
|
||||
@@ -407,10 +407,9 @@ skill_level_definitions (
|
||||
- Reaktion (Koordination, target_level: 2, intensity: mittel)
|
||||
|
||||
**Attribute pro Fähigkeitsbezug:**
|
||||
- is_primary (Haupt- oder Nebenfähigkeit)
|
||||
- intensity (niedrig/mittel/hoch)
|
||||
- required_level (Voraussetzung, 1-5)
|
||||
- target_level (Ziel-Level, 1-5)
|
||||
- `intensity` — Nutzeneinschätzung: **niedrig | mittel | hoch** (Standard **mittel**)
|
||||
- `required_level` / `target_level` — Stufen-Spanne (kanonische Slugs basis … optimierung)
|
||||
- `is_primary` — Legacy-Feld; **nicht mehr in der UI**, beim Speichern immer false; Scoring ignoriert es
|
||||
|
||||
**🆕 Fokusbereich-Filterung:**
|
||||
- Bei Übungen mit Fokusbereich "Karate" sollten primär KARATE-Fähigkeiten zugeordnet werden
|
||||
@@ -474,7 +473,43 @@ skill_level_definitions (
|
||||
|
||||
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
|
||||
|
||||
---
|
||||
### Trainingsmodul (Bibliothek)
|
||||
|
||||
**Abgrenzung:** Wiederverwendbare **Übungsfolge** (`training_modules` + `training_module_items`) — kein Kalendertermin, kein Rahmen-Slot. Übernahme in geplante Einheiten über Planung (`apply-training-module`).
|
||||
|
||||
**Governance:** wie andere Bibliotheksartefakte (`visibility`, `club_id`, `library_content_visibility_sql`).
|
||||
|
||||
### Gewichtetes Fähigkeiten-Profil (Planungs-Bausteine, Phase 3)
|
||||
|
||||
**Zweck:** Aus den verknüpften Übungen eines Planungsartefakts wird ein **Fähigkeiten-Profil** berechnet (Trainingsgewicht je Fähigkeit). Trainer vergleichen Bausteine **innerhalb desselben Typs**, um z. B. das passendste Modul für eine Ziel-Fähigkeit zu finden.
|
||||
|
||||
**Artefakttypen (getrennte Peer-Kontexte):**
|
||||
|
||||
| Typ | Vergleich |
|
||||
|-----|-----------|
|
||||
| `training_module` | nur sichtbare **Module** |
|
||||
| `framework_program` | nur sichtbare **Rahmenprogramme** |
|
||||
| `progression_graph` | nur sichtbare **Regressionspfade** |
|
||||
|
||||
**Metriken (Nutzer):**
|
||||
|
||||
- **Score / Gewicht** — absolut (Dauer × Häufigkeit × Intensität × Stufen-Spanne)
|
||||
- **Prozent** — Anteil am stärksten sichtbaren Peer **desselben Typs** für diese Fähigkeit (max. 100 %)
|
||||
- **★** — stärkster Peer in diesem Kontext
|
||||
|
||||
**UI:** Profile in Editoren; KPI-Kacheln und Filter in Listen (`/planning/framework-programs`, `/planning/training-modules`); Discovery auf der Fähigkeiten-Seite.
|
||||
|
||||
**Technik:** `backend/skill_scoring.py`, `routers/skill_profiles.py` — Spec **`technical/SKILL_SCORING_SPEC.md`**.
|
||||
|
||||
### Parallele Trainingsstreams (Breakout)
|
||||
|
||||
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
|
||||
|
||||
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
|
||||
|
||||
**Umsetzung (2026-05, Migration 063, App 0.8.137 ff.):** Tabellen **`training_unit_phases`** und **`training_unit_parallel_streams`**; **`training_unit_sections`** mit **`phase_id`** und **`parallel_stream_id`** (exakt eine Zuordnung pro Sektion). **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und flache **`sections`**. **Coaching** und **Durchführung** nutzen dieselbe Phasenlogik im Frontend (`trainingPlanUtils.js`).
|
||||
|
||||
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||
|
||||
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||
|
||||
@@ -482,7 +517,7 @@ skill_level_definitions (
|
||||
- **`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.
|
||||
- **Inline-Verweise** in Fließtextfeldern: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
|
||||
|
||||
---
|
||||
|
||||
@@ -640,12 +675,13 @@ skill_level_definitions (
|
||||
- [ ] Level-Definitionen aus Fähigkeitsmatrix extrahieren (optional)
|
||||
- [ ] Skills-Beschreibungen aus Wiki importieren (Migration 024)
|
||||
- [ ] Admin-UI für Fähigkeiten-Kategorien (CRUD)
|
||||
- [ ] Skill-Filter in Übungssuche integrieren
|
||||
- [x] Skill-Filter in Übungssuche (SkillTreeMultiSelect + Stufen)
|
||||
- [x] Gewichtetes Fähigkeiten-Profil für Planungs-Bausteine (Module, Rahmen, Pfade) — siehe `technical/SKILL_SCORING_SPEC.md`
|
||||
- [ ] Reifegradmodelle definieren (Kombination Fokusbereich + Stil + Zielgruppe)
|
||||
- [ ] KI-Unterstützung für Trainingsplanung (basierend auf Fähigkeiten-Level)
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-04-27
|
||||
**Letzte Aktualisierung:** 2026-05-20
|
||||
**Verantwortlich:** Claude Code
|
||||
**Review:** Pending
|
||||
@@ -0,0 +1,114 @@
|
||||
# Parallele Trainingsstreams (Breakout) — Fachkonzept
|
||||
|
||||
**Status:** MVP-Umsetzung **teilweise** (Code) · **Stand:** 2026-05-14
|
||||
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
|
||||
|
||||
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
**Domänenbegriffe (Überblick):** `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||
|
||||
---
|
||||
|
||||
## 1. Ausgangslage und Problem
|
||||
|
||||
In Kinder- und Breitensport-Training ist ein typischer Ablauf:
|
||||
|
||||
1. **Gemeinsam:** Aufwärmen, Koordination, Ansagen.
|
||||
2. **Getrennt:** Kinder in mehrere Gruppen teilen; **Co-Trainer** leiten jeweils eigene Inhalte **gleichzeitig**.
|
||||
3. **Gemeinsam:** Abschluss, gemeinsame Übungen, Verabschiedung.
|
||||
|
||||
Die aktuelle Shinkan-Planung modelliert pro Termin **eine lineare Folge von Abschnitten und Übungen** pro Einheit. Das genügt nicht, wenn **mehrere gleichzeitige „Unter-Sessions“** mit unterschiedlichen Plänen dokumentiert und auf der Matte geführt werden sollen.
|
||||
|
||||
---
|
||||
|
||||
## 2. Ziele (fachlich)
|
||||
|
||||
| ID | Ziel |
|
||||
|----|------|
|
||||
| PT‑01 | Eine **Kalender-Einheit** bleibt **ein** Termin (eine Halle, eine Gruppe, ein Datum) — kein Splitten in künstlich mehrere Kalendereinträge nur für Parallelität. |
|
||||
| PT‑02 | **Unbegrenzte** Anzahl paralleler **Streams** (Teilstrecken) in einer oder mehreren **Parallelphasen**. |
|
||||
| PT‑03 | **Phasenmodell:** klar erkennbar **Gemeinsam** vs. **Parallel** vs. wieder **Gemeinsam** (auch mehrfach hintereinander möglich). |
|
||||
| PT‑04 | **Rollen:** Leitung (Haupttrainer) und Co-Trainer; Zuordnung der Co-Trainer **soll** an konkrete Streams anschließbar sein (heute: nur flache Liste pro Einheit — siehe technische Spec). |
|
||||
| PT‑05 | **Sonderfall Stationen:** rotierender Ablauf (z. B. Wechsel alle 20 Min.) **inhaltlich** unterscheiden zwischen (a) Rotation **innerhalb** einer Teilstrecke und (b) **synchron** getakteter Hallen-Rotation — siehe §5. |
|
||||
| PT‑06 | **Durchführung:** Trainer können „ihre“ Spur auf dem Gerät abarbeiten; Fortschritt pro Spur nachvollziehbar. |
|
||||
|
||||
**Nicht-Ziel (frühe Stufen):** Echtzeit-Synchronisation mehrerer Geräte; individuelles Athleten-Tracking; automatische Raumbelegung.
|
||||
|
||||
---
|
||||
|
||||
## 3. Begriffe
|
||||
|
||||
| Begriff | Definition |
|
||||
|---------|------------|
|
||||
| **Einheit / Termin** | Geplante `training_unit` für Gruppe und Datum — übergeordneter Rahmen des Abends. |
|
||||
| **Phase** | Organisatorischer Block innerhalb der Einheit: entweder **ganze Gruppe** oder **parallel**. |
|
||||
| **Stream / Teilstrecke** | Innerhalb einer Parallelphase: eine von N **gleichzeitig** stattfindenden Unter-Abläufen mit **eigenem** Miniplan (Abschnitte, Übungen, Notizen — analog heutiger Planung). |
|
||||
| **Synchronisationspunkt** | Fachlich: alle treffen sich wieder (Beginn einer **Gemeinschaftsphase** nach Parallelität). |
|
||||
| **Station (Rotation)** | Inhaltlicher Fokus oder Platz, den Teilnehmer **wechselnd** anlaufen; kann als Kombinations-/Zirkellogik oder als koordinierter Hallenrhythmus modelliert werden (§5). |
|
||||
|
||||
**Abgrenzung „Rahmenprogramm-Slot“:** Ein Slot im **Rahmenprogramm** ist eine **Session in einer Serie** (z. B. Woche 1 vs. Woche 2), **nicht** „Teilgruppe A gleichzeitig mit Teilgruppe B in derselben Stunde“. Parallele Streams sind **innerhalb einer Einheit**, orthogonal zum Rahmen-Slot.
|
||||
|
||||
**Abgrenzung **Kombinationsübung**:** Eine Kombi-Übung bündelt **mehrere Einzelübungen** mit Methodenprofil (Archetyp, ggf. Rotation) **in einem Plan-Item**. Sie ersetzt **nicht** mehrere Trainer mit **jeweils eigenem Gesamtablauf**, kann aber **pro Stream** für Stationslogik genutzt werden.
|
||||
|
||||
---
|
||||
|
||||
## 4. Szenarien
|
||||
|
||||
### 4.1 Klassischer Breakout
|
||||
|
||||
30 Min. gemeinsam → 25 Min. drei parallele Streams (Gruppe an Matte / an Schlagsack / Fußarbeit) → 15 Min. gemeinsam.
|
||||
|
||||
### 4.2 Viele Kinder, mehrere Co-Trainer
|
||||
|
||||
Haupttrainer plant die Gesamtstruktur; jeder Co-Trainer sieht in der Durchführung primär die zugewiesene Teilstrecke.
|
||||
|
||||
### 4.3 Rollierendes Stationssystem
|
||||
|
||||
Alle Gruppen arbeiten an **verschiedenen Schwerpunkten** und **wechseln** nach festem Intervall die Station — entweder **nur innerhalb einer Spur** oder **hallenweit synchron** (offene fachliche Präzisierung in MVP vs. später, §5).
|
||||
|
||||
---
|
||||
|
||||
## 5. Sonderfall: Stationen und Kombinationsübungen
|
||||
|
||||
### 5.1 Variante A — Rotation innerhalb einer Teilstrecke
|
||||
|
||||
Eine Teilgruppe rotiert durch mehrere Übungen (Zeit oder Runden). Das liegt nah an einer **Kombinationsübung** mit Archetyp z. B. „Zirkel / zeitgesteuerte Rotation“ und Parametern (Wechselintervall). **Empfehlung:** Diese Variante über **bestehendes** Kombinationsübungs-Konzept in der jeweiligen **Stream-Planung** abbilden (`planning_method_profile`).
|
||||
|
||||
### 5.2 Variante B — Synchron getaktete Hallen-Rotation
|
||||
|
||||
Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächsten Station; Startstation kann pro Teilgruppe **versetzt** sein. Das ist **organisatorisch** schwerer: es braucht entweder **Phasen-Metadaten** (globaler Takt) oder eine explizite **Rot/Matrix**. **Empfehlung:** In einer **zweiten Ausbaustufe** abbilden; MVP kann bei Variante A starten, sofern fachlich ausreichend.
|
||||
|
||||
---
|
||||
|
||||
## 6. Rollen und Verantwortlichkeiten
|
||||
|
||||
- **Leitungstrainer:** Hält den Faden, startet Gemeinschaftsphasen, koordiniert Parallelbeginn/-ende (fachlich; ggf. später UI-Hinweise).
|
||||
- **Co-Trainer:** Verantwortlich für **zugeteilte** Streams; Zuordnung soll **pro Stream** möglich werden (Erweiterung gegenüber reiner Einheits-Co-Trainer-Liste).
|
||||
|
||||
---
|
||||
|
||||
## 7. Offene fachliche Entscheidungen
|
||||
|
||||
1. **MVP Umfang:** Reicht **freie Parallelität** ohne **synchronen** Hallenwechsel (Variante B)?
|
||||
2. **Dauer:** Sollen Phasen oder Streams **Soll-Minuten** tragen (nur Anzeige vs. später Timer)?
|
||||
3. **Vorlagen:** Müssen `training_plan_templates` parallel-fähig werden **vor** oder **mit** der ersten Implementierung?
|
||||
4. **Sichtbarkeit:** Dürfen alle Co-Trainer alle Streams sehen, oder „nur meine Spur“?
|
||||
|
||||
---
|
||||
|
||||
## 9. Umsetzungsstand (kurz, 2026-05-14)
|
||||
|
||||
- **Erreicht:** Datenmodell Phasen/Streams (**063**), API **GET/PUT** mit **`phases`**, Planungs-Breakout-UI, Durchführung und Coach nutzen dieselbe Phasen-/Stream-Logik im Frontend (`trainingPlanUtils.js`). **Synchronisationspunkt** fachlich umgesetzt: vor nächster Ganzgruppenphase oder nächstem Split erscheint im Coach die **Rejoin-Karte** (mehrere Streams), sofern nicht am absoluten Planende.
|
||||
- **Noch offen:** vollständige **Persistenz-Konsistenz** bei nachträglich geänderten Sektionen, **Vorlagen** mit Phasen, **Trainer pro Stream** in der UI, ggf. **Stream-Tabs** in der Durchführungsansicht wie in §5.2 skizziert — siehe **`docs/HANDOVER.md`** (Arbeitspaket-Tabelle).
|
||||
|
||||
---
|
||||
|
||||
## 10. Verwandte Dokumente
|
||||
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slots = Serien-Sessions, **nicht** Intra-Einheit-Parallelität |
|
||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
|
||||
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
|
||||
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
|
||||
| `docs/HANDOVER.md` | Ist-Stand Coach, offene Breakout-Punkte |
|
||||
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gelieferte Features & technische Basis (Q2 2026)
|
||||
|
||||
**Stand:** 2026-05-12
|
||||
**Stand:** 2026-05-20
|
||||
**Referenz:** `backend/version.py` — aktuelle **APP_VERSION** / **DB_SCHEMA_VERSION** (Stand Code u. a. **0.8.96**)
|
||||
|
||||
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
|
||||
@@ -123,7 +123,16 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
||||
|
||||
---
|
||||
|
||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
||||
## 12. Trainingsplan: Phasen & parallele Streams (DB **063**, App **0.8.137–0.8.140**)
|
||||
|
||||
- **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` / `parallel_stream_id`; Default-Ganzgruppenphase für Bestand.
|
||||
- **API:** `GET /api/training-units/:id` mit **`phases`** + **`sections`**; `PUT`/`POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); Rahmen-Slot-Materialisierung kopiert Phasen (**0.8.138**).
|
||||
- **Frontend:** Planung Breakout-Panel (**0.8.139–0.8.140**); **`trainingPlanUtils.js`** — `sectionsWithPlanLocForDisplay`, `flattenPlanTimeline`, `buildCoachSavePlanPayload`, Split-Rejoin (`coachShouldPromptSplitRejoinTransition`); **`TrainingCoachPage`**, **`TrainingUnitRunPage`**.
|
||||
- **Doku:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`, `docs/HANDOVER.md` §3, Arbeitspaket „offen“.
|
||||
|
||||
---
|
||||
|
||||
## 13. 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:
|
||||
|
||||
@@ -150,7 +159,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
||||
|
||||
---
|
||||
|
||||
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
## 14. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||
|
||||
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||
@@ -160,15 +169,41 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
||||
|
||||
---
|
||||
|
||||
## 14. Verweise
|
||||
## 15. Gewichtetes Fähigkeiten-Scoring (Phase 3, Stand 2026-05-20)
|
||||
|
||||
Norm: **`technical/SKILL_SCORING_SPEC.md`**.
|
||||
|
||||
### 15.1 Backend
|
||||
|
||||
- **`skill_scoring.py`:** Gewichtung (Dauer × Vorkommen × Intensität × Stufen); `compute_planning_corpus_by_type()` mit getrennten Corpora; `universal_percent` capped auf 100 %
|
||||
- **`routers/skill_profiles.py`:** Profile-GET pro Artefakt; `POST /api/skill-profiles/batch-summaries`; `GET /api/skill-discovery/suggestions`
|
||||
- Sichtbarkeit: **`library_content_visibility_sql`** (Planungs-Bibliothek, nicht „nur Verein club“)
|
||||
|
||||
### 15.2 Frontend
|
||||
|
||||
- **Listen:** Rahmenprogramme + Trainingsmodule — Filter-Modal (wie Übungen), Chips, `SkillTreeMultiSelect` (Portal-Dropdown)
|
||||
- **KPI:** `SkillProfileCompact` — Top je Unterkategorie, Score + Peer-%
|
||||
- **Editoren + Modal:** `SkillProfilePanel`, `SkillProfileFullModal`
|
||||
- **Discovery:** `SkillDiscoveryPanel` auf Fähigkeiten-Seite
|
||||
|
||||
### 15.3 Offen
|
||||
|
||||
- Corpus-Caching; pytest für Typ-Trennung; Filter-Persistenz; Skill-Filter Import-Dialog „Rahmen übernehmen“
|
||||
|
||||
---
|
||||
|
||||
## 16. Verweise
|
||||
|
||||
| Thema | Dokument |
|
||||
|--------|----------|
|
||||
| Rahmenprogramm / Progressionsgraph | `technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| Fähigkeiten-Scoring Planung | `technical/SKILL_SCORING_SPEC.md` |
|
||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
|
||||
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
|
||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
| Parallele Phasen/Streams | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` |
|
||||
| Coaching/Breakout-Handover | `docs/HANDOVER.md` |
|
||||
| Fachlicher Nutzerüberblick | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` (Repo-Root) |
|
||||
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
||||
@@ -0,0 +1,178 @@
|
||||
# KI-gestützte Trainingsplanung – Zentrales Konzept
|
||||
|
||||
**Version:** 0.1
|
||||
**Datum:** 2026-05-16
|
||||
**Status:** Arbeitsdokument (Verfeinerung durch fachliche Konzept-Agentur vorgesehen)
|
||||
**Ziel:** Einheitlicher Rahmen für **stufenweise** KI-Unterstützung bei der Planung (Abschnitte, Einheiten, später mehrtägig/Rahmen) – ohne vollständigen Katalog im Prompt zu spiegeln.
|
||||
|
||||
**Verwandte Dokumente:**
|
||||
`functional/DOMAIN_MODEL.md` · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (u. a. CURR-003 zu Progressions-/KI-Automatik) · `technical/TRAINING_FRAMEWORK_SPEC.md` · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `docs/FACHLICHE_NUTZERFUNKTIONEN.md` · `docs/HANDOVER.md`
|
||||
|
||||
---
|
||||
|
||||
## 1. Produktliche Leitlinien
|
||||
|
||||
- **Nutzer:** Trainer/Vereinskontext, **Gruppenplanung** – keine Pflicht zur individuellen Sportler-Verfolgung; Kontext soll primär aus **Gruppe**, **bereits geplanten/durchgeführten Einheiten**, **Rahmen-/Zielen** und **berechtigtem Übungskorpus** bestehen.
|
||||
- **Human-in-the-loop:** KI liefert **Vorschläge** (Liste, Reihenfolge, Begründung); schreibende Übernahme in Pläne nur nach **Trainer-Bestätigung** oder expliziter Aktion (analog „Manual First“ in `KI_FEATURES_SPEC.md`).
|
||||
- **Governance-first:** Nur Übungen, die die API bereits für den Mandanten/Kontext **sichtbar** freigibt, dürfen in Kandidatenlisten landen – **vor** Retrieval und **vor** jedem Prompt.
|
||||
|
||||
---
|
||||
|
||||
## 2. Kernproblem: Skalierung des Kontextes
|
||||
|
||||
Aus einer **großen Übungssammlung** („>1000 Übungen“) können weder alle **Felder** (Ziele, Ablauf, Skills, Varianten …) noch alle **Zeilen** sinnvoll in einen LLM-Prompt.
|
||||
|
||||
**Festlegung:** Der LLM-Prompt erhält immer nur ein **begrenztes Kontext-Paket** mit:
|
||||
|
||||
| Paketteil | Zweck |
|
||||
|-----------|--------|
|
||||
| **Auftrag** | z. B. Sektionstyp, Dauerbudget, Schwierigkeit, erlaubte Phasen/Streams |
|
||||
| **Hard Constraints** | Gruppe, Termin/Zeitraum, Governance-Filter bereits angewendet |
|
||||
| **Komprimierte Historie** | Letzte *N* Einheiten als **Liste von Übungs-IDs + Kurzlabels** (+ optional Haupt-Skills), keine vollen Fließtexte |
|
||||
| **Ziele / Rahmen** | Kurztexte aus Rahmen-Slot/Zielblöcken oder Trainer-Prompt |
|
||||
| **Kandidaten-Top‑K** | z. B. 30–120 Übungen, **je Zeile gekürzt** (Titel, `summary`, 2–5 Skill-Namen/Stufen); **nie** der gesamte Katalog |
|
||||
| **Strukturierte Kanten optional** | Kleine Mengen Kanten aus Progressionsgraph: „Nachbarn von zuletzt genutzten Übungen“ |
|
||||
|
||||
**Zahlen‑Richtwerte (überarbeitungsfähig):**
|
||||
Kandidaten **vor** dem LLM typischerweise **50–150** Einträge; im Prompt durch Token-Limit weiter **truncate** oder **zweistufig** (grober Ranking-Schritt ohne LLM, dann finer mit LLM auf Top‑40).
|
||||
|
||||
---
|
||||
|
||||
## 3. Pipeline: „Selektion vor dem Prompt“
|
||||
|
||||
Die **„optimale“** Auswahl entsteht **nicht**, indem das Modell den Katalog „im Kopf“ hält, sondern über eine **mehrstufige Pipeline**:
|
||||
|
||||
### Stufe 1 – Harte Filter (deterministisch, DB)
|
||||
|
||||
Synchron zur bestehenden Suche/List-API-Logik, z. B.:
|
||||
|
||||
- Sichtbarkeit / Verein / `official`‑Regeln
|
||||
- Aktivitäts-/Archiv-Status der Übung
|
||||
- Fokusbereich, Stil, Zielgruppe (wenn Trainings-/Gruppenkontext das vorgibt)
|
||||
- Ausschluss bereits in **dieser Einheit** fester Übernutzung (optional)
|
||||
|
||||
Ergebnis: Menge \(M\) – kann noch sehr groß sein.
|
||||
|
||||
### Stufe 2 – Kontext-Verankerung (deterministisch + Graph)
|
||||
|
||||
- **Historie:** aus letzten *N* Gruppeneinheiten extrahierte `exercise_id`s (optional Variant).
|
||||
- **Progressionsgraph:** ausgehend davon Nachbarn (eingehend/ausgehend begrenzte Tiefe) – bereits im Produkt als **unterstützend** modelliert (**CURR‑013**).
|
||||
- **Rahmen/Slot-Ziele:** Überlapp mit Skill-Tags oder Stichwortliste (falls formalisiert).
|
||||
- **Variantenketten:** `prerequisite_variant_id` / `progression_level` nur innerhalb bereits gewählter Übung prüfen oder als Hint an den LLM-Block durchreichen.
|
||||
|
||||
Ergebnis: **„Anker‑Menge“** + **„Graph‑Nachbarschaft“** → priorisierte Kandidaten.
|
||||
|
||||
### Stufe 3 – Weiches Ranking / Retrieval (halb-strukturiert)
|
||||
|
||||
Mindestens **eine** der folgenden Optionen – kombinierbar:
|
||||
|
||||
1. **Skill-/Facet-Overlap:** Punktezahl, wenn Übungs-Skills mit Ziel-/Matrix-Schwerpunkten übereinstimmen (bereits Daten in `exercise_skills`).
|
||||
2. **Diversitäts-/Wiederholungsstrafe:** häufig in letzten Wochen geübte Übungen abwerten.
|
||||
3. **Textsuche:** PostgreSQL **`tsvector`/Volltext** auf `title`, `summary`, ggf. gekürzte `goal` – für Trainer-Stichwort „Koordination Sprung“.
|
||||
4. **Semantische Suche:** Embeddings + **Ähnlichkeitsuche** auf Kurztexte (siehe §5).
|
||||
|
||||
Ergebnis: sortierte Liste, **Top‑K** für den Prompt.
|
||||
|
||||
### Stufe 4 – LLM (optional zweistufig)
|
||||
|
||||
- **Optional 1:** LLM nur **sortiert/rankted** bereits vorgegebene IDs (Ranking mit kurzer Begründung).
|
||||
- **Optional 2:** Zwei Calls: erst „welche drei Schwerpunkte“ / „Welche Constraints habe ich übersehen?“, zweiter Call nur mit gekürztem Top‑K – nur wenn UX den Mehraufwand rechtfertigt.
|
||||
|
||||
**Ausgabe-Contract:** Zurückkommen dürfen **nur gültige `exercise_id`s** aus der übergebenen Kandidatenliste (Server validiert gegen Set); **Halluzinationsrisiko damit entschärft**.
|
||||
|
||||
---
|
||||
|
||||
## 4. Antwort auf die konkrete Frage: „Alle Übungen in den Prompt?“
|
||||
|
||||
**Nein.** Workflow:
|
||||
|
||||
1. **DB + Regeln + Graph + Historie** reduzieren auf **einige Hundert bis wenige tausend** Rohzeilen höchstens **intern** – aber
|
||||
2. in den **LLM-Prompt** gehen nur **Top‑K kompakte Artefakte** (siehe §2).
|
||||
|
||||
Das LLM löst dann **Ranking, Reihenfolge, Timing-Hinweise, Trainer-sprachliche Kurzkommentare** – nicht die Frage „gibt es diese Übung überhaupt im System?“.
|
||||
|
||||
---
|
||||
|
||||
## 5. Vector DB (z. B. Qdrant) – wann nötig, wann nicht?
|
||||
|
||||
### 5.1 Ziel embeddings
|
||||
|
||||
Semantic Retrieval: „wie springt Coordinative Belastung ohne das Wort ‚Koordination‘ im Titel zu stehen.“ Das ist **über** reine Filtersuche und oft **über** stumpfe Volltextsuche erreichbar.
|
||||
|
||||
### 5.2 Option A – ohne separate Vector DB
|
||||
|
||||
- **PostgreSQL + `pgvector`** (Extension): Embeddings-Spalte an `exercises` (oder an „Search Document“-Zeilen), Indices, Abfrage zusammen mit SQL-Filtern in **einer Transaktions-DB**.
|
||||
- **Größenordnung** einige 10 k–100 k Zeilen für Übungen: für Shinkan **oft ausreichend**.
|
||||
- Vorteile: ein Betriebspfad, Mandanten-/Governance weiter in SQL lösen; Backup wie heute.
|
||||
|
||||
### 5.3 Option B – Qdrant (oder anderer Dediz-Vektorstore)
|
||||
|
||||
Sinnvoller zeitlicher Punkt oder technische Auslöser:
|
||||
|
||||
- sehr hohe Latenz-Anforderung mit **Hybrid-Filter** über viele kombinierte Metadaten in nahezu Echtzeit,
|
||||
- Entkopplung: Embedding-Pipeline läuft asynchron und soll die **Operational DB** nicht beschweren,
|
||||
- später **mehrsprachig** oder **mehrere Embedding-Versionen**/Re-Index ohne großen Migrationstress,
|
||||
- Team bevorzugt **Dedicated** Vector-Ops gegenüber Postgres-Ops.
|
||||
|
||||
### 5.4 Empfehlung für diese Codebasis (überarbeitungsfähig)
|
||||
|
||||
1. **Phase 1:** Harte Filter + Graph + Historie + **PostgreSQL-Volltext** + Top‑K; LLM erst auf komprimierten Kandidaten → hoher Nutzen ohne neuen Infrastructure-Typen.
|
||||
2. **Phase 2:** Bei nachweisbaren „Recall-Lücken“ (Trainer findet nichts Passendes trotz großem Korpus) **`pgvector` in Postgres** evaluieren – **vor** zusätzlicher Infrastruktur wie Qdrant.
|
||||
3. **Phase 3:** Qdrant (o. ä.) wenn Größenordnung, Betrieb oder Produkt-Anforderungen **pgvector** sprengen oder klar eine **embedding-first** Produktstraße geplant wird.
|
||||
|
||||
**Fazit:** Eine dedizierte **Vector DB ist nicht zwingende Voraussetzung** für vernünftige Selektion; sie ist eine **Ausbaustufe**, wenn **semantische Lücke** und Skalierung es rechtfertigen. **Selektion** ist immer **„Filter + Ranking + kleines Top‑K“**, unabhängig vom Speicherort der Vektoren.
|
||||
|
||||
---
|
||||
|
||||
## 6. Datenpflege für gutes Retrieval (fachlicher Hebel)
|
||||
|
||||
Retrieval‑Qualität hängt stärker an **Metadaten** als an der Embedding-Technologie allein:
|
||||
|
||||
- verlässliche **Skills** (`exercise_skills`, ggf. KI-geholfen bereits laut Spez beim Übungs-Anlegen);
|
||||
- sinnvolle **`summary`**-Felder für Karten/Liste/KI-Pack;
|
||||
- **Progressionsgraph** dort, wo pädagogische Ketten gefestigt sind;
|
||||
- konsistente **Fokusbereich/Stil**-Zuordnung.
|
||||
|
||||
Das fachliche Konzept sollte entscheiden: **wie viel automatische Pflege vs. Trainer-Pflichtfelder**.
|
||||
|
||||
---
|
||||
|
||||
## 7. Produkt-/Release-Stufen (Anknüpfung)
|
||||
|
||||
| Stufe | Nutzen | Technik-Schwerpunkt |
|
||||
|-------|--------|---------------------|
|
||||
| A | Backend-KI-Service + Prompt-Slugs unter `technical/AI_PROMPT_SYSTEM_SPEC.md` | OpenRouter, Timeouts, 503 ohne Key |
|
||||
| B | „Übungen für Abschnitt vorschlagen“ | Pipeline §3 Stufen 1–3 + Prompt mit Top‑K |
|
||||
| C | Reihenfolge / Zeitslots innerhalb bestehender Sektion | Graph + LLM Ranking |
|
||||
| D | Ganze Einheit (inkl. Phasen/Streams vereinfacht) | strukturiertere JSON-Ausgabe, strikte Schema-Validation |
|
||||
| E | Mehreinheiten / Rahmen‑Alignment | Ziele aus Rahmenprogramm, Serie von Slots |
|
||||
|
||||
Die **Selektions‑Pipeline §3 bleibt** über alle Stufen konsistent und wird nur parametrierbar erweitert.
|
||||
|
||||
---
|
||||
|
||||
## 8. Compliance & Datenschutz (Kurzhinweis)
|
||||
|
||||
- Datenminimierung: **keine Teilnehmerliste** ohne expliziten Scope; Kontext über **Einheiten-Metadaten** und Übungen.
|
||||
- **OpenRouter**/Modellwahl: Organisation intern klären (AV/Verarbeitungsvertrag, Datenflüsse außerhalb EU – siehe Repo-Compliance-Dokumente).
|
||||
- **Logging:** Prompts keine unnötigen personenbezogenen Daten; wenn Debug: Retention definieren.
|
||||
|
||||
---
|
||||
|
||||
## 9. Offene Punkte für die fachliche Verfeinerung
|
||||
|
||||
- Gewichtung „**Wiederholung** vs. **Progression** vs. **Motivation**“ (domänenspezifisch).
|
||||
- Umgang mit **Kombinationsübungen** und **Coach-Stufen B/C** in der Datenübergabe.
|
||||
- Soll das System **„Lücken“** aus der **Matrix-Auflösung** aktiv quantifizieren oder nur Narrative verwenden?
|
||||
- Akzeptierte **Übersetzungen**: nur Deutsch oder mehrsprachige Embeddings erforderlich?
|
||||
|
||||
---
|
||||
|
||||
## 10. Glossar
|
||||
|
||||
| Begriff | Bedeutung |
|
||||
|---------|-----------|
|
||||
| **Top‑K** | Feste kleine Obergrenze Übungen pro LLM-Anfrage |
|
||||
| **Hard filter** | Deterministische SQL-/Policy-Einschränkung vor KI |
|
||||
| **Kontext-Paket** | Zusammengesetztes, tokenlimitiertes Eingabeobjekt für den Prompt |
|
||||
| **Retrieval** | algorithmischer Schritt ohne Generierung („wer kommt überhaupt in Frage“) |
|
||||
@@ -0,0 +1,144 @@
|
||||
# Navigation — Return-Kontext (Rücksprung)
|
||||
|
||||
**Stand:** 2026-05-20
|
||||
**Status:** Spezifikation + Phase 1–2 umgesetzt
|
||||
**Ziel:** In der PWA (ohne Browser-Back) zuverlässig an den fachlichen Ausgangspunkt zurückkehren — inkl. sinnvollem Label und optional UI-State.
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Viele Flows navigieren von Kontext A zu Editor/Detail B (z. B. Übungsliste → Modulbearbeitung). Die Zielseite kennt A nicht und bietet nur einen **fest verdrahteten** Zurück-Link (z. B. immer „Modul-Bibliothek“). In der installierten PWA fehlt zusätzlich die Browser-Chrome.
|
||||
|
||||
Betroffen u. a.:
|
||||
|
||||
- Übungsliste → Modul anlegen/bearbeiten
|
||||
- Planung → Einheiten-Editor (teilweise gelöst via `planningReturn`)
|
||||
- Modals mit Speichern + Redirect auf Vollseite
|
||||
|
||||
---
|
||||
|
||||
## Strategie (Hybrid)
|
||||
|
||||
| Mechanismus | Wann |
|
||||
|-------------|------|
|
||||
| **Expliziter Return-Kontext** (`appReturn` in Router-State) | Seitenwechsel, bei denen das Ziel einen fachlichen Rücksprung anbieten soll |
|
||||
| **History-Back** (`navigate(-1)`) | Fallback, wenn kein Kontext gesetzt ist und History-Eintrag existiert |
|
||||
| **Default-Pfad** | Fallback der Zielseite (z. B. Modul-Bibliothek) |
|
||||
| **Modal schließen** | Overlays/Peek — kein Routing-Return |
|
||||
|
||||
**Nicht** als alleinige Lösung: reines Browser-Back (History durch `replace`, Deep Links, Reload unzuverlässig).
|
||||
|
||||
---
|
||||
|
||||
## Datenmodell
|
||||
|
||||
Router-State-Schlüssel: **`appReturn`**
|
||||
|
||||
```javascript
|
||||
{
|
||||
v: 1, // Schema-Version
|
||||
path: '/exercises', // Ziel-URL (inkl. Query, falls nötig)
|
||||
label: 'Zurück zur Übungsliste', // Anzeige im UI (vollständiger Satz)
|
||||
kind: 'exerciseList', // optional: Typ für erweiterte Wiederherstellung
|
||||
payload: { ... } // optional: kind-spezifische Daten
|
||||
}
|
||||
```
|
||||
|
||||
### `kind`-Werte (erweiterbar)
|
||||
|
||||
| kind | payload | path-Ableitung |
|
||||
|------|---------|----------------|
|
||||
| `exerciseList` | — | `/exercises` (Filter/Auswahl via sessionStorage) |
|
||||
| `planningHub` | `buildPlanningHubReturnState(...)` | `planningHubPathFromReturnState(payload)` |
|
||||
| `trainingModulesList` | — | `/planning/training-modules` |
|
||||
| `planTemplatesList` | — | `/planning/plan-templates` |
|
||||
| `frameworkProgramsList` | — | `/planning/framework-programs` |
|
||||
| `settings` | — | `/settings` |
|
||||
| `dashboard` | — | `/` |
|
||||
| `mediaLibrary` | — | `/media` |
|
||||
| `trainingRun` | `{ unitId }` | `/planning/run/:unitId` |
|
||||
| `currentLocation` | — | aktuelle Route (z. B. Einheiten-Editor) |
|
||||
| (frei) | — | `path` direkt gesetzt |
|
||||
|
||||
### Legacy-Kompatibilität
|
||||
|
||||
Bestehendes Feld **`planningReturn`** (Planung ↔ Einheiten-Editor) wird beim Lesen in `appReturn` **bridged** — keine Big-Bang-Migration nötig.
|
||||
|
||||
---
|
||||
|
||||
## API (Frontend)
|
||||
|
||||
Zentrale Datei: `frontend/src/utils/navReturnContext.js`
|
||||
|
||||
| Funktion | Zweck |
|
||||
|----------|--------|
|
||||
| `buildNavReturnContext({ path, label, kind?, payload? })` | Kontext-Objekt erzeugen |
|
||||
| `buildExercisesListReturnContext()` | Standard-Rückkehr Übungsliste |
|
||||
| `buildPlanningHubReturnContext(hubState)` | Planungs-Hub inkl. Filter-Query |
|
||||
| `buildTrainingModulesListReturnContext()` | Modul-Bibliothek |
|
||||
| `readNavReturnFromLocation(location)` | Kontext aus `location.state` (+ Legacy) |
|
||||
| `resolveNavReturnTarget(location, fallback)` | `{ path, label }` für UI |
|
||||
| `goNavReturn(navigate, location, fallback?)` | Programmatischer Rücksprung (priorisiert: Kontext → History → Fallback) |
|
||||
| `navigateWithAppReturn(navigate, to, returnContext, options?)` | Navigation mit gesetztem `appReturn` |
|
||||
| `preserveAppReturnOnNavigate(navigate, location, to, options?)` | Weiterleiten, bestehenden Kontext behalten (z. B. nach `replace`) |
|
||||
|
||||
UI-Komponente: **`PageReturnButton`** — app-typischer Zurück-Schalter (Button mit Pfeil, kein Router-Link).
|
||||
Links **zum** Ziel: **`NavStateLink`** mit `returnContext` der Quellseite.
|
||||
|
||||
### Editor-Aktionen
|
||||
|
||||
Auf Vollseiten-Editoren mit **`FormActionBar`** (`placement="bottom"`) oder **`PageFormEditorChrome`**:
|
||||
|
||||
- **Kein** separater Zurück-Link/Button oben (wirkt in der App redundant)
|
||||
- **Abbrechen** → `goBack()` / `goNavReturn(...)` (Einsprungspunkt)
|
||||
- **Speichern & Schließen** → nach erfolgreichem Save ebenfalls `goBack()`
|
||||
- Sticky Action Bar unten nutzen
|
||||
|
||||
**PageReturnButton** nur auf **Leseseiten** ohne Editor-Leiste (z. B. Übungsdetail, Einstellungen-Unterseiten, Trainingsablauf).
|
||||
|
||||
---
|
||||
|
||||
## Regeln für Entwickler
|
||||
|
||||
1. **Jede Navigation** von Kontext A zu Editor B, wo der Nutzer „weitermachen“ soll, setzt `appReturn` (oder nutzt `navigateWithAppReturn`).
|
||||
2. **Zielseite** zeigt `PageReturnButton` mit sinnvollem **Default-Fallback** (Bibliothek/Hub).
|
||||
3. **Nach Create + `replace: true`:** Return-Kontext mit `preserveAppReturnOnNavigate` erhalten.
|
||||
4. **Modals:** Schließen reicht; Redirect nach Speichern = Seiten-Navigation → Return setzen.
|
||||
5. **Kein Return-Kontext** in `location.state` für interne Bibliothek → Detail → Bearbeiten, wenn Herkunft = offensichtliche Elternliste (Default-Fallback genügt).
|
||||
6. **UI-State** (Filter, Auswahl): weiter über bestehende Session-Mechanismen (z. B. `exerciseListSessionState`), nicht im Return-Payload duplizieren, außer kind erfordert Query-Reconstruction (Planung).
|
||||
|
||||
---
|
||||
|
||||
## Umsetzungsstand
|
||||
|
||||
### Phase 1 (Pilot)
|
||||
|
||||
- [x] Spec + Utility + Tests
|
||||
- [x] `PageReturnButton` (ersetzt Link-Variante)
|
||||
- [x] Übungsliste → Modul speichern → Modul-Editor
|
||||
- [x] Planung: `SaveExercisesAsModuleModal` leitet Return-Kontext weiter
|
||||
- [x] `TrainingUnitEditPage`: `goBack` über `goNavReturn` (Legacy-bridge)
|
||||
|
||||
### Phase 2 (Flows verbinden)
|
||||
|
||||
- [x] Listen → Editoren: Übungen, Module, Vorlagen, Rahmenprogramme
|
||||
- [x] Dashboard → Übung bearbeiten / Trainingsablauf / Einheit bearbeiten
|
||||
- [x] Einstellungen-Unterseiten (Rechtliches, Systeminfo)
|
||||
- [x] Trainingsablauf + Coach-Modus (`trainingRun`, Planungs-Fallback)
|
||||
- [x] Medienbibliothek → verknüpfte Übungen/Einheiten
|
||||
- [x] `ExercisePeekModal` → Vollseite mit Return
|
||||
- [x] Editoren: Abbrechen + Speichern & Schließen → Einsprungspunkt
|
||||
|
||||
### Optional (später)
|
||||
|
||||
- Globaler Zurück-Button in App-Chrome (Mobile)
|
||||
- Nach Speichern: explizite Aktion „Zurück zum Ausgang“ im Toast
|
||||
|
||||
---
|
||||
|
||||
## Referenzen
|
||||
|
||||
- Bestehend: `frontend/src/utils/planningUnitRoutes.js` (`planningReturn`)
|
||||
- Session Übungsliste: `frontend/src/utils/exerciseListSessionState.js`
|
||||
- PWA-Kontext: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`, App-Shell in `App.jsx`
|
||||
@@ -0,0 +1,136 @@
|
||||
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
|
||||
|
||||
**Status:** Umsetzung **Phase 1 (teils)** · **Stand:** 2026-05-14
|
||||
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
|
||||
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand 2026-05-14): **`training_unit_phases` / `training_unit_parallel_streams`** (Migration **063**) und **`training_unit_sections`** mit Phasen-/Stream-Bezug; **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung und Coaching über **`TrainingUnitRunPage`**, **`TrainingCoachPage`** und **`trainingPlanUtils.js`**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Ist-Stand (Code, 2026-05-14)
|
||||
|
||||
| Bereich | Aktuell |
|
||||
|---------|---------|
|
||||
| **Schema** | Migration **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` **oder** `parallel_stream_id`. |
|
||||
| **API** | `GET /api/training-units/:id` — **`phases`** (verschachtelt) + flache **`sections`**. `PUT/POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); höchstens eines von `phases`, `sections`, `exercises` pro Request (Planning-Router). Legacy-PUT mit nur `sections` erzeugt/ergänzt Ganzgruppen-Phase. |
|
||||
| **Planung (UI)** | Breakout-Panel: Ganzgruppen-/parallele Phasen, Streams; Speichern phasenbasiert (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`). |
|
||||
| **Durchführung** | `TrainingUnitRunPage.jsx` + `trainingPlanUtils.js` (`sectionsWithPlanLocForDisplay`, `buildPlanRunViewModelFromSections`) — Phasenfolge in „Plan & Ablauf“. |
|
||||
| **Coaching** | `TrainingCoachPage.jsx` + `flattenPlanTimeline`, Stream-Picks, Rejoin vor Ganzgruppe/nächstem Split (`coachShouldPromptSplitRejoinTransition`), Nachbereitung mit `buildCoachSavePlanPayload`, danach Navigation zu `/planning/run/:id`. |
|
||||
| **Kombinationsübung** | Unverändert je Item; `planning_method_profile`, Coach-Kombi-Stufe A. |
|
||||
| **Trainer-Zuweisung** | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am Einheitskopf; **Stream-**`assigned_trainer_profile_ids` im Schema — UI/Policy noch nicht vollständig (siehe **§8 offen**). |
|
||||
| **Rahmenprogramm** | Blueprint-`training_units` können dieselbe Phasenstruktur tragen; Kopie aus Slot (`from-framework-slot`, **0.8.138**). |
|
||||
|
||||
**Hinweis:** Die frühere Planungsvariante „nur lineare `training_unit_sections` ohne Phasen“ gilt weiter für Alt-Daten; Migration **063** ordnet Bestand einer Default-Ganzgruppenphase zu.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielarchitektur (logisch)
|
||||
|
||||
```
|
||||
training_unit (Kalender-Einheit)
|
||||
├── phase (order, kind: whole_group | parallel, optional Metadaten)
|
||||
│ ├── [whole_group] → sections[] → items[] (wie heute)
|
||||
│ └── [parallel] → stream (order, label, optional trainer_ids[])
|
||||
│ └── sections[] → items[]
|
||||
```
|
||||
|
||||
**Abwärtskompatibilität:** Einheiten **ohne** explizite Phasen/Streams verhalten sich wie heute: **implizit** eine einzige „Gemeinschaftsphase“ mit den vorhandenen Sektionen (Migration: alle bestehenden Sektionen an diese Default-Hülle hängen).
|
||||
|
||||
---
|
||||
|
||||
## 3. Datenmodell — Optionen
|
||||
|
||||
**Ist (063):** Die unten skizzierte **empfohlene** Normalform ist unter den genannten Tabellennamen produktiv; die Abschnitte 3.1/3.2 bleiben zur Einordnung erhalten.
|
||||
|
||||
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
|
||||
|
||||
Die Tabellen sind **umgesetzt** (Namen final):
|
||||
|
||||
| Tabelle | Zweck |
|
||||
|---------|--------|
|
||||
| `training_unit_phases` | `training_unit_id`, `order_index`, `phase_kind` (`whole_group` \| `parallel`), optional `title`, `guidance_notes`, optional `planned_duration_min` |
|
||||
| `training_unit_parallel_streams` | `phase_id` (FK, nur wenn parent parallel), `order_index`, `title`/`label`, optional `notes`, optional `assigned_trainer_profile_ids` JSONB (oder 1:n-Hilfstabelle) |
|
||||
|
||||
**Anpassung `training_unit_sections`:** Zusätzliche FK-Spalte(n), z. B.:
|
||||
|
||||
- `phase_id` **NULL** und `parallel_stream_id` **NULL** → **Legacy / Default-Einheitsphase** (Migration setzt Default-Phase); oder
|
||||
- genau einer von `phase_id` (whole group) oder `parallel_stream_id` gesetzt.
|
||||
|
||||
**Constraints:** CHECK: nicht beide gesetzt; bei `phase_kind = parallel` Sektionen nur unter `parallel_stream_id`; bei `whole_group` nur unter `phase_id`.
|
||||
|
||||
**Vorteil:** Klare Semantik, Reporting, API-Shape konsistent.
|
||||
|
||||
### 3.2 Minimalvariante (nicht ideal fachlich)
|
||||
|
||||
Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; Phasen implizit durch „Marker“-Sektionen oder Konvention. **Nicht empfohlen**, erschwert UI und Erklärbarkeit.
|
||||
|
||||
---
|
||||
|
||||
## 4. API
|
||||
|
||||
- **`GET /api/training-units/:id`** (und Listen-Payloads wo vollständiger Plan nötig): verschachtelte Struktur **Phasen → Streams → sections → items** oder flache `sections` mit ausgefüllten `phase_id` / `parallel_stream_id` (Frontend kann normalisieren).
|
||||
- **`PUT/PATCH`:** Atomares Ersetzen der Phasen/Streams/Sektionen analog zu bestehendem `_replace_unit_sections`-Muster; **Validierung** der CHECK-Regeln serverseitig.
|
||||
- **Blueprint / Rahmen:** Blueprint-`training_units` dürfen dieselbe Struktur tragen; `GET` Kalenderliste blendet Blueprints weiter aus (`framework_slot_id IS NOT NULL`).
|
||||
|
||||
**Governance / Mandant:** Unverändert über Einheit → `group_id`; keine neuen Mandanten-Entitäten.
|
||||
|
||||
---
|
||||
|
||||
## 5. Frontend
|
||||
|
||||
### 5.1 Planung (`TrainingPlanningPage`)
|
||||
|
||||
- Darstellung als **vertikale Phasen**: Gemeinschaftsblöcke + Parallelphase mit **N Spalten** (Streams).
|
||||
- **Wiederverwendung:** `TrainingUnitSectionsEditor` **pro Stream** und pro Gemeinschaftsphase — analog zur Wiederverwendung **pro Rahmen-Slot** in `TrainingFrameworkProgramEditPage`.
|
||||
- **Co-Trainer:** UI pro Stream (`assigned_trainer_profile_ids`); Regel zur **Kopfliste** `assistant_trainer_profile_ids` festlegen (z. B. Union aller Stream-Zuweisungen für „Wer ist heute dabei“ + Rückwärtskompatibilität wenn Stream-Felder leer).
|
||||
|
||||
### 5.2 Durchführung (`TrainingUnitRunPage`)
|
||||
|
||||
- Gemeinschaftsphasen: heutiges **lineares** Verhalten.
|
||||
- Parallelphase: **Tabs, Akkordeon oder Swipe** zwischen Streams; Fortschritt **pro Stream** (Storage-Key z. B. `${unitId}:${streamId}`).
|
||||
- Kombi-Items: unverändert `CombinationPlanBracket` / `effectiveComboMethodProfile`.
|
||||
- Optional später: Filter „nur meine Spur“ anhand Session-Profil vs. Stream-Zuweisung.
|
||||
|
||||
### 5.3 Vorlagen (`training_plan_templates`)
|
||||
|
||||
- Erweiterung um **dieselbe** Phasen/Streams-Semantik (Kindtabellen oder serialisiertes JSON — Abgleich mit Kopierlogik aus Vorlage in Einheit).
|
||||
- **Kein** Live-Spiegel: weiterhin Materialisierung beim Anwenden.
|
||||
|
||||
---
|
||||
|
||||
## 6. Bezug Kombinationsübungen
|
||||
|
||||
- **Variante A** (Rotation innerhalb einer Teilstrecke): ein oder mehrere **Items** vom Typ Kombi im jeweiligen Stream; Archetyp und Parameter wie in `TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`.
|
||||
- **Variante B** (synchron Hallenweit): erweiterte **Phasen-** oder **Stream-übergreifende** Metadaten — **nicht** in MVP-Zwang; eigenes Teilpaket nach fachlicher Freigabe (`PARALLEL_TRAINING_STREAMS_CONCEPT.md` §5.2).
|
||||
|
||||
---
|
||||
|
||||
## 7. Migration und Risiken
|
||||
|
||||
1. **Datenmigration:** Alle existierenden `training_unit_sections` einer Einheit einer **Default-Phase** `whole_group` zuordnen.
|
||||
2. **API-Versionierung:** Clients, die nur flache `sections` erwarten, müssen angepasst werden (oder Server liefert **beides** kurzzeitig — nur wenn nötig).
|
||||
3. **Performance:** Tiefe Kopien (Rahmen-Slot, Duplikat Einheit) müssen rekursiv Phasen/Streams mitsamt Sektionen/Items kopieren.
|
||||
4. **Tests:** pytest für PUT/GET mit gemischten Phasen; ggf. Playwright-Smoke für Planung/Run.
|
||||
|
||||
---
|
||||
|
||||
## 8. Implementierungsphasen (Abgleich)
|
||||
|
||||
| Phase | Inhalt | Stand 2026-05-14 |
|
||||
|-------|--------|------------------|
|
||||
| **P1** | Schema Phasen + Streams; Migration **063**; GET/PUT verschachtelt; Planungs-UI; Run + Coach phasenbasiert | **Teilweise erledigt** — Run-UI nutzt Phasen-Timeline in der Anzeige; **Stream-Tabs** optional noch zu vereinheitlichen (§5.2) |
|
||||
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert | **Offen** |
|
||||
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) | **Offen** |
|
||||
|
||||
**Offene Punkte (kurz):** siehe **`docs/HANDOVER.md`** Tabelle „Coaching & Breakout“.
|
||||
|
||||
## 9. Verwandte Dokumente
|
||||
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md` | Fachziele, Begriffe, Entscheidungsfragen |
|
||||
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
|
||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
|
||||
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
|
||||
| `TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Planung, Durchführung, Rahmen |
|
||||
| `frontend/src/utils/trainingPlanUtils.js`, `TrainingCoachPage.jsx` | Phasen-Timeline, Rejoin, Coach-Speichern |
|
||||
@@ -0,0 +1,184 @@
|
||||
# Gewichtetes Fähigkeiten-Scoring (Phase 3)
|
||||
|
||||
**Stand:** 2026-05-20
|
||||
**Status:** Variante A (regelbasiert) umgesetzt — **v1.3** (Peer-Kontext getrennt + Listen-Filter)
|
||||
**Modul:** `backend/skill_scoring.py`, Router `backend/routers/skill_profiles.py`
|
||||
|
||||
## Ziel
|
||||
|
||||
Trainer wählen **Schwerpunkt-Fähigkeiten** und finden passende **Bausteine** für die Trainingsplanung:
|
||||
|
||||
- **Trainingsmodule** — wiederverwendbare Übungsfolgen
|
||||
- **Rahmenprogramme** — Programme mit Zielen und Session-Slots
|
||||
- **Regressionspfade** (Progressionsgraphen) — Übungsketten
|
||||
|
||||
Das Scoring beantwortet: *Wie stark trainiert dieser Baustein eine Fähigkeit?* und *Wie stark ist er im Vergleich zu anderen **sichtbaren** Bausteinen **desselben Typs**?*
|
||||
|
||||
## Fachliche Kernregel: Peer-Kontext (nicht vermischen)
|
||||
|
||||
| Planungs-Artefakt | Vergleichsgruppe (`universal_percent`) |
|
||||
|-------------------|----------------------------------------|
|
||||
| Trainingsmodul | nur andere **sichtbare Module** |
|
||||
| Rahmenprogramm | nur andere **sichtbare Rahmenprogramme** |
|
||||
| Regressionspfad | nur andere **sichtbare Pfade** |
|
||||
|
||||
**Nicht** verglichen werden:
|
||||
|
||||
- Module vs. Rahmenprogramme vs. Pfade (kein Mix)
|
||||
- Artefakte anderer Vereine, auf die der Nutzer keinen Planungszugriff hat
|
||||
|
||||
**Sichtbarkeit:** `library_content_visibility_sql` — private, vereinsinterne und offizielle Inhalte gemäß Mandant/Rolle, analog zu anderen Bibliothekslisten.
|
||||
|
||||
## Datenquellen
|
||||
|
||||
| Artefakt | Übungen aus |
|
||||
|----------|-------------|
|
||||
| Rahmenprogramm (gesamt) | Alle Blueprint-`training_units` der Slots → `training_unit_section_items` |
|
||||
| Rahmenprogramm (pro Slot) | Blueprint einer Session |
|
||||
| Trainingsmodul | `training_module_items` (nur `item_type = exercise`) |
|
||||
| Progressionsgraph | `from_exercise_id` + `to_exercise_id` je Kante (Vorkommen zählt) |
|
||||
|
||||
Fähigkeiten je Übung: `exercise_skills` → `skills` (nur `status = active`).
|
||||
|
||||
## Gewichtungsformel (v1.1 / v1.2)
|
||||
|
||||
Pro **Übungsvorkommen** (eine Zeile im Ablauf / Modul / Kanten-Endpunkt):
|
||||
|
||||
1. **Basis-Minuten** = `planned_duration_min` der Position, sonst Default (Einheit/Modul: 8 Min, Graph: 10 Min).
|
||||
2. Pro verknüpfte Fähigkeit der Übung:
|
||||
- `Beitrag = Basis-Minuten × Anzahl Vorkommen × Link-Faktor`
|
||||
- **Link-Faktor** = Intensität × Stufen-Faktor
|
||||
|
||||
### Intensität (Nutzeneinschätzung, UI-Feld)
|
||||
|
||||
| Wert | Faktor |
|
||||
|------|--------|
|
||||
| niedrig | 0,85 |
|
||||
| mittel / leer | 1,0 |
|
||||
| hoch | 1,2 |
|
||||
|
||||
### Stufen-Spanne (`required_level` → `target_level`, UI „von/bis“)
|
||||
|
||||
Kanonische Slugs: basis … optimierung (1–5). Fehlen beide: Faktor 1,0.
|
||||
|
||||
- **Spanne** = Anzahl Stufen von „von“ bis „bis“ (1–5)
|
||||
- **Mittelpunkt** = durchschnittliche Stufe
|
||||
- Faktor ≈ `(0,92 + 0,04 × Spanne) × (0,95 + 0,025 × Mittelpunkt)` → typisch 0,96–1,20
|
||||
|
||||
### Bewusst nicht im Scoring
|
||||
|
||||
| Feld | Grund |
|
||||
|------|--------|
|
||||
| `is_primary` | Perspektivabhängig; bleibt in Übungs-UI, fließt nicht ins Profil ein |
|
||||
| `development_contribution` | Legacy-DB-Feld, in UI nicht gepflegt |
|
||||
|
||||
## Aggregierte Metriken
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|------|-----------|
|
||||
| `weight` / `score` | Absolutes **Trainingsgewicht** (gewichtete Minuten) — über alle Fähigkeiten eines Artefakts vergleichbar |
|
||||
| `share_percent` | Anteil am `total_weight` **innerhalb dieses Artefakts** (summiert 100 %) — sekundär |
|
||||
| `by_main_category[]` | Je Unterkategorie `top_skill` (stärkste Fähigkeit nach Gewicht) |
|
||||
| `universal_percent` | Anteil am **Maximum derselben Fähigkeit im Peer-Kontext** (max. 100 %) |
|
||||
| `is_club_best_for_skill` | Stärkster sichtbarer Peer für diese Fähigkeit (★ in UI) |
|
||||
| `club_best` | Referenz-Peer (Titel, Typ, Gewicht) — **Legacy-Name**, fachlich Peer-Best |
|
||||
|
||||
### Berechnung `universal_percent`
|
||||
|
||||
```
|
||||
effective_ref = max(max_weight_in_peer_corpus(skill_id), eigenes_gewicht)
|
||||
universal_percent = min(100, weight / effective_ref × 100)
|
||||
```
|
||||
|
||||
Corpus je Typ: `compute_planning_corpus_by_type()` scannt sichtbare Artefakte getrennt nach `framework_program`, `training_module`, `progression_graph`.
|
||||
|
||||
Discovery-Sortierung nutzt **`match_score`** (= Summe absoluter Gewichte der gewählten Fähigkeiten), nicht den Plan-internen Anteil. Discovery verwendet typ-getrennte Referenz (`fw_ref`, `mod_ref`, `graph_ref`).
|
||||
|
||||
## API
|
||||
|
||||
| Methode | Pfad | Beschreibung |
|
||||
|---------|------|--------------|
|
||||
| GET | `/api/training-framework-programs/{id}/skill-profile` | `overall` + `slots[]` mit je `profile`; `reference_scale` (Peer-Kontext Rahmenprogramme) |
|
||||
| GET | `/api/training-modules/{id}/skill-profile` | `overall`; `reference_scale` (Peer-Kontext Module) |
|
||||
| GET | `/api/exercise-progression-graphs/{id}/skill-profile` | `overall`; `reference_scale` (Peer-Kontext Pfade) |
|
||||
| POST | `/api/skill-profiles/batch-summaries` | Kompakte Profile für Listen; Body: `frameworkProgramIds`, `trainingModuleIds`, …; Response: `summaries`, `reference_scale_by_type`, `club_best_by_skill` |
|
||||
| GET | `/api/skill-discovery/suggestions?skill_ids=1,2,3` | Ranking sichtbarer Artefakte; Query `types`, `limit` |
|
||||
|
||||
Zugriff: `get_tenant_context` + `library_content_visibility_sql` wie Parent-Artefakt.
|
||||
|
||||
### `reference_scale` / `reference_scale_by_type`
|
||||
|
||||
```json
|
||||
{
|
||||
"scope": "planning_peer",
|
||||
"artifact_type": "training_module",
|
||||
"artifacts_scanned": 12,
|
||||
"skills_in_corpus": 34,
|
||||
"description": "Prozent = Anteil am stärksten sichtbaren Eintrag unter Trainingsmodulen …"
|
||||
}
|
||||
```
|
||||
|
||||
## UI
|
||||
|
||||
### Bearbeitung (Vollprofil)
|
||||
|
||||
| Ort | Panel | `artifactType` |
|
||||
|-----|-------|----------------|
|
||||
| Rahmenprogramm bearbeiten | Fähigkeiten-Schwerpunkte (+ Sessions) | `framework_program` |
|
||||
| Trainingsmodul bearbeiten | Fähigkeiten im Modul | `training_module` |
|
||||
| Progressionsgraph | Fähigkeiten entlang des Pfads | `progression_graph` |
|
||||
|
||||
Anzeige: Top je Kategorie (Editor) oder alle Fähigkeiten (Modal). Hinweise nennen Peer-Kontext explizit (z. B. „72 % Rahmenpr.“).
|
||||
|
||||
### Listen & Filter (UX wie Übungsliste)
|
||||
|
||||
| Liste | Filter |
|
||||
|-------|--------|
|
||||
| Rahmenprogramme (`/planning/framework-programs`) | Suche, Katalog (Fokus/Trainingsart/Zielgruppe), Session-Dauer, **Fähigkeiten** (`SkillTreeMultiSelect`), Mindest-% im Peer-Kontext, Sortierung nach Stärke |
|
||||
| Trainingsmodule (`/planning/training-modules`) | Suche, **Fähigkeiten** (+ Min-%, Sortierung) |
|
||||
|
||||
- **Filter-Button** mit Badge, entfernbare **Chips**, Einstellungen im **Modal** (`PlanningArtifactFilterModal`)
|
||||
- KPI-Kacheln: Top-Fähigkeit **je Unterkategorie** mit Score + Peer-%
|
||||
- Vollprofil-Modal: `SkillProfileFullModal` mit `displayMode=full`
|
||||
|
||||
Profil wird nach Speichern neu geladen (`skillProfileTick` in Editoren).
|
||||
|
||||
### Discovery
|
||||
|
||||
**Fähigkeiten-Seite → Planungs-Vorschläge:** Multi-Select + API `/api/skill-discovery/suggestions` (optional Filter `types`).
|
||||
|
||||
## Frontend-Module (Auswahl)
|
||||
|
||||
| Pfad | Rolle |
|
||||
|------|--------|
|
||||
| `frontend/src/components/planning/PlanningArtifactFilterModal.jsx` | Filter-Modal |
|
||||
| `frontend/src/components/planning/PlanningSkillFilterSection.jsx` | Fähigkeiten-Block im Modal |
|
||||
| `frontend/src/utils/planningArtifactFilterChips.js` | Chip-Labels + Entfernen |
|
||||
| `frontend/src/utils/frameworkProgramListHelpers.js` | Client-Filter Rahmenprogramme |
|
||||
| `frontend/src/utils/trainingModuleListHelpers.js` | Client-Filter Module |
|
||||
| `frontend/src/components/skills/SkillProfileCompact.jsx` | KPI-Kacheln in Listen |
|
||||
| `frontend/src/components/SkillTreeMultiSelect.jsx` | Baumauswahl (Portal-Dropdown in Modals) |
|
||||
|
||||
## Grenzen / später
|
||||
|
||||
- Kein DB-Cache (`skill_profile_json`) — on-the-fly; bei >50 Artefakten pro Typ serverseitiger Index/Caching
|
||||
- Entwicklungsziele am Rahmenkopf bleiben Freitext (kein Scoring)
|
||||
- KI-Zusammenfassung (Variante B) nicht Teil von v1.0
|
||||
- Trainings**einheiten** (Kalender) optional als nächste Erweiterung
|
||||
- Filter-Persistenz („Als Standard speichern“) wie bei Übungen — noch nicht für Planungslisten
|
||||
- Fähigkeiten-Filter im Dialog **Planung → Rahmen übernehmen** — Katalog ja, Skill-Filter optional nachziehen
|
||||
- API-Feldnamen `club_*` / `skillMinClubPercent` — technische Altlast, semantisch Peer-Kontext
|
||||
|
||||
## Tests
|
||||
|
||||
- `backend/tests/test_skill_scoring.py` — Multiplikator, Aggregation, Match-Score, Cap 100 %
|
||||
- **Offen:** dedizierte Tests für `compute_planning_corpus_by_type` (Typ-Trennung)
|
||||
|
||||
## Verweise
|
||||
|
||||
| Dokument | Inhalt |
|
||||
|----------|--------|
|
||||
| `functional/DOMAIN_MODEL.md` | Domänenabschnitt Planungs-Fähigkeiten-Profil |
|
||||
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick Listen/Filter |
|
||||
| `docs/HANDOVER.md` | Handover-Abschnitt Phase 3 |
|
||||
| `technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` | Sichtbarkeit / Mandant |
|
||||
@@ -15,6 +15,8 @@
|
||||
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
|
||||
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
|
||||
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | **Parallele Streams / Breakout innerhalb einer Einheit** — orthogonale Domäne zu **Rahmen‑Slots** (Serien‑Sessions). |
|
||||
| `technical/SKILL_SCORING_SPEC.md` | **Fähigkeiten-Profil** der Rahmen‑Slots / Module / Pfade; Listen-Filter und Peer‑Vergleich (nur gleicher Artefakttyp). |
|
||||
|
||||
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
| Dokument | Bezug |
|
||||
|----------|--------|
|
||||
| `TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Bibliothek, Slot-Blueprint, Kopiersemantik (`from-framework-slot`) |
|
||||
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | Parallele Teilstrecken **innerhalb einer Einheit**; Kombi-Übungen weiter nutzbar **pro Stream** für Stationsrotation |
|
||||
| `DATABASE_SCHEMA.md` | Aktueller Stand `training_units`, Sektionen, Items |
|
||||
| `functional/DOMAIN_MODEL.md` | Domänenbegriffe (bei Bedarf zu erweitern) |
|
||||
| `EXERCISES_*` (Katalog) | Einzelübungen, Varianten |
|
||||
|
||||
@@ -15,6 +15,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
|
||||
| exercise_progression_graphs | `/api/exercise-progression-graphs*` | ja | `get_tenant_context` | Liste wie Bibliothek; Schreiben Ersteller/Plattform-Admin | Kanten: Lesen wenn Graph lesbar |
|
||||
| training_planning | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Vorlagen-Liste wie Übungen; POST Vorlage Default club_id |
|
||||
| dashboard | `GET /api/dashboard/kpis` | ja | `get_tenant_context` | wie `GET /api/exercises` + `GET /api/training-units` | Aggregat für Dashboard-Kurzüberblick (ein Roundtrip) |
|
||||
| training_modules | `/api/training-modules*` | ja | `get_tenant_context` | ja | Bibliotheks-Module wie Vorlagen/Rahmen; POST Default `club_id` bei `visibility=club` |
|
||||
| training_framework_programs | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Liste + POST Default club_id |
|
||||
| admin_users | `GET /api/admin/users` | Plattform | `require_auth` | Admin-Rolle | EXEMPT `check_access_layer_hints.py` |
|
||||
@@ -37,13 +38,13 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
|
||||
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
||||
|
||||
Letzte Änderung: 2026-05-12 — Trainingsmodule (`/api/training-modules*`); Governance wie Planungsbibliothek.
|
||||
Letzte Änderung: 2026-05-13 — `GET /api/dashboard/kpis` (Kurzüberblick-Aggregat).
|
||||
|
||||
---
|
||||
|
||||
### Changelog (Fortführung)
|
||||
|
||||
- **2026-05-12:** `training_modules` Router dokumentiert.
|
||||
- **2026-05-13:** Dashboard-KPI-Endpunkt dokumentiert.
|
||||
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Rahmenprogramm: Filter, Dauer, Fähigkeiten-Schwerpunkte (Roadmap)
|
||||
|
||||
**Stand:** 2026-05-20
|
||||
**Status:** Phase 1 umgesetzt; Phase 3 v1.0 umgesetzt (regelbasiert); Phase 2 teilweise offen
|
||||
|
||||
## Phase 1 (umgesetzt)
|
||||
|
||||
### Listen-Anzeige Session-Dauer
|
||||
|
||||
- **GET `/api/training-framework-programs`:** `session_duration_min`, `session_duration_max` (aus Blueprint-`training_units.planned_duration_min`), `goal_titles_agg`, ID-Arrays für Katalog-M:N.
|
||||
- **UI:** Rahmenprogramm-Liste, Trainingsplanung (Einheiten-Liste/Kalender), Import-Dialog (Programm + pro Slot).
|
||||
|
||||
### Import-Filter (clientseitig)
|
||||
|
||||
- Textsuche (Titel, Beschreibung, Ziele, Katalog-Namen)
|
||||
- Fokusbereich, Trainingsart, Zielgruppe (Checkboxen, Katalog-API)
|
||||
- Ziel-Session-Dauer in Minuten (±10 Min Toleranz gegen Min/Max der Slots)
|
||||
|
||||
**Grenze:** Entwicklungsziele sind **freie Texte** pro Rahmen (`training_framework_goals.title`), keine kontrollierte Taxonomie → Filter nur Volltext, keine homogene „Ziel-Tags“-Liste.
|
||||
|
||||
## Phase 2 (empfohlen, ohne KI)
|
||||
|
||||
| Kriterium | Datenquelle heute | Verbesserung |
|
||||
|-----------|-------------------|--------------|
|
||||
| Fokusbereich / Stil / Trainingsart / Zielgruppe | M:N am Rahmenkopf | bereits filterbar |
|
||||
| Entwicklungsziele | Freitext-Ziele | Optional: Ziel-Vorlagen-Katalog oder Tags (Migration) |
|
||||
| Session-Dauer | `planned_duration_min` pro Slot | erledigt |
|
||||
| Fähigkeiten-Schwerpunkt | noch nicht | siehe Phase 3 |
|
||||
|
||||
**API-Erweiterung (optional):** `GET /api/training-framework-programs?focus_area_id=&training_type_id=&duration_min=` serverseitig — sinnvoll ab >50 Rahmen in der Bibliothek.
|
||||
|
||||
## Phase 3 — Fähigkeiten aus Übungen (umgesetzt v1.0)
|
||||
|
||||
**Spec:** `.claude/docs/technical/SKILL_SCORING_SPEC.md`
|
||||
|
||||
- Gewichtetes Profil: Rahmenprogramm (gesamt + pro Slot), Trainingsmodul, Progressionsgraph
|
||||
- `GET /api/skill-discovery/suggestions?skill_ids=…` für Bibliotheks-Vorschläge
|
||||
- UI: Profil-Panels in Editoren + Tab „Planungs-Vorschläge“ auf der Fähigkeiten-Seite
|
||||
- **Kein** automatisches Überschreiben der Stammdaten-Fokusbereiche
|
||||
|
||||
### Variante B — KI-Zusammenfassung (OpenRouter, optional, offen)
|
||||
|
||||
1. Input: Titel Rahmen, Ziele (Text), Liste Übungstitel + Dauer + vorhandene Skill-Namen.
|
||||
2. Prompt: strukturiertes JSON (`suggested_focus_areas[]`, `skill_emphasis[]`, `rationale_de`).
|
||||
3. Speichern als `ai_context_summary` (Version, Modell, Timestamp) — **nur Vorschlag**, manuelle Bestätigung vor Übernahme in Stammdaten.
|
||||
|
||||
**Vorteil:** natürliche Schwerpunkte auch bei unvollständigen Skill-Links.
|
||||
**Risiko:** Halluzination, Kosten, Datenschutz (Vereinsdaten in Prompt).
|
||||
|
||||
### Empfehlung
|
||||
|
||||
Zuerst **Variante A** für Listen/Filter und Abgleich mit manuell gesetzten Fokusbereichen; KI nur als **„Vorschlag generieren“-Button** im Rahmen-Editor, wenn Regelwerk und Katalog-Zuordnung zu dünn sind.
|
||||
|
||||
## Offene Produktfragen
|
||||
|
||||
1. Soll Filter **UND** (alle Kriterien) oder **ODER** (mindestens eines) sein? — Import aktuell **UND**.
|
||||
2. Rahmen mit **unterschiedlichen** Slot-Dauern: Liste zeigt Min–Max; Filter „90 Min“ trifft Range.
|
||||
3. Sollen homogenisierte **Entwicklungsziel-Tags** ein eigener Katalog werden (Admin), analog `target_groups`?
|
||||
@@ -0,0 +1,125 @@
|
||||
# Parallele Trainingsstreams — Ist-Analyse und risikoarmer Umsetzungsplan
|
||||
|
||||
**Status:** Stufe A (Analyse/Plan, ohne produktive Umsetzung in jener Session)
|
||||
**Stand:** 2026-05-14
|
||||
**Verbindliche fachliche Basis:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
|
||||
Dieses Dokument **persistiert** die strukturierte Prüfung der realen Codebasis (`training_planning.py`, `training_framework_programs.py`, `training_unit_sections`/`items`, Frontend Planung/Run/Coach) und den empfohlenen Implementierungspfad.
|
||||
|
||||
---
|
||||
|
||||
## 1. Zusammenfassung
|
||||
|
||||
- Plan-Inhalt pro Einheit ist heute **eine flache Liste** `training_unit_sections` mit **`UNIQUE (training_unit_id, order_index)`** (Migration 031) und `training_unit_section_items`; zentral: **`_fetch_sections`**, **`_replace_unit_sections`**, **`_hydrate_training_unit_payload`** in `backend/routers/training_planning.py`.
|
||||
- Parallele Phasen/Streams **passen** zu den Produktregeln (ein Kalendertermin, N Streams, je Miniplan), sind im Schema aber **nicht** abbildbar ohne Erweiterung und **ohne Auflösung** des globalen `order_index`-Modells.
|
||||
- **Empfehlung:** **Normalisierte** Tabellen `training_unit_phases`, `training_unit_parallel_streams`, erweiterte `training_unit_sections` mit FK auf Phase bzw. Stream, **partielle Unique-Indizes** statt `UNIQUE (training_unit_id, order_index)` für alle Sektionen.
|
||||
- **Blocker im Code:** u. a. `POST /api/training-units/{id}/apply-training-module` mit **`section_order_index` global pro Einheit** (`_resolve_training_unit_section_id`).
|
||||
- **Nicht persistiert an anderer Stelle:** Erste Fassung existierte nur als Chat-Antwort; dieses File ist die **kanonische** Arbeitskopie im Repo.
|
||||
|
||||
---
|
||||
|
||||
## 2. Ist-Analyse (kurz)
|
||||
|
||||
### Datenbank
|
||||
|
||||
- `training_unit_sections`: u. a. `training_unit_id`, `order_index`, `UNIQUE (training_unit_id, order_index)`.
|
||||
- `training_unit_section_items`: Übung/Notiz, `planning_method_profile` (Kombi), `source_training_module_id`.
|
||||
|
||||
### Backend (`training_planning.py`)
|
||||
|
||||
- `_replace_unit_sections`: DELETE aller Sektionen der Einheit + INSERT (vollständiger Ersetzungsbaum).
|
||||
- `_sections_clone_payload` + `_copy_blueprint_into_scheduled_unit`: tiefe Kopie für `from-framework-slot`.
|
||||
- `_flatten_exercises_from_sections`: flaches `exercises` am Unit-Payload.
|
||||
- `apply_training_module_to_training_unit`: Sektion per **`section_order_index`** global.
|
||||
|
||||
### Rahmen (`training_framework_programs.py`)
|
||||
|
||||
- Blueprint-`training_units` pro Slot; gleiche `_replace_unit_sections`-Semantik.
|
||||
|
||||
### Frontend
|
||||
|
||||
- Planung: `TrainingPlanningPageRoot.jsx`, `TrainingUnitSectionsEditor`, `buildSectionsPayload` / `normalizeUnitToForm`.
|
||||
- Run: `TrainingUnitRunPage.jsx` — Fortschritt `sessionStorage` Key `sj_training_run_checked_${unitId}`.
|
||||
- Coach: `TrainingCoachPage.jsx` — `flattenPlanTimeline` (linearer Ablauf).
|
||||
|
||||
### Tests
|
||||
|
||||
- Kaum Abdeckung für Plan-Inhalt; vorhanden u. a. `test_training_unit_assignments.py` (Merge Co-Trainer, ohne DB), `test_training_units_list_keyset.py` (Keyset-Validierung).
|
||||
|
||||
---
|
||||
|
||||
## 3. Technische Optionen und Empfehlung
|
||||
|
||||
| Option | Kurz |
|
||||
|--------|------|
|
||||
| A JSONB nur auf `training_units` | Niedriges DDL-Risiko, hohes Drift-/Wartungsrisiko — **nicht empfohlen** |
|
||||
| B Normalisiert Phasen/Streams | **Empfohlen** — eine Wahrheit, saubere Kopie, Rahmen kompatibel |
|
||||
| C Nur UI-Konvention ohne DB | Widerspricht Produkt — **abgelehnt** |
|
||||
|
||||
---
|
||||
|
||||
## 4. Migrations- und Kompatibilitätsstrategie
|
||||
|
||||
- Default **`whole_group`‑Phase** für alle bestehenden Einheiten; alle bisherigen Sektionen erhalten `phase_id`.
|
||||
- Unique-Regel: **pro Phase** bzw. **pro Stream** `order_index` eindeutig (partielle Unique-Indizes).
|
||||
- API optional: zusätzlich abgeleitetes flaches `sections` für Übergang — Entscheidung je nach Consumer (praktisch nur dieses Frontend).
|
||||
|
||||
---
|
||||
|
||||
## 5. API- / Frontend-Hotspots
|
||||
|
||||
- `GET`/`PUT` `/api/training-units/{id}`: verschachtelte `phases` / `streams` / `sections` / `items`.
|
||||
- `POST .../apply-training-module`: Kontext **Phase/Stream + Sektionsindex im Träger**.
|
||||
- Run/Coach: stream-spezifischer Fortschritt; `flattenPlanTimeline` phase-aware oder pro Stream.
|
||||
|
||||
---
|
||||
|
||||
## 6. Implementierungspakete (Überblick)
|
||||
|
||||
0. Spike DDL + Contract-Doku
|
||||
1. **Erledigt (2026-05-14):** Migration **063** + `training_planning`: Phasen/Streams-Schema, Backfill whole_group, `GET` mit `phases`, Legacy-`sections`-PUT unverändert (eine whole_group-Phase).
|
||||
2. PUT mit echten Parallelphasen / Streams, `apply-training-module` mit Stream-Kontext, `from-framework-slot`-Kopie
|
||||
3. Planung UI
|
||||
4. Run + Coach
|
||||
5. Co-Trainer pro Stream
|
||||
6. MVP+ (Duplizieren, Verschieben, „nur meine Spur“)
|
||||
|
||||
---
|
||||
|
||||
## 7. Risiken
|
||||
|
||||
- Migration Unique-Constraint / bestehende Daten.
|
||||
- Regression Run/Coach / Dashboard-Joins (meist unkritisch, solange `training_unit_id` auf Sektionen bleibt).
|
||||
- Rahmen-Blueprints: gleiche Struktur wie Kalender-Einheiten anstreben (oder bewusst zweite Phase nur Kalender).
|
||||
|
||||
---
|
||||
|
||||
## 8. Offene Produkt-/Technikfragen
|
||||
|
||||
- Rahmen-Blueprint parallel im MVP oder erst nach Kalender-Einheit?
|
||||
- Semantik `exercises`-Flatlist bei Parallelität.
|
||||
- Merge-Regel `assistant_trainer_profile_ids` Kopf vs. Stream-Zuweisungen.
|
||||
|
||||
---
|
||||
|
||||
## 9. Verweise
|
||||
|
||||
- Fachkonzept: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
- Technische Spec (Entwurf): `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
- Domänenüberblick: `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
|
||||
- `./PARALLEL_TRAINING_STREAMS_PREREQ_PROMPT.md` — **Prompt** für Folgesession (Performance/Wartung/Vorbereitung)
|
||||
|
||||
---
|
||||
|
||||
## 10. Vorbereitende Arbeiten (Session 2026-05-13)
|
||||
|
||||
Ohne produktives Parallel-Feature, nur Risikoabbau und Transparenz:
|
||||
|
||||
- **`training_planning.py`:** Lesepfad `_fetch_sections` in SQL-Konstanten + `_fetch_section_items_for_section` / `_hydrate_section_item_combination_slots` strukturiert; `_replace_unit_sections` delegiert an `_insert_one_replacement_section`; `_hydrate_training_unit_payload` dokumentiert.
|
||||
- **Tests:** `tests/test_training_planning_sections_pure.py` (flatten, ohne DB); `tests/test_training_planning_sections_integration.py` (Roundtrip replace↔fetch bei `TRAINING_PLANNING_INTEGRATION=1`).
|
||||
- **Frontend:** Kurzkommentare an Planung (`TrainingPlanningPageRoot`, `buildSectionsPayload`), Run, Coach, `flattenPlanTimeline` — Anbindungspunkte für spätere Phase/Stream-Logik.
|
||||
- **DOMAIN_MODEL:** UNIQUE-Hinweis und „keine Migration ohne Freigabe“.
|
||||
|
||||
**Empfohlene nächste Schritte:** Pakete **0** (DDL/Contract festzurren) und **1** (Schema + Migration + hydrate/replace laut Plan Abschnitt 4–6) in einer dedizierten Feature-Session; danach Paket **2** (PUT/Module/Clone).
|
||||
|
||||
---
|
||||
@@ -0,0 +1,41 @@
|
||||
# Prompt: Vorbereitungs- / Vorarbeit-Session (Performance & Wartung) für „Parallele Trainingsstreams“
|
||||
|
||||
**Kontext:** Du arbeitest in **Shinkan Jinkendo** (`c:\Dev\shinkan-jinkendo`). Das Feature **Parallele Trainingsstreams / Breakout** ist **inhaltlich** spezifiziert; eine **Ist-Analyse und ein risikoarmer Umsetzungsplan** liegen **persistiert** in:
|
||||
|
||||
- `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`
|
||||
- Fachlich: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||
- Technik-Entwurf: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||
|
||||
**Deine Rolle:** Du hast bereits **Refaktorierungs- und Wartungsaufgaben** mit Fokus **Performance, Lesbarkeit und Testbarkeit** durchgeführt. In **dieser** Session geht es **nicht** darum, das komplette Parallel-Feature zu bauen, sondern um **Vorarbeiten („Prerequisites“)**, die die geplante Komplexitätsauflösung **sicherer und billiger** machen.
|
||||
|
||||
## Ziele
|
||||
|
||||
1. **Lesepfad Planung vereinheitlichen:** `backend/routers/training_planning.py` ist zentral für `_fetch_sections`, `_replace_unit_sections`, `_hydrate_training_unit_payload`, Klonen, Blueprint-Kopie, `apply-training-module`. Prüfe, ob klar abgegrenzte Hilfsfunktionen (ohne Verhaltensänderung) die **nächste** große Änderung erleichtern — **keine** Feature-Logik für Phasen/Streams hinzufügen, nur Struktur/Tests/Docs wenn nötig.
|
||||
|
||||
2. **Test-Lücken schließen (minimal, hoher Nutzen):** Heute fehlen **DB/API-Tests** für kritische Pfade (`_replace_unit_sections` Roundtrip, `from-framework-slot` Struktur-Kopie, optional `apply-training-module`). Ergänze **kleine, deterministische** Tests (pytest mit DB, falls im Projekt üblich), ohne riesige Fixtures.
|
||||
|
||||
3. **Frontend-Schneidstellen markieren:** kurze Kommentare oder ein **Working-Doc-Update**, wo `TrainingPlanningPageRoot`, `buildSectionsPayload`, `TrainingUnitRunPage`, `TrainingCoachPage` + `trainingPlanUtils.flattenPlanTimeline` später angebunden werden — **kein** großes UI-Rewrite.
|
||||
|
||||
4. **Migrations-Sicherheit:** Dokumentiere in **einem Absatz** im `ANALYSIS`-Dokument oder hier, welche **Unique-Constraints** (`training_unit_sections`: `UNIQUE (training_unit_id, order_index)`) die Parallelität blockieren — **ohne** sie schon zu ändern, außer es ist Teil einer **explizit** freigegebenen ersten Migration.
|
||||
|
||||
5. **Performance nur berührensensible Stellen:** Einzelabruf `GET /api/training-units/{id}` wird mit mehr JOINs kommen. Falls du **jetzt** N+1 oder redundante Arbeit in `_fetch_sections` siehst und das **risikoarm** verbesserbar ist, nur mit **Messpunkt/Messvorstellung** (kein unnötiger Micro-Optimismus).
|
||||
|
||||
## Leitplanken
|
||||
|
||||
- **Stabilität vor Geschwindigkeit:** Keine Änderung, die bestehende Einheiten, Rahmen-Blueprints oder Run-Modus bricht.
|
||||
- **Keine pauschalen Refactors:** Nur Änderungen mit **klarem** Träger für das Parallel-Feature oder mit **Test-Regression-Schutz**.
|
||||
- **Regeln:** `.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht wo relevant.
|
||||
|
||||
## Erwartete Ausgabe
|
||||
|
||||
1. Kurze **Liste erledigter Vorarbeiten** (Dateien, was warum).
|
||||
2. **Empfohlene Reihenfolge** für die **nächste** Session, die Phasen/Streams **implementiert** (verweis auf `PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md` Pakete 0–2).
|
||||
3. Falls nichts Sinnvolles ohne Feature-Branch riskiert werden kann: **explizit** „keine Code-Änderung“, nur Risiko-Notiz.
|
||||
|
||||
## Optionaler Startbefehl
|
||||
|
||||
```
|
||||
Lies zuerst:
|
||||
.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md
|
||||
dann backend/routers/training_planning.py (Abschnitte um _fetch_sections, _replace_unit_sections).
|
||||
```
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Bezug:** `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (Kopf „V3“, inkl. **§ 10.2.1**, **§ 10.4 Coaching-Stufen**, **Anhang A** Implementierungsabgleich — Drift-Schutz)
|
||||
**Technische Entwurfsspezifikation:** `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`
|
||||
**Stand dieses Dokuments:** 2026-05-12 (Abgleich mit Code App **0.8.110**, siehe `backend/version.py`)
|
||||
**Stand dieses Dokuments:** 2026-05-20 (Abgleich mit Code, siehe `backend/version.py`)
|
||||
|
||||
## Ziele
|
||||
|
||||
@@ -12,7 +12,7 @@ Umsetzung der MVP-Punkte aus der Fachspezifikation ohne die bestehende Planung z
|
||||
|
||||
| Phase | Inhalt | Status |
|
||||
|-------|--------|--------|
|
||||
| **1** | **Trainingsmodule (Bibliothek):** Tabellen `training_modules`, `training_module_items`; REST CRUD mit Governance wie andere Bibliotheken; Übernahme in eine bestehende Einheit per `POST /api/training-units/{id}/apply-training-module` (Anfügen ans Ende eines Abschnitts via `section_order_index`); optionale Lineage-Spalte `source_training_module_id` auf Planungsitems; UI: Liste/Editor unter `/planning/training-modules`, Link von der Planung, Modal „Modul übernehmen“ | **umgesetzt (MVP Schritt 1)** |
|
||||
| **1** | **Trainingsmodule (Bibliothek):** Tabellen `training_modules`, `training_module_items`; REST CRUD mit Governance wie andere Bibliotheken; Übernahme in eine bestehende Einheit per `POST /api/training-units/{id}/apply-training-module` (Anfügen ans Ende eines Abschnitts via `section_order_index`); optionale Lineage-Spalte `source_training_module_id` auf Planungsitems; UI: Liste/Editor unter `/planning/training-modules`, Link von der Planung, Modal „Modul übernehmen“; **Ergänzung 2026-05-20:** Fähigkeiten-Profil + Listen-Filter (Peer-Vergleich nur unter Modulen) — `technical/SKILL_SCORING_SPEC.md` | **umgesetzt (MVP Schritt 1)** |
|
||||
| **2** | Kombinationsübungen: `exercise_kind`/`combination_*`, Slots, Pools, `method_archetype`, `method_profile` (JSON) | **teilweise** — wie links; zusätzlich **057** `planning_method_profile`; Planungs-Merge Client (`effectiveComboMethodProfile`); Archetypen weiterhin **nur Code-Konstanten** (kein Admin) | **Offen:** Archetyp-Admin-UI; Profil↔Archetyp-Validierung Backend; „alle Slots vorbelegen“ / Presets (siehe Fachspez **§ 10.6**); Haupt-/Nebenmethoden an Kombi wo Spec es verlangt |
|
||||
| **3** | Planungsblöcke: Gruppierung, Auflösen, „als Modul speichern“, erweiterter Übernahmemodus (Zwischenposition) | geplant |
|
||||
| **4** | Coaching: Archetyp-Support | **teilweise:** **Stufe A** — Merge Katalog+Planung; `CombinationPlanBracket` in Peek/Run; globale Profilzahlen mit Labels (`describeGlobalComboProfile`); Stations-/Timing-Zusammenfassung inkl. Wdh.-Hinweise. **Stufe B/C** — **offen** (§ 10.6, Anhang A) |
|
||||
|
||||
@@ -10,7 +10,7 @@ on:
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
# Wie Mitai-Jinkendo: pytest im laufenden backend-Container (Python aus Image, gleiche DB wie Deploy).
|
||||
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
||||
pytest-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
cd /app &&
|
||||
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
|
||||
python scripts/security_release_checks.py &&
|
||||
ACCESS_LAYER_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
ACCESS_LAYER_INTEGRATION=1 TRAINING_PLANNING_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
|
||||
"
|
||||
|
||||
lint-backend:
|
||||
@@ -88,6 +88,90 @@ jobs:
|
||||
npm run build
|
||||
echo "✓ Frontend build OK"
|
||||
|
||||
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
||||
k6-health-baseline:
|
||||
name: k6 /health Baseline
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
||||
id: e2e
|
||||
run: |
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Prod-Basis."
|
||||
else
|
||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "→ k6 gegen Dev (${DEV_BASE})."
|
||||
fi
|
||||
|
||||
- name: Dev /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Prod /health abwarten
|
||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
||||
run: |
|
||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
||||
echo "Warte auf $BASE/health …"
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "Timeout: Prod /health nicht erreichbar"
|
||||
curl -v "$BASE/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Install k6
|
||||
run: |
|
||||
set -e
|
||||
K6_VER="v0.55.0"
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64) K6_ARCH=amd64 ;;
|
||||
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
|
||||
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||
tar -xzf /tmp/k6.tgz -C /tmp
|
||||
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||
k6 version
|
||||
|
||||
- name: k6 Health-Baseline (parallele /health)
|
||||
env:
|
||||
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
||||
run: |
|
||||
set -e
|
||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||
k6 run scripts/load/k6-health-baseline.js
|
||||
echo "✓ k6 Health-Baseline passed"
|
||||
|
||||
playwright-tests:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -12,8 +12,11 @@
|
||||
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
|
||||
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
> | Fähigkeiten-Scoring (Planungs-Bausteine) | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
|
||||
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
|
||||
> | Fachlicher Nutzerüberblick (Design/Product) | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
||||
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
@@ -84,10 +87,11 @@ frontend/src/
|
||||
|
||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||
|
||||
Kurz (Stand 2026-05-12): App **0.8.96**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
|
||||
Kurz (Stand 2026-05-14): App- und DB-Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit **Phasen & parallelen Streams (Breakout, 063)**, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `PARALLEL_TRAINING_STREAMS_SPEC.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
|
||||
|
||||
### Log (Auszug)
|
||||
|
||||
- 2026-05-20: **Fähigkeiten-Scoring Phase 3** — gewichtete Profile für Module/Rahmen/Pfade; Peer-Vergleich getrennt nach Artefakttyp; Listen-Filter + Discovery — siehe `SKILL_SCORING_SPEC.md`, `docs/HANDOVER.md` §2.6, `FEATURES_DELIVERED_2026-Q2.md` §15.
|
||||
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
|
||||
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
|
||||
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
|
||||
|
||||
+160
-1
@@ -3,7 +3,7 @@ Vereins-Mandanten: Mitgliedschaften, aktiver Vereinskontext, einfache Berechtigu
|
||||
|
||||
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
from typing import Any, Dict, List, Mapping, Optional, Set, Union
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
@@ -155,6 +155,165 @@ def club_ids_for_profile_with_roles(cur, profile_id: int, *role_codes: str) -> S
|
||||
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
|
||||
|
||||
|
||||
def _library_governance_triplet(
|
||||
row: Mapping[str, Any],
|
||||
) -> tuple[str, Optional[int], Optional[int]]:
|
||||
"""visibility, club_id, created_by als normalisierte Werte für Bibliotheks-/Planungsartefakte."""
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
if vis not in _GOVERNANCE_VISIBILITY:
|
||||
vis = "private"
|
||||
cid_raw = row.get("club_id")
|
||||
try:
|
||||
ex_cid = int(cid_raw) if cid_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
ex_cid = None
|
||||
cr_raw = row.get("created_by")
|
||||
try:
|
||||
creator = int(cr_raw) if cr_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
creator = None
|
||||
return vis, ex_cid, creator
|
||||
|
||||
|
||||
def assert_library_content_editable(
|
||||
cur,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||
) -> None:
|
||||
"""Inhalt bearbeiten: wie Übungen — Ersteller, Plattform-Admin oder Planungsberechtigter im Verein."""
|
||||
pid = int(profile_id)
|
||||
ex_vis, ex_cid, creator = _library_governance_triplet(row)
|
||||
if creator is not None and creator == pid:
|
||||
return
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, pid, ex_cid, role):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Bearbeiten dieses Inhalts")
|
||||
|
||||
|
||||
def assert_library_content_deletable(
|
||||
cur,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||
) -> None:
|
||||
"""Löschen: wie Übungen — privat Eigentümer/Vereins-Admin-Kontext, Verein nur Vereinsadmin, offiziell nur Plattform."""
|
||||
pid = int(profile_id)
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis, cid, creator = _library_governance_triplet(row)
|
||||
try:
|
||||
creator_int = int(creator) if creator is not None else None
|
||||
except (TypeError, ValueError):
|
||||
creator_int = None
|
||||
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Offizielle Inhalte dürfen nur von Plattform-Admins gelöscht werden.",
|
||||
)
|
||||
if vis == "club":
|
||||
try:
|
||||
ex_club = int(cid) if cid is not None else None
|
||||
except (TypeError, ValueError):
|
||||
ex_club = None
|
||||
if ex_club is None:
|
||||
raise HTTPException(status_code=400, detail="Vereinsinhalt ohne gültige Vereinszuordnung")
|
||||
if not has_club_role(cur, pid, ex_club, "club_admin"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Vereins-Admins dürfen Vereins-Inhalte löschen.",
|
||||
)
|
||||
return
|
||||
|
||||
if creator_int is not None and creator_int == pid:
|
||||
return
|
||||
if creator_int is not None and club_admin_shares_club_with_creator(cur, pid, creator_int):
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Löschen dieses Inhalts")
|
||||
|
||||
|
||||
def assert_library_content_governance_transition(
|
||||
cur,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
prev_row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||
next_visibility: str,
|
||||
next_club_id: Optional[int],
|
||||
) -> None:
|
||||
"""
|
||||
Zusätzliche Regeln beim Ändern von visibility/club_id (Zielzustand vor assert_valid_governance_visibility prüfen).
|
||||
|
||||
- Abwahl „official“: nur Plattform-Admin.
|
||||
- private → club: nur Ersteller (oder Plattform-Admin).
|
||||
- club → private: Ersteller, Vereinsadmin im bisherigen Verein oder Plattform-Admin.
|
||||
- club → club mit Wechsel club_id: Vereinsadmin im alten oder neuen Verein oder Plattform-Admin.
|
||||
"""
|
||||
nv = str(next_visibility or "").strip().lower()
|
||||
if nv not in _GOVERNANCE_VISIBILITY:
|
||||
raise HTTPException(status_code=400, detail="Ungültige visibility")
|
||||
|
||||
old_vis, old_cid, creator = _library_governance_triplet(prev_row)
|
||||
new_cid: Optional[int]
|
||||
try:
|
||||
new_cid = int(next_club_id) if next_club_id is not None else None
|
||||
except (TypeError, ValueError):
|
||||
new_cid = None
|
||||
|
||||
pid = int(profile_id)
|
||||
try:
|
||||
creator_int = int(creator) if creator is not None else None
|
||||
except (TypeError, ValueError):
|
||||
creator_int = None
|
||||
|
||||
if old_vis == nv and (nv != "club" or old_cid == new_cid):
|
||||
return
|
||||
|
||||
if old_vis == "official" and nv != "official":
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Plattform-Admins dürfen offizielle Inhalte auf Verein oder privat setzen.",
|
||||
)
|
||||
|
||||
if nv == "official":
|
||||
return
|
||||
|
||||
if old_vis == "private" and nv == "club":
|
||||
if creator_int is not None and creator_int != pid and not is_platform_admin(role):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur der Ersteller darf private Inhalte für den Verein freigeben.",
|
||||
)
|
||||
return
|
||||
|
||||
if old_vis == "club" and nv == "private":
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if creator_int is not None and creator_int == pid:
|
||||
return
|
||||
if old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin"):
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Ersteller, Vereins-Admins oder Plattform-Admins dürfen Vereins-Inhalte auf privat setzen.",
|
||||
)
|
||||
|
||||
if old_vis == "club" and nv == "club" and old_cid != new_cid:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
ok_old = old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin")
|
||||
ok_new = new_cid is not None and has_club_role(cur, pid, new_cid, "club_admin")
|
||||
if ok_old or ok_new:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Vereins-Admins oder Plattform-Admins dürfen die Vereinszuordnung ändern.",
|
||||
)
|
||||
|
||||
|
||||
def assert_valid_governance_visibility(
|
||||
cur,
|
||||
profile_id: int,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Hilfen für direkte Python-Aufrufe von FastAPI-Route-Handlern (ohne Request-Kontext)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def unwrap_query_default(value: Any) -> Any:
|
||||
"""
|
||||
Parameter mit Annotation ``= Query(default=…)`` sind im Funktionskörper ``fastapi.params.Query``-Instanzen,
|
||||
solange FastAPI sie nicht durch echte Werte ersetzt hat (interne Aufrufe, Aggregat-Endpunkte).
|
||||
"""
|
||||
try:
|
||||
from fastapi.params import Query
|
||||
except ImportError:
|
||||
return value
|
||||
return value.default if isinstance(value, Query) else value
|
||||
+3
-1
@@ -193,7 +193,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, skill_profiles, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -208,7 +208,9 @@ app.include_router(media_assets.router)
|
||||
app.include_router(media_assets.admin_rights_router)
|
||||
app.include_router(media_assets.admin_legal_hold_router)
|
||||
app.include_router(skills.router)
|
||||
app.include_router(skill_profiles.router)
|
||||
app.include_router(training_planning.router)
|
||||
app.include_router(dashboard.router)
|
||||
app.include_router(training_modules.router)
|
||||
app.include_router(training_framework_programs.router)
|
||||
app.include_router(catalogs.router)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Unterstützung für GET /api/exercises: ORDER BY e.updated_at DESC
|
||||
-- und häufiger Pfad created_by_me (= e.created_by = Profil) mit derselben Sortierung.
|
||||
-- Hinweis: idx_exercises_created_at (014) betrifft created_at, nicht updated_at.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_updated_at_desc ON exercises (updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_created_by_updated_at_desc ON exercises (created_by, updated_at DESC);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- GET /api/training-units: Liste nutzt immer tu.framework_slot_id IS NULL (keine Rahmen-Blueprints)
|
||||
-- und sortiert nach planned_date, planned_time_start (ASC/DESC mit NULLS LAST).
|
||||
-- Teilindex verkleinert die Menge und unterstützt die Sortierung.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_scheduled_order
|
||||
ON training_units (planned_date DESC, planned_time_start DESC NULLS LAST)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Migration 060: Übungslisten bei großem Bestand (Ziel: Tausende Übungen, viele Filterkombinationen).
|
||||
-- Ergänzt 058 (globale Sortierung / created_by): kleinere Partial-Indizes für häufige
|
||||
-- Sichtbarkeits-Pfade der Bibliothek sowie Junction-Indizes für die List-Subqueries
|
||||
-- (primary_focus_name / JSON-Aggregate mit is_primary).
|
||||
--
|
||||
-- Bereits vorhanden und sinnvoll: UNIQUE(exercise_id, …) auf den M:N-Tabellen für EXISTS-Joins;
|
||||
-- GIN auf exercises.search_vector (014); idx_exercises_exercise_kind (056).
|
||||
|
||||
-- Official: OR-Zweig der Bibliothek — kompakter als Full-Table-Scan bei BitmapOr mit anderen Partial-Indizes
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_list_official_updated
|
||||
ON exercises (updated_at DESC)
|
||||
WHERE visibility = 'official'
|
||||
AND COALESCE(status, '') <> 'archived';
|
||||
|
||||
-- Club: häufig club_id + Sortierung nach updated_at (Mandanten-Bibliothek)
|
||||
CREATE INDEX IF NOT EXISTS idx_exercises_list_club_updated
|
||||
ON exercises (club_id, updated_at DESC)
|
||||
WHERE visibility = 'club'
|
||||
AND club_id IS NOT NULL
|
||||
AND COALESCE(status, '') <> 'archived';
|
||||
|
||||
-- List-SELECT: Subqueries / json_agg sortieren zuerst nach is_primary (siehe exercises.py)
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_exercise_primary
|
||||
ON exercise_focus_areas (exercise_id, is_primary DESC NULLS LAST, focus_area_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_style_directions_exercise_primary
|
||||
ON exercise_style_directions (exercise_id, is_primary DESC NULLS LAST, style_direction_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_training_types_exercise_primary
|
||||
ON exercise_training_types (exercise_id, is_primary DESC NULLS LAST, training_type_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_exercise_primary
|
||||
ON exercise_target_groups (exercise_id, is_primary DESC NULLS LAST, target_group_id);
|
||||
@@ -0,0 +1,22 @@
|
||||
-- GET /api/training-units: Keyset über (planned_date, planned_time_start NULLS LAST per Sort, id)
|
||||
-- Ersetzt den reinen Datum/Uhrzeit-Teilindex 059 durch zwei Richtungen mit Tie-Break id.
|
||||
|
||||
DROP INDEX IF EXISTS idx_training_units_scheduled_order;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_desc
|
||||
ON training_units (
|
||||
planned_date DESC,
|
||||
(planned_time_start IS NULL) ASC,
|
||||
planned_time_start DESC NULLS LAST,
|
||||
id DESC
|
||||
)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_asc
|
||||
ON training_units (
|
||||
planned_date ASC,
|
||||
(planned_time_start IS NULL) ASC,
|
||||
planned_time_start ASC NULLS LAST,
|
||||
id ASC
|
||||
)
|
||||
WHERE framework_slot_id IS NULL;
|
||||
@@ -0,0 +1,41 @@
|
||||
-- list_exercises mit skill_min_level / skill_max_level: EXISTS auf exercise_skills mit numerischem Stufen-Rang.
|
||||
-- Ausdruck muss mit backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL (Alias „es“) übereinstimmen.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_skills_exercise_level_rank
|
||||
ON exercise_skills (
|
||||
exercise_id,
|
||||
(CASE COALESCE(
|
||||
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||
)
|
||||
WHEN 'basis' THEN 1
|
||||
WHEN 'grundlagen' THEN 2
|
||||
WHEN 'aufbau' THEN 3
|
||||
WHEN 'fortgeschritten' THEN 4
|
||||
WHEN 'optimierung' THEN 5
|
||||
WHEN 'einsteiger' THEN 1
|
||||
WHEN 'experte' THEN 5
|
||||
WHEN '1' THEN 1
|
||||
WHEN '2' THEN 2
|
||||
WHEN '3' THEN 3
|
||||
WHEN '4' THEN 4
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END)
|
||||
)
|
||||
WHERE (CASE COALESCE(
|
||||
NULLIF(TRIM(LOWER(target_level::text)), ''),
|
||||
NULLIF(TRIM(LOWER(required_level::text)), '')
|
||||
)
|
||||
WHEN 'basis' THEN 1
|
||||
WHEN 'grundlagen' THEN 2
|
||||
WHEN 'aufbau' THEN 3
|
||||
WHEN 'fortgeschritten' THEN 4
|
||||
WHEN 'optimierung' THEN 5
|
||||
WHEN 'einsteiger' THEN 1
|
||||
WHEN 'experte' THEN 5
|
||||
WHEN '1' THEN 1
|
||||
WHEN '2' THEN 2
|
||||
WHEN '3' THEN 3
|
||||
WHEN '4' THEN 4
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END) IS NOT NULL;
|
||||
@@ -0,0 +1,85 @@
|
||||
-- Migration 063: Phasen und parallele Streams pro Trainingseinheit (Grundlage Breakout).
|
||||
-- Bestehende Sektionen werden einer Default-whole_group-Phase zugeordnet.
|
||||
-- UNIQUE (training_unit_id, order_index) auf Sektionen entfällt zugunsten
|
||||
-- eindeutiger order_index je Phase bzw. je parallel_stream.
|
||||
|
||||
-- ── Phasen ───────────────────────────────────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_unit_phases (
|
||||
id SERIAL PRIMARY KEY,
|
||||
training_unit_id INT NOT NULL REFERENCES training_units(id) ON DELETE CASCADE,
|
||||
order_index INT NOT NULL,
|
||||
phase_kind VARCHAR(20) NOT NULL CHECK (phase_kind IN ('whole_group', 'parallel')),
|
||||
title VARCHAR(200),
|
||||
guidance_notes TEXT,
|
||||
UNIQUE (training_unit_id, order_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_phases_unit ON training_unit_phases(training_unit_id);
|
||||
|
||||
-- ── Streams innerhalb einer Parallelphase ──────────────────────────────────
|
||||
CREATE TABLE IF NOT EXISTS training_unit_parallel_streams (
|
||||
id SERIAL PRIMARY KEY,
|
||||
phase_id INT NOT NULL REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||
order_index INT NOT NULL,
|
||||
title VARCHAR(200),
|
||||
notes TEXT,
|
||||
assigned_trainer_profile_ids JSONB,
|
||||
UNIQUE (phase_id, order_index)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_parallel_streams_phase
|
||||
ON training_unit_parallel_streams(phase_id);
|
||||
|
||||
COMMENT ON COLUMN training_unit_parallel_streams.assigned_trainer_profile_ids IS
|
||||
'Optionale Co-Trainer-IDs (JSON-Array von Profil-IDs) für diese Teilstrecke; MVP+';
|
||||
|
||||
-- ── Sektionen: Zuordnung zu Phase (gemeinsam) oder Stream (parallel) ─────
|
||||
ALTER TABLE training_unit_sections
|
||||
ADD COLUMN IF NOT EXISTS phase_id INT REFERENCES training_unit_phases(id) ON DELETE CASCADE,
|
||||
ADD COLUMN IF NOT EXISTS parallel_stream_id INT REFERENCES training_unit_parallel_streams(id) ON DELETE CASCADE;
|
||||
|
||||
-- Backfill: je Einheit mit Sektionen eine whole_group-Phase, alle Sektionen dorthin
|
||||
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title)
|
||||
SELECT tu.id, 0, 'whole_group', NULL
|
||||
FROM training_units tu
|
||||
WHERE EXISTS (SELECT 1 FROM training_unit_sections s WHERE s.training_unit_id = tu.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM training_unit_phases p
|
||||
WHERE p.training_unit_id = tu.id AND p.order_index = 0 AND p.phase_kind = 'whole_group'
|
||||
);
|
||||
|
||||
UPDATE training_unit_sections tus
|
||||
SET phase_id = p.id
|
||||
FROM training_unit_phases p
|
||||
WHERE tus.phase_id IS NULL
|
||||
AND p.training_unit_id = tus.training_unit_id
|
||||
AND p.order_index = 0
|
||||
AND p.phase_kind = 'whole_group';
|
||||
|
||||
-- Alte globale Reihenfolge-Eindeutigkeit pro Einheit entfernen
|
||||
ALTER TABLE training_unit_sections
|
||||
DROP CONSTRAINT IF EXISTS training_unit_sections_training_unit_id_order_index_key;
|
||||
|
||||
-- Genau eine Zielspalte gesetzt: gemeinsame Phase ODER paralleler Stream
|
||||
ALTER TABLE training_unit_sections
|
||||
DROP CONSTRAINT IF EXISTS training_unit_sections_phase_or_stream_chk;
|
||||
|
||||
ALTER TABLE training_unit_sections
|
||||
ADD CONSTRAINT training_unit_sections_phase_or_stream_chk CHECK (
|
||||
(phase_id IS NOT NULL AND parallel_stream_id IS NULL)
|
||||
OR (phase_id IS NULL AND parallel_stream_id IS NOT NULL)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_phase_order
|
||||
ON training_unit_sections (phase_id, order_index)
|
||||
WHERE phase_id IS NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_stream_order
|
||||
ON training_unit_sections (parallel_stream_id, order_index)
|
||||
WHERE parallel_stream_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_phase
|
||||
ON training_unit_sections(phase_id) WHERE phase_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_parallel_stream
|
||||
ON training_unit_sections(parallel_stream_id) WHERE parallel_stream_id IS NOT NULL;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Vorlagen: Phasen/Parallel-Streams wie im Einheiten-Editor (planLoc-Abbild)
|
||||
ALTER TABLE training_plan_template_sections
|
||||
ADD COLUMN IF NOT EXISTS phase_kind VARCHAR(20) NOT NULL DEFAULT 'whole_group',
|
||||
ADD COLUMN IF NOT EXISTS phase_order_index INT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS parallel_stream_order_index INT NULL;
|
||||
|
||||
COMMENT ON COLUMN training_plan_template_sections.parallel_stream_order_index IS
|
||||
'NULL = Ganzgruppen-Abschnitt; 0..n = Stream innerhalb paralleler Phase';
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Migration 065: Wiki-spezifische Felder fuer Fähigkeiten (KarateRelevanz, RelevanzLevel)
|
||||
-- SMW karatetrainer.net; Import mappt in strukturierte Spalten statt nur Freitext in description
|
||||
|
||||
ALTER TABLE skills
|
||||
ADD COLUMN IF NOT EXISTS karate_relevance TEXT;
|
||||
|
||||
ALTER TABLE skills
|
||||
ADD COLUMN IF NOT EXISTS relevance_level SMALLINT CHECK (relevance_level IS NULL OR relevance_level BETWEEN 1 AND 3);
|
||||
|
||||
COMMENT ON COLUMN skills.karate_relevance IS 'Wiki Karate-Relevanz (Plaintext aus SMW Property KarateRelevanz)';
|
||||
COMMENT ON COLUMN skills.relevance_level IS 'Wiki-RelevanzLevel 1–3 (Semantic MediaWiki)';
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Geplante Gesamt- und Abschnittsdauer; Rahmenprogramm: Fokus/Stil als M:N (wie Trainingsarten/Zielgruppen)
|
||||
|
||||
ALTER TABLE training_units
|
||||
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
|
||||
|
||||
ALTER TABLE training_unit_sections
|
||||
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
|
||||
|
||||
ALTER TABLE training_plan_template_sections
|
||||
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_framework_program_focus_areas (
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (framework_program_id, focus_area_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tfpfa_focus ON training_framework_program_focus_areas(focus_area_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_framework_program_style_directions (
|
||||
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
|
||||
style_direction_id INT NOT NULL REFERENCES style_directions(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (framework_program_id, style_direction_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tfpsd_style ON training_framework_program_style_directions(style_direction_id);
|
||||
|
||||
INSERT INTO training_framework_program_focus_areas (framework_program_id, focus_area_id)
|
||||
SELECT id, focus_area_id FROM training_framework_programs
|
||||
WHERE focus_area_id IS NOT NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO training_framework_program_style_directions (framework_program_id, style_direction_id)
|
||||
SELECT id, style_direction_id FROM training_framework_programs
|
||||
WHERE style_direction_id IS NOT NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
@@ -117,6 +117,8 @@ class SkillCreate(BaseModel):
|
||||
description: Optional[str] = None
|
||||
importance: Optional[int] = Field(None, ge=1, le=5)
|
||||
keywords: Optional[List[str]] = []
|
||||
karate_relevance: Optional[str] = None
|
||||
relevance_level: Optional[int] = Field(None, ge=1, le=3)
|
||||
|
||||
class SkillResponse(BaseModel):
|
||||
id: int
|
||||
@@ -125,6 +127,8 @@ class SkillResponse(BaseModel):
|
||||
description: Optional[str]
|
||||
importance: Optional[int]
|
||||
keywords: Optional[List[str]]
|
||||
karate_relevance: Optional[str] = None
|
||||
relevance_level: Optional[int] = None
|
||||
status: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
+1
-1
@@ -6,5 +6,5 @@ python_functions = test_*
|
||||
addopts = -q --tb=short
|
||||
markers =
|
||||
smoke: Schnelle Kern-Regression.
|
||||
integration: PostgreSQL-Mandanten-Integration (ACCESS_LAYER_INTEGRATION=1).
|
||||
integration: PostgreSQL-Integration (z. B. ACCESS_LAYER_INTEGRATION=1, TRAINING_PLANNING_INTEGRATION=1).
|
||||
slow: Lange/schwere Tests; in CI wie Mitai-Jinkendo ausgeschlossen (Auswahl: not slow).
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
Dashboard: zusammengefasste Kennzahlen (ein Roundtrip statt mehrerer Listen).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
from routers.exercises import list_exercises_like_get
|
||||
from routers.training_planning import list_training_units
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["dashboard"])
|
||||
|
||||
|
||||
def _slice_training_home_notes(planned_pool: List[Dict[str, Any]], max_notes: int = 5) -> List[Dict[str, Any]]:
|
||||
out = []
|
||||
for u in planned_pool:
|
||||
tn = (u.get("trainer_notes") or "").strip()
|
||||
n = (u.get("notes") or "").strip()
|
||||
if tn or n:
|
||||
out.append(u)
|
||||
if len(out) >= max_notes:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/dashboard/kpis")
|
||||
def get_dashboard_kpis(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
"""
|
||||
Kurzüberblick: Übungs-KPIs + YTD-Einheiten + Trainings-Home (nächste Termine, Vermerke, offene Rückschau)
|
||||
in einem Roundtrip — gleiche Filter wie zuvor im Dashboard (mehrere Client-Calls).
|
||||
"""
|
||||
year = date.today().year
|
||||
year_start = f"{year}-01-01"
|
||||
year_end = f"{year}-12-31"
|
||||
today = date.today().isoformat()
|
||||
|
||||
draft_list = list_exercises_like_get(
|
||||
tenant, created_by_me=True, status="draft", limit=100
|
||||
)
|
||||
mine_list = list_exercises_like_get(
|
||||
tenant, created_by_me=True, status=None, limit=100
|
||||
)
|
||||
ytd_completed = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=year_start,
|
||||
end_date=year_end,
|
||||
status="completed",
|
||||
assigned_to_me=True,
|
||||
debrief_pending=False,
|
||||
sort="desc",
|
||||
limit=250,
|
||||
tenant=tenant,
|
||||
)
|
||||
planned_pool = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=today,
|
||||
end_date=None,
|
||||
status="planned",
|
||||
assigned_to_me=True,
|
||||
debrief_pending=False,
|
||||
sort="asc",
|
||||
limit=40,
|
||||
tenant=tenant,
|
||||
)
|
||||
review_pending = list_training_units(
|
||||
group_id=None,
|
||||
club_id=None,
|
||||
start_date=None,
|
||||
end_date=None,
|
||||
status=None,
|
||||
assigned_to_me=True,
|
||||
debrief_pending=True,
|
||||
sort="desc",
|
||||
limit=8,
|
||||
tenant=tenant,
|
||||
)
|
||||
|
||||
draft_preview = [
|
||||
{"id": int(ex["id"]), "title": ex.get("title") or f"Übung #{ex['id']}"}
|
||||
for ex in draft_list[:8]
|
||||
]
|
||||
|
||||
return {
|
||||
"year": year,
|
||||
"draft_count": len(draft_list),
|
||||
"draft_capped": len(draft_list) >= 100,
|
||||
"draft_preview": draft_preview,
|
||||
"mine_count": len(mine_list),
|
||||
"mine_capped": len(mine_list) >= 100,
|
||||
"ytd_completed_count": len(ytd_completed),
|
||||
"ytd_capped": len(ytd_completed) >= 250,
|
||||
"training_home": {
|
||||
"upcoming": planned_pool[:8],
|
||||
"planned_with_notes": _slice_training_home_notes(planned_pool),
|
||||
"review_pending": review_pending,
|
||||
},
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
|
||||
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
||||
AuthZ analog training_plan_templates (_template_access / _has_planning_role).
|
||||
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
|
||||
"""
|
||||
from typing import Any, List, Optional
|
||||
|
||||
@@ -12,8 +12,10 @@ from psycopg2 import IntegrityError
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
from club_tenancy import (
|
||||
assert_library_content_deletable,
|
||||
assert_library_content_editable,
|
||||
assert_library_content_governance_transition,
|
||||
assert_valid_governance_visibility,
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
|
||||
@@ -111,13 +113,7 @@ def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||
|
||||
|
||||
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
created_by = row.get("created_by")
|
||||
if created_by is not None:
|
||||
created_by = int(created_by)
|
||||
if created_by != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
||||
assert_library_content_editable(cur, profile_id, role, row)
|
||||
|
||||
|
||||
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||
@@ -333,6 +329,7 @@ def update_progression_graph(
|
||||
)
|
||||
|
||||
gov_club = next_club if next_vis == "club" else None
|
||||
assert_library_content_governance_transition(cur, profile_id, role, row, next_vis, gov_club)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
|
||||
|
||||
fields: List[str] = []
|
||||
@@ -376,7 +373,9 @@ def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_require_graph_write(cur, graph_id, profile_id, role)
|
||||
row = _graph_row(cur, graph_id)
|
||||
_assert_graph_readable(cur, row, profile_id, role)
|
||||
assert_library_content_deletable(cur, profile_id, role, row)
|
||||
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@@ -9,6 +9,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple
|
||||
from urllib.parse import quote
|
||||
@@ -18,6 +19,8 @@ from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from fastapi_param_unwrap import unwrap_query_default
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from club_tenancy import (
|
||||
assert_valid_governance_visibility,
|
||||
@@ -96,6 +99,7 @@ CASE COALESCE(
|
||||
WHEN '5' THEN 5
|
||||
ELSE NULL END
|
||||
""".strip()
|
||||
# Bei Änderung: Migration 062 idx_exercise_skills_exercise_level_rank (SQL-Ausdruck) synchron halten.
|
||||
|
||||
|
||||
def normalize_exercise_skill_level(value) -> Optional[str]:
|
||||
@@ -109,6 +113,25 @@ def normalize_exercise_skill_level(value) -> Optional[str]:
|
||||
return s
|
||||
return _LEGACY_SKILL_LEVEL_SLUG.get(s)
|
||||
|
||||
|
||||
_ALLOWED_SKILL_INTENSITY = frozenset({"niedrig", "mittel", "hoch"})
|
||||
|
||||
|
||||
def normalize_exercise_skill_intensity(value) -> str:
|
||||
"""Kanonische Nutzeneinschätzung; leer/ungültig → mittel (kein leerer Wert)."""
|
||||
if value is None:
|
||||
return "mittel"
|
||||
key = str(value).strip().lower()
|
||||
if key in ("low",):
|
||||
return "niedrig"
|
||||
if key in ("medium",):
|
||||
return "mittel"
|
||||
if key in ("high",):
|
||||
return "hoch"
|
||||
if key in _ALLOWED_SKILL_INTENSITY:
|
||||
return key
|
||||
return "mittel"
|
||||
|
||||
MEDIA_ROOT = Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent.parent / "media")))
|
||||
MAX_EXERCISE_MEDIA = 10
|
||||
# Upload-Limits (Übungs-Medien): Trainer wie bisher kleiner; Admin/Superadmin höheres Limit für große Videos
|
||||
@@ -1098,13 +1121,15 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
FROM exercise_skills es
|
||||
JOIN skills s ON es.skill_id = s.id
|
||||
WHERE es.exercise_id = %s
|
||||
ORDER BY es.is_primary DESC, s.name""",
|
||||
ORDER BY s.name""",
|
||||
(exercise_id,)
|
||||
)
|
||||
exercise["skills"] = [r2d(r) for r in cur.fetchall()]
|
||||
for sk in exercise["skills"]:
|
||||
sk["required_level"] = normalize_exercise_skill_level(sk.get("required_level"))
|
||||
sk["target_level"] = normalize_exercise_skill_level(sk.get("target_level"))
|
||||
sk["intensity"] = normalize_exercise_skill_intensity(sk.get("intensity"))
|
||||
sk["is_primary"] = False
|
||||
|
||||
# Variants (1:N) - mit Progression (Reihenfolge: sequence_order, dann progression_level)
|
||||
cur.execute(
|
||||
@@ -1219,8 +1244,8 @@ def assign_exercise_relations(
|
||||
(
|
||||
exercise_id,
|
||||
skill["skill_id"],
|
||||
skill.get("is_primary", False),
|
||||
skill.get("intensity"),
|
||||
False,
|
||||
normalize_exercise_skill_intensity(skill.get("intensity")),
|
||||
normalize_exercise_skill_level(skill.get("required_level")),
|
||||
normalize_exercise_skill_level(skill.get("target_level")),
|
||||
skill.get("ai_suggested", False),
|
||||
@@ -1653,6 +1678,20 @@ def bulk_patch_exercises_metadata(
|
||||
}
|
||||
|
||||
|
||||
def _parse_cursor_updated_at_list(raw: Optional[str]) -> datetime:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
raise HTTPException(status_code=400, detail="cursor_updated_at leer")
|
||||
if s.endswith("Z"):
|
||||
s = s[:-1] + "+00:00"
|
||||
try:
|
||||
return datetime.fromisoformat(s)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="cursor_updated_at ungültig (ISO-8601 erwartet)"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises")
|
||||
def list_exercises(
|
||||
focus_area_ids: list[int] = Query(default=[], description="ODER: mind. einer dieser Fokusbereiche"),
|
||||
@@ -1678,6 +1717,15 @@ def list_exercises(
|
||||
),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
cursor_updated_at: Optional[str] = Query(
|
||||
default=None,
|
||||
description="Keyset: ISO-8601 von updated_at der letzten Zeile; zusammen mit cursor_id (offset dann 0)",
|
||||
),
|
||||
cursor_id: Optional[int] = Query(
|
||||
default=None,
|
||||
ge=1,
|
||||
description="Keyset: id der letzten Zeile (Tie‑break bei gleichem updated_at); mit cursor_updated_at",
|
||||
),
|
||||
include_variants: bool = Query(
|
||||
default=False,
|
||||
description="Wenn true: Feld variants[] pro Übung (id, variant_name, sequence_order) für Planung/UI",
|
||||
@@ -1746,9 +1794,31 @@ def list_exercises(
|
||||
Liste aller Übungen mit Filtern.
|
||||
Lightweight Response (ohne M:N Details, nur IDs und Namen).
|
||||
Optional include_variants für Variantenauswahl in der Trainingsplanung.
|
||||
Keyset: cursor_updated_at + cursor_id ersetzt große OFFSET-Werte (Sortierung: updated_at DESC, id DESC).
|
||||
"""
|
||||
cursor_updated_at = unwrap_query_default(cursor_updated_at)
|
||||
cursor_id = unwrap_query_default(cursor_id)
|
||||
limit = unwrap_query_default(limit)
|
||||
offset = unwrap_query_default(offset)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
|
||||
c_ts_raw = (cursor_updated_at or "").strip() or None
|
||||
use_keyset = c_ts_raw is not None and cursor_id is not None
|
||||
if (c_ts_raw is not None) != (cursor_id is not None):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="cursor_updated_at und cursor_id müssen zusammen gesetzt werden",
|
||||
)
|
||||
if use_keyset and offset != 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Keyset-Pagination: offset nicht kombinieren (nur cursor_* oder nur offset)",
|
||||
)
|
||||
cursor_ts_val: Optional[datetime] = None
|
||||
if use_keyset:
|
||||
cursor_ts_val = _parse_cursor_updated_at_list(c_ts_raw)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
@@ -1981,6 +2051,12 @@ def list_exercises(
|
||||
where.append("e.search_vector @@ plainto_tsquery('german', %s)")
|
||||
params.append(qtext)
|
||||
|
||||
if cursor_ts_val is not None and cursor_id is not None:
|
||||
where.append(
|
||||
"(e.updated_at < %s OR (e.updated_at = %s AND e.id < %s))"
|
||||
)
|
||||
params.extend([cursor_ts_val, cursor_ts_val, cursor_id])
|
||||
|
||||
variants_sql = ""
|
||||
if include_variants:
|
||||
variants_sql = """,
|
||||
@@ -2040,16 +2116,26 @@ def list_exercises(
|
||||
FROM exercise_training_types ett
|
||||
JOIN training_types tt ON tt.id = ett.training_type_id
|
||||
WHERE ett.exercise_id = e.id
|
||||
) AS training_type_names
|
||||
) AS training_type_names,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM exercise_variants ev
|
||||
WHERE ev.exercise_id = e.id
|
||||
) AS variant_count,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM exercise_media em
|
||||
WHERE em.exercise_id = e.id
|
||||
) AS media_count
|
||||
{variants_sql}
|
||||
FROM exercises e
|
||||
LEFT JOIN profiles p ON e.created_by = p.id
|
||||
LEFT JOIN clubs c ON e.club_id = c.id
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY e.updated_at DESC
|
||||
ORDER BY e.updated_at DESC, e.id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
"""
|
||||
params.extend([limit, offset])
|
||||
params.extend([limit, 0 if use_keyset else offset])
|
||||
|
||||
cur.execute(query, params)
|
||||
rows = cur.fetchall()
|
||||
@@ -2063,6 +2149,8 @@ def list_exercises(
|
||||
d["focus_area_names"] = _coerce_json_str_list(d.get("focus_area_names"))
|
||||
d["style_direction_names"] = _coerce_json_str_list(d.get("style_direction_names"))
|
||||
d["training_type_names"] = _coerce_json_str_list(d.get("training_type_names"))
|
||||
d["variant_count"] = int(d.get("variant_count") or 0)
|
||||
d["media_count"] = int(d.get("media_count") or 0)
|
||||
if include_variants:
|
||||
v = d.get("variants")
|
||||
if isinstance(v, str):
|
||||
@@ -2076,6 +2164,58 @@ def list_exercises(
|
||||
return out
|
||||
|
||||
|
||||
def list_exercises_like_get(
|
||||
tenant: TenantContext,
|
||||
*,
|
||||
created_by_me: bool,
|
||||
status: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Programmatischer Aufruf mit gleicher Semantik wie GET /api/exercises
|
||||
(ohne FastAPI-Query-Default-Objekte an list_exercises zu übergeben).
|
||||
"""
|
||||
return list_exercises(
|
||||
focus_area_ids=[],
|
||||
focus_area=None,
|
||||
visibility_any=[],
|
||||
visibility=None,
|
||||
status_any=[],
|
||||
status=status,
|
||||
skill_ids=[],
|
||||
skill_id=None,
|
||||
style_direction_ids=[],
|
||||
style_direction_id=None,
|
||||
training_type_ids=[],
|
||||
training_type_id=None,
|
||||
target_group_ids=[],
|
||||
target_group_id=None,
|
||||
skill_min_level=None,
|
||||
skill_max_level=None,
|
||||
search=None,
|
||||
ai_search=None,
|
||||
limit=limit,
|
||||
offset=0,
|
||||
include_variants=False,
|
||||
visibility_exclude_any=[],
|
||||
status_exclude_any=[],
|
||||
exclude_without_focus=False,
|
||||
focus_only_without_focus_areas=False,
|
||||
focus_area_must_include_ids=[],
|
||||
focus_area_must_exclude_ids=[],
|
||||
style_direction_must_include_ids=[],
|
||||
style_direction_must_exclude_ids=[],
|
||||
training_type_must_include_ids=[],
|
||||
training_type_must_exclude_ids=[],
|
||||
target_group_must_include_ids=[],
|
||||
target_group_must_exclude_ids=[],
|
||||
include_archived=False,
|
||||
created_by_me=created_by_me,
|
||||
exercise_kind_any=[],
|
||||
tenant=tenant,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises/{exercise_id}")
|
||||
def get_exercise(
|
||||
exercise_id: int,
|
||||
|
||||
@@ -18,6 +18,7 @@ from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from smw_client import SmwClient, SmwClientError
|
||||
from smw_mapper import map_wiki_to_exercise, map_wiki_to_skill, map_wiki_to_method, build_skill_assignments
|
||||
from routers.exercises import normalize_exercise_skill_intensity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -30,6 +31,17 @@ CATEGORY_METHODS = os.getenv("MEDIAWIKI_CATEGORY_METHODS", "Methodenbeschrei
|
||||
CATEGORY_MODELS = os.getenv("MEDIAWIKI_CATEGORY_MODELS", "Reifegradmodelle")
|
||||
|
||||
|
||||
def _wiki_category_or_default(category: Optional[str], import_type: str) -> str:
|
||||
"""Leeres category ⇒ Standard je import_type."""
|
||||
if (category or "").strip():
|
||||
return category.strip()
|
||||
if import_type == "skill":
|
||||
return CATEGORY_SKILLS
|
||||
if import_type == "method":
|
||||
return CATEGORY_METHODS
|
||||
return CATEGORY_EXERCISES
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Pydantic Models #
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -59,7 +71,7 @@ def require_admin(session: dict = Depends(require_auth)) -> dict:
|
||||
|
||||
@router.get("/import/mediawiki/preview")
|
||||
async def preview_import(
|
||||
category: str = Query(default=CATEGORY_EXERCISES),
|
||||
category: Optional[str] = Query(default=None),
|
||||
import_type: str = Query(default="exercise"),
|
||||
limit: int = Query(default=10, ge=1, le=500),
|
||||
session: dict = Depends(require_admin),
|
||||
@@ -68,9 +80,10 @@ async def preview_import(
|
||||
Zeigt Vorschau: Welche Seiten würden importiert werden?
|
||||
Überprüft Duplikate und mapped Felder ohne zu speichern.
|
||||
"""
|
||||
resolved_category = _wiki_category_or_default(category, import_type)
|
||||
client = SmwClient()
|
||||
try:
|
||||
members = await client.get_category_members(category, limit=limit)
|
||||
members = await client.get_category_members(resolved_category, limit=limit)
|
||||
except SmwClientError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Wiki-API nicht erreichbar: {e}")
|
||||
|
||||
@@ -129,7 +142,7 @@ async def preview_import(
|
||||
})
|
||||
|
||||
return {
|
||||
"category": category,
|
||||
"category": resolved_category,
|
||||
"import_type": import_type,
|
||||
"total_found": len(members),
|
||||
"preview": preview,
|
||||
@@ -151,6 +164,7 @@ async def execute_import(
|
||||
Gibt sofort log_id zurück – Status via GET /import/mediawiki/status/{log_id}.
|
||||
"""
|
||||
profile_id = session["profile_id"]
|
||||
resolved_category = _wiki_category_or_default(body.category, body.import_type)
|
||||
|
||||
# Log-Eintrag anlegen
|
||||
with get_db() as conn:
|
||||
@@ -160,7 +174,7 @@ async def execute_import(
|
||||
(import_type, import_status, category, dry_run, reimport, imported_by)
|
||||
VALUES (%s, 'running', %s, %s, %s, %s)
|
||||
RETURNING id""",
|
||||
(body.import_type, body.category, body.dry_run, body.reimport_existing, profile_id)
|
||||
(body.import_type, resolved_category, body.dry_run, body.reimport_existing, profile_id)
|
||||
)
|
||||
log_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
@@ -169,7 +183,7 @@ async def execute_import(
|
||||
background_tasks.add_task(
|
||||
_run_import,
|
||||
log_id=log_id,
|
||||
category=body.category,
|
||||
category=resolved_category,
|
||||
import_type=body.import_type,
|
||||
reimport=body.reimport_existing,
|
||||
dry_run=body.dry_run,
|
||||
@@ -602,21 +616,23 @@ def _assign_exercise_skills(cur, conn, exercise_id: int, skill_assignments: list
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (exercise_id, skill_id) DO UPDATE SET
|
||||
target_level = EXCLUDED.target_level,
|
||||
is_primary = EXCLUDED.is_primary""",
|
||||
required_level = EXCLUDED.required_level,
|
||||
intensity = EXCLUDED.intensity,
|
||||
is_primary = false""",
|
||||
(
|
||||
exercise_id,
|
||||
sid,
|
||||
assignment.get("target_level"),
|
||||
assignment.get("required_level"),
|
||||
assignment.get("intensity"),
|
||||
assignment.get("is_primary", False),
|
||||
normalize_exercise_skill_intensity(assignment.get("intensity")),
|
||||
False,
|
||||
)
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
|
||||
"""Legt Skill an oder überspringt bei Duplikat."""
|
||||
def _upsert_skill(mapped: dict, _reimport: bool) -> Optional[int]:
|
||||
"""Legt Skill an oder aktualisiert bestehenden Datensatz bei Namenskonflikt (Wiki-Reimport)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
@@ -626,17 +642,27 @@ def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
|
||||
cur.execute("SELECT id FROM skill_categories WHERE name ILIKE %s", (mapped["category_name"],))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
category_id = row['id']
|
||||
category_id = row["id"]
|
||||
|
||||
cur.execute(
|
||||
"""INSERT INTO skills (name, description, category_id)
|
||||
VALUES (%s, %s, %s)
|
||||
"""INSERT INTO skills (name, description, category_id, karate_relevance, relevance_level)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (name) DO UPDATE SET
|
||||
description = EXCLUDED.description
|
||||
description = COALESCE(EXCLUDED.description, skills.description),
|
||||
category_id = COALESCE(EXCLUDED.category_id, skills.category_id),
|
||||
karate_relevance = COALESCE(EXCLUDED.karate_relevance, skills.karate_relevance),
|
||||
relevance_level = COALESCE(EXCLUDED.relevance_level, skills.relevance_level),
|
||||
updated_at = NOW()
|
||||
RETURNING id""",
|
||||
(mapped["name"], mapped.get("description"), category_id)
|
||||
(
|
||||
mapped["name"],
|
||||
mapped.get("description"),
|
||||
category_id,
|
||||
mapped.get("karate_relevance"),
|
||||
mapped.get("relevance_level"),
|
||||
),
|
||||
)
|
||||
skill_id = cur.fetchone()['id']
|
||||
skill_id = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
return skill_id
|
||||
|
||||
|
||||
@@ -0,0 +1,689 @@
|
||||
"""
|
||||
Fähigkeiten-Profile und Vorschläge (Phase 3) für Planungsartefakte.
|
||||
|
||||
GET …/skill-profile — gewichtetes Profil aus verknüpften Übungen.
|
||||
GET /api/skill-discovery/suggestions — Rahmenprogramme, Module, Progressionsgraphen nach Fähigkeiten.
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
|
||||
from skill_scoring import (
|
||||
GRAPH_DEFAULT_ITEM_MINUTES,
|
||||
ExerciseOccurrence,
|
||||
batch_compute_profiles,
|
||||
batch_framework_occurrences_by_id,
|
||||
batch_module_occurrences_by_id,
|
||||
collect_module_exercise_occurrences,
|
||||
collect_progression_graph_exercise_occurrences,
|
||||
collect_unit_exercise_occurrences,
|
||||
compact_profile_summary,
|
||||
compute_planning_corpus_by_type,
|
||||
compute_club_corpus_reference,
|
||||
compute_corpus_skill_max_weights,
|
||||
compute_skill_profile,
|
||||
corpus_for_artifact_type,
|
||||
fetch_exercise_skills_bulk,
|
||||
match_score_for_skill_ids,
|
||||
profile_for_occurrences,
|
||||
reference_scale_meta,
|
||||
top_categories_summary,
|
||||
)
|
||||
|
||||
from routers.training_framework_programs import _framework_access
|
||||
from routers.training_modules import _module_access
|
||||
from routers.exercise_progression_graphs import _require_graph_read
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["skill_profiles"])
|
||||
|
||||
|
||||
def _parse_skill_ids_param(raw: Optional[str]) -> List[int]:
|
||||
if not raw or not str(raw).strip():
|
||||
return []
|
||||
out: List[int] = []
|
||||
for part in str(raw).split(","):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
try:
|
||||
n = int(part)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="skill_ids: ungültige ID") from None
|
||||
if n > 0 and n not in out:
|
||||
out.append(n)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/training-framework-programs/{framework_id}/skill-profile")
|
||||
def framework_program_skill_profile(
|
||||
framework_id: int,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = _framework_access(cur, framework_id, profile_id, role)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id, s.sort_order, s.title,
|
||||
tu.id AS blueprint_unit_id
|
||||
FROM training_framework_slots s
|
||||
LEFT JOIN training_units tu ON tu.framework_slot_id = s.id
|
||||
WHERE s.framework_program_id = %s
|
||||
ORDER BY s.sort_order
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
slots_raw = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
bundle = _load_planning_corpus(cur, tenant)
|
||||
tc = corpus_for_artifact_type(bundle, "framework_program")
|
||||
ref_max = tc["max_by_skill"]
|
||||
ref_by_skill = tc["ref_by_skill"]
|
||||
|
||||
all_occurrences: List[ExerciseOccurrence] = []
|
||||
slot_profiles: List[Dict[str, Any]] = []
|
||||
|
||||
for slot in slots_raw:
|
||||
uid = slot.get("blueprint_unit_id")
|
||||
slot_occ: List[ExerciseOccurrence] = []
|
||||
slot_label = (slot.get("title") or "").strip() or f"Session {(slot.get('sort_order') or 0) + 1}"
|
||||
if uid:
|
||||
raw_occ = collect_unit_exercise_occurrences(cur, int(uid))
|
||||
slot_occ = [
|
||||
ExerciseOccurrence(
|
||||
exercise_id=o.exercise_id,
|
||||
planned_duration_min=o.planned_duration_min,
|
||||
context_label=slot_label,
|
||||
)
|
||||
for o in raw_occ
|
||||
]
|
||||
all_occurrences.extend(slot_occ)
|
||||
else:
|
||||
slot_occ = []
|
||||
slot_profile = (
|
||||
profile_for_occurrences(cur, slot_occ, reference_max_by_skill=ref_max)
|
||||
if slot_occ
|
||||
else _empty_profile()
|
||||
)
|
||||
slot_profiles.append(
|
||||
{
|
||||
"slot_id": slot["id"],
|
||||
"slot_title": slot.get("title"),
|
||||
"sort_order": slot.get("sort_order"),
|
||||
"blueprint_training_unit_id": uid,
|
||||
"exercise_occurrence_count": len(slot_occ),
|
||||
"profile": slot_profile,
|
||||
}
|
||||
)
|
||||
|
||||
overall = (
|
||||
profile_for_occurrences(cur, all_occurrences, reference_max_by_skill=ref_max)
|
||||
if all_occurrences
|
||||
else _empty_profile()
|
||||
)
|
||||
_enrich_profile_club_best(overall, ref_by_skill, "framework_program", framework_id)
|
||||
for slot in slot_profiles:
|
||||
_enrich_profile_club_best(
|
||||
slot.get("profile") or {},
|
||||
ref_by_skill,
|
||||
"framework_program",
|
||||
framework_id,
|
||||
)
|
||||
|
||||
return {
|
||||
"artifact_type": "framework_program",
|
||||
"artifact_id": framework_id,
|
||||
"artifact_title": row.get("title"),
|
||||
"reference_scale": reference_scale_meta(
|
||||
tc, "framework_program", effective_club_id=tenant.effective_club_id
|
||||
),
|
||||
"club_best_by_skill": {
|
||||
str(k): v for k, v in ref_by_skill.items()
|
||||
},
|
||||
"overall": overall,
|
||||
"slots": slot_profiles,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/training-modules/{module_id}/skill-profile")
|
||||
def training_module_skill_profile(
|
||||
module_id: int,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = _module_access(cur, module_id, profile_id, role)
|
||||
bundle = _load_planning_corpus(cur, tenant)
|
||||
tc = corpus_for_artifact_type(bundle, "training_module")
|
||||
ref_max = tc["max_by_skill"]
|
||||
ref_by_skill = tc["ref_by_skill"]
|
||||
occurrences = collect_module_exercise_occurrences(cur, module_id)
|
||||
overall = (
|
||||
profile_for_occurrences(cur, occurrences, reference_max_by_skill=ref_max)
|
||||
if occurrences
|
||||
else _empty_profile()
|
||||
)
|
||||
_enrich_profile_club_best(overall, ref_by_skill, "training_module", module_id)
|
||||
return {
|
||||
"artifact_type": "training_module",
|
||||
"artifact_id": module_id,
|
||||
"artifact_title": row.get("title"),
|
||||
"reference_scale": reference_scale_meta(
|
||||
tc, "training_module", effective_club_id=tenant.effective_club_id
|
||||
),
|
||||
"club_best_by_skill": {
|
||||
str(k): v for k, v in ref_by_skill.items()
|
||||
},
|
||||
"overall": overall,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/exercise-progression-graphs/{graph_id}/skill-profile")
|
||||
def progression_graph_skill_profile(
|
||||
graph_id: int,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = _require_graph_read(cur, graph_id, profile_id, role)
|
||||
bundle = _load_planning_corpus(cur, tenant)
|
||||
tc = corpus_for_artifact_type(bundle, "progression_graph")
|
||||
ref_max = tc["max_by_skill"]
|
||||
ref_by_skill = tc["ref_by_skill"]
|
||||
occurrences = collect_progression_graph_exercise_occurrences(cur, graph_id)
|
||||
overall = (
|
||||
profile_for_occurrences(
|
||||
cur,
|
||||
occurrences,
|
||||
default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES,
|
||||
reference_max_by_skill=ref_max,
|
||||
)
|
||||
if occurrences
|
||||
else _empty_profile()
|
||||
)
|
||||
_enrich_profile_club_best(overall, ref_by_skill, "progression_graph", graph_id)
|
||||
return {
|
||||
"artifact_type": "progression_graph",
|
||||
"artifact_id": graph_id,
|
||||
"artifact_title": row.get("name"),
|
||||
"reference_scale": reference_scale_meta(
|
||||
tc, "progression_graph", effective_club_id=tenant.effective_club_id
|
||||
),
|
||||
"club_best_by_skill": {
|
||||
str(k): v for k, v in ref_by_skill.items()
|
||||
},
|
||||
"overall": overall,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/skill-profiles/batch-summaries")
|
||||
def batch_skill_profile_summaries(
|
||||
data: dict,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Kompakte Fähigkeiten-Profile für Listen (ein Corpus-Scan, Batch-SQL).
|
||||
Body: { framework_program_ids?: number[], training_module_ids?: number[] }
|
||||
"""
|
||||
fp_ids = _parse_id_list(data.get("framework_program_ids"))
|
||||
mod_ids = _parse_id_list(data.get("training_module_ids"))
|
||||
if not fp_ids and not mod_ids:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="framework_program_ids oder training_module_ids erforderlich",
|
||||
)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
summaries: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
bundle = compute_planning_corpus_by_type(
|
||||
cur,
|
||||
profile_id=tenant.profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
include_artifact_summaries=True,
|
||||
)
|
||||
|
||||
allowed_fp: List[int] = []
|
||||
if fp_ids:
|
||||
for fid in fp_ids:
|
||||
try:
|
||||
_framework_access(cur, fid, profile_id, role)
|
||||
allowed_fp.append(fid)
|
||||
except HTTPException:
|
||||
pass
|
||||
|
||||
allowed_mod: List[int] = []
|
||||
if mod_ids:
|
||||
for mid in mod_ids:
|
||||
try:
|
||||
_module_access(cur, mid, profile_id, role)
|
||||
allowed_mod.append(mid)
|
||||
except HTTPException:
|
||||
pass
|
||||
|
||||
summaries = _merge_batch_summaries(
|
||||
cur,
|
||||
bundle=bundle,
|
||||
allowed_fp=allowed_fp,
|
||||
allowed_mod=allowed_mod,
|
||||
)
|
||||
ref_by_skill = {}
|
||||
for t in ("framework_program", "training_module", "progression_graph"):
|
||||
ref_by_skill.update(corpus_for_artifact_type(bundle, t).get("ref_by_skill") or {})
|
||||
|
||||
skill_ids_seen: set[int] = set()
|
||||
for summary in summaries.values():
|
||||
for sk in summary.get("skills") or []:
|
||||
if sk.get("skill_id") is not None:
|
||||
skill_ids_seen.add(int(sk["skill_id"]))
|
||||
|
||||
club_best_subset = {
|
||||
str(sid): ref_by_skill[sid]
|
||||
for sid in skill_ids_seen
|
||||
if sid in ref_by_skill
|
||||
}
|
||||
|
||||
return {
|
||||
"reference_scale_by_type": {
|
||||
t: reference_scale_meta(
|
||||
corpus_for_artifact_type(bundle, t),
|
||||
t,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
for t in ("framework_program", "training_module", "progression_graph")
|
||||
},
|
||||
"club_best_by_skill": club_best_subset,
|
||||
"summaries": summaries,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/skill-discovery/suggestions")
|
||||
def skill_discovery_suggestions(
|
||||
skill_ids: str = Query(..., description="Komma-getrennte skill-IDs"),
|
||||
types: Optional[str] = Query(
|
||||
default="framework_program,training_module,progression_graph",
|
||||
description="Artefakttypen, komma-getrennt",
|
||||
),
|
||||
limit: int = Query(default=20, ge=1, le=50),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
Findet Bibliotheksartefakte, deren Übungs-Fähigkeiten-Profil die gewünschten Fähigkeiten stark abdeckt.
|
||||
"""
|
||||
wanted = _parse_skill_ids_param(skill_ids)
|
||||
if not wanted:
|
||||
raise HTTPException(status_code=400, detail="skill_ids ist Pflicht (mindestens eine ID)")
|
||||
|
||||
type_set = {t.strip() for t in (types or "").split(",") if t.strip()}
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
results: List[Dict[str, Any]] = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
planning_bundle = _load_planning_corpus(cur, tenant)
|
||||
fw_ref = corpus_for_artifact_type(planning_bundle, "framework_program")["max_by_skill"]
|
||||
mod_ref = corpus_for_artifact_type(planning_bundle, "training_module")["max_by_skill"]
|
||||
graph_ref = corpus_for_artifact_type(planning_bundle, "progression_graph")["max_by_skill"]
|
||||
|
||||
if "framework_program" in type_set:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT fp.id, fp.title
|
||||
FROM training_framework_programs fp
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY fp.updated_at DESC NULLS LAST
|
||||
LIMIT 80
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
for fp_row in cur.fetchall():
|
||||
fid = int(fp_row["id"])
|
||||
try:
|
||||
_framework_access(cur, fid, profile_id, role)
|
||||
except HTTPException:
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tu.id
|
||||
FROM training_framework_slots s
|
||||
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
|
||||
WHERE s.framework_program_id = %s
|
||||
""",
|
||||
(fid,),
|
||||
)
|
||||
occ: List[ExerciseOccurrence] = []
|
||||
for u in cur.fetchall():
|
||||
occ.extend(collect_unit_exercise_occurrences(cur, int(u["id"])))
|
||||
if not occ:
|
||||
continue
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=fw_ref)
|
||||
match = match_score_for_skill_ids(prof, wanted)
|
||||
if match["match_weight"] <= 0:
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"artifact_type": "framework_program",
|
||||
"artifact_id": fid,
|
||||
"artifact_title": fp_row["title"],
|
||||
"path": f"/planning/framework-programs/{fid}",
|
||||
"match": match,
|
||||
"skill_profile_summary": {
|
||||
"total_score": prof.get("total_score"),
|
||||
"top_by_category": top_categories_summary(prof),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if "training_module" in type_set:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="m",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT m.id, m.title
|
||||
FROM training_modules m
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY m.updated_at DESC NULLS LAST
|
||||
LIMIT 80
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
for m_row in cur.fetchall():
|
||||
mid = int(m_row["id"])
|
||||
try:
|
||||
_module_access(cur, mid, profile_id, role)
|
||||
except HTTPException:
|
||||
continue
|
||||
occ = collect_module_exercise_occurrences(cur, mid)
|
||||
if not occ:
|
||||
continue
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=mod_ref)
|
||||
match = match_score_for_skill_ids(prof, wanted)
|
||||
if match["match_weight"] <= 0:
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"artifact_type": "training_module",
|
||||
"artifact_id": mid,
|
||||
"artifact_title": m_row["title"],
|
||||
"path": f"/planning/training-modules/{mid}",
|
||||
"match": match,
|
||||
"skill_profile_summary": {
|
||||
"total_score": prof.get("total_score"),
|
||||
"top_by_category": top_categories_summary(prof),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if "progression_graph" in type_set:
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.id, g.name
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY g.updated_at DESC NULLS LAST
|
||||
LIMIT 80
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
for g_row in cur.fetchall():
|
||||
gid = int(g_row["id"])
|
||||
try:
|
||||
_require_graph_read(cur, gid, profile_id, role)
|
||||
except HTTPException:
|
||||
continue
|
||||
occ = collect_progression_graph_exercise_occurrences(cur, gid)
|
||||
if not occ:
|
||||
continue
|
||||
prof = profile_for_occurrences(
|
||||
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES,
|
||||
reference_max_by_skill=graph_ref,
|
||||
)
|
||||
match = match_score_for_skill_ids(prof, wanted)
|
||||
if match["match_weight"] <= 0:
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"artifact_type": "progression_graph",
|
||||
"artifact_id": gid,
|
||||
"artifact_title": g_row["name"],
|
||||
"path": None,
|
||||
"match": match,
|
||||
"skill_profile_summary": {
|
||||
"total_score": prof.get("total_score"),
|
||||
"top_by_category": top_categories_summary(prof),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
results.sort(
|
||||
key=lambda x: -float(x.get("match", {}).get("match_score") or x.get("match", {}).get("match_weight") or 0),
|
||||
)
|
||||
return {
|
||||
"skill_ids": wanted,
|
||||
"types": sorted(type_set),
|
||||
"suggestions": results[:limit],
|
||||
}
|
||||
|
||||
|
||||
def _top_categories_summary(profile: Dict[str, Any], limit: int = 6) -> List[Dict[str, Any]]:
|
||||
"""Kurzliste Top-Fähigkeit je Unterkategorie für Discovery-Treffer."""
|
||||
out: List[Dict[str, Any]] = []
|
||||
for mc in profile.get("by_main_category") or []:
|
||||
for cat in mc.get("categories") or []:
|
||||
top = cat.get("top_skill")
|
||||
if not top:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"main_category_name": mc.get("main_category_name"),
|
||||
"category_name": cat.get("category_name"),
|
||||
"skill_id": top.get("skill_id"),
|
||||
"skill_name": top.get("skill_name"),
|
||||
"score": top.get("score") or top.get("weight"),
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
def _parse_id_list(raw: Any, *, max_count: int = 120) -> List[int]:
|
||||
if not raw:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise HTTPException(status_code=400, detail="ID-Listen müssen Arrays sein")
|
||||
out: List[int] = []
|
||||
for item in raw:
|
||||
try:
|
||||
n = int(item)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="Ungültige ID in Liste") from None
|
||||
if n > 0 and n not in out:
|
||||
out.append(n)
|
||||
if len(out) >= max_count:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _load_planning_corpus(cur, tenant: TenantContext) -> Dict[str, Any]:
|
||||
return compute_planning_corpus_by_type(
|
||||
cur,
|
||||
profile_id=tenant.profile_id,
|
||||
role=tenant.global_role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
|
||||
|
||||
def _enrich_profile_club_best(
|
||||
profile: Dict[str, Any],
|
||||
ref_by_skill: Dict[int, Dict[str, Any]],
|
||||
artifact_type: Optional[str] = None,
|
||||
artifact_id: Optional[int] = None,
|
||||
) -> None:
|
||||
"""Hängt Vereins-Referenz-Artefakt an Fähigkeiten an (wenn nicht selbst Spitze)."""
|
||||
if not profile or not ref_by_skill:
|
||||
return
|
||||
|
||||
def attach(sk: Optional[Dict[str, Any]]) -> None:
|
||||
if not sk or sk.get("skill_id") is None:
|
||||
return
|
||||
sid = int(sk["skill_id"])
|
||||
ref = ref_by_skill.get(sid)
|
||||
if not ref:
|
||||
return
|
||||
if (
|
||||
artifact_type
|
||||
and artifact_id is not None
|
||||
and ref.get("artifact_type") == artifact_type
|
||||
and int(ref.get("artifact_id") or 0) == int(artifact_id)
|
||||
):
|
||||
return
|
||||
w = float(sk.get("weight") or 0)
|
||||
if w < float(ref.get("weight") or 0) - 0.01:
|
||||
sk["club_best"] = ref
|
||||
|
||||
for sk in profile.get("skills") or []:
|
||||
attach(sk)
|
||||
for mc in profile.get("by_main_category") or []:
|
||||
for cat in mc.get("categories") or []:
|
||||
attach(cat.get("top_skill"))
|
||||
|
||||
|
||||
def _empty_profile() -> Dict[str, Any]:
|
||||
return compute_skill_profile([], {})
|
||||
|
||||
|
||||
def _summarize_framework_program(
|
||||
cur,
|
||||
framework_id: int,
|
||||
ref_max: Dict[int, float],
|
||||
ref_by_skill: Dict[int, Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tu.id
|
||||
FROM training_framework_slots s
|
||||
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
|
||||
WHERE s.framework_program_id = %s
|
||||
""",
|
||||
(int(framework_id),),
|
||||
)
|
||||
occ: List[ExerciseOccurrence] = []
|
||||
for u in cur.fetchall():
|
||||
occ.extend(collect_unit_exercise_occurrences(cur, int(u["id"])))
|
||||
prof = (
|
||||
profile_for_occurrences(cur, occ, reference_max_by_skill=ref_max)
|
||||
if occ
|
||||
else _empty_profile()
|
||||
)
|
||||
_enrich_profile_club_best(prof, ref_by_skill, "framework_program", int(framework_id))
|
||||
return compact_profile_summary(prof, ref_by_skill)
|
||||
|
||||
|
||||
def _summarize_training_module(
|
||||
cur,
|
||||
module_id: int,
|
||||
ref_max: Dict[int, float],
|
||||
ref_by_skill: Dict[int, Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
occ = collect_module_exercise_occurrences(cur, int(module_id))
|
||||
prof = (
|
||||
profile_for_occurrences(cur, occ, reference_max_by_skill=ref_max)
|
||||
if occ
|
||||
else _empty_profile()
|
||||
)
|
||||
_enrich_profile_club_best(prof, ref_by_skill, "training_module", int(module_id))
|
||||
return compact_profile_summary(prof, ref_by_skill)
|
||||
|
||||
|
||||
def _merge_batch_summaries(
|
||||
cur,
|
||||
*,
|
||||
bundle: Dict[str, Any],
|
||||
allowed_fp: List[int],
|
||||
allowed_mod: List[int],
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""Summaries für angeforderte IDs — Referenz je Planungs-Kontext (Typ getrennt)."""
|
||||
fw_tc = corpus_for_artifact_type(bundle, "framework_program")
|
||||
mod_tc = corpus_for_artifact_type(bundle, "training_module")
|
||||
fw_cached = fw_tc.get("artifact_summaries") or {}
|
||||
mod_cached = mod_tc.get("artifact_summaries") or {}
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
fw_ref_max = fw_tc["max_by_skill"]
|
||||
fw_ref_by = fw_tc["ref_by_skill"]
|
||||
missing_fp = [fid for fid in allowed_fp if f"framework_program:{fid}" not in fw_cached]
|
||||
if missing_fp:
|
||||
occ_map = batch_framework_occurrences_by_id(cur, missing_fp)
|
||||
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
|
||||
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
|
||||
profiles = batch_compute_profiles(
|
||||
occ_map, skills_map, reference_max_by_skill=fw_ref_max
|
||||
)
|
||||
for fid in missing_fp:
|
||||
key = f"framework_program:{fid}"
|
||||
prof = profiles.get(fid) or _empty_profile()
|
||||
_enrich_profile_club_best(prof, fw_ref_by, "framework_program", fid)
|
||||
out[key] = compact_profile_summary(prof, fw_ref_by)
|
||||
|
||||
mod_ref_max = mod_tc["max_by_skill"]
|
||||
mod_ref_by = mod_tc["ref_by_skill"]
|
||||
missing_mod = [mid for mid in allowed_mod if f"training_module:{mid}" not in mod_cached]
|
||||
if missing_mod:
|
||||
occ_map = batch_module_occurrences_by_id(cur, missing_mod)
|
||||
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
|
||||
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
|
||||
profiles = batch_compute_profiles(
|
||||
occ_map, skills_map, reference_max_by_skill=mod_ref_max
|
||||
)
|
||||
for mid in missing_mod:
|
||||
key = f"training_module:{mid}"
|
||||
prof = profiles.get(mid) or _empty_profile()
|
||||
_enrich_profile_club_best(prof, mod_ref_by, "training_module", mid)
|
||||
out[key] = compact_profile_summary(prof, mod_ref_by)
|
||||
|
||||
for fid in allowed_fp:
|
||||
key = f"framework_program:{fid}"
|
||||
if key in fw_cached:
|
||||
out[key] = fw_cached[key]
|
||||
elif key not in out:
|
||||
out[key] = _summarize_framework_program(cur, fid, fw_ref_max, fw_ref_by)
|
||||
|
||||
for mid in allowed_mod:
|
||||
key = f"training_module:{mid}"
|
||||
if key in mod_cached:
|
||||
out[key] = mod_cached[key]
|
||||
elif key not in out:
|
||||
out[key] = _summarize_training_module(cur, mid, mod_ref_max, mod_ref_by)
|
||||
|
||||
return out
|
||||
@@ -181,9 +181,10 @@ def create_skill(data: dict, session=Depends(require_auth)):
|
||||
"""
|
||||
INSERT INTO skills (
|
||||
name, category, description, importance, keywords, status,
|
||||
category_id, main_category_id, focus_areas, sort_order
|
||||
category_id, main_category_id, focus_areas, sort_order,
|
||||
karate_relevance, relevance_level
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
@@ -197,6 +198,8 @@ def create_skill(data: dict, session=Depends(require_auth)):
|
||||
main_id,
|
||||
focus if focus is not None else "[]",
|
||||
data.get("sort_order"),
|
||||
data.get("karate_relevance"),
|
||||
data.get("relevance_level"),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -232,6 +235,8 @@ def update_skill(skill_id: int, data: dict, session=Depends(require_auth)):
|
||||
"category_id",
|
||||
"main_category_id",
|
||||
"sort_order",
|
||||
"karate_relevance",
|
||||
"relevance_level",
|
||||
):
|
||||
if key in data:
|
||||
sets.append(f"{key} = %s")
|
||||
|
||||
@@ -3,13 +3,16 @@ Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere
|
||||
|
||||
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
||||
nicht über group_id oder training_unit_id am Rahmen.
|
||||
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
|
||||
Lesen wie Übungen (official / private / club); Bearbeiten wie Übungen; Löschen nach Rolle (s. club_tenancy).
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from club_tenancy import (
|
||||
assert_library_content_deletable,
|
||||
assert_library_content_editable,
|
||||
assert_library_content_governance_transition,
|
||||
assert_valid_governance_visibility,
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
@@ -21,6 +24,7 @@ from routers.training_planning import (
|
||||
_hydrate_training_unit_payload,
|
||||
_optional_positive_int,
|
||||
_insert_sections_from_legacy_exercises,
|
||||
_replace_unit_phases,
|
||||
_replace_unit_sections,
|
||||
_validate_variant_for_exercise,
|
||||
)
|
||||
@@ -55,13 +59,6 @@ def _framework_assert_readable(
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
||||
|
||||
|
||||
def _framework_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if row.get("created_by") != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
||||
|
||||
|
||||
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||
row = _fetch_framework_row(cur, framework_id)
|
||||
_framework_assert_readable(cur, row, profile_id, role)
|
||||
@@ -102,6 +99,32 @@ def _target_group_ids(cur, framework_id: int) -> List[int]:
|
||||
return [r["target_group_id"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _focus_area_ids(cur, framework_id: int) -> List[int]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT focus_area_id
|
||||
FROM training_framework_program_focus_areas
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY focus_area_id
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
return [r["focus_area_id"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _style_direction_ids(cur, framework_id: int) -> List[int]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT style_direction_id
|
||||
FROM training_framework_program_style_directions
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY style_direction_id
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
return [r["style_direction_id"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
fid = row["id"]
|
||||
cur.execute(
|
||||
@@ -132,18 +155,30 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
row_b = cur.fetchone()
|
||||
if not row_b:
|
||||
s["blueprint_training_unit_id"] = None
|
||||
s["phases"] = []
|
||||
s["sections"] = []
|
||||
s["exercises"] = []
|
||||
continue
|
||||
uid = row_b["id"]
|
||||
s["blueprint_training_unit_id"] = uid
|
||||
unit_min: Dict[str, Any] = {"id": uid}
|
||||
cur.execute(
|
||||
"SELECT planned_duration_min FROM training_units WHERE id = %s",
|
||||
(uid,),
|
||||
)
|
||||
urow = cur.fetchone()
|
||||
s["planned_duration_min"] = (
|
||||
urow["planned_duration_min"] if urow else None
|
||||
)
|
||||
_hydrate_training_unit_payload(cur, unit_min)
|
||||
s["phases"] = unit_min.get("phases", [])
|
||||
s["sections"] = unit_min.get("sections", [])
|
||||
s["exercises"] = unit_min.get("exercises", [])
|
||||
row["slots"] = slots
|
||||
row["training_type_ids"] = _training_type_ids(cur, fid)
|
||||
row["target_group_ids"] = _target_group_ids(cur, fid)
|
||||
row["focus_area_ids"] = _focus_area_ids(cur, fid)
|
||||
row["style_direction_ids"] = _style_direction_ids(cur, fid)
|
||||
return row
|
||||
|
||||
|
||||
@@ -210,6 +245,53 @@ def _replace_target_groups(cur, framework_id: int, ids: Sequence[int]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _replace_focus_areas(cur, framework_id: int, ids: Sequence[int]) -> None:
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_program_focus_areas WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
for fid in ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_program_focus_areas (framework_program_id, focus_area_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(framework_id, fid),
|
||||
)
|
||||
|
||||
|
||||
def _replace_style_directions(cur, framework_id: int, ids: Sequence[int]) -> None:
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_program_style_directions WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
for sid in ids:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_program_style_directions (framework_program_id, style_direction_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(framework_id, sid),
|
||||
)
|
||||
|
||||
|
||||
def _parse_context_ids_from_payload(data: dict) -> tuple:
|
||||
"""focus_area_ids / style_direction_ids (M:N); Legacy focus_area_id / style_direction_id."""
|
||||
fa_ids = _parse_positive_int_ids(data.get("focus_area_ids"), "focus_area_ids")
|
||||
if not fa_ids and data.get("focus_area_id") not in (None, ""):
|
||||
one = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
|
||||
if one is not None:
|
||||
fa_ids = [one]
|
||||
sd_ids = _parse_positive_int_ids(data.get("style_direction_ids"), "style_direction_ids")
|
||||
if not sd_ids and data.get("style_direction_id") not in (None, ""):
|
||||
one = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
|
||||
if one is not None:
|
||||
sd_ids = [one]
|
||||
return fa_ids, sd_ids
|
||||
|
||||
|
||||
def _insert_goal_rows(cur, framework_id: int, goals_in: List[Any]) -> None:
|
||||
if not goals_in:
|
||||
raise HTTPException(status_code=400, detail="Mindestens ein Entwicklungsziel (goals) ist erforderlich")
|
||||
@@ -250,6 +332,7 @@ def _insert_slots_and_blueprints(
|
||||
framework_id: int,
|
||||
slots_in: Optional[List[Any]],
|
||||
profile_id: int,
|
||||
role: str,
|
||||
) -> None:
|
||||
if slots_in is None:
|
||||
return
|
||||
@@ -277,29 +360,35 @@ def _insert_slots_and_blueprints(
|
||||
)
|
||||
sid = cur.fetchone()["id"]
|
||||
|
||||
slot_pdur = _optional_positive_int(
|
||||
slot.get("planned_duration_min"), "planned_duration_min"
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date,
|
||||
planned_time_start, planned_time_end, planned_focus,
|
||||
planned_time_start, planned_time_end, planned_duration_min, planned_focus,
|
||||
status, notes, trainer_notes,
|
||||
created_by, plan_template_id, framework_slot_id
|
||||
) VALUES (
|
||||
NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
NULL, NULL, %s, NULL,
|
||||
'planned', NULL, NULL,
|
||||
%s, NULL, %s
|
||||
)
|
||||
RETURNING id
|
||||
""",
|
||||
(profile_id, sid),
|
||||
(slot_pdur, profile_id, sid),
|
||||
)
|
||||
bid = cur.fetchone()["id"]
|
||||
|
||||
phases_in = slot.get("phases")
|
||||
sections_in = slot.get("sections")
|
||||
exercises_in = slot.get("exercises")
|
||||
|
||||
if sections_in is not None:
|
||||
if phases_in is not None and isinstance(phases_in, list) and len(phases_in) > 0:
|
||||
_replace_unit_phases(cur, bid, phases_in, profile_id, role, profile_id)
|
||||
elif sections_in is not None:
|
||||
if len(sections_in) == 0:
|
||||
_insert_default_blueprint_section(cur, bid)
|
||||
else:
|
||||
@@ -324,8 +413,6 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
|
||||
cur = get_cursor(conn)
|
||||
base_sel = """
|
||||
SELECT fp.*,
|
||||
fa.name AS focus_area_name,
|
||||
sd.name AS style_direction_name,
|
||||
(SELECT COUNT(*)::int FROM training_framework_goals g WHERE g.framework_program_id = fp.id)
|
||||
AS goals_count,
|
||||
(SELECT COUNT(*)::int FROM training_framework_slots s WHERE s.framework_program_id = fp.id)
|
||||
@@ -334,6 +421,18 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
|
||||
WHERE t.framework_program_id = fp.id) AS training_types_count,
|
||||
(SELECT COUNT(*)::int FROM training_framework_program_target_groups tg
|
||||
WHERE tg.framework_program_id = fp.id) AS target_groups_count,
|
||||
(
|
||||
SELECT STRING_AGG(fa.name::text, ', ' ORDER BY fa.name)
|
||||
FROM training_framework_program_focus_areas j
|
||||
JOIN focus_areas fa ON fa.id = j.focus_area_id
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS focus_area_names_agg,
|
||||
(
|
||||
SELECT STRING_AGG(sd.name::text, ', ' ORDER BY sd.name)
|
||||
FROM training_framework_program_style_directions j
|
||||
JOIN style_directions sd ON sd.id = j.style_direction_id
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS style_direction_names_agg,
|
||||
(
|
||||
SELECT STRING_AGG(typ.name::text, ', ' ORDER BY typ.sort_order NULLS LAST, typ.name)
|
||||
FROM training_framework_program_training_types j
|
||||
@@ -345,10 +444,47 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
|
||||
FROM training_framework_program_target_groups j
|
||||
JOIN target_groups tg ON tg.id = j.target_group_id
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS target_group_names_agg
|
||||
) AS target_group_names_agg,
|
||||
(
|
||||
SELECT STRING_AGG(g.title::text, ' | ' ORDER BY g.sort_order)
|
||||
FROM training_framework_goals g
|
||||
WHERE g.framework_program_id = fp.id
|
||||
) AS goal_titles_agg,
|
||||
(
|
||||
SELECT MIN(tu.planned_duration_min)::int
|
||||
FROM training_framework_slots fs
|
||||
INNER JOIN training_units tu ON tu.framework_slot_id = fs.id
|
||||
WHERE fs.framework_program_id = fp.id
|
||||
AND tu.planned_duration_min IS NOT NULL
|
||||
) AS session_duration_min,
|
||||
(
|
||||
SELECT MAX(tu.planned_duration_min)::int
|
||||
FROM training_framework_slots fs
|
||||
INNER JOIN training_units tu ON tu.framework_slot_id = fs.id
|
||||
WHERE fs.framework_program_id = fp.id
|
||||
AND tu.planned_duration_min IS NOT NULL
|
||||
) AS session_duration_max,
|
||||
(
|
||||
SELECT COALESCE(json_agg(j.focus_area_id ORDER BY j.focus_area_id), '[]'::json)
|
||||
FROM training_framework_program_focus_areas j
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS focus_area_ids,
|
||||
(
|
||||
SELECT COALESCE(json_agg(j.style_direction_id ORDER BY j.style_direction_id), '[]'::json)
|
||||
FROM training_framework_program_style_directions j
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS style_direction_ids,
|
||||
(
|
||||
SELECT COALESCE(json_agg(j.training_type_id ORDER BY j.training_type_id), '[]'::json)
|
||||
FROM training_framework_program_training_types j
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS training_type_ids,
|
||||
(
|
||||
SELECT COALESCE(json_agg(j.target_group_id ORDER BY j.target_group_id), '[]'::json)
|
||||
FROM training_framework_program_target_groups j
|
||||
WHERE j.framework_program_id = fp.id
|
||||
) AS target_group_ids
|
||||
FROM training_framework_programs fp
|
||||
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
|
||||
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
|
||||
"""
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
@@ -400,10 +536,11 @@ def create_training_framework_program(
|
||||
if not isinstance(goals_in, list) or not goals_in:
|
||||
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
|
||||
|
||||
fa_id = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
|
||||
sd_id = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
|
||||
fa_ids, sd_ids = _parse_context_ids_from_payload(data)
|
||||
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
|
||||
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
|
||||
fa_legacy = fa_ids[0] if len(fa_ids) == 1 else None
|
||||
sd_legacy = sd_ids[0] if len(sd_ids) == 1 else None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -415,26 +552,26 @@ def create_training_framework_program(
|
||||
planned_period_start, planned_period_end,
|
||||
visibility, club_id, created_by,
|
||||
focus_area_id, style_direction_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
) VALUES (%s, %s, NULL, NULL, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
title[:200],
|
||||
data.get("description"),
|
||||
data.get("planned_period_start"),
|
||||
data.get("planned_period_end"),
|
||||
vis,
|
||||
club_id,
|
||||
profile_id,
|
||||
fa_id,
|
||||
sd_id,
|
||||
fa_legacy,
|
||||
sd_legacy,
|
||||
),
|
||||
)
|
||||
fid = cur.fetchone()["id"]
|
||||
_insert_goal_rows(cur, fid, goals_in)
|
||||
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id)
|
||||
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id, role)
|
||||
_replace_training_types(cur, fid, tt_ids)
|
||||
_replace_target_groups(cur, fid, tg_ids)
|
||||
_replace_focus_areas(cur, fid, fa_ids)
|
||||
_replace_style_directions(cur, fid, sd_ids)
|
||||
conn.commit()
|
||||
|
||||
return _response_framework_detail(fid, profile_id, role)
|
||||
@@ -452,7 +589,7 @@ def update_training_framework_program(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_prev = _fetch_framework_row(cur, framework_id)
|
||||
_framework_assert_writable(cur, row_prev, profile_id, role)
|
||||
assert_library_content_editable(cur, profile_id, role, row_prev)
|
||||
|
||||
merged_vis = row_prev.get("visibility") or "private"
|
||||
merged_club = row_prev.get("club_id")
|
||||
@@ -465,7 +602,12 @@ def update_training_framework_program(
|
||||
merged_club = data.get("club_id")
|
||||
if merged_club in ("", []):
|
||||
merged_club = None
|
||||
if merged_vis == "club" and merged_club is None:
|
||||
merged_club = tenant.effective_club_id
|
||||
if "visibility" in data or "club_id" in data:
|
||||
assert_library_content_governance_transition(
|
||||
cur, profile_id, role, row_prev, merged_vis, merged_club
|
||||
)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
||||
|
||||
header_fields = []
|
||||
@@ -481,13 +623,6 @@ def update_training_framework_program(
|
||||
if "description" in data:
|
||||
header_fields.append("description = %s")
|
||||
header_params.append(data.get("description"))
|
||||
if "planned_period_start" in data:
|
||||
header_fields.append("planned_period_start = %s")
|
||||
header_params.append(data.get("planned_period_start"))
|
||||
if "planned_period_end" in data:
|
||||
header_fields.append("planned_period_end = %s")
|
||||
header_params.append(data.get("planned_period_end"))
|
||||
|
||||
if "visibility" in data:
|
||||
header_fields.append("visibility = %s")
|
||||
header_params.append(merged_vis)
|
||||
@@ -495,18 +630,26 @@ def update_training_framework_program(
|
||||
header_fields.append("club_id = %s")
|
||||
header_params.append(merged_club)
|
||||
|
||||
if "focus_area_id" in data:
|
||||
fidv = data.get("focus_area_id")
|
||||
if "focus_area_ids" in data or "focus_area_id" in data:
|
||||
fa_ids = _parse_positive_int_ids(data.get("focus_area_ids"), "focus_area_ids")
|
||||
if not fa_ids and data.get("focus_area_id") not in (None, ""):
|
||||
one = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
|
||||
if one is not None:
|
||||
fa_ids = [one]
|
||||
header_fields.append("focus_area_id = %s")
|
||||
header_params.append(
|
||||
None if fidv in (None, "") else _optional_positive_int(fidv, "focus_area_id")
|
||||
header_params.append(fa_ids[0] if len(fa_ids) == 1 else None)
|
||||
_replace_focus_areas(cur, framework_id, fa_ids)
|
||||
if "style_direction_ids" in data or "style_direction_id" in data:
|
||||
sd_ids = _parse_positive_int_ids(
|
||||
data.get("style_direction_ids"), "style_direction_ids"
|
||||
)
|
||||
if "style_direction_id" in data:
|
||||
sidv = data.get("style_direction_id")
|
||||
if not sd_ids and data.get("style_direction_id") not in (None, ""):
|
||||
one = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
|
||||
if one is not None:
|
||||
sd_ids = [one]
|
||||
header_fields.append("style_direction_id = %s")
|
||||
header_params.append(
|
||||
None if sidv in (None, "") else _optional_positive_int(sidv, "style_direction_id")
|
||||
)
|
||||
header_params.append(sd_ids[0] if len(sd_ids) == 1 else None)
|
||||
_replace_style_directions(cur, framework_id, sd_ids)
|
||||
|
||||
if header_fields:
|
||||
header_fields.append("updated_at = NOW()")
|
||||
@@ -543,9 +686,21 @@ def update_training_framework_program(
|
||||
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
_insert_slots_and_blueprints(cur, framework_id, data.get("slots") or [], profile_id)
|
||||
_insert_slots_and_blueprints(
|
||||
cur, framework_id, data.get("slots") or [], profile_id, role
|
||||
)
|
||||
|
||||
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
|
||||
if (
|
||||
header_fields
|
||||
or "goals" in data
|
||||
or "slots" in data
|
||||
or "training_type_ids" in data
|
||||
or "target_group_ids" in data
|
||||
or "focus_area_ids" in data
|
||||
or "focus_area_id" in data
|
||||
or "style_direction_ids" in data
|
||||
or "style_direction_id" in data
|
||||
):
|
||||
cur.execute(
|
||||
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
|
||||
(framework_id,),
|
||||
@@ -565,7 +720,7 @@ def delete_training_framework_program(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_fw = _fetch_framework_row(cur, framework_id)
|
||||
_framework_assert_writable(cur, row_fw, profile_id, role)
|
||||
assert_library_content_deletable(cur, profile_id, role, row_fw)
|
||||
cur.execute(
|
||||
"DELETE FROM training_framework_programs WHERE id = %s",
|
||||
(framework_id,),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
|
||||
|
||||
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
|
||||
Liste/Detail über `library_content_visibility_sql`; Schreiben: Ersteller oder Plattform‑Admin.
|
||||
Liste/Detail über `library_content_visibility_sql`; Bearbeiten/Löschen wie Übungen (s. club_tenancy).
|
||||
|
||||
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
|
||||
"""
|
||||
@@ -13,6 +13,9 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from db import get_db, get_cursor, r2d
|
||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||
from club_tenancy import (
|
||||
assert_library_content_deletable,
|
||||
assert_library_content_editable,
|
||||
assert_library_content_governance_transition,
|
||||
assert_valid_governance_visibility,
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
@@ -47,13 +50,6 @@ def _module_assert_readable(cur, row: Dict[str, Any], profile_id: int, role: Opt
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
|
||||
|
||||
|
||||
def _module_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
if row.get("created_by") != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Nur der Ersteller darf dieses Modul ändern")
|
||||
|
||||
|
||||
def _module_access(cur, mid: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||
row = _fetch_training_module_row(cur, mid)
|
||||
_module_assert_readable(cur, row, profile_id, role)
|
||||
@@ -288,7 +284,7 @@ def update_training_module(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_prev = _fetch_training_module_row(cur, module_id)
|
||||
_module_assert_writable(cur, row_prev, profile_id, role)
|
||||
assert_library_content_editable(cur, profile_id, role, row_prev)
|
||||
|
||||
merged_vis = row_prev.get("visibility") or "club"
|
||||
merged_club = row_prev.get("club_id")
|
||||
@@ -303,8 +299,12 @@ def update_training_module(
|
||||
merged_club = data.get("club_id")
|
||||
if merged_club in ("", []):
|
||||
merged_club = None
|
||||
|
||||
if merged_vis == "club" and merged_club is None:
|
||||
merged_club = tenant.effective_club_id
|
||||
if "visibility" in data or "club_id" in data:
|
||||
assert_library_content_governance_transition(
|
||||
cur, profile_id, role, row_prev, merged_vis, merged_club
|
||||
)
|
||||
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
||||
|
||||
fields: List[str] = []
|
||||
@@ -375,7 +375,7 @@ def delete_training_module(module_id: int, tenant: TenantContext = Depends(get_t
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row_del = _fetch_training_module_row(cur, module_id)
|
||||
_module_assert_writable(cur, row_del, profile_id, role)
|
||||
assert_library_content_deletable(cur, profile_id, role, row_del)
|
||||
cur.execute("DELETE FROM training_modules WHERE id = %s", (module_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
+1345
-179
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,985 @@
|
||||
"""
|
||||
Gewichtetes Fähigkeiten-Scoring aus Übungsvorkommen (Phase 3, regelbasiert).
|
||||
|
||||
Aggregiert exercise_skills über alle Übungen eines Artefakts mit Gewichten aus:
|
||||
geplanter Dauer, Vorkommen, Intensität (Nutzeneinschätzung) und Stufen-Spanne (von/bis).
|
||||
|
||||
is_primary wird bewusst nicht genutzt (perspektivabhängig). development_contribution ist
|
||||
in der UI nicht gepflegt und wird ignoriert.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
DEFAULT_ITEM_MINUTES = 8
|
||||
GRAPH_DEFAULT_ITEM_MINUTES = 10
|
||||
|
||||
_INTENSITY_MULT = {
|
||||
"niedrig": 0.85,
|
||||
"low": 0.85,
|
||||
"mittel": 1.0,
|
||||
"medium": 1.0,
|
||||
"hoch": 1.2,
|
||||
"high": 1.2,
|
||||
}
|
||||
|
||||
# Synchron zu backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL / skillLevels.js
|
||||
_LEVEL_RANK = {
|
||||
"basis": 1,
|
||||
"grundlagen": 2,
|
||||
"aufbau": 3,
|
||||
"fortgeschritten": 4,
|
||||
"optimierung": 5,
|
||||
"einsteiger": 1,
|
||||
"experte": 5,
|
||||
"1": 1,
|
||||
"2": 2,
|
||||
"3": 3,
|
||||
"4": 4,
|
||||
"5": 5,
|
||||
}
|
||||
|
||||
|
||||
def _level_rank(value: Optional[str]) -> Optional[int]:
|
||||
if value is None:
|
||||
return None
|
||||
key = str(value).strip().lower()
|
||||
if not key:
|
||||
return None
|
||||
rank = _LEVEL_RANK.get(key)
|
||||
return rank if rank is not None else None
|
||||
|
||||
|
||||
def _level_range_multiplier(
|
||||
required_level: Optional[str] = None,
|
||||
target_level: Optional[str] = None,
|
||||
) -> float:
|
||||
"""
|
||||
Stufen-Spanne (von/bis): breitere und höhere Entwicklungsstufen → etwas höheres Gewicht.
|
||||
Fehlen beide Angaben: neutral (1.0).
|
||||
"""
|
||||
rr = _level_rank(required_level)
|
||||
rt = _level_rank(target_level)
|
||||
if rr is None and rt is None:
|
||||
return 1.0
|
||||
if rr is None:
|
||||
rr = rt
|
||||
if rt is None:
|
||||
rt = rr
|
||||
if rr > rt:
|
||||
rr, rt = rt, rr
|
||||
span = max(1, min(5, rt - rr + 1))
|
||||
midpoint = (rr + rt) / 2.0
|
||||
span_mult = 0.92 + 0.04 * span
|
||||
depth_mult = 0.95 + 0.025 * midpoint
|
||||
return span_mult * depth_mult
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExerciseOccurrence:
|
||||
exercise_id: int
|
||||
planned_duration_min: Optional[int] = None
|
||||
"""Optional label for UI (e.g. slot title)."""
|
||||
context_label: Optional[str] = None
|
||||
|
||||
|
||||
def _item_base_minutes(planned: Optional[int], default: int = DEFAULT_ITEM_MINUTES) -> float:
|
||||
if planned is not None:
|
||||
try:
|
||||
m = int(planned)
|
||||
if m > 0:
|
||||
return float(m)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return float(default)
|
||||
|
||||
|
||||
def _skill_link_multiplier(
|
||||
*,
|
||||
intensity: Optional[str] = None,
|
||||
required_level: Optional[str] = None,
|
||||
target_level: Optional[str] = None,
|
||||
) -> float:
|
||||
mult = 1.0
|
||||
if intensity:
|
||||
key = str(intensity).strip().lower()
|
||||
mult *= _INTENSITY_MULT.get(key, 1.0)
|
||||
mult *= _level_range_multiplier(required_level, target_level)
|
||||
return mult
|
||||
|
||||
|
||||
def _round2(val: float) -> float:
|
||||
return round(val, 2)
|
||||
|
||||
|
||||
def _build_by_main_category(skills_out: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""Hierarchie Hauptkategorie → Unterkategorie, je Top-Fähigkeit nach absolutem Gewicht."""
|
||||
main_map: Dict[int, Dict[str, Any]] = {}
|
||||
|
||||
for sk in skills_out:
|
||||
mc_id = int(sk.get("main_category_id") or 0)
|
||||
mc_name = (sk.get("main_category_name") or "").strip() or "—"
|
||||
cat_id = int(sk.get("category_id") or 0)
|
||||
cat_name = (sk.get("category_name") or sk.get("category") or "").strip() or "—"
|
||||
|
||||
if mc_id not in main_map:
|
||||
main_map[mc_id] = {
|
||||
"main_category_id": mc_id if mc_id else None,
|
||||
"main_category_name": mc_name,
|
||||
"weight": 0.0,
|
||||
"categories": {},
|
||||
}
|
||||
main = main_map[mc_id]
|
||||
main["weight"] += float(sk.get("weight") or 0)
|
||||
|
||||
if cat_id not in main["categories"]:
|
||||
main["categories"][cat_id] = {
|
||||
"category_id": cat_id if cat_id else None,
|
||||
"category_name": cat_name,
|
||||
"weight": 0.0,
|
||||
"skills": [],
|
||||
}
|
||||
cat = main["categories"][cat_id]
|
||||
cat["weight"] += float(sk.get("weight") or 0)
|
||||
cat["skills"].append(sk)
|
||||
|
||||
result: List[Dict[str, Any]] = []
|
||||
for mc in sorted(main_map.values(), key=lambda x: (-x["weight"], x.get("main_category_name") or "")):
|
||||
cats_out: List[Dict[str, Any]] = []
|
||||
for cat in sorted(
|
||||
mc["categories"].values(),
|
||||
key=lambda x: (-x["weight"], x.get("category_name") or ""),
|
||||
):
|
||||
cat_skills = sorted(
|
||||
cat["skills"],
|
||||
key=lambda x: (-float(x.get("weight") or 0), x.get("skill_name") or ""),
|
||||
)
|
||||
top = cat_skills[0] if cat_skills else None
|
||||
cats_out.append(
|
||||
{
|
||||
"category_id": cat["category_id"],
|
||||
"category_name": cat["category_name"],
|
||||
"weight": _round2(cat["weight"]),
|
||||
"skills_count": len(cat_skills),
|
||||
"top_skill": top,
|
||||
}
|
||||
)
|
||||
result.append(
|
||||
{
|
||||
"main_category_id": mc["main_category_id"],
|
||||
"main_category_name": mc["main_category_name"],
|
||||
"weight": _round2(mc["weight"]),
|
||||
"categories": cats_out,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _club_universal_percent(
|
||||
weight: float,
|
||||
corpus_ref: float,
|
||||
) -> tuple[Optional[float], bool]:
|
||||
"""
|
||||
Anteil am Vereins-Maximum (max. 100 %).
|
||||
effective_ref = max(Korpus-Max, eigenes Gewicht) — verhindert Werte >100 %,
|
||||
wenn das Artefakt stärker ist als der bisherige Vereins-Vergleich (z. B. official).
|
||||
"""
|
||||
w = float(weight or 0)
|
||||
ref = float(corpus_ref or 0)
|
||||
if w <= 0:
|
||||
return None, False
|
||||
effective_ref = max(ref, w)
|
||||
pct = min(100.0, w / effective_ref * 100.0)
|
||||
is_best = ref <= 0 or w >= ref - 0.01
|
||||
return _round2(pct), is_best
|
||||
|
||||
|
||||
def _apply_reference_universal_percent(
|
||||
skills_out: List[Dict[str, Any]],
|
||||
reference_max_by_skill: Optional[Dict[int, float]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Stärke relativ zum Vereins-Maximum je Fähigkeit (gecappt auf 100 %).
|
||||
"""
|
||||
if not reference_max_by_skill:
|
||||
for sk in skills_out:
|
||||
sk["universal_percent"] = None
|
||||
sk["is_club_best_for_skill"] = False
|
||||
return
|
||||
for sk in skills_out:
|
||||
sid = int(sk["skill_id"])
|
||||
ref = float(reference_max_by_skill.get(sid) or 0)
|
||||
w = float(sk.get("weight") or 0)
|
||||
pct, is_best = _club_universal_percent(w, ref)
|
||||
sk["universal_percent"] = pct
|
||||
sk["is_club_best_for_skill"] = is_best
|
||||
|
||||
|
||||
def compute_skill_profile(
|
||||
occurrences: Sequence[ExerciseOccurrence],
|
||||
skill_rows_by_exercise: Dict[int, List[Dict[str, Any]]],
|
||||
*,
|
||||
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
|
||||
reference_max_by_skill: Optional[Dict[int, float]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Erzeugt ein normalisiertes Fähigkeiten-Profil aus Übungsvorkommen und exercise_skills.
|
||||
"""
|
||||
exercise_meta: Dict[int, Dict[str, Any]] = defaultdict(
|
||||
lambda: {"occurrence_count": 0, "minutes": 0.0, "context_labels": []}
|
||||
)
|
||||
total_occurrences = 0
|
||||
for occ in occurrences or []:
|
||||
eid = int(occ.exercise_id)
|
||||
mins = _item_base_minutes(occ.planned_duration_min, default_item_minutes)
|
||||
exercise_meta[eid]["occurrence_count"] += 1
|
||||
exercise_meta[eid]["minutes"] += mins
|
||||
total_occurrences += 1
|
||||
if occ.context_label and occ.context_label not in exercise_meta[eid]["context_labels"]:
|
||||
exercise_meta[eid]["context_labels"].append(occ.context_label)
|
||||
|
||||
skill_acc: Dict[int, Dict[str, Any]] = {}
|
||||
total_weight = 0.0
|
||||
exercises_with_skills: set[int] = set()
|
||||
|
||||
for eid, meta in exercise_meta.items():
|
||||
links = skill_rows_by_exercise.get(eid) or []
|
||||
if not links:
|
||||
continue
|
||||
exercises_with_skills.add(eid)
|
||||
occ_count = meta["occurrence_count"]
|
||||
minutes_per_occ = meta["minutes"] / occ_count if occ_count else float(default_item_minutes)
|
||||
|
||||
for link in links:
|
||||
sid = link.get("skill_id")
|
||||
if sid is None:
|
||||
continue
|
||||
sid = int(sid)
|
||||
link_mult = _skill_link_multiplier(
|
||||
intensity=link.get("intensity"),
|
||||
required_level=link.get("required_level"),
|
||||
target_level=link.get("target_level"),
|
||||
)
|
||||
contribution = minutes_per_occ * occ_count * link_mult
|
||||
if contribution <= 0:
|
||||
continue
|
||||
|
||||
if sid not in skill_acc:
|
||||
skill_acc[sid] = {
|
||||
"skill_id": sid,
|
||||
"skill_name": link.get("skill_name") or f"Fähigkeit #{sid}",
|
||||
"category": link.get("category_name") or link.get("category"),
|
||||
"category_id": link.get("category_id"),
|
||||
"category_name": link.get("category_name") or link.get("category"),
|
||||
"main_category_id": link.get("main_category_id"),
|
||||
"main_category_name": link.get("main_category_name"),
|
||||
"focus_areas": link.get("focus_areas"),
|
||||
"weight": 0.0,
|
||||
"occurrence_count": 0,
|
||||
"exercises": {},
|
||||
}
|
||||
acc = skill_acc[sid]
|
||||
acc["weight"] += contribution
|
||||
acc["occurrence_count"] += occ_count
|
||||
ex_key = str(eid)
|
||||
if ex_key not in acc["exercises"]:
|
||||
acc["exercises"][ex_key] = {
|
||||
"exercise_id": eid,
|
||||
"title": link.get("exercise_title") or f"Übung #{eid}",
|
||||
"weight": 0.0,
|
||||
"occurrence_count": occ_count,
|
||||
}
|
||||
acc["exercises"][ex_key]["weight"] += contribution
|
||||
total_weight += contribution
|
||||
|
||||
skills_out: List[Dict[str, Any]] = []
|
||||
for sid, acc in skill_acc.items():
|
||||
share = (acc["weight"] / total_weight * 100.0) if total_weight > 0 else 0.0
|
||||
ex_list = sorted(
|
||||
acc["exercises"].values(),
|
||||
key=lambda x: (-x["weight"], x.get("title") or ""),
|
||||
)[:8]
|
||||
for ex in ex_list:
|
||||
ex["weight"] = _round2(ex["weight"])
|
||||
if total_weight > 0:
|
||||
ex["share_percent"] = _round2(ex["weight"] / total_weight * 100.0)
|
||||
else:
|
||||
ex["share_percent"] = 0.0
|
||||
skills_out.append(
|
||||
{
|
||||
"skill_id": sid,
|
||||
"skill_name": acc["skill_name"],
|
||||
"category": acc.get("category_name") or acc.get("category"),
|
||||
"category_id": acc.get("category_id"),
|
||||
"category_name": acc.get("category_name") or acc.get("category"),
|
||||
"main_category_id": acc.get("main_category_id"),
|
||||
"main_category_name": acc.get("main_category_name"),
|
||||
"focus_areas": acc.get("focus_areas"),
|
||||
"weight": _round2(acc["weight"]),
|
||||
"score": _round2(acc["weight"]),
|
||||
"artifact_share_percent": _round2(share),
|
||||
"share_percent": _round2(share),
|
||||
"occurrence_count": acc["occurrence_count"],
|
||||
"top_exercises": ex_list,
|
||||
}
|
||||
)
|
||||
skills_out.sort(key=lambda x: (-x["weight"], x.get("skill_name") or ""))
|
||||
|
||||
_apply_reference_universal_percent(skills_out, reference_max_by_skill)
|
||||
|
||||
by_main_category = _build_by_main_category(skills_out)
|
||||
for mc in by_main_category:
|
||||
for cat in mc.get("categories") or []:
|
||||
top = cat.get("top_skill")
|
||||
if top and reference_max_by_skill:
|
||||
sid = int(top["skill_id"])
|
||||
ref = float(reference_max_by_skill.get(sid) or 0)
|
||||
pct, is_best = _club_universal_percent(float(top.get("weight") or 0), ref)
|
||||
top["universal_percent"] = pct
|
||||
top["is_club_best_for_skill"] = is_best
|
||||
|
||||
unique_exercises = len(exercise_meta)
|
||||
return {
|
||||
"computed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"scoring_version": "1.2",
|
||||
"score_unit": "weighted_minutes",
|
||||
"score_unit_label": "Trainingsgewicht (gewichtete Minuten, über Programme vergleichbar)",
|
||||
"total_weight": _round2(total_weight),
|
||||
"total_score": _round2(total_weight),
|
||||
"exercise_occurrence_count": total_occurrences,
|
||||
"distinct_exercise_count": unique_exercises,
|
||||
"exercises_with_skills_count": len(exercises_with_skills),
|
||||
"skills": skills_out,
|
||||
"by_main_category": by_main_category,
|
||||
"has_reference_scale": bool(reference_max_by_skill),
|
||||
}
|
||||
|
||||
|
||||
def fetch_exercise_skills_bulk(
|
||||
cur, exercise_ids: Iterable[int]
|
||||
) -> Dict[int, List[Dict[str, Any]]]:
|
||||
ids = sorted({int(x) for x in exercise_ids if x})
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT es.exercise_id, es.skill_id, es.is_primary, es.intensity,
|
||||
es.development_contribution, es.required_level, es.target_level,
|
||||
s.name AS skill_name, s.category,
|
||||
sc.id AS category_id, sc.name AS category_name,
|
||||
mc.id AS main_category_id, mc.name AS main_category_name,
|
||||
s.focus_areas,
|
||||
e.title AS exercise_title
|
||||
FROM exercise_skills es
|
||||
JOIN skills s ON s.id = es.skill_id
|
||||
LEFT JOIN skill_categories sc ON sc.id = s.category_id
|
||||
LEFT JOIN skill_main_categories mc ON mc.id = COALESCE(s.main_category_id, sc.main_category_id)
|
||||
JOIN exercises e ON e.id = es.exercise_id
|
||||
WHERE es.exercise_id IN ({ph})
|
||||
AND (s.status = 'active' OR s.status IS NULL)
|
||||
ORDER BY es.exercise_id, s.name, es.skill_id
|
||||
""",
|
||||
ids,
|
||||
)
|
||||
out: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
|
||||
for row in cur.fetchall():
|
||||
d = dict(row)
|
||||
eid = int(d["exercise_id"])
|
||||
fa = d.get("focus_areas")
|
||||
if fa is not None and not isinstance(fa, list):
|
||||
try:
|
||||
import json
|
||||
|
||||
fa = json.loads(fa) if isinstance(fa, str) else fa
|
||||
except Exception:
|
||||
fa = []
|
||||
d["focus_areas"] = fa if isinstance(fa, list) else []
|
||||
out[eid].append(d)
|
||||
return dict(out)
|
||||
|
||||
|
||||
def collect_unit_exercise_occurrences(cur, unit_id: int) -> List[ExerciseOccurrence]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tusi.exercise_id, tusi.planned_duration_min
|
||||
FROM training_unit_section_items tusi
|
||||
INNER JOIN training_unit_sections tus ON tus.id = tusi.section_id
|
||||
WHERE tus.training_unit_id = %s
|
||||
AND tusi.item_type = 'exercise'
|
||||
AND tusi.exercise_id IS NOT NULL
|
||||
ORDER BY tus.order_index, tusi.order_index
|
||||
""",
|
||||
(int(unit_id),),
|
||||
)
|
||||
return [
|
||||
ExerciseOccurrence(
|
||||
exercise_id=int(r["exercise_id"]),
|
||||
planned_duration_min=r.get("planned_duration_min"),
|
||||
)
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
|
||||
def collect_module_exercise_occurrences(cur, module_id: int) -> List[ExerciseOccurrence]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT exercise_id, planned_duration_min
|
||||
FROM training_module_items
|
||||
WHERE module_id = %s
|
||||
AND item_type = 'exercise'
|
||||
AND exercise_id IS NOT NULL
|
||||
ORDER BY order_index
|
||||
""",
|
||||
(int(module_id),),
|
||||
)
|
||||
return [
|
||||
ExerciseOccurrence(
|
||||
exercise_id=int(r["exercise_id"]),
|
||||
planned_duration_min=r.get("planned_duration_min"),
|
||||
)
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
|
||||
def collect_progression_graph_exercise_occurrences(cur, graph_id: int) -> List[ExerciseOccurrence]:
|
||||
"""Jedes Vorkommen als from- oder to-Endpunkt einer Kante zählt (ohne Dauer → Default)."""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT from_exercise_id AS exercise_id FROM exercise_progression_edges WHERE graph_id = %s
|
||||
UNION ALL
|
||||
SELECT to_exercise_id AS exercise_id FROM exercise_progression_edges WHERE graph_id = %s
|
||||
""",
|
||||
(int(graph_id), int(graph_id)),
|
||||
)
|
||||
return [
|
||||
ExerciseOccurrence(
|
||||
exercise_id=int(r["exercise_id"]),
|
||||
planned_duration_min=None,
|
||||
context_label=None,
|
||||
)
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
|
||||
def profile_for_occurrences(
|
||||
cur,
|
||||
occurrences: Sequence[ExerciseOccurrence],
|
||||
*,
|
||||
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
|
||||
reference_max_by_skill: Optional[Dict[int, float]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
eids = [o.exercise_id for o in occurrences]
|
||||
skills_map = fetch_exercise_skills_bulk(cur, eids)
|
||||
return compute_skill_profile(
|
||||
occurrences,
|
||||
skills_map,
|
||||
default_item_minutes=default_item_minutes,
|
||||
reference_max_by_skill=reference_max_by_skill,
|
||||
)
|
||||
|
||||
|
||||
def merge_skill_weights_into_max(
|
||||
target: Dict[int, float],
|
||||
profile: Dict[str, Any],
|
||||
) -> None:
|
||||
for sk in profile.get("skills") or []:
|
||||
sid = int(sk["skill_id"])
|
||||
w = float(sk.get("weight") or 0)
|
||||
if w > target.get(sid, 0.0):
|
||||
target[sid] = w
|
||||
|
||||
|
||||
def merge_skill_weights_with_reference(
|
||||
max_by_skill: Dict[int, float],
|
||||
ref_by_skill: Dict[int, Dict[str, Any]],
|
||||
profile: Dict[str, Any],
|
||||
*,
|
||||
artifact_type: str,
|
||||
artifact_id: int,
|
||||
artifact_title: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Aktualisiert Vereins-Maximum je Fähigkeit inkl. Quell-Artefakt."""
|
||||
for sk in profile.get("skills") or []:
|
||||
sid = int(sk["skill_id"])
|
||||
w = float(sk.get("weight") or 0)
|
||||
if w <= 0:
|
||||
continue
|
||||
if w > max_by_skill.get(sid, 0.0):
|
||||
max_by_skill[sid] = w
|
||||
ref_by_skill[sid] = {
|
||||
"artifact_type": artifact_type,
|
||||
"artifact_id": int(artifact_id),
|
||||
"artifact_title": (artifact_title or "").strip() or None,
|
||||
"weight": _round2(w),
|
||||
}
|
||||
|
||||
|
||||
def top_categories_summary(profile: Dict[str, Any], limit: int = 6) -> List[Dict[str, Any]]:
|
||||
"""Top-Fähigkeit je Unterkategorie (kompakt für Listen/Discovery)."""
|
||||
out: List[Dict[str, Any]] = []
|
||||
for mc in profile.get("by_main_category") or []:
|
||||
for cat in mc.get("categories") or []:
|
||||
top = cat.get("top_skill")
|
||||
if not top:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"main_category_name": mc.get("main_category_name"),
|
||||
"category_name": cat.get("category_name"),
|
||||
"skill_id": top.get("skill_id"),
|
||||
"skill_name": top.get("skill_name"),
|
||||
"score": top.get("score") or top.get("weight"),
|
||||
"weight": top.get("weight"),
|
||||
"universal_percent": top.get("universal_percent"),
|
||||
"is_club_best_for_skill": top.get("is_club_best_for_skill"),
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
def _apply_reference_to_profile(
|
||||
profile: Dict[str, Any],
|
||||
reference_max_by_skill: Optional[Dict[int, float]],
|
||||
) -> None:
|
||||
_apply_reference_universal_percent(profile.get("skills") or [], reference_max_by_skill)
|
||||
profile["by_main_category"] = _build_by_main_category(profile.get("skills") or [])
|
||||
for mc in profile.get("by_main_category") or []:
|
||||
for cat in mc.get("categories") or []:
|
||||
top = cat.get("top_skill")
|
||||
if top and reference_max_by_skill:
|
||||
sid = int(top["skill_id"])
|
||||
ref = float(reference_max_by_skill.get(sid) or 0)
|
||||
pct, is_best = _club_universal_percent(float(top.get("weight") or 0), ref)
|
||||
top["universal_percent"] = pct
|
||||
top["is_club_best_for_skill"] = is_best
|
||||
profile["has_reference_scale"] = bool(reference_max_by_skill)
|
||||
|
||||
|
||||
def compact_profile_summary(
|
||||
profile: Dict[str, Any],
|
||||
ref_by_skill: Optional[Dict[int, Dict[str, Any]]] = None,
|
||||
*,
|
||||
skills_limit: int = 0,
|
||||
category_limit: int = 48,
|
||||
) -> Dict[str, Any]:
|
||||
"""Leichtgewichtiges Profil für Listen — ohne Übungsdetails. skills_limit=0 → alle Fähigkeiten."""
|
||||
skills_out: List[Dict[str, Any]] = []
|
||||
for s in profile.get("skills") or []:
|
||||
sid = int(s["skill_id"])
|
||||
w = float(s.get("weight") or 0)
|
||||
entry: Dict[str, Any] = {
|
||||
"skill_id": sid,
|
||||
"skill_name": s.get("skill_name"),
|
||||
"category_name": s.get("category_name") or s.get("category"),
|
||||
"main_category_name": s.get("main_category_name"),
|
||||
"weight": s.get("weight"),
|
||||
"score": s.get("score") or s.get("weight"),
|
||||
"universal_percent": s.get("universal_percent"),
|
||||
}
|
||||
ref = (ref_by_skill or {}).get(sid)
|
||||
if ref and w < float(ref.get("weight") or 0) - 0.01:
|
||||
entry["club_best"] = ref
|
||||
if s.get("is_club_best_for_skill"):
|
||||
entry["is_club_best_for_skill"] = True
|
||||
skills_out.append(entry)
|
||||
if skills_limit > 0 and len(skills_out) >= skills_limit:
|
||||
break
|
||||
return {
|
||||
"total_score": profile.get("total_score"),
|
||||
"total_weight": profile.get("total_weight"),
|
||||
"exercise_occurrence_count": profile.get("exercise_occurrence_count"),
|
||||
"skills_count": len(profile.get("skills") or []),
|
||||
"top_by_category": top_categories_summary(profile, limit=category_limit),
|
||||
"skills": skills_out,
|
||||
}
|
||||
|
||||
|
||||
def batch_framework_occurrences_by_id(
|
||||
cur, framework_ids: Sequence[int]
|
||||
) -> Dict[int, List[ExerciseOccurrence]]:
|
||||
ids = sorted({int(x) for x in framework_ids if x})
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT s.framework_program_id,
|
||||
COALESCE(NULLIF(TRIM(s.title), ''), 'Session ' || (s.sort_order + 1)::text) AS slot_label,
|
||||
tusi.exercise_id,
|
||||
tusi.planned_duration_min
|
||||
FROM training_framework_slots s
|
||||
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
|
||||
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
|
||||
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
|
||||
WHERE s.framework_program_id IN ({ph})
|
||||
AND tusi.item_type = 'exercise'
|
||||
AND tusi.exercise_id IS NOT NULL
|
||||
ORDER BY s.framework_program_id, s.sort_order, tus.order_index, tusi.order_index
|
||||
""",
|
||||
ids,
|
||||
)
|
||||
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
|
||||
for row in cur.fetchall():
|
||||
fid = int(row["framework_program_id"])
|
||||
out[fid].append(
|
||||
ExerciseOccurrence(
|
||||
exercise_id=int(row["exercise_id"]),
|
||||
planned_duration_min=row.get("planned_duration_min"),
|
||||
context_label=row.get("slot_label"),
|
||||
)
|
||||
)
|
||||
return dict(out)
|
||||
|
||||
|
||||
def batch_module_occurrences_by_id(
|
||||
cur, module_ids: Sequence[int]
|
||||
) -> Dict[int, List[ExerciseOccurrence]]:
|
||||
ids = sorted({int(x) for x in module_ids if x})
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT module_id, exercise_id, planned_duration_min
|
||||
FROM training_module_items
|
||||
WHERE module_id IN ({ph})
|
||||
AND item_type = 'exercise'
|
||||
AND exercise_id IS NOT NULL
|
||||
ORDER BY module_id, order_index
|
||||
""",
|
||||
ids,
|
||||
)
|
||||
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
|
||||
for row in cur.fetchall():
|
||||
mid = int(row["module_id"])
|
||||
out[mid].append(
|
||||
ExerciseOccurrence(
|
||||
exercise_id=int(row["exercise_id"]),
|
||||
planned_duration_min=row.get("planned_duration_min"),
|
||||
)
|
||||
)
|
||||
return dict(out)
|
||||
|
||||
|
||||
def batch_compute_profiles(
|
||||
occ_by_artifact: Dict[int, List[ExerciseOccurrence]],
|
||||
skills_map: Dict[int, List[Dict[str, Any]]],
|
||||
*,
|
||||
reference_max_by_skill: Optional[Dict[int, float]] = None,
|
||||
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
|
||||
) -> Dict[int, Dict[str, Any]]:
|
||||
return {
|
||||
aid: compute_skill_profile(
|
||||
occ,
|
||||
skills_map,
|
||||
default_item_minutes=default_item_minutes,
|
||||
reference_max_by_skill=reference_max_by_skill,
|
||||
)
|
||||
for aid, occ in occ_by_artifact.items()
|
||||
}
|
||||
|
||||
|
||||
def _empty_type_corpus() -> Dict[str, Any]:
|
||||
return {
|
||||
"max_by_skill": {},
|
||||
"ref_by_skill": {},
|
||||
"artifact_count": 0,
|
||||
"artifact_summaries": {},
|
||||
}
|
||||
|
||||
|
||||
def corpus_for_artifact_type(
|
||||
bundle: Dict[str, Any],
|
||||
artifact_type: str,
|
||||
) -> Dict[str, Any]:
|
||||
by_type = bundle.get("by_type") or {}
|
||||
return by_type.get(artifact_type) or _empty_type_corpus()
|
||||
|
||||
|
||||
def _scan_artifact_type_corpus(
|
||||
cur,
|
||||
*,
|
||||
artifact_type: str,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
effective_club_id: Optional[int],
|
||||
include_artifact_summaries: bool,
|
||||
) -> Dict[str, Any]:
|
||||
"""Referenz je Fähigkeit nur innerhalb eines Planungs-Kontexts (ein Artefakttyp, sichtbare Bibliothek)."""
|
||||
from tenant_context import library_content_visibility_sql
|
||||
|
||||
max_by_skill: Dict[int, float] = {}
|
||||
ref_by_skill: Dict[int, Dict[str, Any]] = {}
|
||||
artifact_count = 0
|
||||
raw_profiles: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
def ingest(aid: int, title: Optional[str], prof: Dict[str, Any]) -> None:
|
||||
nonlocal artifact_count
|
||||
if not prof.get("skills"):
|
||||
return
|
||||
artifact_count += 1
|
||||
merge_skill_weights_with_reference(
|
||||
max_by_skill,
|
||||
ref_by_skill,
|
||||
prof,
|
||||
artifact_type=artifact_type,
|
||||
artifact_id=aid,
|
||||
artifact_title=title,
|
||||
)
|
||||
if include_artifact_summaries:
|
||||
raw_profiles[f"{artifact_type}:{aid}"] = prof
|
||||
|
||||
if artifact_type == "framework_program":
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="fp",
|
||||
profile_id=profile_id,
|
||||
role=role or "",
|
||||
effective_club_id=effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT fp.id, fp.title
|
||||
FROM training_framework_programs fp
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY fp.updated_at DESC NULLS LAST
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
if rows:
|
||||
ids = [int(r["id"]) for r in rows]
|
||||
titles = {int(r["id"]): r.get("title") for r in rows}
|
||||
occ_map = batch_framework_occurrences_by_id(cur, ids)
|
||||
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
|
||||
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
|
||||
profiles = batch_compute_profiles(occ_map, skills_map)
|
||||
for aid, prof in profiles.items():
|
||||
ingest(aid, titles.get(aid), prof)
|
||||
|
||||
elif artifact_type == "training_module":
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="m",
|
||||
profile_id=profile_id,
|
||||
role=role or "",
|
||||
effective_club_id=effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT m.id, m.title
|
||||
FROM training_modules m
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY m.updated_at DESC NULLS LAST
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
if rows:
|
||||
ids = [int(r["id"]) for r in rows]
|
||||
titles = {int(r["id"]): r.get("title") for r in rows}
|
||||
occ_map = batch_module_occurrences_by_id(cur, ids)
|
||||
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
|
||||
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
|
||||
profiles = batch_compute_profiles(occ_map, skills_map)
|
||||
for aid, prof in profiles.items():
|
||||
ingest(aid, titles.get(aid), prof)
|
||||
|
||||
elif artifact_type == "progression_graph":
|
||||
vis_clause, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role or "",
|
||||
effective_club_id=effective_club_id,
|
||||
)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.id, g.name
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY g.updated_at DESC NULLS LAST
|
||||
""",
|
||||
vis_params,
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
gid = int(row["id"])
|
||||
occ = collect_progression_graph_exercise_occurrences(cur, gid)
|
||||
if not occ:
|
||||
continue
|
||||
prof = profile_for_occurrences(
|
||||
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES
|
||||
)
|
||||
ingest(gid, row.get("name"), prof)
|
||||
|
||||
artifact_summaries: Dict[str, Dict[str, Any]] = {}
|
||||
if include_artifact_summaries and raw_profiles:
|
||||
for key, prof in raw_profiles.items():
|
||||
_apply_reference_to_profile(prof, max_by_skill)
|
||||
artifact_summaries[key] = compact_profile_summary(prof, ref_by_skill)
|
||||
|
||||
return {
|
||||
"max_by_skill": max_by_skill,
|
||||
"ref_by_skill": ref_by_skill,
|
||||
"artifact_count": artifact_count,
|
||||
"artifact_summaries": artifact_summaries,
|
||||
}
|
||||
|
||||
|
||||
def compute_planning_corpus_by_type(
|
||||
cur,
|
||||
*,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
effective_club_id: Optional[int],
|
||||
include_artifact_summaries: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Referenz je Fähigkeit getrennt nach Planungs-Kontext:
|
||||
Rahmenprogramme, Trainingsmodule und Regressionspfade jeweils für sich,
|
||||
jeweils über die sichtbare Bibliothek (library_content_visibility_sql).
|
||||
"""
|
||||
by_type = {
|
||||
"framework_program": _scan_artifact_type_corpus(
|
||||
cur,
|
||||
artifact_type="framework_program",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=effective_club_id,
|
||||
include_artifact_summaries=include_artifact_summaries,
|
||||
),
|
||||
"training_module": _scan_artifact_type_corpus(
|
||||
cur,
|
||||
artifact_type="training_module",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=effective_club_id,
|
||||
include_artifact_summaries=include_artifact_summaries,
|
||||
),
|
||||
"progression_graph": _scan_artifact_type_corpus(
|
||||
cur,
|
||||
artifact_type="progression_graph",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=effective_club_id,
|
||||
include_artifact_summaries=include_artifact_summaries,
|
||||
),
|
||||
}
|
||||
return {
|
||||
"effective_club_id": effective_club_id,
|
||||
"by_type": by_type,
|
||||
}
|
||||
|
||||
|
||||
def compute_club_corpus_reference(
|
||||
cur,
|
||||
*,
|
||||
profile_id: int,
|
||||
effective_club_id: Optional[int],
|
||||
include_artifact_summaries: bool = False,
|
||||
role: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Legacy-Hülle — merged summaries über alle Typen (vermeiden für neue Aufrufer)."""
|
||||
bundle = compute_planning_corpus_by_type(
|
||||
cur,
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=effective_club_id,
|
||||
include_artifact_summaries=include_artifact_summaries,
|
||||
)
|
||||
tc = corpus_for_artifact_type(bundle, "framework_program")
|
||||
merged_summaries: Dict[str, Dict[str, Any]] = {}
|
||||
for t in ("framework_program", "training_module", "progression_graph"):
|
||||
merged_summaries.update((bundle["by_type"][t].get("artifact_summaries") or {}))
|
||||
return {
|
||||
"club_id": effective_club_id,
|
||||
"max_by_skill": tc["max_by_skill"],
|
||||
"ref_by_skill": tc["ref_by_skill"],
|
||||
"artifact_count": sum(
|
||||
(bundle["by_type"][t].get("artifact_count") or 0)
|
||||
for t in bundle["by_type"]
|
||||
),
|
||||
"artifact_summaries": merged_summaries,
|
||||
}
|
||||
|
||||
|
||||
_ARTIFACT_TYPE_LABELS = {
|
||||
"framework_program": "Rahmenprogrammen",
|
||||
"training_module": "Trainingsmodulen",
|
||||
"progression_graph": "Regressionspfaden",
|
||||
}
|
||||
|
||||
|
||||
def reference_scale_meta(
|
||||
type_corpus: Dict[str, Any],
|
||||
artifact_type: str,
|
||||
*,
|
||||
effective_club_id: Optional[int] = None,
|
||||
) -> Dict[str, Any]:
|
||||
label = _ARTIFACT_TYPE_LABELS.get(artifact_type, artifact_type)
|
||||
return {
|
||||
"scope": "planning_peer",
|
||||
"artifact_type": artifact_type,
|
||||
"effective_club_id": effective_club_id,
|
||||
"skills_in_corpus": len(type_corpus.get("max_by_skill") or {}),
|
||||
"artifacts_scanned": type_corpus.get("artifact_count") or 0,
|
||||
"description": (
|
||||
f"Prozent = Anteil am stärksten sichtbaren Eintrag unter {label} je Fähigkeit "
|
||||
f"(nicht gemischt mit anderen Planungs-Artefakttypen)"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def compute_corpus_skill_max_weights(
|
||||
cur,
|
||||
*,
|
||||
profile_id: int,
|
||||
role: Optional[str],
|
||||
effective_club_id: Optional[int],
|
||||
limit_per_type: int = 50,
|
||||
artifact_type: str = "framework_program",
|
||||
) -> Dict[int, float]:
|
||||
"""Referenz je Fähigkeit innerhalb eines Planungs-Kontexts (Legacy-Hülle)."""
|
||||
del limit_per_type
|
||||
bundle = compute_planning_corpus_by_type(
|
||||
cur,
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=effective_club_id,
|
||||
)
|
||||
return corpus_for_artifact_type(bundle, artifact_type)["max_by_skill"]
|
||||
|
||||
|
||||
def match_score_for_skill_ids(profile: Dict[str, Any], skill_ids: Sequence[int]) -> Dict[str, Any]:
|
||||
"""Überlappung eines Profils mit gewünschten Fähigkeiten (für Vorschläge)."""
|
||||
wanted = {int(x) for x in skill_ids if x is not None}
|
||||
if not wanted:
|
||||
return {
|
||||
"match_weight": 0.0,
|
||||
"match_score": 0.0,
|
||||
"match_percent": 0.0,
|
||||
"artifact_focus_percent": 0.0,
|
||||
"matched_skill_ids": [],
|
||||
"matched_skills": [],
|
||||
}
|
||||
matched = []
|
||||
match_weight = 0.0
|
||||
total = float(profile.get("total_weight") or 0)
|
||||
for sk in profile.get("skills") or []:
|
||||
sid = int(sk["skill_id"])
|
||||
if sid in wanted:
|
||||
matched.append(sk)
|
||||
match_weight += float(sk.get("weight") or 0)
|
||||
artifact_focus = (match_weight / total * 100.0) if total > 0 else 0.0
|
||||
return {
|
||||
"match_weight": _round2(match_weight),
|
||||
"match_score": _round2(match_weight),
|
||||
"match_percent": _round2(artifact_focus),
|
||||
"artifact_focus_percent": _round2(artifact_focus),
|
||||
"matched_skill_ids": [int(m["skill_id"]) for m in matched],
|
||||
"matched_skills": matched,
|
||||
}
|
||||
+26
-4
@@ -20,6 +20,26 @@ class SmwClientError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize_mw_category(category: str) -> str:
|
||||
"""
|
||||
Bereinigt Kategorienamen für API cmtitle=Kategorie:…
|
||||
Erlaubt z. B. 'Fähigkeitsbeschreibung', ' Kategorie:X ', 'kategorie:X' ohne Doppel-Prefix.
|
||||
"""
|
||||
c = (category or "").strip()
|
||||
if not c:
|
||||
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
|
||||
|
||||
pref = "kategorie:"
|
||||
while c.lower().startswith(pref):
|
||||
c = c[len(pref) :].lstrip()
|
||||
|
||||
remaining = (c or "").strip()
|
||||
if not remaining:
|
||||
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
|
||||
|
||||
return remaining
|
||||
|
||||
|
||||
class SmwClient:
|
||||
"""Stateless MediaWiki/SMW API Client mit Session-Login."""
|
||||
|
||||
@@ -110,12 +130,13 @@ class SmwClient:
|
||||
"""
|
||||
members = []
|
||||
cmcontinue = None
|
||||
cat = _normalize_mw_category(category)
|
||||
|
||||
while True:
|
||||
params = {
|
||||
"action": "query",
|
||||
"list": "categorymembers",
|
||||
"cmtitle": f"Kategorie:{category}",
|
||||
"cmtitle": f"Kategorie:{cat}",
|
||||
"cmlimit": min(limit, 500),
|
||||
"cmtype": "page", # Nur Seiten, keine Unterkategorien
|
||||
"cmprop": "ids|title",
|
||||
@@ -134,8 +155,8 @@ class SmwClient:
|
||||
|
||||
# Rekursiv durch Unterkategorien gehen
|
||||
if recursive:
|
||||
subcats = await self._get_subcategories(category)
|
||||
logger.info(f"Kategorie '{category}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
|
||||
subcats = await self._get_subcategories(cat)
|
||||
logger.info(f"Kategorie '{cat}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
|
||||
|
||||
for subcat in subcats:
|
||||
if len(members) >= limit:
|
||||
@@ -150,12 +171,13 @@ class SmwClient:
|
||||
"""Gibt alle Unterkategorien einer Kategorie zurück."""
|
||||
subcats = []
|
||||
cmcontinue = None
|
||||
cat = _normalize_mw_category(category)
|
||||
|
||||
while True:
|
||||
params = {
|
||||
"action": "query",
|
||||
"list": "categorymembers",
|
||||
"cmtitle": f"Kategorie:{category}",
|
||||
"cmtitle": f"Kategorie:{cat}",
|
||||
"cmlimit": 500,
|
||||
"cmtype": "subcat", # Nur Unterkategorien
|
||||
"cmprop": "ids|title",
|
||||
|
||||
+54
-11
@@ -63,8 +63,8 @@ EXERCISE_PROPERTY_MAP = {
|
||||
# Fähigkeiten (skills) – Kategorie: Fähigkeitsbeschreibung
|
||||
SKILL_PROPERTY_MAP = {
|
||||
"Summary": "description",
|
||||
"KarateRelevanz": "karate_relevance", # Wird in description ergänzt
|
||||
"RelevanzLevel": "relevance_level", # 1-3, nicht direkt in skills DB
|
||||
"KarateRelevanz": "karate_relevance", # Spalte skills.karate_relevance (+ Wiki-Import)
|
||||
"RelevanzLevel": "relevance_level", # Spalte skills.relevance_level 1–3
|
||||
}
|
||||
|
||||
# Trainingsmethoden – Kategorie: Methodenbeschreibung
|
||||
@@ -172,6 +172,27 @@ def map_capability_level(level_str: str) -> str:
|
||||
return CAPABILITY_LEVEL_MAP.get(level_str.strip(), "basis")
|
||||
|
||||
|
||||
def parse_wiki_relevance_level(raw: str | None) -> Optional[int]:
|
||||
"""
|
||||
RelevanzLevel aus Wiki (typisch 1–3). Erlaubt Zahl oder Text mit Ziffer z.B. "Level_2".
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
s = str(raw).strip()
|
||||
if not s:
|
||||
return None
|
||||
digits = re.findall(r"\d+", s)
|
||||
if not digits:
|
||||
return None
|
||||
try:
|
||||
n = int(digits[0])
|
||||
except ValueError:
|
||||
return None
|
||||
if n < 1 or n > 3:
|
||||
return None
|
||||
return n
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# SMW-Property-Label → Mapper-Zielfeld (Werte wie in EXERCISE_PROPERTY_MAP) #
|
||||
# browse_subject liefert Anzeigenamen, nicht zwingend interne Property-IDs. #
|
||||
@@ -184,6 +205,23 @@ def _norm_prop_synonym(name: str) -> str:
|
||||
return "".join(c for c in s if c.isalnum())
|
||||
|
||||
|
||||
# Alternative SMW-Anzeigelabel → Zielfeld (gleiche Targets wie SKILL_PROPERTY_MAP)
|
||||
SKILL_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
|
||||
"karaterelevanz": "karate_relevance",
|
||||
"karatebezug": "karate_relevance",
|
||||
"relevanzlevel": "relevance_level",
|
||||
"wikirelevanz": "karate_relevance",
|
||||
}
|
||||
|
||||
|
||||
def _skill_property_target(prop_name: str) -> str | None:
|
||||
"""Ermittelt Zielfeld für eine Skill-SMW-Property."""
|
||||
if prop_name in SKILL_PROPERTY_MAP:
|
||||
return SKILL_PROPERTY_MAP[prop_name]
|
||||
n = _norm_prop_synonym(prop_name)
|
||||
return SKILL_PROPERTY_SYNONYM_TO_TARGET.get(n)
|
||||
|
||||
|
||||
# alternative Labels → Zielfeld-Name (gleiche Strings wie Werte in EXERCISE_PROPERTY_MAP)
|
||||
EXERCISE_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
|
||||
"primarycapability": "skill_names",
|
||||
@@ -339,8 +377,8 @@ def build_skill_assignments(mapped: dict) -> list[dict]:
|
||||
"skill_name": skill_name,
|
||||
"target_level": target_slug,
|
||||
"required_level": None,
|
||||
"intensity": None,
|
||||
"is_primary": idx == 0,
|
||||
"intensity": "mittel",
|
||||
"is_primary": False,
|
||||
})
|
||||
return assignments
|
||||
|
||||
@@ -359,24 +397,29 @@ def map_wiki_to_skill(
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
description_parts = []
|
||||
description_text: Optional[str] = None
|
||||
|
||||
for prop_name, values in smw_props.items():
|
||||
if not values:
|
||||
continue
|
||||
target = SKILL_PROPERTY_MAP.get(prop_name)
|
||||
target = _skill_property_target(prop_name)
|
||||
if not target:
|
||||
continue
|
||||
first_value = values[0] if isinstance(values, list) else values
|
||||
|
||||
if target == "description":
|
||||
description_parts.insert(0, wikitext_to_plaintext(first_value))
|
||||
description_text = wikitext_to_plaintext(str(first_value))
|
||||
elif target == "karate_relevance":
|
||||
rel = wikitext_to_plaintext(first_value)
|
||||
description_parts.append(f"\nKarate-Relevanz: {rel}")
|
||||
mapped["karate_relevance"] = wikitext_to_plaintext(str(first_value))
|
||||
elif target == "relevance_level":
|
||||
parsed = parse_wiki_relevance_level(first_value if isinstance(first_value, str) else str(first_value))
|
||||
if parsed is None:
|
||||
mapped["warnings"].append(f"Unbekanntes RelevanzLevel: {first_value!r}")
|
||||
else:
|
||||
mapped["relevance_level"] = parsed
|
||||
|
||||
if description_parts:
|
||||
mapped["description"] = "\n".join(description_parts).strip()
|
||||
if description_text:
|
||||
mapped["description"] = description_text
|
||||
|
||||
return mapped
|
||||
|
||||
|
||||
@@ -107,6 +107,33 @@ def library_content_visibility_sql(
|
||||
return "(" + " OR ".join(parts) + ")", params
|
||||
|
||||
|
||||
def club_library_visibility_sql(
|
||||
*,
|
||||
alias: str,
|
||||
profile_id: int,
|
||||
effective_club_id: Optional[int],
|
||||
) -> tuple[str, List[Any]]:
|
||||
"""
|
||||
Nur Inhalte des aktiven Vereins (visibility=club, club_id=active).
|
||||
Für Skill-Vergleiche im Vereinskontext — ohne official/private anderer Mandanten.
|
||||
"""
|
||||
if effective_club_id is None:
|
||||
return "(1=0)", []
|
||||
return (
|
||||
f"""(
|
||||
{alias}.visibility = 'club'
|
||||
AND {alias}.club_id = %s
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM club_members cm
|
||||
WHERE cm.profile_id = %s
|
||||
AND cm.club_id = {alias}.club_id
|
||||
AND cm.status = 'active'
|
||||
)
|
||||
)""",
|
||||
[effective_club_id, profile_id],
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TenantContext:
|
||||
profile_id: int
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""GET /api/dashboard/kpis: Auth + interne Aufruf-Hilfen."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import Query
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from fastapi_param_unwrap import unwrap_query_default
|
||||
from main import app
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_unwrap_query_default_for_direct_route_calls() -> None:
|
||||
assert unwrap_query_default(Query(default=None)) is None
|
||||
assert unwrap_query_default("2026-01-01") == "2026-01-01"
|
||||
assert unwrap_query_default(7) == 7
|
||||
|
||||
|
||||
def test_dashboard_kpis_unauthenticated_401(client: TestClient) -> None:
|
||||
r = client.get("/api/dashboard/kpis")
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def _fake_tenant_for_kpis() -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=42,
|
||||
global_role="trainer",
|
||||
effective_club_id=7,
|
||||
club_ids=frozenset({7}),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
@patch("routers.dashboard.list_training_units")
|
||||
@patch("routers.dashboard.list_exercises_like_get")
|
||||
def test_dashboard_kpis_200_when_inner_lists_mocked(
|
||||
mock_list_ex: object,
|
||||
mock_list_tu: object,
|
||||
client: TestClient,
|
||||
) -> None:
|
||||
mock_list_ex.return_value = []
|
||||
mock_list_tu.return_value = []
|
||||
app.dependency_overrides[get_tenant_context] = _fake_tenant_for_kpis
|
||||
try:
|
||||
r = client.get("/api/dashboard/kpis")
|
||||
assert r.status_code == 200, r.text
|
||||
data = r.json()
|
||||
assert "year" in data
|
||||
assert data["draft_count"] == 0
|
||||
assert data["mine_count"] == 0
|
||||
assert data["ytd_completed_count"] == 0
|
||||
th = data["training_home"]
|
||||
assert th["upcoming"] == []
|
||||
assert th["planned_with_notes"] == []
|
||||
assert th["review_pending"] == []
|
||||
assert mock_list_ex.call_count == 2
|
||||
assert mock_list_tu.call_count == 3
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Normalisierung Übung ↔ Fähigkeit Intensität."""
|
||||
from routers.exercises import normalize_exercise_skill_intensity
|
||||
|
||||
|
||||
def test_normalize_exercise_skill_intensity_defaults_to_mittel():
|
||||
assert normalize_exercise_skill_intensity(None) == "mittel"
|
||||
assert normalize_exercise_skill_intensity("") == "mittel"
|
||||
assert normalize_exercise_skill_intensity("—") == "mittel"
|
||||
|
||||
|
||||
def test_normalize_exercise_skill_intensity_canonical():
|
||||
assert normalize_exercise_skill_intensity("niedrig") == "niedrig"
|
||||
assert normalize_exercise_skill_intensity("mittel") == "mittel"
|
||||
assert normalize_exercise_skill_intensity("hoch") == "hoch"
|
||||
|
||||
|
||||
def test_normalize_exercise_skill_intensity_legacy_aliases():
|
||||
assert normalize_exercise_skill_intensity("low") == "niedrig"
|
||||
assert normalize_exercise_skill_intensity("medium") == "mittel"
|
||||
assert normalize_exercise_skill_intensity("high") == "hoch"
|
||||
@@ -0,0 +1,82 @@
|
||||
"""GET /api/exercises: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
|
||||
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_list_exercises_keyset_incomplete_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={"cursor_id": "42"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_updated_at" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_exercises_keyset_with_offset_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_updated_at": "2026-01-01T12:00:00.000Z",
|
||||
"offset": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "offset" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_exercises_keyset_bad_timestamp_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
r = client.get(
|
||||
"/api/exercises",
|
||||
params={"cursor_id": "1", "cursor_updated_at": "not-a-date"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Resolver für leere/fehlende Kategorie je import_type."""
|
||||
|
||||
from routers.import_wiki import (
|
||||
CATEGORY_EXERCISES,
|
||||
CATEGORY_METHODS,
|
||||
CATEGORY_SKILLS,
|
||||
_wiki_category_or_default,
|
||||
)
|
||||
|
||||
|
||||
def test_wiki_category_or_default_explicit():
|
||||
assert _wiki_category_or_default(" MeineKat ", "skill") == "MeineKat"
|
||||
|
||||
|
||||
def test_wiki_category_or_default_falls_through():
|
||||
assert _wiki_category_or_default(None, "exercise") == CATEGORY_EXERCISES
|
||||
assert _wiki_category_or_default("", "skill") == CATEGORY_SKILLS
|
||||
assert _wiki_category_or_default(" ", "method") == CATEGORY_METHODS
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Unit-Tests für gewichtetes Fähigkeiten-Scoring (Phase 3)."""
|
||||
from skill_scoring import (
|
||||
ExerciseOccurrence,
|
||||
compute_skill_profile,
|
||||
match_score_for_skill_ids,
|
||||
_club_universal_percent,
|
||||
_level_range_multiplier,
|
||||
_skill_link_multiplier,
|
||||
)
|
||||
|
||||
|
||||
def test_skill_link_multiplier_intensity_and_levels():
|
||||
assert _skill_link_multiplier(intensity="hoch") == 1.2
|
||||
assert _skill_link_multiplier(intensity="niedrig") == 0.85
|
||||
wide = _skill_link_multiplier(
|
||||
intensity="mittel",
|
||||
required_level="basis",
|
||||
target_level="optimierung",
|
||||
)
|
||||
narrow = _skill_link_multiplier(
|
||||
intensity="mittel",
|
||||
required_level="grundlagen",
|
||||
target_level="grundlagen",
|
||||
)
|
||||
assert wide > narrow
|
||||
|
||||
|
||||
def test_level_range_multiplier_span():
|
||||
assert _level_range_multiplier(None, None) == 1.0
|
||||
assert _level_range_multiplier("aufbau", "fortgeschritten") > _level_range_multiplier("basis", "basis")
|
||||
|
||||
|
||||
def test_compute_skill_profile_aggregates_weights():
|
||||
occurrences = [
|
||||
ExerciseOccurrence(exercise_id=1, planned_duration_min=60),
|
||||
ExerciseOccurrence(exercise_id=1, planned_duration_min=30),
|
||||
]
|
||||
skills_map = {
|
||||
1: [
|
||||
{
|
||||
"skill_id": 10,
|
||||
"skill_name": "Distanz",
|
||||
"category": "kihon",
|
||||
"category_id": 1,
|
||||
"category_name": "kihon",
|
||||
"main_category_id": 100,
|
||||
"main_category_name": "Technik",
|
||||
"intensity": "hoch",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"exercise_title": "Übung A",
|
||||
},
|
||||
{
|
||||
"skill_id": 11,
|
||||
"skill_name": "Balance",
|
||||
"category": "kihon",
|
||||
"category_id": 1,
|
||||
"category_name": "kihon",
|
||||
"main_category_id": 100,
|
||||
"main_category_name": "Technik",
|
||||
"intensity": "niedrig",
|
||||
"required_level": "basis",
|
||||
"target_level": "basis",
|
||||
"exercise_title": "Übung A",
|
||||
},
|
||||
],
|
||||
}
|
||||
profile = compute_skill_profile(occurrences, skills_map)
|
||||
assert profile["scoring_version"] == "1.2"
|
||||
assert profile["exercise_occurrence_count"] == 2
|
||||
assert profile["distinct_exercise_count"] == 1
|
||||
assert len(profile["skills"]) == 2
|
||||
assert profile["skills"][0]["skill_id"] == 10
|
||||
assert profile["total_weight"] > profile["skills"][1]["weight"]
|
||||
assert abs(sum(s["share_percent"] for s in profile["skills"]) - 100.0) < 0.1
|
||||
assert len(profile["by_main_category"]) == 1
|
||||
assert profile["by_main_category"][0]["categories"][0]["top_skill"]["skill_id"] == 10
|
||||
|
||||
|
||||
def test_universal_percent_against_corpus_max():
|
||||
occurrences = [ExerciseOccurrence(exercise_id=1, planned_duration_min=50)]
|
||||
skills_map = {
|
||||
1: [
|
||||
{
|
||||
"skill_id": 10,
|
||||
"skill_name": "Koordination",
|
||||
"category_name": "Koordination",
|
||||
"category_id": 2,
|
||||
"main_category_id": 200,
|
||||
"main_category_name": "Körper",
|
||||
},
|
||||
],
|
||||
}
|
||||
profile = compute_skill_profile(
|
||||
occurrences,
|
||||
skills_map,
|
||||
reference_max_by_skill={10: 100.0},
|
||||
)
|
||||
assert profile["has_reference_scale"] is True
|
||||
assert profile["skills"][0]["universal_percent"] == 50.0
|
||||
assert profile["skills"][0]["is_club_best_for_skill"] is False
|
||||
|
||||
|
||||
def test_club_universal_percent_capped_at_100():
|
||||
pct, is_best = _club_universal_percent(150.0, 100.0)
|
||||
assert pct == 100.0
|
||||
assert is_best is True
|
||||
pct2, _ = _club_universal_percent(72.6, 100.0)
|
||||
assert pct2 == 72.6
|
||||
|
||||
|
||||
def test_match_score_for_skill_ids():
|
||||
profile = {
|
||||
"total_weight": 100.0,
|
||||
"skills": [
|
||||
{"skill_id": 1, "skill_name": "A", "weight": 40.0},
|
||||
{"skill_id": 2, "skill_name": "B", "weight": 60.0},
|
||||
],
|
||||
}
|
||||
m = match_score_for_skill_ids(profile, [1])
|
||||
assert m["match_weight"] == 40.0
|
||||
assert m["match_score"] == 40.0
|
||||
assert m["match_percent"] == 40.0
|
||||
assert m["artifact_focus_percent"] == 40.0
|
||||
assert m["matched_skill_ids"] == [1]
|
||||
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
from smw_client import _normalize_mw_category, SmwClientError
|
||||
|
||||
|
||||
def test_normalize_strips_optional_kategorie_prefix():
|
||||
assert _normalize_mw_category("Fähigkeitsbeschreibung") == "Fähigkeitsbeschreibung"
|
||||
assert _normalize_mw_category(" Kategorie:Fähigkeitsbeschreibung ") == "Fähigkeitsbeschreibung"
|
||||
assert _normalize_mw_category("kategorie:test") == "test"
|
||||
|
||||
|
||||
def test_normalize_strips_duplicate_prefix_chain():
|
||||
assert _normalize_mw_category("Kategorie:Kategorie:Foo") == "Foo"
|
||||
|
||||
|
||||
def test_normalize_rejects_empty():
|
||||
with pytest.raises(SmwClientError, match="leer"):
|
||||
_normalize_mw_category("")
|
||||
with pytest.raises(SmwClientError, match="leer"):
|
||||
_normalize_mw_category(" Kategorie: ")
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Tests: Wiki → Skill Mapping (KarateRelevanz, RelevanzLevel)."""
|
||||
|
||||
from smw_mapper import (
|
||||
map_wiki_to_skill,
|
||||
parse_wiki_relevance_level,
|
||||
)
|
||||
|
||||
|
||||
def test_parse_wiki_relevance_level_accepted_range():
|
||||
assert parse_wiki_relevance_level("1") == 1
|
||||
assert parse_wiki_relevance_level("3") == 3
|
||||
assert parse_wiki_relevance_level("Level_2_-_foo") == 2
|
||||
|
||||
|
||||
def test_parse_wiki_relevance_level_rejects():
|
||||
assert parse_wiki_relevance_level("") is None
|
||||
assert parse_wiki_relevance_level("4") is None
|
||||
assert parse_wiki_relevance_level("0") is None
|
||||
assert parse_wiki_relevance_level("text") is None
|
||||
|
||||
|
||||
def test_map_wiki_to_skill_karate_and_level():
|
||||
out = map_wiki_to_skill(
|
||||
"Test_Skill",
|
||||
99,
|
||||
{
|
||||
"Summary": ["Kurztext"],
|
||||
"KarateRelevanz": ["''Wichtig'' für [[Kumite]]"],
|
||||
"RelevanzLevel": ["2"],
|
||||
},
|
||||
)
|
||||
assert out["name"] == "Test_Skill"
|
||||
assert out["description"] == "Kurztext"
|
||||
assert "Kumite" in out["karate_relevance"]
|
||||
assert out["relevance_level"] == 2
|
||||
assert out["warnings"] == []
|
||||
|
||||
|
||||
def test_map_wiki_to_skill_synonym_props():
|
||||
out = map_wiki_to_skill("S", None, {"relevanzlevel": ["3"], "karaterelevanz": ["Nur Karate"]})
|
||||
assert out["relevance_level"] == 3
|
||||
assert out["karate_relevance"] == "Nur Karate"
|
||||
|
||||
|
||||
def test_map_wiki_to_skill_invalid_level_warning():
|
||||
out = map_wiki_to_skill("S", None, {"RelevanzLevel": ["9"]})
|
||||
assert "relevance_level" not in out
|
||||
assert len(out["warnings"]) == 1
|
||||
assert "9" in out["warnings"][0]
|
||||
@@ -0,0 +1,206 @@
|
||||
"""
|
||||
PostgreSQL-Integration: Rahmenprogramm-Slot mit verschachtelten `phases` (Blueprint-Unit).
|
||||
|
||||
Aktivierung:
|
||||
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
||||
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf.
|
||||
|
||||
Prüft `_insert_slots_and_blueprints` → `_replace_unit_phases` wie beim API-PUT mit Slot-Payload.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from routers.training_framework_programs import _insert_slots_and_blueprints
|
||||
from routers.training_planning import _fetch_phases_nested
|
||||
|
||||
|
||||
def _integration_enabled() -> bool:
|
||||
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.integration,
|
||||
pytest.mark.skipif(
|
||||
not _integration_enabled(),
|
||||
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _db_ping() -> bool:
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT 1 AS ok")
|
||||
row = cur.fetchone()
|
||||
return row is not None and row.get("ok") == 1
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def db_ready():
|
||||
if not _db_ping():
|
||||
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
|
||||
|
||||
|
||||
def test_framework_blueprint_slot_phases_roundtrip(db_ready):
|
||||
"""Ein Slot mit `phases` erzeugt eine Blueprint-Unit mit identischer Phasenstruktur."""
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
club_name = f"fw_ph_club_{suffix}"
|
||||
email = f"fw_ph_{suffix}@test.local"
|
||||
|
||||
from auth import hash_pin
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||
(club_name, "F", "active"),
|
||||
)
|
||||
club_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(email, hash_pin("x"), f"FWPH {suffix}", "trainer", club_id),
|
||||
)
|
||||
profile_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(f"Übung FWPH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||
)
|
||||
ex_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_programs (
|
||||
title, description,
|
||||
planned_period_start, planned_period_end,
|
||||
visibility, club_id, created_by,
|
||||
focus_area_id, style_direction_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
f"Rahmen FWPH {suffix}",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
"private",
|
||||
club_id,
|
||||
profile_id,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
)
|
||||
fw_id = int(cur.fetchone()["id"])
|
||||
|
||||
phases_in = [
|
||||
{
|
||||
"phase_kind": "whole_group",
|
||||
"order_index": 0,
|
||||
"title": "Aufwärmen",
|
||||
"sections": [
|
||||
{
|
||||
"title": "Gemeinsam",
|
||||
"order_index": 0,
|
||||
"items": [
|
||||
{"item_type": "note", "order_index": 0, "note_body": "Los"},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"phase_kind": "parallel",
|
||||
"order_index": 1,
|
||||
"title": "Breakout",
|
||||
"streams": [
|
||||
{
|
||||
"order_index": 0,
|
||||
"title": "Matte A",
|
||||
"sections": [
|
||||
{
|
||||
"title": "Technik A",
|
||||
"order_index": 0,
|
||||
"items": [
|
||||
{
|
||||
"item_type": "exercise",
|
||||
"order_index": 0,
|
||||
"exercise_id": ex_id,
|
||||
"planned_duration_min": 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
slots_in = [
|
||||
{
|
||||
"sort_order": 0,
|
||||
"title": "Session 1",
|
||||
"notes": None,
|
||||
"phases": phases_in,
|
||||
},
|
||||
]
|
||||
|
||||
_insert_slots_and_blueprints(cur, fw_id, slots_in, profile_id, "trainer")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM training_framework_slots
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY sort_order
|
||||
LIMIT 1
|
||||
""",
|
||||
(fw_id,),
|
||||
)
|
||||
slot_row = cur.fetchone()
|
||||
assert slot_row is not None
|
||||
slot_id = int(slot_row["id"])
|
||||
|
||||
cur.execute(
|
||||
"SELECT id FROM training_units WHERE framework_slot_id = %s",
|
||||
(slot_id,),
|
||||
)
|
||||
bu_row = cur.fetchone()
|
||||
assert bu_row is not None
|
||||
blueprint_unit_id = int(bu_row["id"])
|
||||
|
||||
nested = _fetch_phases_nested(cur, blueprint_unit_id)
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
assert len(nested) == 2
|
||||
assert nested[0]["phase_kind"] == "whole_group"
|
||||
assert len(nested[0].get("sections") or []) == 1
|
||||
assert nested[1]["phase_kind"] == "parallel"
|
||||
streams = nested[1].get("streams") or []
|
||||
assert len(streams) == 1
|
||||
assert len(streams[0].get("sections") or []) == 1
|
||||
assert streams[0]["sections"][0]["title"] == "Technik A"
|
||||
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
|
||||
finally:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM training_framework_programs WHERE id = %s", (fw_id,))
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||
conn.commit()
|
||||
@@ -0,0 +1,290 @@
|
||||
"""
|
||||
PostgreSQL-Integration: Roundtrip _replace_unit_sections / _replace_unit_phases ↔ Fetch-Helfer.
|
||||
|
||||
Aktivierung:
|
||||
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
||||
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf (deployter Backend-Container + PostgreSQL).
|
||||
|
||||
Voraussetzung: migrierte DB, DB_* wie Docker-Compose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from routers.training_planning import (
|
||||
_fetch_phases_nested,
|
||||
_fetch_sections,
|
||||
_replace_unit_phases,
|
||||
_replace_unit_sections,
|
||||
)
|
||||
|
||||
|
||||
def _integration_enabled() -> bool:
|
||||
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.integration,
|
||||
pytest.mark.skipif(
|
||||
not _integration_enabled(),
|
||||
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _db_ping() -> bool:
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT 1 AS ok")
|
||||
row = cur.fetchone()
|
||||
return row is not None and row.get("ok") == 1
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def db_ready():
|
||||
if not _db_ping():
|
||||
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
|
||||
|
||||
|
||||
def test_replace_sections_roundtrip(db_ready):
|
||||
"""INSERT-Hilfsdaten, replace, fetch — gleiche Semantik wie produktiver PUT-Pfad."""
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
club_name = f"tpl_it_club_{suffix}"
|
||||
email = f"tpl_it_{suffix}@test.local"
|
||||
|
||||
from auth import hash_pin
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||
(club_name, "T", "active"),
|
||||
)
|
||||
club_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(email, hash_pin("x"), f"TP {suffix}", "trainer", club_id),
|
||||
)
|
||||
profile_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_groups (club_id, name, trainer_id, status)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(club_id, f"Gruppe {suffix}", profile_id, "active"),
|
||||
)
|
||||
group_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(f"Übung {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||
)
|
||||
ex_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date, status, created_by
|
||||
) VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(group_id, "2026-06-01", "planned", profile_id),
|
||||
)
|
||||
unit_id = int(cur.fetchone()["id"])
|
||||
|
||||
sections_in = [
|
||||
{
|
||||
"title": "A1",
|
||||
"order_index": 0,
|
||||
"guidance_notes": "gn",
|
||||
"items": [
|
||||
{
|
||||
"item_type": "note",
|
||||
"order_index": 0,
|
||||
"note_body": "Hinweis",
|
||||
},
|
||||
{
|
||||
"item_type": "exercise",
|
||||
"order_index": 1,
|
||||
"exercise_id": ex_id,
|
||||
"planned_duration_min": 5,
|
||||
"notes": "n1",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"title": "B2",
|
||||
"order_index": 1,
|
||||
"items": [],
|
||||
},
|
||||
]
|
||||
_replace_unit_sections(cur, unit_id, sections_in)
|
||||
loaded = _fetch_sections(cur, unit_id)
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
assert len(loaded) == 2
|
||||
assert loaded[0]["title"] == "A1"
|
||||
assert loaded[0]["guidance_notes"] == "gn"
|
||||
assert loaded[0]["order_index"] == 0
|
||||
assert len(loaded[0]["items"]) == 2
|
||||
assert loaded[0]["items"][0]["item_type"] == "note"
|
||||
assert loaded[0]["items"][0]["note_body"] == "Hinweis"
|
||||
assert loaded[0]["items"][1]["item_type"] == "exercise"
|
||||
assert int(loaded[0]["items"][1]["exercise_id"]) == ex_id
|
||||
assert loaded[0]["items"][1]["planned_duration_min"] == 5
|
||||
assert loaded[1]["title"] == "B2"
|
||||
assert loaded[1]["items"] == []
|
||||
finally:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def test_replace_phases_roundtrip_parallel_stream(db_ready):
|
||||
"""Phasen inkl. parallel-Stream-Sektionen ersetzen und wieder laden."""
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
club_name = f"ph_it_club_{suffix}"
|
||||
email = f"ph_it_{suffix}@test.local"
|
||||
|
||||
from auth import hash_pin
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||
(club_name, "P", "active"),
|
||||
)
|
||||
club_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(email, hash_pin("x"), f"PH {suffix}", "trainer", club_id),
|
||||
)
|
||||
profile_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_groups (club_id, name, trainer_id, status)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(club_id, f"Gruppe PH {suffix}", profile_id, "active"),
|
||||
)
|
||||
group_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(f"Übung PH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||
)
|
||||
ex_id = int(cur.fetchone()["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date, status, created_by
|
||||
) VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(group_id, "2026-06-02", "planned", profile_id),
|
||||
)
|
||||
unit_id = int(cur.fetchone()["id"])
|
||||
|
||||
phases_in = [
|
||||
{
|
||||
"phase_kind": "whole_group",
|
||||
"order_index": 0,
|
||||
"title": "Aufwärmen",
|
||||
"sections": [
|
||||
{
|
||||
"title": "Gemeinsam",
|
||||
"order_index": 0,
|
||||
"items": [
|
||||
{"item_type": "note", "order_index": 0, "note_body": "Los"},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"phase_kind": "parallel",
|
||||
"order_index": 1,
|
||||
"title": "Breakout",
|
||||
"streams": [
|
||||
{
|
||||
"order_index": 0,
|
||||
"title": "Matte A",
|
||||
"sections": [
|
||||
{
|
||||
"title": "Technik A",
|
||||
"order_index": 0,
|
||||
"items": [
|
||||
{
|
||||
"item_type": "exercise",
|
||||
"order_index": 0,
|
||||
"exercise_id": ex_id,
|
||||
"planned_duration_min": 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
_replace_unit_phases(cur, unit_id, phases_in, profile_id, "trainer", profile_id)
|
||||
nested = _fetch_phases_nested(cur, unit_id)
|
||||
flat_sec = _fetch_sections(cur, unit_id)
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
assert len(nested) == 2
|
||||
assert nested[0]["phase_kind"] == "whole_group"
|
||||
assert len(nested[0].get("sections") or []) == 1
|
||||
assert nested[1]["phase_kind"] == "parallel"
|
||||
streams = nested[1].get("streams") or []
|
||||
assert len(streams) == 1
|
||||
assert len(streams[0].get("sections") or []) == 1
|
||||
assert streams[0]["sections"][0]["title"] == "Technik A"
|
||||
assert len(streams[0]["sections"][0].get("items") or []) == 1
|
||||
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
|
||||
assert len(flat_sec) == 2
|
||||
finally:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||
conn.commit()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Unit-Tests ohne DB: abgeleitete Trainingseinheit-Payload-Helfer."""
|
||||
import pytest
|
||||
|
||||
from routers.training_planning import _flatten_exercises_from_sections
|
||||
|
||||
|
||||
def test_flatten_exercises_from_sections_order():
|
||||
unit = {
|
||||
"sections": [
|
||||
{
|
||||
"order_index": 1,
|
||||
"items": [
|
||||
{"order_index": 1, "item_type": "exercise", "exercise_id": 10},
|
||||
{"order_index": 0, "item_type": "note"},
|
||||
{"order_index": 2, "item_type": "exercise", "exercise_id": 20},
|
||||
],
|
||||
},
|
||||
{
|
||||
"order_index": 0,
|
||||
"items": [{"order_index": 0, "item_type": "exercise", "exercise_id": 5}],
|
||||
},
|
||||
]
|
||||
}
|
||||
_flatten_exercises_from_sections(unit)
|
||||
# Sektionen nach order_index; innerhalb nur exercise-Items nach order_index
|
||||
assert [x["exercise_id"] for x in unit["exercises"]] == [5, 10, 20]
|
||||
|
||||
|
||||
def test_flatten_exercises_from_sections_empty():
|
||||
unit = {"sections": []}
|
||||
_flatten_exercises_from_sections(unit)
|
||||
assert unit["exercises"] == []
|
||||
@@ -0,0 +1,108 @@
|
||||
"""GET /api/training-units: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
|
||||
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 _tenant() -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=1,
|
||||
global_role="trainer",
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
def test_list_training_units_keyset_incomplete_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={"cursor_id": "42"},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_planned_date" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_without_limit_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "2026-05-10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "limit" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_bad_date_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "not-a-date",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_list_training_units_keyset_bad_time_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_id": "1",
|
||||
"cursor_planned_date": "2026-05-10",
|
||||
"cursor_planned_time": "25:99",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert "cursor_planned_time" in r.json().get("detail", "").lower()
|
||||
|
||||
|
||||
def test_list_training_units_keyset_time_without_id_returns_400(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||
app.dependency_overrides[get_tenant_context] = _tenant
|
||||
r = client.get(
|
||||
"/api/training-units",
|
||||
params={
|
||||
"cursor_planned_time": "18:00",
|
||||
"limit": "10",
|
||||
},
|
||||
headers={"X-Auth-Token": "test"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
+298
-9
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.110"
|
||||
BUILD_DATE = "2026-05-12"
|
||||
DB_SCHEMA_VERSION = "20260512057"
|
||||
APP_VERSION = "0.8.151"
|
||||
BUILD_DATE = "2026-05-20"
|
||||
DB_SCHEMA_VERSION = "20260520066"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -19,14 +19,16 @@ MODULE_VERSIONS = {
|
||||
"media_legal_hold": "1.0.0", # P-11: Sofortsperre-Services (set_legal_hold, release_legal_hold)
|
||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
"groups": "0.1.0",
|
||||
"skills": "0.1.0",
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.27.3", # load_combination_slots_for_exercise (gemeinsam mit GET Übung); Hydrate für Planung
|
||||
"training_units": "0.2.0",
|
||||
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.9.3", # GET training-units/:id Sektions-Items: combination_slots + Kandidaten-Titel für Druck/Run
|
||||
"training_modules": "1.0.0",
|
||||
"import_wiki": "1.0.0",
|
||||
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
|
||||
"dashboard": "1.1.0", # GET /api/dashboard/kpis inkl. training_home (ein Client-Roundtrip für KPIs + nächste Termine)
|
||||
"training_modules": "1.1.0", # PUT/DELETE: assert_library_content_* (Vereinsadmin löscht Vereins-Inhalt, Trainer bearbeitet club wie Übungen)
|
||||
"import_wiki": "1.0.3", # Default-Kategorie Fähigkeiten: Fähigkeitsbeschreibung; cmtitle-Normalisierung; UI Preview/Execute Defaults je Typ
|
||||
"admin": "1.0.0",
|
||||
"membership": "1.0.0",
|
||||
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
|
||||
@@ -35,6 +37,293 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.151",
|
||||
"date": "2026-05-20",
|
||||
"changes": [
|
||||
"Phase 3 Fähigkeiten-Scoring: skill_scoring.py (Dauer × Vorkommen × Primär/Intensität/Beitrag)",
|
||||
"GET skill-profile für Rahmenprogramm (gesamt + pro Slot), Trainingsmodul, Progressionsgraph",
|
||||
"GET /api/skill-discovery/suggestions nach skill_ids",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.149",
|
||||
"date": "2026-05-19",
|
||||
"changes": [
|
||||
"Trainingsplanung: Einheiten-Editor als Vollseite (/planning/units/new|/:id/edit); Hub ohne Modal; Legacy ?unit= Redirect",
|
||||
"Drift-Schutz: planningUnitRoutes.js, trainingUnitEditorCore.js, Vitest; Playwright 14–15",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.148",
|
||||
"date": "2026-05-19",
|
||||
"changes": [
|
||||
"Planung Vorlagen: Strukturvorschau (Split-Sessions), Kurzbeschreibung, Bearbeitungsseite; Liste liefert sections[] mit",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.147",
|
||||
"date": "2026-05-19",
|
||||
"changes": [
|
||||
"Planung: Liste – Rahmen-Session & Übungen→Modul; Dialog Modul aus Einheit; klarere Rahmen-Unit-ID aus Liste",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.146",
|
||||
"date": "2026-05-19",
|
||||
"changes": [
|
||||
"Planung: Trainingseinheit → Rahmenprogramm (Session-Slot) speichern; API POST /api/training-units/{id}/publish-to-framework",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.145",
|
||||
"date": "2026-05-16",
|
||||
"changes": [
|
||||
"Wiki-Import: Standard-Kategorie Fähigkeiten korrigiert auf „Fähigkeitsbeschreibung“ (korrekter Wiki-Name).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.144",
|
||||
"date": "2026-05-16",
|
||||
"changes": [
|
||||
"Wiki-Import: Default-Kategorie Fähigkeiten; SMW-Client entfernt versehentliches „Kategorie:“-Prefix; Vorschau/Ausführung nutzen Default-Kategorie je import_type wenn leer.",
|
||||
"Admin UI Wiki-Import: Wechsel Import-Typ setzt passende Standard-Kategorie.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.143",
|
||||
"date": "2026-05-16",
|
||||
"changes": [
|
||||
"DB 065: skills.karate_relevance + skills.relevance_level (Wiki KarateRelevanz / RelevanzLevel 1–3); smw_mapper + Wiki-Import upsert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.142",
|
||||
"date": "2026-05-16",
|
||||
"changes": [
|
||||
"Bibliothek Planung: Bearbeiten/Löschen von Vorlagen, Rahmenprogrammen, Trainingsmodulen, Progressionsgraphen nach RBAC wie Übungen (club_tenancy.assert_library_content_* + Governance-Übergänge)",
|
||||
"Planungs-UI: Sichtbarkeit/Verein beim Speichern neuer Trainingsvorlage",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.141",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"DB 064: Vorlagen-Sektionen mit phase_kind / phase_order_index / parallel_stream_order_index; Speichern und Anwenden behält Split-Sessions; Server: Vorlage → Einheit über Phasen-Replace.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.140",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Trainingsplanung: Breakout-Panel (neue Ganzgruppen-/parallele Phase, Stream in letzter parallelen Phase); pro Abschnitt Zuordnung zu Phase/Stream oder klassischer Ein-Ganzgruppen-Ablauf.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.139",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Trainingsplanung: GET phases → Editor mit planLoc pro Abschnitt; Speichern sendet PUT phases bei Breakout-Einheiten (sonst weiter sections); Modul-Dialog zeigt Phase/Stream in der Abschnittsauswahl.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.138",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Planung Paket 2: POST/PUT training_units mit phases (voller Phasen-/Stream-Plan); höchstens eines von phases, sections, exercises pro Request; Rahmen-Blueprint→Termin kopiert verschachtelten Plan; apply-training-module optional phase_order_index + parallel_stream_order_index.",
|
||||
"Fix: POST from-framework-slot übergibt role an _copy_blueprint_into_scheduled_unit (Stream-Trainer-Validierung).",
|
||||
"Integrationstest test_replace_phases_roundtrip_parallel_stream.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.137",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"DB 063: training_unit_phases, training_unit_parallel_streams; Sektionen mit phase_id oder parallel_stream_id; Default whole_group für Bestand.",
|
||||
"Planung: GET training_unit liefert phases (verschachtelt) + sections (flach sortiert); Legacy-PUT sections weiterhin eine whole_group-Phase.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.136",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: api/exercises.js — Mandanten-Header für Raw-fetch (PUT Übung, Medien-Upload, Bulk-Archiv) über lokale withActiveClubHeaders statt mergeActiveClubHeader-Import (ReferenceError beim Speichern).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.135",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 3: frontend/src/api/exercises.js (Übungen, Medien/Archiv, Progressionsgraphen, KI); client.js exportiert API_URL und mergeActiveClubHeader; utils/api.js re-exportiert Modul, api-Objekt spread exercises.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.134",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 2: frontend/src/api/planning.js (Trainingsplanung); utils/api.js re-exportiert Modul, api-Objekt spread planning.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.133",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 4 Welle 1: frontend/src/api/client.js (request, ACTIVE_CLUB_STORAGE_KEY); utils/api.js importiert Client, bleibt Facade. Roadmap Phase 4 gestartet.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.132",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend Phase 3 abgeschlossen: TrainingPlanningPageRoot, ExerciseFormPageRoot, ExercisesListPageRoot unter components/; pages/ nur Re-Export (Soft-Limit). Roadmap UMSETZUNGSPLAN Phase 3 / M3 aktualisiert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.131",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningUnitFormModal (Neu/Bearbeiten-Einheit); frameworkLineageText in trainingPlanningPageHelpers; BASELINE_SNAPSHOT §3.4 k6-Log-Mapping.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.130",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: PUT/POST training_units — assistant_trainer_profile_ids als JSONB mit psycopg2.extras.Json schreiben (rohe Python-Liste → ProgrammingError/500 bei Co-Zuweisung).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.129",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningTrainerAssignModal (Trainer zuweisen) aus Trainingsplanungsseite; Handler per useCallback.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.128",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningModuleApplyModal (Trainingsmodul einfügen) aus Trainingsplanungsseite; gemeinsamer Callback onModuleApplySectionIndexChange.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.126",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3: TrainingPlanningFrameworkImportModal aus Trainingsplanungsseite; Playwright-Test 13 (Rahmen-Dialog, skip ohne Gruppe).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.125",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Tests: Playwright 11 (Übungsliste Bulk-Toolbar), 12 (Trainingsplanung); Dashboard-Test 8 prüft HTTP 200 auf /api/dashboard/kpis; pytest test_dashboard_kpis_200_when_inner_lists_mocked.",
|
||||
"Frontend Phase 3: trainingPlanningPageHelpers.js aus TrainingPlanningPage; ExerciseListBulkToolbar data-testid.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.124",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): ExerciseListBulkToolbar-Komponente; Übungsliste nur Verdrahtung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.123",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Fix: GET /api/dashboard/kpis — interne Aufrufe von list_exercises / list_training_units erhielten FastAPI-Query-Defaults statt None; .strip() auf Query-Objekt → 500. unwrap_query_default in beiden Handlern (Hilfsmodul fastapi_param_unwrap.py).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.122",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): useExerciseListCatalogsAndQuery — Katalog-Fetch und Übungslisten-Laden/Keyset-Pagination aus ExercisesListPage in Hook ausgelagert.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.121",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): Übungsliste — Suchleiste/Chips in ExerciseListSearchBar; API-Query-Bau und Filter-Chips in utils/exerciseListQuery.js bzw. exerciseListFilterChips.js.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.120",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend: Übungsliste — Filter- und Massenänderungs-Dialoge in ExerciseListFilterModal / ExerciseListBulkModal ausgelagert; Playwright-Test 10 (Filter-Dialog).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.119",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"Frontend Phase 3 (Teil): Übungsliste — ExerciseListCard-Komponente, Progressions-Tab lazy (Suspense); Übungspicker-Modal mit @tanstack/react-virtual; content-visibility auf Karten im Übungs-Gitter; Playwright-Test 9 Übungsliste.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.118",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/dashboard/kpis liefert training_home (upcoming, planned_with_notes, review_pending) — gleiche Logik wie zuvor zwei listTrainingUnits-Calls; Dashboard-Frontend ein Request.",
|
||||
"Migration 062: Index exercise_skills(exercise_id, level_rank_expr) für list_exercises Stufenfilter; Ausdruck wie _EXERCISE_SKILL_LEVEL_RANK_SQL.",
|
||||
"Phase 2: Vorlagen EXPLAIN unter scripts/load/explain-readpaths.sql; Playwright-Test 8 erwartet 0× GET /api/training-units auf dem Dashboard.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.117",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/training-units: optionale Keyset-Pagination (cursor_planned_date YYYY-MM-DD, cursor_id, optional cursor_planned_time bei gesetzter Startzeit; bei Keyset ist limit erforderlich). Sortierung um stabile Tie-Breaks ergänzt: (planned_time_start IS NULL), id.",
|
||||
"Migration 061: Teilindizes training_units für ASC/DESC-Keyset inkl. id (ersetzt idx_training_units_scheduled_order).",
|
||||
"frontend api.listTrainingUnits: Query-Parameter für Cursor durchreichen.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.116",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Frontend: Org-Posteingang lädt beim ersten Mount per requestIdleCallback (Fallback setTimeout), um parallele API-Aufrufe beim Dashboard-Start zu entzerren; refresh/Inbox-Seite unverändert sofort.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.115",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"GET /api/exercises: optionale Keyset-Pagination (cursor_updated_at ISO-8601 + cursor_id), stabile Sortierung updated_at DESC, id DESC; „Mehr laden“ in Übungsliste und Picker nutzt Keyset statt OFFSET.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.114",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 060: Skalierung GET /api/exercises — Partial-Indizes official/club (+ updated_at, ohne archiviert); Junction-Indizes (exercise_id, is_primary) für List-Subqueries.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.113",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 059: Teilindex training_units(planned_date, planned_time_start) nur für Zeilen ohne framework_slot_id — list_training_units Sortierung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.112",
|
||||
"date": "2026-05-14",
|
||||
"changes": [
|
||||
"Migration 058: Indizes exercises(updated_at DESC) und (created_by, updated_at DESC) für list_exercises-Sortierung und „meine Übungen“.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.111",
|
||||
"date": "2026-05-13",
|
||||
"changes": [
|
||||
"GET /api/dashboard/kpis: Kurzüberblick (meine Entwürfe, meine Übungen, abgeschlossene Einheiten Kalenderjahr) in einem Aufruf; Dashboard-UI nutzt den Endpunkt.",
|
||||
"Hilfsfunktion list_exercises_like_get in exercises-Router für programmatische Listen ohne Query-Defaults.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.110",
|
||||
"date": "2026-05-12",
|
||||
|
||||
@@ -66,6 +66,8 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
||||
- **Globaler Fähigkeitskatalog** mit hierarchischer Struktur (Kategorien, Stufen); Zuordnung zu Übungen.
|
||||
- **Trainingsmethoden-Katalog** (bestehende Domäne).
|
||||
- **Admin/Katalog-Pflege** für Fokusbereiche, Stile, Zielgruppen und Zusammenhänge (Plattform-Admin-Bereich).
|
||||
- **Planungs-Vorschläge (Phase 3):** Auf der Fähigkeiten-Seite können Schwerpunkte gewählt werden; Shinkan schlägt passende **Rahmenprogramme**, **Trainingsmodule** und **Regressionspfade** vor (Sortierung nach Trainingsgewicht).
|
||||
- **Fähigkeiten-Profile an Planungs-Bausteinen:** Listen zeigen pro Modul/Rahmenprogramm KPI-Kacheln (Top je Kategorie) mit **Score** und **Peer-Prozent** — Vergleich nur unter sichtbaren Bausteinen **desselben Typs** (Modul vs. Modul, nicht Modul vs. Plan). Filter analog zur Übungsliste (Modal, Chips, Baumauswahl).
|
||||
|
||||
### 4.3 Reifegradmodelle (Fähigkeitsmatrix)
|
||||
|
||||
@@ -75,10 +77,14 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
||||
### 4.4 Trainingsplanung
|
||||
|
||||
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
|
||||
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden.
|
||||
- **Phasen & parallele Streams (Breakout):** Eine Einheit kann aus abwechselnden **Ganzgruppenphasen** und **Parallelphasen** bestehen; in einer Parallelphase führen **mehrere Streams** (Teilstrecken) je eigene Abschnitte/Übungen. Planung über Breakout-UI; API liefert **`phases`** und flache **`sections`** (Migration **063**, siehe **`docs/HANDOVER.md`**). Technische Details: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden (Phasen in Vorlagen: Ausbau siehe Handover „offen“).
|
||||
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
|
||||
- **Trainingsmodule (Bibliothek):** wiederverwendbare Übungsfolgen; Übernahme in geplante Einheiten; **Fähigkeiten-Profil** und **Filter** in der Modul-Liste (Peer-Vergleich nur unter Modulen).
|
||||
- **Rahmenprogramm-Liste:** Suche und Filter (Katalog, Dauer, Fähigkeiten) — Peer-Vergleich nur unter Rahmenprogrammen.
|
||||
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
|
||||
- **Durchführung:** Ansicht zum Abarbeiten einer Einheit; **Coaching-Modus** als separater Erlebnispfad (generischer Zeit-Block pro Platzierung); bei **Kombinationsübungen** zusätzliche **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** siehe Kombination-Fachspez **Anhang A** (implementierter Umfang vs. nächste Stufen).
|
||||
- **Durchführung („Plan & Ablauf“):** Ablauf anhand Phasen/Streams darstellen und abarbeiten (inkl. Split-Logik in der Anzeige).
|
||||
- **Coaching-Modus:** eigener Ablauf mit Schritt-für-Schritt-Timeline, Stream-Wahl pro Parallelphase, Hinweis **„Parallelphase · Abschluss“** (Gruppen zusammenführen) vor der nächsten Ganzgruppenphase oder vor dem nächsten Split; **Nachbereitung** mit Ist-Minuten und Speichern wie in der Planung (inkl. **`phases`**). Nach erfolgreichem Speichern Wechsel zur **Plan- und Ablaufsicht** derselben Einheit. Bei **Kombinationsübungen** zusätzlich **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** (Fachspez **Anhang A**; Ausbauschritte B/C).
|
||||
|
||||
### 4.5 Medienbibliothek und Archiv
|
||||
|
||||
@@ -118,7 +124,8 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
|
||||
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
|
||||
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
|
||||
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
|
||||
- **Coach / Kombination:** nächste Stufen **Zeitleisten-Splitting** und **Archetyp-Timer** (Fachspez § 10.4 Stufe B/C; Umsetzungsplan Phase 4b–d); **geführtes Erfassen** von `method_profile` im Übungseditor.
|
||||
- **Coach / Kombination:** Kombi-spezifische **Archetyp-Stufen B/C** (Zeitleisten-Splitting, archetypnahe Timer — Fachspez § 10.4); **geführtes Erfassen** von `method_profile` im Übungseditor.
|
||||
- **Breakout:** vollständige **Server-Spiegelung** neuer Abschnitte in **`phases`**; **Vorlagen** phasengleich mit Kalendereinheit; optional **Stream-Tabs** in der Durchführungsansicht laut technischer Spec — siehe **`docs/HANDOVER.md`** (Arbeitspaket „Coaching & Breakout“).
|
||||
|
||||
---
|
||||
|
||||
@@ -126,5 +133,7 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-05-20 | Fähigkeiten-Scoring Phase 3: Peer-Kontext, Listen-Filter Module/Rahmen, Planungs-Vorschläge. |
|
||||
| 2026-05-14 | Trainingsplanung: Phasen/parallele Streams, Coaching (Rejoin, Nachbereitung → Planansicht); Lücken §5 ergänzt. Verweis `HANDOVER.md`. |
|
||||
| 2026-05-12 | Erstfassung für Übergabe an fachliches Design; Abgleich mit Code-Navigation, `version.py`, `HANDOVER.md`, `FEATURES_DELIVERED`, `DOMAIN_MODEL`. |
|
||||
| 2026-05-12 | Kombinationsübungen + Coaching Stufe A; Verweise auf Fachspezifikation (`…Kombinationsuebungen…` V3 Anhang A) und `TRAINING_MODULES_IMPLEMENTATION_PLAN.md`. |
|
||||
+61
-15
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-12
|
||||
**App-Version / DB-Schema:** App **0.8.110**, DB-Schema **`20260512057`** (`backend/version.py`: `APP_VERSION`, `DB_SCHEMA_VERSION`)
|
||||
**Stand:** 2026-05-20
|
||||
**App-Version / DB-Schema:** App **`0.8.149`** (Einheiten-Editor Vollseite), DB-Schema **`20260515063`** — maßgeblich **`backend/version.py`**: `APP_VERSION`, `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**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
|
||||
|
||||
@@ -20,6 +20,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
| Thema | Pfad |
|
||||
|--------|------|
|
||||
| **Architektur-Zielbild, Refaktor, Roadmap, Regeln** | **`docs/architecture/README.md`** |
|
||||
| **Performance-Baseline (Phase 0)** | **`docs/architecture/BASELINE_SNAPSHOT.md`**, **`scripts/load/README.md`** |
|
||||
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
|
||||
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
|
||||
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||
@@ -33,6 +35,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| **Umsetzungsplan** (Module/Kombination/Coach) | `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` |
|
||||
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
|
||||
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
|
||||
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
|
||||
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
|
||||
@@ -67,6 +70,15 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
|
||||
|
||||
### 2.6 Gewichtetes Fähigkeiten-Scoring (Phase 3, Stand 2026-05-20)
|
||||
|
||||
- **Spec:** `.claude/docs/technical/SKILL_SCORING_SPEC.md`
|
||||
- **Backend:** `skill_scoring.py`, `routers/skill_profiles.py` — Profile on-the-fly aus Übungsvorkommen + `exercise_skills`; **Peer-Kontext getrennt** (`framework_program` | `training_module` | `progression_graph`) über `library_content_visibility_sql`
|
||||
- **Metriken:** Trainingsgewicht (`weight`); **Peer-%** (`universal_percent`, max. 100 %) nur unter sichtbaren Bausteinen **desselben Typs**; ★ = stärkster Peer je Fähigkeit
|
||||
- **API:** Skill-Profile pro Artefakt; `POST /api/skill-profiles/batch-summaries` für Listen; `GET /api/skill-discovery/suggestions`
|
||||
- **Frontend:** KPI-Kacheln + Filter-Modal (UX wie Übungsliste) auf **`/planning/framework-programs`** und **`/planning/training-modules`**; Panels in Editoren; Discovery auf Fähigkeiten-Seite; `SkillTreeMultiSelect` mit Portal-Dropdown in Modals
|
||||
- **Offen (Backlog):** Corpus-Caching bei großen Bibliotheken; Tests für Typ-Trennung; Filter-Persistenz; Skill-Filter im Dialog „Rahmen übernehmen“; API-Umbenennung `club_*` → Peer-Namen
|
||||
|
||||
---
|
||||
|
||||
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
|
||||
@@ -74,7 +86,39 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
|
||||
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||
|
||||
### Trainingsmodule, Kombinationsübungen und Coach (Stand **0.8.110**)
|
||||
### Trainingsplanung: Einheiten-Editor als Vollseite (Stand **0.8.149**)
|
||||
|
||||
- **Routen:** `/planning` (Hub), `/planning/units/new`, `/planning/units/:id/edit`; Legacy `/planning?unit={id}` → Redirect auf Edit-Route.
|
||||
- **Code:** `TrainingUnitEditPage.jsx`, `TrainingUnitFormShell.jsx`, `planningUnitRoutes.js`, `trainingUnitEditorCore.js` (Payload-Drift-Schutz + Vitest).
|
||||
- **Hub:** `TrainingPlanningPageRoot.jsx` ohne Einheiten-Modal; Modals nur noch Import, Trainer zuweisen, Rahmen-Session/Modul aus Liste.
|
||||
- **Spec / DoD:** `docs/architecture/TRAINING_UNIT_EDIT_PAGE_MIGRATION.md`; Playwright **14–15** (Edit-Route, Legacy-Redirect).
|
||||
|
||||
### Trainingsplan: Phasen, parallele Streams und Coaching (Stand **0.8.137–0.8.140**)
|
||||
|
||||
- **Schema / API:** Migration **063** — `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` bzw. `parallel_stream_id`. **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und weiterhin flache **`sections`**. **`PUT/POST`** mit **`phases`** für Breakout-Einheiten (vgl. `CHANGELOG` **0.8.138**); Legacy: flache `sections` → implizite Ganzgruppen-Phase.
|
||||
- **Planung (Frontend):** Breakout-Panel — neue Ganzgruppen-/parallele Phase, Streams in der Parallelphase; Speichern sendet `phases` bei phasierten Einheiten (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`).
|
||||
- **Durchführung „Plan & Ablauf“:** `TrainingUnitRunPage.jsx` nutzt **`sectionsWithPlanLocForDisplay`** / **`buildPlanRunViewModelFromSections`** aus **`frontend/src/utils/trainingPlanUtils.js`**, damit Anzeige mit Phasen/Streams konsistent ist (inkl. Normalisierung fehlender `planLoc` auf flachen Sektionen).
|
||||
- **Coaching-Modus (`TrainingCoachPage.jsx`):**
|
||||
- Flache Timeline aus Phasen (`flattenPlanTimeline`): **Split-Punkte** (`branch_gate`) bis Stream-Wahl, eine gewählte Spur pro Parallelphase, **Outline**, Timer, Ist-Minuten pro Item.
|
||||
- **Rejoin nach Parallelphase:** Beim Übergang **Parallel → Ganzgruppe** (oder **Parallel → nächster Split** / `branch_gate`) erscheint die Karte „Parallelphase · Abschluss“ mit **„Gruppen zusammengeführt — weiter mit dem Plan“**, solange noch Einträge folgen; am Planende weiter **„Zur Nachbereitung“** (`coachShouldPromptSplitRejoinTransition` in `trainingPlanUtils.js`).
|
||||
- **Nachbereitung / Speichern:** Payload über **`buildCoachSavePlanPayload`** (wie Planungseditor: **`phases`**, keine Zerstörung phasierter Struktur). Nach erfolgreichem Speichern: Coach-Session-Storage bereinigt, **`navigate('/planning/run/:unitId', { replace: true })`** (Plan & Ablauf).
|
||||
- **Robustheit:** Abschnitte ohne Eintrag im `phases`-Baum, die nach Erben fälschlich **`parallel`** wären, werden für die **Anzeige** als **Ganzgruppenblock** nach der letzten bekannten Phasen-Ordnung ausgewiesen (`sectionsWithPlanLocForDisplay`).
|
||||
- **Konzept / technische Spec:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||
|
||||
#### Arbeitspaket „Coaching & Breakout“ — noch offen
|
||||
|
||||
| # | Thema | Kurzbeschreibung |
|
||||
|---|--------|------------------|
|
||||
| 1 | **Backend / Datenkonsistenz** | Neue oder verschobene Sektionen konsistent in **`phases`** persistieren (nicht nur Client-Normalisierung). |
|
||||
| 2 | **UX nach Speichern** | Optional: **im Coach bleiben** vs. **Planansicht** (aktuell: immer Plan & Ablauf). |
|
||||
| 3 | **Kantenfälle Coach** | „Fertig“ bei abweichendem **Timer-Owner** vs. **Rejoin**/letzter Schritt prüfen. |
|
||||
| 4 | **Tests** | Smoke: zwei Splitphasen, Ganzgruppe dazwischen/am Ende, Nachbereitung speichern, Rejoin. |
|
||||
| 5 | **Run-UI vs. Spec** | Technische Spec §5.2 (Tabs pro Stream): Abgleich mit **`TrainingUnitRunPage`**. |
|
||||
| 6 | **Trainer pro Stream** | UI und Policy zu **`assigned_trainer_profile_ids`** / Kopf-Co-Trainer offen. |
|
||||
| 7 | **Vorlagen** | `training_plan_templates` phasen-/stream-kompatibel (Spec §5.3). |
|
||||
| 8 | **Kombi-Coach B/C** | Fachspez **§ 10.4 / § 10.6**, `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` Phase **4**. |
|
||||
|
||||
### Trainingsmodule, Kombinationsübungen und Coach Stufe A
|
||||
|
||||
- **Fachspez & Drift-Schutz:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (**§ 10.2.1** IDs, **§ 10.4** Coaching-Stufen, **§ 10.6** Produkt-Backlog, **Anhang A** Abgleich).
|
||||
- **Umsetzungsplan:** `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase **2** / **4** teilweise; Pakete **4a–g** — u. a. **4e** Archetyp-Admin, **4f** Massen-Vorbelegung, **4g** Backend-Validierung).
|
||||
@@ -153,17 +197,18 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
## 7. Nächste Session — sinnvolle Arbeitspakete
|
||||
|
||||
1. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
||||
2. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||
3. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
4. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
5. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||
6. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||
7. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||
8. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||
9. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||
10. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||
11. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
|
||||
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
||||
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||
|
||||
---
|
||||
|
||||
@@ -172,7 +217,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Bereich | Einstieg |
|
||||
|---------|----------|
|
||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
||||
| Coach-Kombination / Merge-Profil (Frontend) | `TrainingCoachPage.jsx`, `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
|
||||
| Coach, Plan-Timeline, PUT-Payload phasiert | `TrainingCoachPage.jsx`, **`frontend/src/utils/trainingPlanUtils.js`** (`flattenPlanTimeline`, `buildCoachSavePlanPayload`, `sectionsWithPlanLocForDisplay`, Split-Rejoin-Helfer), `TrainingUnitRunPage.jsx` |
|
||||
| Coach-Kombination / Merge-Profil (Frontend) | `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
|
||||
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
|
||||
| Frontend API | `frontend/src/utils/api.js` |
|
||||
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Phase 0 – Performance-Baseline (Shinkan Jinkendo)
|
||||
|
||||
**Zweck:** Reproduzierbarer Startpunkt **vor** Phase 2 (Backend-Lesepfade, Summary-API).
|
||||
**Stand:** 2026-05-13 · Backend-App-Version laut `backend/version.py`: **0.8.110**
|
||||
|
||||
Nach grösseren Deployments oder Schema-Änderungen: Bundle-Abschnitt neu erfassen (`npm run build`); API-/k6-Werte bei Bedarf aktualisieren.
|
||||
|
||||
---
|
||||
|
||||
## 1. Frontend-Bundle (`npm run build`)
|
||||
|
||||
Messung: Repo-Root → `cd frontend && npm run build` (Vite Production).
|
||||
**Hinweis:** Dateinamen mit Hash (`index-*.js`) ändern sich pro Build; relevant sind Grössenordnungen und gzip.
|
||||
|
||||
### 1.1 Einstieg & globale Vendor-Chunks (Auszug letzter Lauf CI-lokal)
|
||||
|
||||
| Asset (Muster) | raw kB | gzip kB | Rolle |
|
||||
|----------------|--------|---------|--------|
|
||||
| `index.html` | 1.84 | 0.73 | Einstieg |
|
||||
| `index-*.css` | 127.55 | 21.58 | Globale Styles |
|
||||
| `index-*.js` (App-Shell / Router) | 64.83 | 17.45 | Haupteinstieg nach Code-Splitting |
|
||||
| `vendor-react-*.js` | 142.42 | 45.67 | React + DOM |
|
||||
| `vendor-router-*.js` | 65.94 | 22.51 | react-router |
|
||||
| `vendor-markdown-*.js` | 161.54 | 49.31 | Markdown-Stack (wird mit Routen geladen) |
|
||||
| `vendor-pdf-*.js` | 390.80 | 128.98 | jsPDF (Route-bezogen) |
|
||||
|
||||
### 1.2 Schwerste Route-Chunks (lazy, nach Route)
|
||||
|
||||
| Bereich | typ. Chunk-Grösse (raw / gzip) | Datei-Muster (Beispiel) |
|
||||
|---------|-------------------------------|-------------------------|
|
||||
| Trainingsplanung | 71.81 kB / 18.67 kB | `TrainingPlanningPage-*.js` |
|
||||
| Übung bearbeiten | 91.31 kB / 22.49 kB | `ExerciseFormPage-*.js` |
|
||||
| Medienbibliothek | 59.42 kB / 13.69 kB | `MediaLibraryPage-*.js` |
|
||||
| Dashboard | 19.97 kB / 5.93 kB | `Dashboard-*.js` |
|
||||
|
||||
**Abnahme Phase 0 (Bundle):** Zahlen dokumentiert; Re-Run: `npm run build` und Tabelle abgleichen.
|
||||
|
||||
---
|
||||
|
||||
## 2. API-Latenz (p95) – Top-Routen
|
||||
|
||||
**Messung** erfolgt auf **Zielumgebung** (z. B. dev.shinkan / prod) mit gleicher Topologie wie Nutzer (HTTPS, Proxy). Nicht aus dem leeren Arbeitsverzeichnis ohne laufendes Backend messbar.
|
||||
|
||||
### 2.1 Vorgehen (empfohlen)
|
||||
|
||||
- **Access-Logs** des Reverse-Proxy (Request-Zeit), oder
|
||||
- **APM** / OpenTelemetry, oder
|
||||
- **k6** mit authentifizierten Szenarien (Token aus Testaccount; Header `X-Auth-Token`, ggf. `X-Active-Club-Id`), oder
|
||||
- manuell: wiederholte `curl -w '%{time_total}\n'` mit gleichem Token
|
||||
|
||||
### 2.2 Vorlage (aus Umgebung ausfüllen)
|
||||
|
||||
| Route (Beispiel) | Methode | p95 (ms) | Datum / Umgebung | Bemerkung |
|
||||
|------------------|---------|----------|------------------|-----------|
|
||||
| `/api/profiles/me` | GET | *—* | *nach Messung* | |
|
||||
| `/api/exercises` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
|
||||
| `/api/training-units` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
|
||||
| `/api/media-assets` (Liste) | GET | *—* | *nach Messung* | |
|
||||
| `/health` | GET | *—* | *nach Messung* | k6: siehe `scripts/load/` |
|
||||
|
||||
**Abnahme Phase 0 (API):** Verfahren steht; Tabelle mindestens für **`/health`** nach erstem k6-Lauf befüllbar; übrige Zeilen bei nächstem Monitoring-Export.
|
||||
|
||||
---
|
||||
|
||||
## 3. Lasttestszenario
|
||||
|
||||
### 3.1 E2E-Smoke (fachlicher Pfad)
|
||||
|
||||
- **Befehl:** Repository-Root, `npm run test:e2e` (setzt `PLAYWRIGHT_BASE_URL`, Testuser per Env, siehe `.gitea/workflows/test.yml`).
|
||||
- **Abdeckung:** Login, Dashboard, Navigation u. a. – entspricht grob „Login → Dashboard → weitere Screens“.
|
||||
- **Baseline notieren:** Dauer eines vollen Laufs, Anzahl passed (z. B. 26 Tests), Datum.
|
||||
|
||||
| Messung | Wert | Datum |
|
||||
|---------|------|-------|
|
||||
| Playwright Gesamtlauf (lokal/CI) | *—* | *nach Messung* |
|
||||
| passed / total | 26 / 26 (Ziel) | |
|
||||
|
||||
### 3.2 EXPLAIN (Phase 2 – Lesepfade)
|
||||
|
||||
- **Datei:** **`scripts/load/explain-readpaths.sql`** — repräsentative Statements für `list_exercises` / Stufenfilter / `training_units`; auf der Ziel-DB mit `EXPLAIN (ANALYZE, BUFFERS)` ausführen (Token/Tenant nicht im Skript; wie bei echten API-Queries filtern).
|
||||
|
||||
### 3.3 k6 – parallele /health
|
||||
|
||||
- **Skript:** `scripts/load/k6-health-baseline.js`
|
||||
- **CI:** Läuft **automatisch** im Gitea-Workflow im Job **`k6-health-baseline`** (eigenständig, ohne Playwright; `.gitea/workflows/test.yml`). Parallel dazu **Playwright** im Job **`playwright-tests`**.
|
||||
- **Lokal:** siehe `scripts/load/README.md`
|
||||
- **Baseline notieren:** k6-Ausgabe `http_req_duration` p(95), Checks succeeded.
|
||||
|
||||
| Szenario | p95 / Fehlerquote | Datum / BASE_URL |
|
||||
|----------|-------------------|------------------|
|
||||
| 10 VUs, 30 s `/health` | *—* | *nach Messung* |
|
||||
|
||||
### 3.4 Aus dem Deployment-/CI-Log übernehmen (k6 `k6-health-baseline`)
|
||||
|
||||
Das Skript `scripts/load/k6-health-baseline.js` nutzt **10 VUs**, **30 s**, Ziel **`GET {BASE_URL}/health`** (siehe Workflow-Env für `BASE_URL`).
|
||||
|
||||
**In die Tabelle oben (Abschnitt 3.3) eintragen — aus der k6-Zusammenfassung am Ende des Jobs:**
|
||||
|
||||
| Feld in BASELINE_SNAPSHOT | Wo im k6-Log (typisch) |
|
||||
|---------------------------|-------------------------|
|
||||
| **p95** (Latenz ms) | Zeile **`http_req_duration`** → Wert **`p(95)=…`** (ganze Zahl oder ms mit Einheit wie `12.34ms`) |
|
||||
| **Fehlerquote** | Zeile **`http_req_failed`** → z. B. `0.00%` bzw. `✓ 0%` — oder kurz „0 %“ notieren |
|
||||
| **Checks** (optional) | Zeile **`checks`** → Anteil **`✓`** (soll **100 %** sein, sonst Hinweis) |
|
||||
| **Datum / BASE_URL** | Deploy-Datum + die **öffentliche** Basis-URL des Laufs (wie im Workflow gesetzt, z. B. `https://dev.shinkan.jinkendo.de`) |
|
||||
| **App-Version** (optional) | dieselbe wie im Deploy (`backend/version.py` / Release), damit M2-Vergleich ressortfähig bleibt |
|
||||
|
||||
**Zusätzlich (Abschnitt 2.2):** nur die Zeile **`/health` GET`** mit dem **gleichen** p95 befüllen, wenn ihr dort noch Platzhalter habt — echte API-Routen (`/api/...`) kommen weiter aus Monitoring/k6 mit Auth, nicht aus diesem Job.
|
||||
|
||||
---
|
||||
|
||||
## 4. Nächster Schritt (Roadmap)
|
||||
|
||||
- **Phase 0** ist für den Pipeline-Teil **abgeschlossen**: Bundle dokumentiert; **k6** läuft in CI nach jedem relevanten Deploy (mit Test-Suite); API-p95-Tabellen kann das Team aus Monitoring weiter befüllen (optional, kein Deploy-Blocker).
|
||||
- **Phase 2** (Backend Lesepfade) ist **abgeschlossen** — siehe [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md); nach Deploy **p95 erneut messen** und mit den Werten aus Abschnitt 2 dieser Datei vergleichen (**Meilenstein M2**).
|
||||
|
||||
---
|
||||
|
||||
## Verweise
|
||||
|
||||
- Roadmap: [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md)
|
||||
- k6: [scripts/load/README.md](../../scripts/load/README.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
# Architektur: Zielbild, Refaktor, Regeln (Shinkan Jinkendo)
|
||||
|
||||
Dieses Bündel ist die **Leitlinie für die große Refaktorierung** nach dem MVP. Es ergänzt die bestehenden Pflichtdokumente (`.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht, Media-Spec) und ist für **Wartbarkeit, Performance und sichere Erweiterung** verbindlich, soweit hier ausdrücklich festgelegt.
|
||||
|
||||
## Inhalt
|
||||
|
||||
| Datei | Zweck |
|
||||
|--------|--------|
|
||||
| [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md) | Zielarchitektur (Frontend, API, Daten), Qualitätsziele, Einbindung neuer Features |
|
||||
| [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md) | Erfasste Architekturschuld, Reihenfolge und Massnahmen zur Behebung |
|
||||
| [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md) | Phasen, Meilensteine, Abnahmekriterien, Aufwandsschwerpunkte |
|
||||
| [`frontend/src/api/client.js`](../../frontend/src/api/client.js) | Phase 4: zentraler HTTP-Client (`request`, `ACTIVE_CLUB_STORAGE_KEY`, `API_URL`, `mergeActiveClubHeader`) |
|
||||
| [`frontend/src/api/exercises.js`](../../frontend/src/api/exercises.js) | Phase 4: Übungen, Medien/Archiv, Progressionsgraphen, KI-Hilfen |
|
||||
| [`frontend/src/api/planning.js`](../../frontend/src/api/planning.js) | Phase 4: Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, KPIs) |
|
||||
| [BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md) | Phase 0: Bundle-, API- und Last-Baseline (Messvorlagen, Vergleich nach Phase 2) |
|
||||
| [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) | **Verbindliche** Shinkan-spezifische Regeln (Ergänzung zu den globalen Rules) |
|
||||
|
||||
## Tests (E2E / Refaktor-Budget)
|
||||
|
||||
- **`tests/dev-smoke-test.spec.js`** – Playwright-Suite (Smoke + Compliance). Enthält u. a. **Test 8:** nach Login und **Reload** des Dashboards werden GET-Aufrufe zu `/api/profiles/me` und `/api/training-units` gezählt (Absicherung Dashboard-Refaktor Phase 1). Ausführung: `npm run test:e2e`; CI: `.gitea/workflows/test.yml` Job **playwright-tests**. **k6**-Baseline: Job **`k6-health-baseline`** (siehe `scripts/load/README.md`).
|
||||
|
||||
## Pflege
|
||||
|
||||
- Bei abgeschlossenen Phasen: Roadmap und Remediation-Dokument aktualisieren; bei Regeländerungen: nur mit **expliziter Projektfreigabe** (gleiches Verfahren wie bei `.claude/rules/ARCHITECTURE.md`).
|
||||
- Querschnitt: **`docs/HANDOVER.md`** soll auf die aktive Roadmap-Phase verweisen.
|
||||
|
||||
## Bezug MVP
|
||||
|
||||
Die aktuelle Codebasis ist funktional MVP-tauglich; strukturell bestehen bekannte Schwerpunkte (grosse Seiten-Monolithen, API-Monolith im Client, redundante Lesepfade, schwere Listenqueries). Dieses Bündel definiert, wie nach **dem** MVP weitergebaut wird, ohne jedes neue Feature erneut mit **architektonischer Schuld** zu überfrachten.
|
||||
@@ -0,0 +1,133 @@
|
||||
# Architekturschuld – Erfassung und Behebungsschritte
|
||||
|
||||
Dieses Dokument listet **bewusst** die aus MVP und Code-Review bekannten strukturellen Themen auf und ordnet **konkrete Massnahmen** zu. Reihenfolge ist an die Roadmap gekoppelt; hier die inhaltliche Detailierung.
|
||||
|
||||
---
|
||||
|
||||
## A. Frontend
|
||||
|
||||
### A1 – „God Pages“ (Training, Übungsformular, Vereine)
|
||||
|
||||
**Schuld:** Sehr grosse Dateien (tausende Zeilen) mit viel State, vielen Effekten und eingebetteten Modals.
|
||||
|
||||
**Risiko:** Hohe Re-Render-Kosten, schwerer zu testen, hoher RAM auf schwachen Geräten, neue Features vergrössern die Datei weiter.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. **Inventar:** pro Page kurze Gliederung (Abschnitte) und Ziel-Komponenten benennen.
|
||||
2. **Extrahieren:** Zuerst isolierbare Blöcke (Listen, Modals, Sidebar, Form-Sektionen) in Unterkomponenten; Props/Oberfläche dokumentieren.
|
||||
3. **Hooks:** wiederkehrende Logik (`useEffect`-Ketten, Filter-State) in `useXxx`-Hooks pro Domäne.
|
||||
4. **Optional `features/training/` o. ä.:** wenn 3+ zusammengehörige Komponenten entstehen.
|
||||
|
||||
**Erfolgskriterium:** Page-Datei unter dem in `VERBINDLICHE_REGELN_SHINKAN.md` genannten Soft-Limit oder dokumentierte Ausnahme.
|
||||
|
||||
---
|
||||
|
||||
### A2 – Monolithischer API-Client (`utils/api.js`)
|
||||
|
||||
**Schuld:** Eine Datei bündelt alle Endpoints; erschwert Tree-Shaking, Navigation und domänenweise Ownership.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. Verzeichnisstruktur festlegen, z. B. `frontend/src/api/` mit `client.js` (Token, `request`), `exercises.js`, `planning.js`, …
|
||||
2. Bestehende `api.js` schrittweise zur **Facade** (`export * from …`) degradieren oder re-exportieren.
|
||||
3. Neue Features **nur** in domänenspezifischen Dateien implementieren.
|
||||
|
||||
**Erfolgskriterium:** Kein Wachstum des Monolithen über bestehende Endpoint-Anzahl hinaus; mittelfristig dominieren kleine Module.
|
||||
|
||||
---
|
||||
|
||||
### A3 – Redundante und „chatty“ Client-Requests
|
||||
|
||||
**Schuld (Beispiele):** Dashboard lädt Profil erneut trotz Auth; mehrere nahezu gleiche `listTrainingUnits`-Aufrufe; doppelte `listExercises` für KPIs.
|
||||
|
||||
**Risiko:** Mehr Last auf API/DB, schlechtere UX auf langsamen Geräten.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. **Profil:** eine kanonische Quelle (Auth-Profil reicht für Anzeige; fehlende Felder gezielt nachladen oder Auth-Check erweitern – fachlich klären).
|
||||
2. **Dashboard:** einen **Summary-Endpoint** spezifizieren und implementieren (siehe Backend B1) oder Client auf einen aggregierten Aufruf reduzieren.
|
||||
3. **Org-Inbox / globale Fetches:** Ladestrategie definieren (on-demand vs. TTL vs. sichtbarkeitsabhängig) und `OrgInboxContext` entsprechend umbauen.
|
||||
|
||||
**Stand Umsetzung:** Gemeinsame Funktion `fetchOrgInboxSnapshot` für Mount und `refreshOrgInbox` (ein Codepfad, gleiche API-Calls). Optionales verzögertes Laden / TTL weiterhin offen.
|
||||
|
||||
**Erfolgskriterium:** Dashboard-Initialisierung ohne redundanten `getCurrentProfile`; ohne drei parallele fast gleiche Trainingslisten (oder dokumentierte Ausnahme).
|
||||
|
||||
---
|
||||
|
||||
### A4 – Schwere Abhängigkeiten
|
||||
|
||||
**Schuld:** PDF/Markdown/Canvas-Pfade ziehen grosse Chunks.
|
||||
|
||||
**Behebungsschritte:** Strikte `import()` an Nutzeraktion; keine statischen Top-Level-Imports schwerer Libs in gemeinsamen Einstiegspfaden.
|
||||
|
||||
**Erfolgskriterium:** Lighthouse / Bundle-Analyse zeigt schwere Libs nur auf betroffenen Routen.
|
||||
|
||||
---
|
||||
|
||||
## B. Backend
|
||||
|
||||
### B1 – Aggregations- und Summary-APIs
|
||||
|
||||
**Schuld:** Bildschirme holen mehrere Listen und aggregieren im Client.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. Endpoint(s) z. B. `GET /api/dashboard/summary` oder domänenspezifisch mit gleicher Sichtbarkeitslogik wie Einzel-Listen.
|
||||
2. Tests oder manuelle Checkliste gegen **Tenant-Leaks** (nur eigene/sehbare Daten).
|
||||
3. Versionierung in `version.py` bei neuem Router-Block oder signifikantem Modul-Update.
|
||||
|
||||
**Erfolgskriterium:** Fertigest Dashboard mit einer serverseitigen Zusammenfassung (oder festgelegte Client-Reduktion mit Messung).
|
||||
|
||||
---
|
||||
|
||||
### B2 – Listenqueries (z. B. Übungsliste)
|
||||
|
||||
**Schuld:** Korrelierte Subqueries pro Zeile können bei Wachstum teuer werden.
|
||||
|
||||
**Behebungsschritte:**
|
||||
|
||||
1. `EXPLAIN (ANALYZE, BUFFERS)` auf Produktions-näher Konfiguration mit realistischem `limit`.
|
||||
2. Indizes für Filter und Sortierung ergänzen.
|
||||
3. Refactoring: JOINs/LATERAL statt N-facher Subquery, wo messbar besser.
|
||||
|
||||
**Erfolgskriterium:** Dokumentierte p95-Zielwerte erreicht oder Trend verbessert (siehe Roadmap).
|
||||
|
||||
---
|
||||
|
||||
### B3 – Pagination
|
||||
|
||||
**Schuld:** Tiefe `OFFSET`-Werte skalieren schlecht.
|
||||
|
||||
**Behebungsschritte:** Keyset-Pagination für grosse Listen in späteren Phasen einführen; API-Vertrag dokumentieren.
|
||||
|
||||
---
|
||||
|
||||
## C. Querschnitt
|
||||
|
||||
### C1 – Messbarkeit
|
||||
|
||||
**Schuld:** Optimierung ohne Baseline.
|
||||
|
||||
**Behebungsschritte:** Einmalig Baseline (API p95, Bundle-Grössen Haupt-Route, ein Lasttest-Szenario) festhalten; wiederholen nach grossen Phasen.
|
||||
|
||||
---
|
||||
|
||||
### C2 – Dokumentation und Audit
|
||||
|
||||
**Schuld:** Wissen nur in Chats.
|
||||
|
||||
**Behebungsschritte:** `HANDOVER.md` und `ACCESS_LAYER_ENDPOINT_AUDIT.md` bei jedem grösseren API-Block aktualisieren; Roadmap-Phase abhaken.
|
||||
|
||||
---
|
||||
|
||||
## Mapping: Schuld → Regel
|
||||
|
||||
| Schuld | Primär-Regel (Shinkan) |
|
||||
|--------|-------------------------|
|
||||
| God Pages | S1, S2 |
|
||||
| API-Monolith | S3 |
|
||||
| Globale Fetches | S4 |
|
||||
| Chatty API | S5 |
|
||||
| Caching-Ideen | S6 |
|
||||
| Grössere Features ohne Messung | S7, S8 |
|
||||
@@ -0,0 +1,126 @@
|
||||
# Migration: Trainings-Einheit — Modal → Vollseiten-Editor
|
||||
|
||||
**Status:** Phase C abgeschlossen (Hub + Edit-Route produktiv)
|
||||
**Stand:** 2026-05-19
|
||||
**Bezug:** Architektur-Schuld A1 (`SCHULDEN_UND_REMEDIATION.md`), UX-Grundsatz Modals vs. Vollseiten
|
||||
|
||||
---
|
||||
|
||||
## 1. Ausgangslage
|
||||
|
||||
| Aspekt | Ist (Modal) | Soll (Vollseite) |
|
||||
|--------|-------------|------------------|
|
||||
| Bearbeiten / Neu | `TrainingPlanningUnitFormModal` über `TrainingPlanningPageRoot` | `TrainingUnitEditPage` unter eigener Route |
|
||||
| Hub | Liste + Kalender auf `/planning` | unverändert — nur Übersicht & Kurzaktionen |
|
||||
| Deep-Link | `/planning?unit={id}` (öffnet Modal, Query wird entfernt) | `/planning/units/{id}/edit` (bookmarkbar) |
|
||||
| Vergleich | Rahmenprogramm, Modul, Vorlage, Run/Coach | gleiches Muster |
|
||||
|
||||
**Warum Modal historisch:** Frontend Phase 3 (0.8.131) — Extraktion aus God-Page, **kein** bewusstes UX-Zielbild.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielbild (verbindlich)
|
||||
|
||||
### 2.1 Routen
|
||||
|
||||
| Route | Zweck |
|
||||
|-------|--------|
|
||||
| `/planning` | Hub: Gruppe, Liste/Kalender, Import, Zuweisen, Löschen, Links „Bearbeiten“ |
|
||||
| `/planning/units/new` | Neue Einheit (Query: `group`, `date`, optional `template`) |
|
||||
| `/planning/units/:id/edit` | Bestehende Einheit bearbeiten (Query optional: `mode=debrief`) |
|
||||
| `/planning/run/:unitId` | Durchführung (unverändert) |
|
||||
| `/planning/run/:unitId/coach` | Coaching (unverändert) |
|
||||
|
||||
Implementierung: `frontend/src/utils/planningUnitRoutes.js` — **einzige** Quelle für Pfade und Rückkehr-Kontext (Drift-Schutz).
|
||||
|
||||
### 2.2 Was Modal bleibt (Hub + Editor)
|
||||
|
||||
| Dialog | Ort | Begründung |
|
||||
|--------|-----|------------|
|
||||
| Rahmen-Import | Hub | Mehrfachauswahl + Datums-Vorschläge |
|
||||
| Trainer zuweisen | Hub | Kurzaktion aus Liste/Kalender |
|
||||
| Rahmen-Session / Modul aus Liste | Hub | Aktion auf gespeicherter Einheit ohne Editor |
|
||||
| Übungspicker, Modul einfügen, Peek | **Editor-Seite** | Kontext des Ablaufs |
|
||||
| Rahmen übernehmen / Modul aus Editor | **Editor-Seite** | Nach Speichern des Ablaufs |
|
||||
| Kombi-Ablauf bearbeiten | SectionsEditor (Sheet) | Fokussierter Sub-Dialog |
|
||||
|
||||
### 2.3 UI-Shell Editor
|
||||
|
||||
- `TrainingUnitFormShell.jsx` — reine Formular-UI (ohne Overlay), `page-form-shell` + `FormActionBar` (`variant="page"`).
|
||||
- Kein `FormModalOverlay` / kein Scroll-Lock auf der Editor-Seite nötig.
|
||||
|
||||
### 2.4 Rückkehr zum Hub
|
||||
|
||||
Beim Navigieren vom Hub zum Editor wird `location.state.planningReturn` gesetzt (Gruppe, Ansicht, Monat, Datumsfilter).
|
||||
Abbrechen / Speichern & schließen → `/planning?…` mit wiederhergestellten Query-Parametern.
|
||||
|
||||
Legacy: `/planning?unit={id}` → Redirect auf `/planning/units/{id}/edit` (301/Replace via Router).
|
||||
|
||||
---
|
||||
|
||||
## 3. Code-Struktur (Ziel)
|
||||
|
||||
```
|
||||
frontend/src/
|
||||
├── utils/
|
||||
│ ├── planningUnitRoutes.js # Pfade, Return-State, Legacy-Redirect
|
||||
│ ├── planningUnitRoutes.test.js # Vitest
|
||||
│ └── trainingUnitEditorCore.js # Reine Payload-/Form-Helfer
|
||||
│ └── trainingUnitEditorCore.test.js
|
||||
├── hooks/
|
||||
│ └── useTrainingUnitEditor.js # Laden, Speichern, Form-State (Edit-Page)
|
||||
├── components/planning/
|
||||
│ ├── TrainingUnitFormShell.jsx # Formular-UI (ex Modal-Inhalt)
|
||||
│ └── TrainingPlanningPageRoot.jsx # Hub only (~ weniger State)
|
||||
└── pages/
|
||||
└── TrainingUnitEditPage.jsx # Route-Container
|
||||
```
|
||||
|
||||
**Soft-Limit (S1):** `TrainingUnitEditPage.jsx` delegiert an Hook + Shell; PageRoot verliert Modal-State.
|
||||
|
||||
---
|
||||
|
||||
## 4. Phasen & Abnahme
|
||||
|
||||
| Phase | Inhalt | Abnahme / Tests |
|
||||
|-------|--------|-----------------|
|
||||
| **A** | Doku, `planningUnitRoutes`, `trainingUnitEditorCore`, Vitest | `npm run test --prefix frontend` grün |
|
||||
| **B** | `TrainingUnitFormShell`, `TrainingUnitEditPage`, Routen, Hub-Navigation, Modal entfernen | Playwright 14–15; Build grün |
|
||||
| **C** | Hub liest Return-Query; Dashboard-Links direkt auf Edit-Route; PageRoot weiter entschlacken | Manuell + E2E |
|
||||
| **D** (optional) | `useTrainingUnitEditor` weiter modularisieren; ungespeichert-Blocker wie Modul-Edit | S8 Checkliste |
|
||||
|
||||
### Definition of Done (Phase B)
|
||||
|
||||
- [x] Kein `TrainingPlanningUnitFormModal` mehr in Produktionspfad
|
||||
- [x] `data-testid="planning-unit-form"` auf Editor-Seite
|
||||
- [x] Speichern sendet identisches Payload wie zuvor (`buildTrainingUnitSavePayload`)
|
||||
- [x] Split-Sessions / `phases`-PUT unverändert (`buildPlanPayloadForSave`)
|
||||
- [x] Playwright 12–13 weiter grün; 14–15 neu
|
||||
- [x] `docs/HANDOVER.md` + Roadmap aktualisiert
|
||||
|
||||
---
|
||||
|
||||
## 5. Risiken & Mitigation
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Payload-Drift beim Speichern | Logik in `trainingUnitEditorCore.js` + Unit-Tests |
|
||||
| Kontextverlust Hub | `planningReturn` in `planningUnitRoutes.js` + Hub-Query-Restore |
|
||||
| Modul-Einfügen / Picker | Nur auf Edit-Page; gleiche Handler wie zuvor |
|
||||
| Doppelte Einträge Deep-Link | Legacy-Redirect; Dashboard später auf neue URL |
|
||||
| Große Edit-Page | Hook + Shell; PageRoot schrumpft |
|
||||
|
||||
---
|
||||
|
||||
## 6. Nicht-Ziele (dieser Sprint)
|
||||
|
||||
- Backend-API-Änderungen
|
||||
- Virtualisierung der Einheitenliste
|
||||
- Refactor `TrainingUnitSectionsEditor`
|
||||
- Coach/Run-Flows
|
||||
|
||||
---
|
||||
|
||||
## 7. Pflege
|
||||
|
||||
Nach Abschluss Phase B: Eintrag in `UMSETZUNGSPLAN_ROADMAP.md` (Phase 3 Nachzug), `SCHULDEN_UND_REMEDIATION.md` A1 Fortschritt, `backend/version.py` CHANGELOG.
|
||||
@@ -0,0 +1,157 @@
|
||||
# Umsetzungsplan und Roadmap – Refaktorierung Shinkan Jinkendo
|
||||
|
||||
**Aktueller Stand (laufend):**
|
||||
|
||||
- **Phase 0:** abgeschlossen – siehe **[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)** (Bundle festgehalten, API-/k6-Vorlagen + Skripte unter `scripts/load/`).
|
||||
- **Phase 1 (Teil):** Dashboard: kein zweites `getCurrentProfile`; Trainings-Vorschau über **`GET /api/dashboard/kpis`** (`training_home`); Playwright **Test 8** sichert API-Budget ab.
|
||||
- **Phase 1 (Teil):** Org-Inbox: **ein** gemeinsamer Ladepfad `fetchOrgInboxSnapshot` für Mount-`useEffect` und `refreshOrgInbox` (gleiche Requests, weniger Drift-Risiko; Verhalten unverändert).
|
||||
- **Phase 2:** **abgeschlossen** (2026-05-14) — Indizes 058–062, Keyset `/api/exercises` + `/api/training-units`, **`/api/dashboard/kpis`** inkl. `training_home`, EXPLAIN-Vorlagen **`scripts/load/explain-readpaths.sql`**.
|
||||
- **Offen Phase 1:** Inbox optional **TTL** / nur bei sichtbarem Widget.
|
||||
- **Phase 3 (abgeschlossen 2026-05-14):** Übungsliste modularisiert; Trainingsplanung/Übungsformular: **Page-Dateien unter Soft-Limit** — Implementierung in `TrainingPlanningPageRoot.jsx`, `ExerciseFormPageRoot.jsx`, `ExercisesListPageRoot.jsx`; `pages/*.jsx` nur Re-Export. Playwright **Tests 9–10**.
|
||||
- **Phase 4 (fortlaufend 2026-05-14):** API **Welle 1** `client.js`; **Welle 2** `planning.js`; **Welle 3** `exercises.js`; `utils/api.js` bleibt Facade (`export *`, `api`-Objekt `...exercises`, `...planning`).
|
||||
- **Trainingsplan Breakout / Coach (2026-05-14):** Phasen + parallele Streams (**063**, Frontend **0.8.137–0.8.140**), Coach-Rejoin und Nachbereitung — siehe **`docs/HANDOVER.md`**, **`technical/PARALLEL_TRAINING_STREAMS_SPEC.md`**.
|
||||
|
||||
**Ziel:** Nach MVP eine **nachhaltige** Architektur für Wachstum, **Performance** (Server + schwache Clients) und **sichere Feature-Erweiterung**.
|
||||
**Leitdokumente:** [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md), [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md), [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md).
|
||||
|
||||
---
|
||||
|
||||
## Leitplanken (vereinbart)
|
||||
|
||||
- **Kein Breaking** der Zugriffsschicht: neue und geänderte Endpoints folgen `get_tenant_context` / Audit wie bisher.
|
||||
- **Inkrementell:** Jede Phase liefert **nutzbaren** Stand (kein Big-Bang-Stillstand).
|
||||
- **Neue Features** während der Roadmap: **S8 Checkliste** und **S1/S3** strikt; wo möglich gleich im neuen API-Modul-Pfad.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 – Baseline (kurz, Pflicht)
|
||||
|
||||
**Status:** **Erledigt** (2026-05-13). Siehe **`docs/architecture/BASELINE_SNAPSHOT.md`** und **`scripts/load/`**.
|
||||
|
||||
| Task | Output |
|
||||
|------|--------|
|
||||
| API p95 der Top-5-Routen messen (z. B. `profiles/me`, `exercises` list, `training-units` list, `media-assets` list) | Vorlage + Messverfahren in **BASELINE_SNAPSHOT.md**; Werte nach erstem Lauf auf Dev/Prod eintragen |
|
||||
| Ein Lasttestszenario (Login → Dashboard → Übungen → Planung) | Playwright `npm run test:e2e` + k6 **`scripts/load/k6-health-baseline.js`** (README dort) |
|
||||
| Bundle: Grösse Einstieg + schwerste Route | In **BASELINE_SNAPSHOT.md** dokumentiert (Auszug `vite build`) |
|
||||
|
||||
**Abnahme:** Bundle dokumentiert; Mess- und Lastskripte vorhanden; API-Tabelle iterativ befüllbar. **Phase 2** beginnt nach diesem Freeze-Punkt.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 – Quick Wins Netzwerk (hoher ROI, geringes Risiko)
|
||||
|
||||
**Fokus:** Weniger redundante Requests, bessere Mobile-UX, kaum strukturelle Risiken.
|
||||
|
||||
| Task | Bezug Remediation | Status |
|
||||
|------|-------------------|--------|
|
||||
| Dashboard: Doppel-`getCurrentProfile` auflösen; kanonisches Profil klären | A3 | erledigt |
|
||||
| Dashboard: `listTrainingUnits`-Reduktion (ein Call statt zweier identischer) | A3 | erledigt |
|
||||
| Dashboard: `listExercises`-Doppelabruf / Summary-Call | A3, B1 | erledigt (`GET /api/dashboard/kpis`) |
|
||||
| Org-Inbox: Ladestrategie; Umsetzung Teil 1 (gemeinsamer Ladepfad, keine doppelte Logik) | A3 | erledigt |
|
||||
| Org-Inbox: TTL / verzögertes Laden (nur nach Bedarf) | A3 | teils (Erstlade per `requestIdleCallback`, max. 1,5s) |
|
||||
|
||||
**Abnahme:** Kein funktionales Leck; Netzwerk-Tab zeigt messbar weniger parallele gleiche Muster beim ersten Dashboard-Load.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 – Backend Lesepfade (Skalierung „viele Nutzer“)
|
||||
|
||||
**Status:** **Abgeschlossen** (2026-05-14).
|
||||
|
||||
**Voraussetzung:** Phase 0 abgeschlossen (**[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)**). Nach Deploy: p95 der Top-Routen erneut messen und mit Baseline vergleichen ([M2](#meilensteine-empfohlen)).
|
||||
|
||||
**Fokus:** DB und API stabil unter parallelen Lesern.
|
||||
|
||||
| Task | Bezug | Status |
|
||||
|------|-------|--------|
|
||||
| `EXPLAIN` + Index-Tuning für `list_exercises` und nächste schwere Listen | B2 | erledigt (Indizes 058–060, 062; Vorlagen **[explain-readpaths.sql](../../scripts/load/explain-readpaths.sql)**; Messung Team) |
|
||||
| Summary-API finalisieren/erweitern falls in P1 nur Teilbereich | B1 | erledigt (`GET /api/dashboard/kpis` + **`training_home`**) |
|
||||
| Keyset-Pagination für Listen mit Sort-Key | B3 | erledigt (`/api/exercises`, `/api/training-units`) |
|
||||
|
||||
**Lieferung:** Migrationen **058–062**; Keyset-Parameter wie dokumentiert in OpenAPI/Router; Dashboard nutzt **ein** KPI-Request für Kennzahlen und Trainings-Vorschau.
|
||||
|
||||
**Abnahme:** p95 der optimierten Routen nach Messung dokumentiert verbessert ggü. Phase 0 oder Obergrenze notiert (siehe Baseline-Tabelle).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 – Frontend-Struktur (Wartbarkeit + Client-Performance)
|
||||
|
||||
**Fokus:** God-Pages abbauen, Virtualisierung wo nötig.
|
||||
|
||||
| Task | Bezug |
|
||||
|------|--------|
|
||||
| Eine Page komplett zerteilen als Referenz (z. B. `TrainingPlanningPage` **oder** `ExerciseFormPage`) – Rest priorisiert nach Nutzung | A1 |
|
||||
| Virtualisierung für die längste produktive Liste | A1, S2 |
|
||||
| Schwere Imports auf `import()` umziehen (gezielt) | A4 |
|
||||
|
||||
**Teil umgesetzt (2026-05-13):** `ExercisesListPage` — Karten `ExerciseListCard.jsx`; Filter/Massenänderung `ExerciseListFilterModal.jsx` / `ExerciseListBulkModal.jsx`; Tab „Progressionsgraphen“ **lazy**; **Picker** virtualisiert; Gitter `data-testid` + `content-visibility`; Playwright **Tests 9–10**.
|
||||
|
||||
**Abgeschlossen (2026-05-14):** Routen bleiben unter `frontend/src/pages/`; schwere Implementierung in **`components/planning/TrainingPlanningPageRoot.jsx`**, **`components/exercises/ExerciseFormPageRoot.jsx`**, **`components/exercises/ExercisesListPageRoot.jsx`** — **`pages/*` nur Re-Export** (Soft-Limit ~500 Zeilen laut `VERBINDLICHE_REGELN_SHINKAN.md`).
|
||||
|
||||
**Abnahme:** Referenz-Page unter Soft-Limit; Regel S1 für neue Änderungen durchsetzbar.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 – API-Client Modularisierung
|
||||
|
||||
**Status:** **fortlaufend** (2026-05-14) — Welle 1: **`client.js`**; Welle 2: **`planning.js`**; Welle 3: **`exercises.js`**; **`utils/api.js`** bleibt vollständige Facade.
|
||||
|
||||
**Fokus:** Wartbarkeit für viele neue Features.
|
||||
|
||||
| Task | Bezug | Status |
|
||||
|------|-------|--------|
|
||||
| `frontend/src/api/client.js` — zentraler HTTP-Client | A2 | erledigt (Welle 1) |
|
||||
| `frontend/src/api/planning.js` — Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, Dashboard-KPIs) | A2 | erledigt (Welle 2) |
|
||||
| `frontend/src/api/exercises.js` — Übungen, Medien/Archiv, Varianten, Progressionsgraphen, KI | A2 | erledigt (Welle 3) |
|
||||
| Weitere Domänen-Module unter `frontend/src/api/` + Entlastung von `utils/api.js` | A2 | offen |
|
||||
| Neue Endpoints primär in Domänen-Dateien | S3 | offen |
|
||||
|
||||
**Abnahme:** Anteil neuer Module > X% der neuen Zeilen (Team-Ziel); Monolith wächst nicht weiter.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 – Vertiefung DB & Pagination
|
||||
|
||||
**Fokus:** Wachstum Datenbestand.
|
||||
|
||||
| Task | Bezug |
|
||||
|------|--------|
|
||||
| Keyset für weitere Listen | B3 |
|
||||
| Weitere Query-Refactorings nach Monitoring | B2 |
|
||||
|
||||
**Abnahme:** Dokumentierte Paginierungs-API; keine Regression in der Zugriffsschicht.
|
||||
|
||||
---
|
||||
|
||||
## Meilensteine (empfohlen)
|
||||
|
||||
| Meilenstein | Inhalt |
|
||||
|-------------|--------|
|
||||
| **M1** | Phase 0 + 1 abgeschlossen, HANDOVER aktualisiert |
|
||||
| **M2** | Phase 2 abgeschlossen, Lasttest / p95 nachziehen |
|
||||
| **M3** | Phase 3 abgeschlossen: Page-Dateien Soft-Limit (Re-Export); Virtualisierung Übungsliste |
|
||||
| **M4** | Phase 4 migrationsbereit für alle neuen Features |
|
||||
| **M5** | Phase 5 für Top-Listen abgeschlossen |
|
||||
|
||||
---
|
||||
|
||||
## Parallel: neue Features
|
||||
|
||||
- Jedes Feature: [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) **S8**.
|
||||
- Berührung schwerer Pfade: kurzer Performance-Nachweis (S7).
|
||||
|
||||
---
|
||||
|
||||
## Risiken und Mitigation
|
||||
|
||||
| Risiko | Mitigation |
|
||||
|--------|------------|
|
||||
| Summary-Endpoint falsch gefiltert | Code-Review + Abgleich mit Einzel-Endpoint-Logik; Tests mit mehreren Rollen |
|
||||
| Refaktor bricht PWA/Offline | Smoke-Test nach grossen Frontend-Phasen |
|
||||
| Keyset bricht alte Clients | Versionierte Query-Parameter oder Übergangsfenster |
|
||||
|
||||
---
|
||||
|
||||
## Pflege
|
||||
|
||||
Nach jeder Phase: **README** dieses Bündels prüfen; **Roadmap** Checkboxen/Status; **HANDOVER** nächste Phase nennen.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Verbindliche Architekturregeln – Shinkan (Ergänzung)
|
||||
|
||||
**Status:** verbindlich für die Shinkan-Codebasis, **ergänzend** zu:
|
||||
|
||||
- `.claude/rules/ARCHITECTURE.md`
|
||||
- `.claude/rules/CODING_RULES.md`
|
||||
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
|
||||
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
|
||||
|
||||
Bei Widerspruch gewinnt die **spezifischere** Regel zur **Zugriffsschicht und Governance** (Sicherheit vor Komfort). Bei Widerspruch zwischen diesem Dokument und allgemeinen Mitai-Template-Resten in `ARCHITECTURE.md` gilt für **Shinkan** dieses Dokument und die Shinkan-Pflichtlektüre in `CLAUDE.md`.
|
||||
|
||||
---
|
||||
|
||||
## S1 – Frontend: Grösse und Zerlegung von Seiten
|
||||
|
||||
1. **Soft-Limit:** Neue oder stark erweiterte Seiten sollen **unter ~500 Zeilen** im Page-File bleiben. Darüber: Auslagern in Komponenten/Hooks/Feature-Module mit klaren Namen.
|
||||
2. **Ausnahmen** nur mit Kurzbegründung im PR und Verweis auf Messung (Bundle/Performance) oder fachliche Unteilbarkeit.
|
||||
3. **Wiederkehrende UI-Blöcke** nicht per Copy-Paste über Seiten hinweg duplizieren; extrahieren in `components/` oder `features/`.
|
||||
|
||||
## S2 – Frontend: Listen und Speicher
|
||||
|
||||
1. Listen, die **typischerweise > 100 sichtbare oder gehaltene Einträge** im DOM ermöglichen, **müssen** virtualisiert werden (oder serverseitig strikt begrenzt + „mehr laden“ mit dokumentiertem UX – nicht beides unbegründet ignorieren).
|
||||
2. **Modals und zweite Raster** gleichzeitig zum Hauptbaum nur laden, wenn geöffnet (lazy mount), wo technisch machbar ohne UX-Bruch.
|
||||
|
||||
## S3 – Frontend: API-Zugriff
|
||||
|
||||
1. **Alle** API-Aufrufe über die zentrale Schicht (`utils/api` bzw. nach Modularisierung dessen Module). **Kein** `fetch('/api/...')` ohne diese Schicht.
|
||||
2. Während der Migration vom API-Monolithen: **neue** Endpoints ausschliesslich im **domänenspezifischen** Modul anlegen; nur bei Bedarf Re-Export über die Facade.
|
||||
|
||||
## S4 – Frontend: Globale Daten und Context
|
||||
|
||||
1. Neue **global** geladene Daten (jede authentifizierte Session) **bedürfen** technischer Begründung (Badge-Kritikalität, Sicherheit). Alternative: **on-demand** beim ersten Bezug oder **TTL-Cache** mit dokumentierter Invalidierung (`shinkan:…`-Events bleiben möglich).
|
||||
2. Context-`value`-Objekte **müssen** stabil gehalten werden (`useMemo` / `useCallback`), wenn nicht-triviale Unterbäume davon abhängen (bereits etabliert für Auth; gleiches Muster für neue Contexts).
|
||||
|
||||
## S5 – Backend: Lesepfad-Design
|
||||
|
||||
1. **Keine** mehrfachen fast identischen Listenaufrufe durch den Client für **denselben** zusammensetzbaren Bildschirm, wenn ein **einzelner** Summary-Endpoint unter gleicher Sichtbarkeitslogik möglich ist. Ausnahme: nachweislich unterschiedliche Cache-Lebensdauer oder unterschiedliche Rechte – dokumentieren.
|
||||
2. Neue Listen-Endpoints: **Paginierung** (`limit`/`offset` oder Keyset nach Roadmap) und Obergrenzen; keine „unbegrenzt alles“-Defaults für grosse Tabellen.
|
||||
3. Schwere SQL-Konstruktionen (viele korrelierte Subqueries pro Zeile) **nur** mit Kommentar **Warum** und Hinweis auf Indexlage oder geplantes Refactoring-Ticket.
|
||||
|
||||
## S6 – Backend: Mandanten und Caching
|
||||
|
||||
1. **Kein** HTTP- oder Anwendungs-Cache für mandantenspezifische oder nutzerspezifische Daten **ohne** expliziten Schlüssel (mindestens: Tenant-Kontext + relevante Parameter) und **Invalidierungsstrategie**.
|
||||
2. Öffentliche oder global geteilte Katalogdaten dürfen mit `ETag` / kurzem Cache optimiert werden – **nach** Abgleich mit Governance.
|
||||
|
||||
## S7 – Performance und Messung (Definition of Done für grössere Features)
|
||||
|
||||
1. Features, die neue Listen schwerer als bestehende Top-10-Queries machen oder **> ~50 KB** zusätzliches Client-JS pro Route erzeugen: **kurz** messen (Lighthouse mobil oder Netzwerk-Timing) und im PR festhalten.
|
||||
2. Regressions in **p95** der betroffenen API nach Deploy: bei Bedarf Rollback- oder Nachsteuerungskriterium mit Team vereinbaren (Zahlen Zielbild/Roadmap).
|
||||
|
||||
## S8 – Feature-Checkliste (DoD)
|
||||
|
||||
Vor Merge einer grösseren Erweiterung:
|
||||
|
||||
- [ ] Zugriffsschicht / Audit aktualisiert (falls zutreffend)
|
||||
- [ ] Kein Verstoss gegen S1–S7 ohne dokumentierte Ausnahme
|
||||
- [ ] Keine neue direkte DB-Nutzung im Frontend
|
||||
- [ ] Medien/Lifecycle (falls Medien betroffen) nach Media-Spec
|
||||
|
||||
---
|
||||
|
||||
**Änderungen** an diesen Regeln nur mit **expliziter Projektfreigabe** (analog zu `ARCHITECTURE.md`).
|
||||
@@ -0,0 +1,78 @@
|
||||
# Architektur-Zielbild – Shinkan Jinkendo
|
||||
|
||||
**Geltungsbereich:** Trainer-/Vereinsplattform, Multi-Tenancy und Governance nach bestehender Zugriffsschicht.
|
||||
**Ziele:** dauerhaft tragfähig, performant bei vielen gleichzeitigen Nutzern, akzeptabel auf **geringer Client-Leistung** (wenig RAM/CPU), **wartbar** und so strukturiert, dass **neue Features** ohne neue Grosseinkaufe an technischer Schuld einbindbar sind.
|
||||
|
||||
---
|
||||
|
||||
## 1. Leitprinzipien
|
||||
|
||||
1. **API-first, Mandanten-sicher** – Fachlogik und Sichtbarkeit serverseitig; das Frontend orchestriert und zeigt. Unverändert gemäss bestehender Regeln (`ACCESS_LAYER`, Governance-Helfer).
|
||||
2. **Schlanke Client-Oberfläche** – JavaScript pro Route begrenzen; schwere Abhängigkeiten nur bei Bedarf laden; Listen dort virtualisieren, wo Grössenordnungen wachsen.
|
||||
3. **Explizite Lesepfade** – Aggregation und Zusammenfassungen dort, wo mehrere fast gleiche Requests heute nötig sind (Dashboard, Badges), **statt** Chatty-Client-Muster.
|
||||
4. **Vorhersehbarkeit für die DB** – Listenqueries ohne unnötige O(n)·Subquery-Kosten pro Zeile; Indizes und Paginierungsstrategie sind Teil des Designs.
|
||||
5. **Feature-Einbindung per Checkliste** – Jedes neue Feature durchläuft die gleiche Architektur- und Performance-Checkliste (siehe Regeldokument), bevor es als „fertig“ gilt.
|
||||
|
||||
---
|
||||
|
||||
## 2. Zielbild Frontend
|
||||
|
||||
### 2.1 Struktur
|
||||
|
||||
- **Seiten (`pages/`)** bleiben Routing-Einstiege und Komposition; **keine** Dauerlösung für Logikblöcke > ~400–500 Zeilen in einer Datei – Auslagerung in `components/`, `hooks/`, `features/<name>/`.
|
||||
- **Feature-Ordner (Ziel):** wo sinnvoll `frontend/src/features/<domäne>/` mit klarer Grenze: UI + feature-spezifische Hooks; geteilte Helfer in `utils/` nur wenn domänenübergreifend.
|
||||
- **State:** Server-State über API (keine Business-Duplikation); UI-State lokal oder in bestehenden Contexts nur, wenn mehrere Schichten der Shell betroffen sind.
|
||||
|
||||
### 2.2 Performance und schwache Endgeräte
|
||||
|
||||
- Route-basiertes Code-Splitting bleibt Standard; **zusätzlich** innere `dynamic import()` für schwere Pakete (PDF, grosse Editoren), sobald eine Route sie braucht.
|
||||
- Lange Listen: **Virtualisierung** ab einer projektdefinierten Schwelle (siehe Regeln).
|
||||
- Globale Daten (Posteingang, Badges): **bedarfsgesteuert oder mit klar dokumentiertem Cache/TTL**, nicht pauschal jede Session mit voller Last – konkrete Strategie in Roadmap/Remediation.
|
||||
|
||||
### 2.3 API-Schicht im Client
|
||||
|
||||
- **Ziel:** Aufteilung des heutigen `utils/api.js`-Monolithen in **domänenspezifische Module** (z. B. `api/exercises`, `api/planning`, `api/media`), mit einer dünnen **Barrel- oder Facade-Export** für Kompatibilität während der Migration.
|
||||
- **Konstante:** alle HTTP-Aufrufe mit Token/Mandanten-Headern zentral; kein Rohtransport aus Komponenten.
|
||||
|
||||
---
|
||||
|
||||
## 3. Zielbild Backend / API
|
||||
|
||||
- **Router-Disziplin** unverändert: ein fachliches Modul, ein Router (bestehende Architekturregeln).
|
||||
- **Read-Model / Summary-Endpoints** für Dashboards und wiederkehrende Kacheln: **eine** abgestimmte Antwort pro Bildschirm, wo heute mehrere Listen parallel zusammengerechnet werden – unter strikt gleicher Sichtbarkeitslogik wie die Einzel-Endpoints.
|
||||
- **Listen:** sortierte Indizes passend zu `WHERE` + `ORDER BY`; für grosse Datenmengen langfristig **Keyset-Pagination** statt tiefer Offsets.
|
||||
- **Schwere Queries:** Korrelierte Subqueries pro Zeile nur, wenn messbar unkritisch; sonst JOIN-/Aggregate-Refactoring mit Review.
|
||||
|
||||
---
|
||||
|
||||
## 4. Zielbild Datenhaltung
|
||||
|
||||
- PostgreSQL bleibt System der Wahrheit; Migrationen nummeriert, wie heute.
|
||||
- Kein Mandanten-Cache ohne expliziten Key und Invalidierungskonzept (Regeldokument).
|
||||
|
||||
---
|
||||
|
||||
## 5. Einbindung neuer Features (vereinbartes Muster)
|
||||
|
||||
1. Fachliche Kurzspez (oder Ticket) mit **Sichtbarkeit** und **Nutzungskontext** (Mobile/Desktop, erwartete Listenlängen).
|
||||
2. API-Design: Endpoints, Payload-Grösse, Paginierung; Zugriffsschicht-Check.
|
||||
3. UI-Modul: Route lazy, Komponentengrösse, ggf. Virtualisierung.
|
||||
4. Messung: minimal Lighthouse/Netzwerk oder Server-Timing für den neuen Pfad.
|
||||
5. Audit-Eintrag bei neuen geschützten Endpoints (bestehendes Verfahren).
|
||||
|
||||
---
|
||||
|
||||
## 6. Nicht-Ziele dieses Zielbilds
|
||||
|
||||
- Ersetzen der Zugriffsschicht oder der Medien-Spec.
|
||||
- Microservices oder zweite Schreib-Datenbank ohne ausdrücklichen Projektbeschluss.
|
||||
- „Framework-Wechsel“ (React bleibt, solange nicht separat entschieden).
|
||||
|
||||
---
|
||||
|
||||
## 7. Abnahme „Zielbild erreicht“ (high level)
|
||||
|
||||
- Keine bekannten **God-Pages** oberhalb dokumentierter Schwellen ohne dokumentierte Ausnahme.
|
||||
- API-Client modularisiert oder klar phasierter Migrationsstand mit festem Enddatum.
|
||||
- Dashboard und vergleichbare Homescreens ohne redundante Mehrfach-Listen desselben Objekttyps (oder dokumentierte technische Begründung + Messung).
|
||||
- Datenbank-Lesepfade der Top-5-Listen unter definierter Latenz-Schwelle auf Referenz-Hardware in Lasttests (Werte in Roadmap festzulegen).
|
||||
@@ -5,9 +5,12 @@
|
||||
"scripts": {
|
||||
"dev": "vite --port 3098",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.13.24",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^0.344.0",
|
||||
"marked": "^18.0.3",
|
||||
@@ -19,6 +22,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"vite": "^5.1.4"
|
||||
"vite": "^5.1.4",
|
||||
"vitest": "^3.0.5"
|
||||
}
|
||||
}
|
||||
+35
-16
@@ -8,6 +8,7 @@ import {
|
||||
Outlet,
|
||||
} from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||
import { FormEditorActionsProvider, FormEditorBottomSlot } from './context/FormEditorActionsContext'
|
||||
import { ToastProvider } from './context/ToastContext'
|
||||
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
||||
import DesktopSidebar from './components/DesktopSidebar'
|
||||
@@ -30,6 +31,9 @@ const ClubsPage = lazy(() => import('./pages/ClubsPage'))
|
||||
const InboxPage = lazy(() => import('./pages/InboxPage'))
|
||||
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
|
||||
const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
|
||||
const TrainingPlanTemplatesListPage = lazy(() => import('./pages/TrainingPlanTemplatesListPage'))
|
||||
const TrainingPlanTemplateEditPage = lazy(() => import('./pages/TrainingPlanTemplateEditPage'))
|
||||
const PlanningLayout = lazy(() => import('./layouts/PlanningLayout'))
|
||||
const TrainingFrameworkProgramsListPage = lazy(() =>
|
||||
import('./pages/TrainingFrameworkProgramsListPage'),
|
||||
)
|
||||
@@ -39,6 +43,7 @@ const TrainingFrameworkProgramEditPage = lazy(() =>
|
||||
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
|
||||
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
|
||||
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
|
||||
const TrainingUnitEditPage = lazy(() => import('./pages/TrainingUnitEditPage'))
|
||||
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
|
||||
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
|
||||
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
|
||||
@@ -141,22 +146,26 @@ function ProtectedLayout() {
|
||||
|
||||
return (
|
||||
<OrgInboxProvider user={user}>
|
||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||
<div className="app-shell">
|
||||
<div className="app-shell__column">
|
||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||
<div className="app-header-mobile__top">
|
||||
<div className="app-logo">🥋 Shinkan</div>
|
||||
<FormEditorActionsProvider>
|
||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||
<div className="app-shell">
|
||||
<div className="app-shell__column">
|
||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||
<div className="app-header-mobile__top">
|
||||
<div className="app-logo">🥋 Shinkan</div>
|
||||
</div>
|
||||
<ActiveClubSwitcher variant="mobile" />
|
||||
</div>
|
||||
<ActiveClubSwitcher variant="mobile" />
|
||||
<div className="app-main">
|
||||
<InactiveMembershipBanner />
|
||||
<Outlet />
|
||||
</div>
|
||||
<FormEditorBottomSlot>
|
||||
<Nav showAdminNav={showAdminNav} />
|
||||
</FormEditorBottomSlot>
|
||||
</div>
|
||||
<div className="app-main">
|
||||
<InactiveMembershipBanner />
|
||||
<Outlet />
|
||||
</div>
|
||||
<Nav showAdminNav={showAdminNav} />
|
||||
</div>
|
||||
</div>
|
||||
</FormEditorActionsProvider>
|
||||
</OrgInboxProvider>
|
||||
)
|
||||
}
|
||||
@@ -223,15 +232,25 @@ const appRouter = createBrowserRouter([
|
||||
{ path: 'clubs', element: <ClubsPage /> },
|
||||
{ path: 'inbox', element: <InboxPage /> },
|
||||
{ path: 'skills', element: <SkillsPage /> },
|
||||
{
|
||||
path: 'planning',
|
||||
element: <PlanningLayout />,
|
||||
children: [
|
||||
{ index: true, element: <TrainingPlanningPage /> },
|
||||
{ path: 'framework-programs', element: <TrainingFrameworkProgramsListPage /> },
|
||||
{ path: 'training-modules', element: <TrainingModulesListPage /> },
|
||||
{ path: 'plan-templates', element: <TrainingPlanTemplatesListPage /> },
|
||||
{ path: 'units/new', element: <TrainingUnitEditPage /> },
|
||||
{ path: 'units/:id/edit', element: <TrainingUnitEditPage /> },
|
||||
],
|
||||
},
|
||||
{ path: 'planning/framework-programs/new', element: <TrainingFrameworkProgramEditPage /> },
|
||||
{ path: 'planning/framework-programs/:id', element: <TrainingFrameworkProgramEditPage /> },
|
||||
{ path: 'planning/framework-programs', element: <TrainingFrameworkProgramsListPage /> },
|
||||
{ path: 'planning/training-modules/new', element: <TrainingModuleEditPage /> },
|
||||
{ path: 'planning/training-modules/:id', element: <TrainingModuleEditPage /> },
|
||||
{ path: 'planning/training-modules', element: <TrainingModulesListPage /> },
|
||||
{ path: 'planning/plan-templates/:id', element: <TrainingPlanTemplateEditPage /> },
|
||||
{ path: 'planning/run/:unitId/coach', element: <TrainingCoachPage /> },
|
||||
{ path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
|
||||
{ path: 'planning', element: <TrainingPlanningPage /> },
|
||||
{ path: 'admin', element: <AdminHomeRedirect /> },
|
||||
{
|
||||
path: 'admin/users',
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* HTTP-Client: Token, Mandanten-Header, Fehler-Mapping.
|
||||
* Alle API-Aufrufe laufen über request() — siehe utils/api.js (Facade) und Domänenmodule (planning.js, exercises.js).
|
||||
*/
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
/** LocalStorage + Request-Header für Mandanten-Kontext */
|
||||
export const ACTIVE_CLUB_STORAGE_KEY = 'shinkan_active_club_id'
|
||||
|
||||
export function mergeActiveClubHeader(headers = {}) {
|
||||
const cid = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
if (cid && /^\d+$/.test(String(cid).trim())) {
|
||||
return { ...headers, 'X-Active-Club-Id': String(cid).trim() }
|
||||
}
|
||||
return { ...headers }
|
||||
}
|
||||
|
||||
/**
|
||||
* Generischer API-Aufruf inkl. X-Auth-Token und X-Active-Club-Id.
|
||||
*/
|
||||
export async function request(endpoint, options = {}) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
|
||||
const headers = mergeActiveClubHeader({
|
||||
...options.headers,
|
||||
})
|
||||
if (method !== 'GET' && method !== 'HEAD') {
|
||||
if (!headers['Content-Type'] && !headers['content-type']) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['X-Auth-Token'] = token
|
||||
}
|
||||
|
||||
const url = `${API_URL}${endpoint}`
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const d = parsed.detail
|
||||
throw new Error(typeof d === 'string' ? d : JSON.stringify(d))
|
||||
}
|
||||
if (response.status === 502) {
|
||||
throw new Error(
|
||||
'HTTP 502 (Bad Gateway): Der Reverse-Proxy hat die API nicht korrekt erreicht. Ist `shinkan-api` aktiv (`docker compose ps`, `docker logs shinkan-api`)? Bei Host-Routing nur einen Weg verwenden — alles auf Port 3003 (Nginx nach `backend:8000`) oder sauber `/api` → Backend-Port.'
|
||||
)
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError && (e.message === 'Failed to fetch' || e.message.includes('fetch'))) {
|
||||
const hint =
|
||||
API_URL && API_URL.length > 0
|
||||
? `Verbindung zum API unter ${API_URL} fehlgeschlagen. Läuft das Backend (z. B. Port 8098) und ist CORS erlaubt?`
|
||||
: 'Kein VITE_API_URL gesetzt: Anfragen gehen an die Frontend-URL und schlagen oft fehl. Setze in .env z. B. VITE_API_URL=http://localhost:8098 und starte Vite neu.'
|
||||
throw new Error(`${hint} [Technisch: ${e.message}; URL war ${endpoint}]`)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
/**
|
||||
* Übungen: Liste/CRUD, Medien & Archiv-Anbindung, Progressionsgraphen, KI-Hilfen.
|
||||
*/
|
||||
|
||||
import { stripHtmlToText } from '../utils/htmlUtils'
|
||||
import { normalizeAdvanceMode, parseComboRepSeriesCountUi } from '../utils/combinationMethodProfileUi'
|
||||
import { normalizeExerciseSkillIntensity } from '../constants/exerciseSkillIntensity'
|
||||
import { request, API_URL, ACTIVE_CLUB_STORAGE_KEY } from './client.js'
|
||||
|
||||
/** Wie `mergeActiveClubHeader` in client.js — lokal, damit Raw-`fetch`-Pfade nicht von einem Namensimport abhängen. */
|
||||
function withActiveClubHeaders(headers = {}) {
|
||||
const cid = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
|
||||
if (cid && /^\d+$/.test(String(cid).trim())) {
|
||||
return { ...headers, 'X-Active-Club-Id': String(cid).trim() }
|
||||
}
|
||||
return { ...headers }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Exercises
|
||||
// ============================================================================
|
||||
|
||||
export async function listExercises(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
Object.entries(filters).forEach(([k, v]) => {
|
||||
if (v === undefined || v === null) return
|
||||
if (typeof v === 'boolean') {
|
||||
q.set(k, v ? 'true' : 'false')
|
||||
return
|
||||
}
|
||||
if (Array.isArray(v)) {
|
||||
if (v.length === 0) return
|
||||
v.forEach((item) => {
|
||||
if (item !== '' && item !== undefined && item !== null && String(item).trim() !== '') {
|
||||
q.append(k, String(item))
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
if (String(v).trim() !== '') q.set(k, String(v))
|
||||
})
|
||||
const query = q.toString()
|
||||
return request(`/api/exercises${query ? '?' + query : ''}`)
|
||||
}
|
||||
|
||||
/** Formular → API-Body (M:N gemäß EXERCISES_API_SPEC + training_types) */
|
||||
export function buildExerciseApiPayload(formData, extras = {}) {
|
||||
const num = (v) => (v === '' || v == null ? null : Number(v))
|
||||
|
||||
const goalHtml = formData.goal || ''
|
||||
const execHtml = formData.execution || ''
|
||||
const goalText = stripHtmlToText(goalHtml)
|
||||
const execText = stripHtmlToText(execHtml)
|
||||
|
||||
if (!goalText && !execText) {
|
||||
throw new Error('Ziel oder Durchführung ausfüllen (mindestens eines, auch mit Formatierung).')
|
||||
}
|
||||
|
||||
const mapFocus = (formData.focus_areas_multi || [])
|
||||
.filter((x) => x && x.focus_area_id)
|
||||
.map((x) => ({ focus_area_id: Number(x.focus_area_id), is_primary: !!x.is_primary }))
|
||||
const mapStyles = (formData.training_styles_multi || [])
|
||||
.filter((x) => x && x.training_style_id)
|
||||
.map((x) => ({ training_style_id: Number(x.training_style_id), is_primary: !!x.is_primary }))
|
||||
const mapTTypes = (formData.training_types_multi || [])
|
||||
.filter((x) => x && x.training_type_id)
|
||||
.map((x) => ({ training_type_id: Number(x.training_type_id), is_primary: !!x.is_primary }))
|
||||
const mapTg = (formData.target_groups_multi || [])
|
||||
.filter((x) => x && x.target_group_id)
|
||||
.map((x) => ({ target_group_id: Number(x.target_group_id), is_primary: !!x.is_primary }))
|
||||
|
||||
const visibilityNorm = String(formData.visibility || 'private').trim().toLowerCase()
|
||||
|
||||
const payload = {
|
||||
title: (formData.title || '').trim(),
|
||||
summary: formData.summary || null,
|
||||
goal: goalHtml.trim() ? goalHtml : null,
|
||||
execution: execHtml.trim() ? execHtml : null,
|
||||
preparation: formData.preparation || null,
|
||||
trainer_notes: formData.trainer_notes || null,
|
||||
duration_min: num(formData.duration_min),
|
||||
duration_max: num(formData.duration_max),
|
||||
group_size_min: num(formData.group_size_min),
|
||||
group_size_max: num(formData.group_size_max),
|
||||
equipment: Array.isArray(formData.equipment) ? formData.equipment : [],
|
||||
focus_areas_multi: mapFocus,
|
||||
training_styles_multi: mapStyles,
|
||||
training_types_multi: mapTTypes,
|
||||
target_groups_multi: mapTg,
|
||||
age_groups: [],
|
||||
skills: (formData.skills || []).map((s) => ({
|
||||
skill_id: s.skill_id,
|
||||
intensity: normalizeExerciseSkillIntensity(s.intensity),
|
||||
required_level: s.required_level || null,
|
||||
target_level: s.target_level || null,
|
||||
})),
|
||||
visibility: visibilityNorm,
|
||||
status: formData.status || 'draft',
|
||||
club_id: visibilityNorm === 'club' ? num(formData.club_id) : null,
|
||||
exercise_kind:
|
||||
String(formData.exercise_kind || 'simple').toLowerCase() === 'combination'
|
||||
? 'combination'
|
||||
: 'simple',
|
||||
...extras,
|
||||
}
|
||||
|
||||
const isCombo = payload.exercise_kind === 'combination'
|
||||
|
||||
if (isCombo) {
|
||||
let mpObj = {}
|
||||
const mpRaw = typeof formData.method_profile_json === 'string' ? formData.method_profile_json.trim() : ''
|
||||
if (mpRaw) {
|
||||
try {
|
||||
const parsed = JSON.parse(mpRaw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('Ablaufprofil muss ein JSON-Objekt sein.')
|
||||
}
|
||||
mpObj = parsed
|
||||
} catch (e) {
|
||||
if (e instanceof SyntaxError) {
|
||||
throw new Error('Ablaufprofil (JSON): Syntax ungültig.')
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const slotRows = Array.isArray(formData.combination_slots) ? formData.combination_slots : []
|
||||
const combination_slots = []
|
||||
|
||||
function parseTimingField(raw) {
|
||||
if (raw === '' || raw == null || raw === undefined) return undefined
|
||||
const n = parseInt(String(raw), 10)
|
||||
return Number.isFinite(n) ? n : undefined
|
||||
}
|
||||
|
||||
for (let i = 0; i < slotRows.length; i += 1) {
|
||||
const row = slotRows[i] || {}
|
||||
let ids = Array.isArray(row.candidate_exercise_ids)
|
||||
? row.candidate_exercise_ids.map((x) => Number(x)).filter((n) => Number.isFinite(n))
|
||||
: []
|
||||
|
||||
/** Legacy: noch idsText Unterstützung für Import von älteren FormStand */
|
||||
if ((!ids || ids.length === 0) && typeof row.idsText === 'string' && row.idsText.trim()) {
|
||||
ids = row.idsText
|
||||
.split(/[\s,;]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((s) => parseInt(s, 10))
|
||||
.filter((n) => Number.isFinite(n))
|
||||
}
|
||||
|
||||
combination_slots.push({
|
||||
slot_index: i,
|
||||
title: (typeof row.title === 'string' && row.title.trim()) || null,
|
||||
candidate_exercise_ids: ids,
|
||||
})
|
||||
}
|
||||
|
||||
const slot_profiles_v1_next = []
|
||||
for (let i = 0; i < slotRows.length; i += 1) {
|
||||
const row = slotRows[i] || {}
|
||||
const o = { slot_index: i }
|
||||
const advanceMode = normalizeAdvanceMode(row.advance_mode)
|
||||
if (advanceMode !== 'timed') o.advance_mode = advanceMode
|
||||
const load = parseTimingField(row.load_sec)
|
||||
const crs = parseTimingField(row.consecutive_reps)
|
||||
const rsc = parseTimingField(row.rep_series_count)
|
||||
const intra = parseTimingField(row.intra_rep_rest_sec)
|
||||
const tran = parseTimingField(row.transition_after_sec)
|
||||
const serienUi = parseComboRepSeriesCountUi(row.rep_series_count)
|
||||
const allowInterSeriesPause =
|
||||
advanceMode === 'timed' ||
|
||||
((advanceMode === 'rep' || advanceMode === 'manual') && serienUi >= 2)
|
||||
|
||||
if (advanceMode === 'timed' && load !== undefined && load >= 0) o.load_sec = Math.round(load)
|
||||
if (crs !== undefined && crs >= 1) o.consecutive_reps = Math.round(crs)
|
||||
if (
|
||||
rsc !== undefined &&
|
||||
rsc >= 1 &&
|
||||
(advanceMode === 'rep' || advanceMode === 'manual')
|
||||
) {
|
||||
o.rep_series_count = Math.round(rsc)
|
||||
}
|
||||
if (intra !== undefined && intra >= 0 && allowInterSeriesPause) o.intra_rep_rest_sec = Math.round(intra)
|
||||
if (tran !== undefined && tran >= 0) o.transition_after_sec = Math.round(tran)
|
||||
if (Object.keys(o).length > 1) slot_profiles_v1_next.push(o)
|
||||
}
|
||||
|
||||
payload.method_archetype = (formData.method_archetype || '').trim() || null
|
||||
if (slot_profiles_v1_next.length > 0) mpObj.slot_profiles_v1 = slot_profiles_v1_next
|
||||
else delete mpObj.slot_profiles_v1
|
||||
payload.method_profile = mpObj
|
||||
payload.combination_slots = combination_slots
|
||||
} else {
|
||||
payload.method_archetype = null
|
||||
payload.method_profile = {}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
export async function uploadExerciseMedia(exerciseId, formData) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({})
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const response = await fetch(`${API_URL}/api/exercises/${exerciseId}/media`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const d = parsed?.detail
|
||||
if (
|
||||
response.status === 409 &&
|
||||
d &&
|
||||
typeof d === 'object' &&
|
||||
!Array.isArray(d) &&
|
||||
typeof d.code === 'string'
|
||||
) {
|
||||
const e = new Error(
|
||||
typeof d.message === 'string' ? d.message : 'Upload konnte nicht verarbeitet werden',
|
||||
)
|
||||
e.code = d.code
|
||||
e.status = 409
|
||||
e.payload = d
|
||||
throw e
|
||||
}
|
||||
if (response.status === 413) {
|
||||
const nginx = (text || '').toLowerCase().includes('nginx')
|
||||
throw new Error(
|
||||
nginx
|
||||
? 'Die Anfrage ist zu groß (413). Häufig: nginx „client_max_body_size“ — z. B. große/r mehrere Videos oder Bulk-Upload. Dateien kleiner aufteilen oder Server-Limit erhöhen (Frontend-Image Neu bauen).'
|
||||
: 'Die Anfrage ist zu groß (413). Dateigröße oder Server-Limit prüfen.',
|
||||
)
|
||||
}
|
||||
const msg =
|
||||
typeof d === 'string'
|
||||
? d
|
||||
: d != null && typeof d === 'object' && typeof d.message === 'string'
|
||||
? d.message
|
||||
: d != null
|
||||
? JSON.stringify(d)
|
||||
: text && text.length < 400 && !/^\s*</.test(text)
|
||||
? `HTTP ${response.status}: ${text.trim()}`
|
||||
: `HTTP ${response.status}`
|
||||
throw new Error(msg)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export async function updateExerciseMedia(exerciseId, mediaId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/media/${mediaId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseMedia(exerciseId, mediaId) {
|
||||
return request(`/api/exercises/${exerciseId}/media/${mediaId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function reorderExerciseMedia(exerciseId, mediaIds) {
|
||||
return request(`/api/exercises/${exerciseId}/media/reorder`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ media_ids: mediaIds }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Papierkorb / Recovery — `action`: trash_soft | trash_hidden | recover | purge | reactivate */
|
||||
export async function postMediaAssetLifecycle(assetId, action, extra = {}) {
|
||||
return request(`/api/media-assets/${assetId}/lifecycle`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ action, ...extra }),
|
||||
})
|
||||
}
|
||||
|
||||
/** Archiv: aktive media_assets sichtbar für den Nutzer (Bibliotheksrechte). */
|
||||
export async function listMediaAssets(params = {}) {
|
||||
const sp = new URLSearchParams()
|
||||
if (params.q) sp.set('q', params.q)
|
||||
if (params.limit != null) sp.set('limit', String(params.limit))
|
||||
if (params.offset != null) sp.set('offset', String(params.offset))
|
||||
if (params.lifecycle) sp.set('lifecycle', String(params.lifecycle))
|
||||
if (params.media_kind) sp.set('media_kind', String(params.media_kind))
|
||||
if (params.club_id != null && params.club_id !== '') sp.set('club_id', String(params.club_id))
|
||||
if (params.uploaded_by != null && params.uploaded_by !== '') sp.set('uploaded_by', String(params.uploaded_by))
|
||||
if (params.include_filter_meta) sp.set('include_filter_meta', 'true')
|
||||
const qs = sp.toString()
|
||||
return request(`/api/media-assets${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function patchMediaAsset(assetId, data) {
|
||||
return request(`/api/media-assets/${assetId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function bulkMediaLifecycle(data) {
|
||||
return request('/api/media-assets/bulk-lifecycle', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function bulkPatchMediaAssets(data) {
|
||||
return request('/api/media-assets/bulk-patch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Mehrere Dateien ins Medienarchiv (`POST /api/media-assets/bulk-upload`).
|
||||
* @param {File[]} files
|
||||
* @param {{ visibility?: string, club_id?: number }} [options]
|
||||
*/
|
||||
export async function bulkUploadMediaAssets(files, options = {}) {
|
||||
const visibility = options.visibility || 'private'
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({})
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const formData = new FormData()
|
||||
formData.append('visibility', String(visibility))
|
||||
if (options.club_id != null && options.club_id !== '') {
|
||||
formData.append('club_id', String(options.club_id))
|
||||
}
|
||||
// Copyright + P-06: Rechte-Erklaerung + Kontextfelder
|
||||
if (options.copyright_notice != null && String(options.copyright_notice).trim())
|
||||
formData.append('copyright_notice', String(options.copyright_notice).trim())
|
||||
const p06Fields = [
|
||||
'rights_holder_confirmed',
|
||||
'contains_identifiable_persons',
|
||||
'person_consent_confirmed',
|
||||
'person_consent_context',
|
||||
'contains_minors',
|
||||
'parental_consent_confirmed',
|
||||
'parental_consent_context',
|
||||
'contains_music',
|
||||
'music_rights_confirmed',
|
||||
'music_rights_context',
|
||||
'contains_third_party_content',
|
||||
'third_party_rights_confirmed',
|
||||
'third_party_rights_context',
|
||||
]
|
||||
for (const f of p06Fields) {
|
||||
if (options[f] != null && options[f] !== '') formData.append(f, String(options[f]))
|
||||
}
|
||||
const arr = Array.isArray(files) ? files : [files]
|
||||
for (const f of arr) {
|
||||
if (f) formData.append('files', f)
|
||||
}
|
||||
const url = `${API_URL}/api/media-assets/bulk-upload`
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const d = parsed.detail
|
||||
throw new Error(typeof d === 'string' ? d : JSON.stringify(d))
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** Übung: bestehendes Archiv-Medium verknüpfen (`POST /api/exercises/{id}/media/from-asset`). */
|
||||
export async function getMediaAssetJournal(assetId) {
|
||||
return request(`/api/admin/media-rights/assets/${assetId}/journal`)
|
||||
}
|
||||
|
||||
export async function addMediaAssetDeclarationCorrection(assetId, body) {
|
||||
return request(`/api/admin/media-rights/assets/${assetId}/correction`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function attachExerciseMediaFromAsset(exerciseId, body) {
|
||||
return request(`/api/exercises/${exerciseId}/media/from-asset`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
// P-11: Legal-Hold-Endpunkte
|
||||
export async function setMediaAssetLegalHold(assetId, reasonCode, reasonNote) {
|
||||
return request(`/api/admin/media-assets/${assetId}/legal-hold`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason_code: reasonCode, reason_note: reasonNote }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function releaseMediaAssetLegalHold(assetId, releaseNote) {
|
||||
return request(`/api/admin/media-assets/${assetId}/legal-hold/release`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ release_note: releaseNote }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listMediaAssetsWithLegalHold(limit = 100, offset = 0) {
|
||||
return request(`/api/admin/media-assets/legal-hold?limit=${limit}&offset=${offset}`)
|
||||
}
|
||||
|
||||
export async function getExercise(id) {
|
||||
return request(`/api/exercises/${id}`)
|
||||
}
|
||||
|
||||
export async function createExercise(data) {
|
||||
return request('/api/exercises', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExercise(id, data) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const headers = withActiveClubHeaders({ 'Content-Type': 'application/json' })
|
||||
if (token) headers['X-Auth-Token'] = token
|
||||
const url = `${API_URL}/api/exercises/${id}`
|
||||
const response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
let parsed = null
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const d = parsed?.detail
|
||||
if (
|
||||
response.status === 422 &&
|
||||
d &&
|
||||
typeof d === 'object' &&
|
||||
!Array.isArray(d) &&
|
||||
typeof d.code === 'string'
|
||||
) {
|
||||
const e = new Error(typeof d.message === 'string' ? d.message : 'Validierung fehlgeschlagen')
|
||||
e.status = 422
|
||||
e.code = d.code
|
||||
e.payload = d
|
||||
throw e
|
||||
}
|
||||
if (parsed?.detail != null) {
|
||||
const msg = typeof parsed.detail === 'string' ? parsed.detail : JSON.stringify(parsed.detail)
|
||||
throw new Error(msg)
|
||||
}
|
||||
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** Massenänderung Übungen: Sichtbarkeit, Status, Katalog-Zuordnungen (`PATCH /api/exercises/bulk-metadata`). */
|
||||
export async function bulkPatchExercisesMetadata(data) {
|
||||
return request('/api/exercises/bulk-metadata', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExercise(id) {
|
||||
return request(`/api/exercises/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function createExerciseVariant(exerciseId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/variants`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseVariant(exerciseId, variantId, data) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/${variantId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseVariant(exerciseId, variantId) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/${variantId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function reorderExerciseVariants(exerciseId, variantIds) {
|
||||
return request(`/api/exercises/${exerciseId}/variants/reorder`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ variant_ids: variantIds }),
|
||||
})
|
||||
}
|
||||
|
||||
// Progressionsgraphen (Übung → Übung), Migration 032/033
|
||||
export async function listExerciseProgressionGraphs() {
|
||||
return request('/api/exercise-progression-graphs')
|
||||
}
|
||||
|
||||
export async function getExerciseProgressionGraph(id, { includeEdges = false } = {}) {
|
||||
const q = includeEdges ? '?include_edges=true' : ''
|
||||
return request(`/api/exercise-progression-graphs/${id}${q}`)
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionGraph(data) {
|
||||
return request('/api/exercise-progression-graphs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseProgressionGraph(id, data) {
|
||||
return request(`/api/exercise-progression-graphs/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionGraph(id) {
|
||||
return request(`/api/exercise-progression-graphs/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function listExerciseProgressionEdges(graphId, query = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (query.from_exercise_id != null) q.set('from_exercise_id', String(query.from_exercise_id))
|
||||
if (query.to_exercise_id != null) q.set('to_exercise_id', String(query.to_exercise_id))
|
||||
const qs = q.toString()
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionEdge(graphId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateExerciseProgressionEdge(graphId, edgeId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/${edgeId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionEdge(graphId, edgeId) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/${edgeId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function createExerciseProgressionSequence(graphId, data) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/sequence`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExerciseProgressionEdgesBatch(graphId, edgeIds) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/edges/delete-batch`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ edge_ids: edgeIds }),
|
||||
})
|
||||
}
|
||||
|
||||
/** KI-Ausbaustufe (EXERCISES_API_SPEC): benötigt Backend + z. B. OPENROUTER_API_KEY. */
|
||||
export async function suggestExerciseAi(payload) {
|
||||
return request('/api/exercises/ai/suggest', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function regenerateExerciseAi(exerciseId, payload) {
|
||||
return request(`/api/exercises/${exerciseId}/ai/regenerate`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Trainingsplanung: Einheiten, Vorlagen, Module, Rahmenprogramme, Dashboard-KPIs.
|
||||
* Facade: weiterhin `utils/api.js` (default + Named Exports).
|
||||
*/
|
||||
import { request } from './client.js'
|
||||
|
||||
/** Query-Parameter wie GET /api/training-units. */
|
||||
export async function listTrainingUnits(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (filters.group_id != null && filters.group_id !== '') {
|
||||
q.set('group_id', String(filters.group_id))
|
||||
}
|
||||
if (filters.club_id != null && filters.club_id !== '') {
|
||||
q.set('club_id', String(filters.club_id))
|
||||
}
|
||||
if (filters.start_date) q.set('start_date', filters.start_date)
|
||||
if (filters.end_date) q.set('end_date', filters.end_date)
|
||||
if (filters.status) q.set('status', filters.status)
|
||||
if (filters.debrief_pending === true) q.set('debrief_pending', 'true')
|
||||
if (filters.assigned_to_me === true) q.set('assigned_to_me', 'true')
|
||||
if (filters.sort) q.set('sort', String(filters.sort))
|
||||
if (filters.limit != null && filters.limit !== '') q.set('limit', String(filters.limit))
|
||||
if (filters.cursor_planned_date) q.set('cursor_planned_date', String(filters.cursor_planned_date))
|
||||
if (filters.cursor_planned_time != null && filters.cursor_planned_time !== '') {
|
||||
q.set('cursor_planned_time', String(filters.cursor_planned_time))
|
||||
}
|
||||
if (filters.cursor_id != null && filters.cursor_id !== '') q.set('cursor_id', String(filters.cursor_id))
|
||||
const qs = q.toString()
|
||||
return request(`/api/training-units${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
/** Dashboard Kurzüberblick: Entwürfe / meine Übungen / YTD abgeschlossene Einheiten (ein Roundtrip). */
|
||||
export async function getDashboardKpis() {
|
||||
return request('/api/dashboard/kpis')
|
||||
}
|
||||
|
||||
/** Dashboard: Übungen in geplanten Einheiten, die für den Verein noch auf Sichtbarkeit „Verein“ gehören. */
|
||||
export async function getTrainingExerciseClubVisibilityQueue(filters = {}) {
|
||||
const q = new URLSearchParams()
|
||||
if (filters.start_date) q.set('start_date', String(filters.start_date))
|
||||
if (filters.end_date) q.set('end_date', String(filters.end_date))
|
||||
if (filters.assigned_to_me === false) q.set('assigned_to_me', 'false')
|
||||
if (filters.limit_units != null && filters.limit_units !== '') {
|
||||
q.set('limit_units', String(filters.limit_units))
|
||||
}
|
||||
const qs = q.toString()
|
||||
return request(`/api/training-units/exercises-club-visibility-queue${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function getTrainingUnit(id) {
|
||||
return request(`/api/training-units/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingUnit(data) {
|
||||
return request('/api/training-units', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingUnit(id, data) {
|
||||
return request(`/api/training-units/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingUnit(id) {
|
||||
return request(`/api/training-units/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function quickCreateTrainingUnit(data) {
|
||||
return request('/api/training-units/quick-create', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/** Rahmen-Slot → geplante Einheit (tiefe Kopie, origin_framework_slot_id). */
|
||||
export async function createTrainingUnitFromFrameworkSlot(data) {
|
||||
return request('/api/training-units/from-framework-slot', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listTrainingPlanTemplates() {
|
||||
return request('/api/training-plan-templates')
|
||||
}
|
||||
|
||||
export async function getTrainingPlanTemplate(id) {
|
||||
return request(`/api/training-plan-templates/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingPlanTemplate(data) {
|
||||
return request('/api/training-plan-templates', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingPlanTemplate(id, data) {
|
||||
return request(`/api/training-plan-templates/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingPlanTemplate(id) {
|
||||
return request(`/api/training-plan-templates/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function listTrainingModules() {
|
||||
return request('/api/training-modules')
|
||||
}
|
||||
|
||||
export async function getTrainingModule(id) {
|
||||
return request(`/api/training-modules/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingModule(data) {
|
||||
return request('/api/training-modules', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingModule(id, data) {
|
||||
return request(`/api/training-modules/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingModule(id) {
|
||||
return request(`/api/training-modules/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
/** Kopiert Modul-Inhalte ans Ende eines Abschnitts (section_order_index 0-basiert). */
|
||||
export async function applyTrainingModuleToTrainingUnit(unitId, data) {
|
||||
return request(`/api/training-units/${unitId}/apply-training-module`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
/** Geplanten Ablauf als Session-Blueprint in ein Rahmenprogramm schreiben (neu oder bestehend). */
|
||||
export async function publishTrainingUnitToFramework(unitId, data) {
|
||||
return request(`/api/training-units/${unitId}/publish-to-framework`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listTrainingFrameworkPrograms() {
|
||||
return request('/api/training-framework-programs')
|
||||
}
|
||||
|
||||
export async function getTrainingFrameworkProgram(id) {
|
||||
return request(`/api/training-framework-programs/${id}`)
|
||||
}
|
||||
|
||||
export async function createTrainingFrameworkProgram(data) {
|
||||
return request('/api/training-framework-programs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTrainingFrameworkProgram(id, data) {
|
||||
return request(`/api/training-framework-programs/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteTrainingFrameworkProgram(id) {
|
||||
return request(`/api/training-framework-programs/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { request } from './client.js'
|
||||
|
||||
export async function getFrameworkProgramSkillProfile(frameworkId) {
|
||||
return request(`/api/training-framework-programs/${frameworkId}/skill-profile`)
|
||||
}
|
||||
|
||||
export async function getTrainingModuleSkillProfile(moduleId) {
|
||||
return request(`/api/training-modules/${moduleId}/skill-profile`)
|
||||
}
|
||||
|
||||
export async function getProgressionGraphSkillProfile(graphId) {
|
||||
return request(`/api/exercise-progression-graphs/${graphId}/skill-profile`)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number[]} skillIds
|
||||
* @param {{ types?: string, limit?: number }} opts
|
||||
*/
|
||||
export async function getSkillDiscoverySuggestions(skillIds, opts = {}) {
|
||||
const ids = (skillIds || []).filter((x) => x != null && Number(x) > 0).join(',')
|
||||
if (!ids) return { skill_ids: [], suggestions: [] }
|
||||
const params = new URLSearchParams({ skill_ids: ids })
|
||||
if (opts.types) params.set('types', opts.types)
|
||||
if (opts.limit != null) params.set('limit', String(opts.limit))
|
||||
return request(`/api/skill-discovery/suggestions?${params.toString()}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch-Summaries für Listen (ein Vereins-Corpus-Scan).
|
||||
* @param {{ frameworkProgramIds?: number[], trainingModuleIds?: number[] }} payload
|
||||
*/
|
||||
export async function batchSkillProfileSummaries(payload = {}) {
|
||||
return request('/api/skill-profiles/batch-summaries', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
framework_program_ids: payload.frameworkProgramIds || [],
|
||||
training_module_ids: payload.trainingModuleIds || [],
|
||||
}),
|
||||
})
|
||||
}
|
||||
+2336
-7
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ export default function CombinationPlanBracket({
|
||||
/** 'none' | 'link' (Router) | 'button' (z. B. ExercisePeekModal / PWA-sicher) */
|
||||
candidateInteraction = 'none',
|
||||
onCandidatePeek,
|
||||
className,
|
||||
}) {
|
||||
const arch = typeof methodArchetype === 'string' ? methodArchetype.trim() : ''
|
||||
const archLabel = arch ? combinationArchetypeLabel(arch) : null
|
||||
@@ -59,7 +60,7 @@ export default function CombinationPlanBracket({
|
||||
const coachHint = arch ? archetypeCoachHint(arch) : ''
|
||||
|
||||
return (
|
||||
<div className="combo-plan-bracket">
|
||||
<div className={['combo-plan-bracket', className].filter(Boolean).join(' ')}>
|
||||
<div className="combo-plan-bracket__accent" aria-hidden />
|
||||
<div className="combo-plan-bracket__body">
|
||||
<header className="combo-plan-bracket__head">
|
||||
|
||||
@@ -268,7 +268,7 @@ export default function DashboardTrainingVisibilityWidget({ user }) {
|
||||
}}
|
||||
>
|
||||
<Link
|
||||
to={`/planning?unit=${first.id}`}
|
||||
to={`/planning/units/${first.id}/edit`}
|
||||
className="btn-ghost"
|
||||
style={{
|
||||
padding: '2px 4px',
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import NavStateLink from './NavStateLink'
|
||||
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
|
||||
import CombinationPlanBracket from './CombinationPlanBracket'
|
||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||
@@ -36,6 +37,8 @@ export default function ExercisePeekModal({
|
||||
titleFallback,
|
||||
/** Nur Planung: effektives method_profile aus Zeilen-Katalog + Planungs-Override */
|
||||
peekExtras,
|
||||
/** Rücksprung-Kontext für „Vollständige Übungsseite“ */
|
||||
returnContext,
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [err, setErr] = useState(null)
|
||||
@@ -255,13 +258,24 @@ export default function ExercisePeekModal({
|
||||
</div>
|
||||
{top?.exerciseId != null ? (
|
||||
<div style={{ padding: '0 1rem 1rem', flexShrink: 0 }}>
|
||||
<Link
|
||||
to={`/exercises/${top.exerciseId}`}
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%', textDecoration: 'none', textAlign: 'center', display: 'block' }}
|
||||
>
|
||||
Vollständige Übungsseite öffnen
|
||||
</Link>
|
||||
{returnContext ? (
|
||||
<NavStateLink
|
||||
to={`/exercises/${top.exerciseId}`}
|
||||
returnContext={returnContext}
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%', textDecoration: 'none', textAlign: 'center', display: 'block' }}
|
||||
>
|
||||
Vollständige Übungsseite öffnen
|
||||
</NavStateLink>
|
||||
) : (
|
||||
<Link
|
||||
to={`/exercises/${top.exerciseId}`}
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%', textDecoration: 'none', textAlign: 'center', display: 'block' }}
|
||||
>
|
||||
Vollständige Übungsseite öffnen
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
* Übungssuche mit Volltext-, KI-/Semantikfeld (aktuell gleiche Engine wie Suche) und erweiterten Filtern.
|
||||
* Paginierung bis max. 100 Treffer pro Request (API-Limit).
|
||||
*/
|
||||
import React, { useState, useEffect, useMemo, useCallback } from 'react'
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../constants/exerciseGovernanceLabels'
|
||||
import {
|
||||
INITIAL_EXERCISE_LIST_FILTERS,
|
||||
mergeExerciseListPrefsFromApi,
|
||||
splitMnCatalogRules,
|
||||
splitScalarCatalogRules,
|
||||
} from '../constants/exerciseListFilters'
|
||||
import MultiSelectCombo from './MultiSelectCombo'
|
||||
import SkillTreeMultiSelect from './SkillTreeMultiSelect'
|
||||
import ExerciseFocusRulePicker from './ExerciseFocusRulePicker'
|
||||
import CatalogRulePicker from './CatalogRulePicker'
|
||||
|
||||
@@ -53,13 +55,13 @@ export default function ExercisePickerModal({
|
||||
const [list, setList] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [multiPicked, setMultiPicked] = useState([])
|
||||
const [quickOpen, setQuickOpen] = useState(false)
|
||||
const [quickTitle, setQuickTitle] = useState('')
|
||||
const [quickSummary, setQuickSummary] = useState('')
|
||||
const [quickSaving, setQuickSaving] = useState(false)
|
||||
const pickerScrollRef = useRef(null)
|
||||
|
||||
const toggleMultiPick = (ex) => {
|
||||
setMultiPicked((prev) =>
|
||||
@@ -87,7 +89,7 @@ export default function ExercisePickerModal({
|
||||
api.listStyleDirections(),
|
||||
api.listTrainingTypes(),
|
||||
api.listTargetGroups(),
|
||||
api.listSkills(),
|
||||
api.listSkillsCatalog(),
|
||||
])
|
||||
if (!cancelled) {
|
||||
setCatalogs({
|
||||
@@ -118,7 +120,6 @@ export default function ExercisePickerModal({
|
||||
setFilters({ ...INITIAL_FILTERS })
|
||||
setFilterOpen(false)
|
||||
setList([])
|
||||
setOffset(0)
|
||||
setHasMore(false)
|
||||
setMultiPicked([])
|
||||
setQuickOpen(false)
|
||||
@@ -146,10 +147,6 @@ export default function ExercisePickerModal({
|
||||
() => catalogs.targetGroups.map((g) => ({ id: g.id, label: g.name || String(g.id) })),
|
||||
[catalogs.targetGroups]
|
||||
)
|
||||
const skillOptions = useMemo(
|
||||
() => catalogs.skills.map((s) => ({ id: s.id, label: s.name || String(s.id) })),
|
||||
[catalogs.skills]
|
||||
)
|
||||
const visibilityOptions = useMemo(
|
||||
() => [
|
||||
{ id: 'private', label: 'Privat' },
|
||||
@@ -227,7 +224,6 @@ export default function ExercisePickerModal({
|
||||
const reload = useCallback(async () => {
|
||||
if (!open || !catalogsReady) return
|
||||
setLoading(true)
|
||||
setOffset(0)
|
||||
try {
|
||||
const batch = await api.listExercises({
|
||||
...queryBase,
|
||||
@@ -238,7 +234,6 @@ export default function ExercisePickerModal({
|
||||
})
|
||||
setList(Array.isArray(batch) ? batch : [])
|
||||
setHasMore(batch?.length === PAGE_SIZE)
|
||||
setOffset(batch?.length ?? 0)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert(e.message || 'Laden fehlgeschlagen')
|
||||
@@ -255,6 +250,8 @@ export default function ExercisePickerModal({
|
||||
|
||||
const loadMore = async () => {
|
||||
if (!hasMore || loadingMore || loading) return
|
||||
const last = list[list.length - 1]
|
||||
if (!last?.id || last.updated_at == null) return
|
||||
setLoadingMore(true)
|
||||
try {
|
||||
const batch = await api.listExercises({
|
||||
@@ -262,11 +259,14 @@ export default function ExercisePickerModal({
|
||||
include_archived: true,
|
||||
include_variants: true,
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
cursor_updated_at:
|
||||
typeof last.updated_at === 'string'
|
||||
? last.updated_at
|
||||
: new Date(last.updated_at).toISOString(),
|
||||
cursor_id: last.id,
|
||||
})
|
||||
setList((prev) => [...prev, ...(Array.isArray(batch) ? batch : [])])
|
||||
setHasMore(batch?.length === PAGE_SIZE)
|
||||
setOffset((o) => o + (batch?.length ?? 0))
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert(e.message || 'Mehr laden fehlgeschlagen')
|
||||
@@ -275,6 +275,14 @@ export default function ExercisePickerModal({
|
||||
}
|
||||
}
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: list.length,
|
||||
getScrollElement: () => pickerScrollRef.current,
|
||||
estimateSize: () => 88,
|
||||
overscan: 8,
|
||||
getItemKey: (index) => String(list[index]?.id ?? index),
|
||||
})
|
||||
|
||||
const resetFilters = () => setFilters({ ...INITIAL_FILTERS })
|
||||
|
||||
const submitQuickCreate = async () => {
|
||||
@@ -366,7 +374,7 @@ export default function ExercisePickerModal({
|
||||
{quickOpen ? (
|
||||
<div style={{ marginTop: '12px', display: 'grid', gap: '10px' }}>
|
||||
<p style={{ margin: 0, fontSize: '13px', color: 'var(--text2)', lineHeight: 1.45 }}>
|
||||
Wird mit Sichtbarkeit <strong>privat</strong> und Status <strong>Entwurf</strong> gespeichert und
|
||||
Wird mit Freigabelevel <strong>privat</strong> und Status <strong>Entwurf</strong> gespeichert und
|
||||
erscheint auf dem Dashboard zum Weiterbearbeiten. Nach dem Speichern wird die Übung direkt in den
|
||||
Ablauf übernommen.
|
||||
</p>
|
||||
@@ -455,7 +463,7 @@ export default function ExercisePickerModal({
|
||||
<div style={{ marginTop: '0.35rem', fontSize: '13px', color: 'var(--text2)' }}>
|
||||
<p style={{ margin: '0 0 12px 0' }}>
|
||||
Felder gelten mit <strong>UND</strong>. Kataloge: mehrere „+“ = alle zutreffend; „−“ schließt aus.
|
||||
Sichtbarkeit/Status: mehrere „+“ = eine davon (ODER); „−“ blendet aus.
|
||||
Freigabelevel/Status: mehrere „+“ = eine davon (ODER); „−“ blendet aus.
|
||||
</p>
|
||||
<ExerciseFocusRulePicker
|
||||
focusOptions={focusOptions}
|
||||
@@ -495,10 +503,10 @@ export default function ExercisePickerModal({
|
||||
</div>
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<label className="form-label">Fähigkeit</label>
|
||||
<MultiSelectCombo
|
||||
<SkillTreeMultiSelect
|
||||
value={filters.skill_ids}
|
||||
onChange={(v) => setFilters((f) => ({ ...f, skill_ids: v }))}
|
||||
options={skillOptions}
|
||||
skills={catalogs.skills}
|
||||
placeholder="Fähigkeit …"
|
||||
/>
|
||||
<div className="exercise-filter-skill-levels-row" style={{ marginTop: 8 }}>
|
||||
@@ -532,12 +540,12 @@ export default function ExercisePickerModal({
|
||||
</div>
|
||||
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--two exercise-filters-modal-grid--catalog" style={{ marginTop: 12 }}>
|
||||
<CatalogRulePicker
|
||||
label="Sichtbarkeit"
|
||||
label={EXERCISE_VISIBILITY_FIELD_LABEL}
|
||||
options={visibilityOptions}
|
||||
rules={filters.visibility_rules}
|
||||
rulesFieldName="visibility_rules"
|
||||
idKind="string"
|
||||
placeholder="Sichtbarkeit …"
|
||||
placeholder="Freigabelevel …"
|
||||
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
|
||||
/>
|
||||
<CatalogRulePicker
|
||||
@@ -584,7 +592,11 @@ export default function ExercisePickerModal({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 1rem' }}>
|
||||
<div
|
||||
ref={pickerScrollRef}
|
||||
data-testid="exercise-picker-scroll"
|
||||
style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 1rem' }}
|
||||
>
|
||||
{!catalogsReady || (loading && list.length === 0) ? (
|
||||
<div style={{ textAlign: 'center', padding: '2rem' }}>
|
||||
<div className="spinner" />
|
||||
@@ -596,8 +608,18 @@ export default function ExercisePickerModal({
|
||||
<p style={{ fontSize: '13px', color: 'var(--text2)', marginBottom: 10 }}>
|
||||
{list.length} angezeigt{hasMore ? ' · weiter unten „Mehr laden“' : ''}
|
||||
</p>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{list.map((ex) => {
|
||||
<div
|
||||
role="list"
|
||||
aria-label="Übungstreffer"
|
||||
style={{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
height: rowVirtualizer.getTotalSize(),
|
||||
}}
|
||||
>
|
||||
{rowVirtualizer.getVirtualItems().map((vi) => {
|
||||
const ex = list[vi.index]
|
||||
if (!ex) return null
|
||||
const picked = multiPicked.some((p) => p.id === ex.id)
|
||||
const rowInner = (
|
||||
<>
|
||||
@@ -629,9 +651,22 @@ export default function ExercisePickerModal({
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
if (multiSelect) {
|
||||
return (
|
||||
<li key={ex.id}>
|
||||
return (
|
||||
<div
|
||||
key={vi.key}
|
||||
role="listitem"
|
||||
data-index={vi.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
transform: `translateY(${vi.start}px)`,
|
||||
paddingBottom: 8,
|
||||
}}
|
||||
>
|
||||
{multiSelect ? (
|
||||
<label
|
||||
className="tu-ex-picker-multi-row"
|
||||
style={{
|
||||
@@ -641,7 +676,6 @@ export default function ExercisePickerModal({
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
marginBottom: 8,
|
||||
borderRadius: '8px',
|
||||
border: picked ? '2px solid var(--accent)' : '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
@@ -658,34 +692,30 @@ export default function ExercisePickerModal({
|
||||
/>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>{rowInner}</div>
|
||||
</label>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<li key={ex.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelectExercise(ex)
|
||||
onClose()
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
marginBottom: 8,
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{rowInner}
|
||||
</button>
|
||||
</li>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelectExercise(ex)
|
||||
onClose()
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '10px 12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{rowInner}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
{hasMore && (
|
||||
<div style={{ textAlign: 'center', marginTop: 12 }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={loadingMore} onClick={loadMore}>
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import SkillProfilePanel from './skills/SkillProfilePanel'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import ExercisePickerModal from './ExercisePickerModal'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../constants/exerciseGovernanceLabels'
|
||||
|
||||
const VIS_OPTIONS = [
|
||||
{ value: 'private', label: 'Privat' },
|
||||
@@ -136,6 +138,9 @@ export default function ExerciseProgressionGraphPanel({
|
||||
const [editingEdgeNotes, setEditingEdgeNotes] = useState(null)
|
||||
const [notesDraft, setNotesDraft] = useState('')
|
||||
const [uiTab, setUiTab] = useState('overview')
|
||||
const [skillProfileData, setSkillProfileData] = useState(null)
|
||||
const [skillProfileLoading, setSkillProfileLoading] = useState(false)
|
||||
const [skillProfileError, setSkillProfileError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedGraphId(null)
|
||||
@@ -180,6 +185,32 @@ export default function ExerciseProgressionGraphPanel({
|
||||
}
|
||||
}, [refreshGraphs, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedGraphId) {
|
||||
setSkillProfileData(null)
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setSkillProfileLoading(true)
|
||||
setSkillProfileError('')
|
||||
try {
|
||||
const data = await api.getProgressionGraphSkillProfile(selectedGraphId)
|
||||
if (!cancelled) setSkillProfileData(data)
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setSkillProfileData(null)
|
||||
setSkillProfileError(e.message || 'Fähigkeiten-Profil nicht geladen')
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setSkillProfileLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [selectedGraphId, edges.length])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedGraphId) {
|
||||
setEdges([])
|
||||
@@ -575,7 +606,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ flex: '1 1 140px', marginBottom: 0 }}>
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<label className="form-label">{EXERCISE_VISIBILITY_FIELD_LABEL}</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={newGraphVisibility}
|
||||
@@ -612,7 +643,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<label className="form-label">{EXERCISE_VISIBILITY_FIELD_LABEL}</label>
|
||||
<select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}>
|
||||
{filteredGraphVisOptions.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
@@ -652,6 +683,15 @@ export default function ExerciseProgressionGraphPanel({
|
||||
|
||||
{selectedGraphId && uiTab === 'overview' && (
|
||||
<>
|
||||
<SkillProfilePanel
|
||||
title="Fähigkeiten entlang des Pfads"
|
||||
hint="Alle Übungen als Knoten im Graph (Standardgewicht pro Übung; Intensität und Stufen aus der Übungsverknüpfung)."
|
||||
profile={skillProfileData?.overall}
|
||||
loading={skillProfileLoading}
|
||||
error={skillProfileError}
|
||||
defaultExpanded
|
||||
artifactType="progression_graph"
|
||||
/>
|
||||
<div className="card" style={{ marginBottom: '12px' }}>
|
||||
<h3 style={{ marginTop: 0, fontSize: '1rem' }}>Sequenz / Reihe anlegen</h3>
|
||||
<p style={{ fontSize: '12px', color: 'var(--text3)', marginTop: 0 }}>
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Check, Save, X } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Feste Aktionsleiste für Formulare/Modale: Speichern, Speichern & schließen, Abbrechen.
|
||||
* Bleibt sichtbar (sticky), während der Formularinhalt scrollt.
|
||||
*/
|
||||
function ActionLabel({ Icon, long, short, saving, savingShort = '…' }) {
|
||||
if (saving) {
|
||||
return <span className="form-action-bar__saving">{savingShort}</span>
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{Icon ? <Icon size={17} strokeWidth={2.25} className="form-action-bar__icon" aria-hidden /> : null}
|
||||
<span className="form-action-bar__text form-action-bar__text--long">{long}</span>
|
||||
{short != null && short !== '' ? (
|
||||
<span className="form-action-bar__text form-action-bar__text--short">{short}</span>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default function FormActionBar({
|
||||
placement = 'bottom',
|
||||
variant = 'default',
|
||||
saving = false,
|
||||
saveLabel,
|
||||
saveShortLabel,
|
||||
saveAndCloseLabel = 'Speichern & schließen',
|
||||
saveAndCloseShortLabel,
|
||||
cancelLabel = 'Abbrechen',
|
||||
onSave,
|
||||
onSaveAndClose,
|
||||
onCancel,
|
||||
showSave = true,
|
||||
showSaveAndClose = true,
|
||||
showCancel = true,
|
||||
formId,
|
||||
isNew = false,
|
||||
primaryIsSaveOnly = false,
|
||||
}) {
|
||||
const labelSave = saveLabel ?? (isNew ? 'Anlegen' : 'Speichern')
|
||||
const shortSave = saveShortLabel ?? (isNew ? 'Neu' : 'Sichern')
|
||||
const shortClose = saveAndCloseShortLabel ?? 'Fertig'
|
||||
const showSaveBtn = showSave && (Boolean(onSave) || Boolean(formId))
|
||||
const showCloseBtn = showSaveAndClose && (Boolean(onSaveAndClose) || Boolean(formId))
|
||||
const showCancelBtn = showCancel && Boolean(onCancel)
|
||||
|
||||
if (!showSaveBtn && !showCloseBtn && !showCancelBtn) return null
|
||||
|
||||
const saveBtnClass = `btn form-action-bar__btn${
|
||||
primaryIsSaveOnly ? ' btn-primary' : ' btn-secondary'
|
||||
}`
|
||||
const closeBtnClass = `btn form-action-bar__btn${
|
||||
primaryIsSaveOnly ? ' btn-secondary' : ' btn-primary'
|
||||
}`
|
||||
|
||||
const primaryCount = (showSaveBtn ? 1 : 0) + (showCloseBtn ? 1 : 0)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`form-action-bar form-action-bar--${placement} form-action-bar--${variant}${
|
||||
primaryCount === 1 ? ' form-action-bar--single-primary' : ''
|
||||
}`}
|
||||
role="group"
|
||||
aria-label="Formularaktionen"
|
||||
>
|
||||
<div className="form-action-bar__inner">
|
||||
{showCancelBtn ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary form-action-bar__btn form-action-bar__btn--cancel"
|
||||
onClick={onCancel}
|
||||
disabled={saving}
|
||||
aria-label={cancelLabel}
|
||||
title={cancelLabel}
|
||||
>
|
||||
<ActionLabel Icon={X} long={cancelLabel} short="" saving={saving} />
|
||||
</button>
|
||||
) : null}
|
||||
<div className="form-action-bar__primary-group">
|
||||
{showSaveBtn ? (
|
||||
<button
|
||||
type={formId && !onSave ? 'submit' : 'button'}
|
||||
form={formId && !onSave ? formId : undefined}
|
||||
className={saveBtnClass}
|
||||
disabled={saving}
|
||||
onClick={onSave || undefined}
|
||||
title={labelSave}
|
||||
>
|
||||
<ActionLabel Icon={Save} long={labelSave} short={shortSave} saving={saving} />
|
||||
</button>
|
||||
) : null}
|
||||
{showCloseBtn ? (
|
||||
<button
|
||||
type={formId && !onSaveAndClose ? 'submit' : 'button'}
|
||||
form={formId && !onSaveAndClose ? formId : undefined}
|
||||
className={closeBtnClass}
|
||||
disabled={saving}
|
||||
onClick={onSaveAndClose || undefined}
|
||||
title={saveAndCloseLabel}
|
||||
>
|
||||
<ActionLabel
|
||||
Icon={Check}
|
||||
long={saveAndCloseLabel}
|
||||
short={shortClose}
|
||||
saving={saving}
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React, { useEffect, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useModalScrollLock } from '../hooks/useModalScrollLock'
|
||||
|
||||
/**
|
||||
* Formular-Modal am document.body (Portal) — volle Viewport-Breite, kein Hintergrund-Scroll.
|
||||
*/
|
||||
export default function FormModalOverlay({
|
||||
open,
|
||||
children,
|
||||
raised = false,
|
||||
className = '',
|
||||
onBackdropClick,
|
||||
'data-testid': testId,
|
||||
}) {
|
||||
const overlayRef = useRef(null)
|
||||
useModalScrollLock(open)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return undefined
|
||||
const t = window.setTimeout(() => {
|
||||
overlayRef.current?.focus({ preventScroll: true })
|
||||
}, 0)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const overlayClass = [
|
||||
'modal-overlay',
|
||||
'modal-overlay--form',
|
||||
raised ? 'modal-overlay--raised' : '',
|
||||
className,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
ref={overlayRef}
|
||||
tabIndex={-1}
|
||||
data-testid={testId}
|
||||
className={overlayClass}
|
||||
onClick={
|
||||
onBackdropClick
|
||||
? (e) => {
|
||||
if (e.target === e.currentTarget) onBackdropClick()
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { linkStateWithAppReturn } from '../utils/navReturnContext'
|
||||
|
||||
/** Router-Link mit appReturn im State (Rücksprung vom Zielscreen). */
|
||||
export default function NavStateLink({ to, returnContext, state, children, ...rest }) {
|
||||
return (
|
||||
<Link to={to} state={linkStateWithAppReturn(returnContext, state)} {...rest}>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import React from 'react'
|
||||
import { useFormEditorActions } from '../context/FormEditorActionsContext'
|
||||
import PageReturnButton from './PageReturnButton'
|
||||
|
||||
/**
|
||||
* Vollseiten-Editor: optional Zurück oben; FormActionBar fix unten (FormEditorBottomSlot).
|
||||
* Mit actionConfig ist showReturn standardmäßig aus — Rücksprung über Abbrechen / Speichern & Schließen.
|
||||
*/
|
||||
export default function PageFormEditorChrome({
|
||||
title,
|
||||
fallbackPath,
|
||||
fallbackLabel,
|
||||
actionConfig,
|
||||
children,
|
||||
testId,
|
||||
showReturn = false,
|
||||
}) {
|
||||
useFormEditorActions(actionConfig)
|
||||
|
||||
return (
|
||||
<div className="page-form-editor" data-testid={testId}>
|
||||
<header className="page-form-editor__header">
|
||||
{showReturn && fallbackPath && fallbackLabel ? (
|
||||
<PageReturnButton
|
||||
fallbackPath={fallbackPath}
|
||||
fallbackLabel={fallbackLabel}
|
||||
className="page-return-btn page-form-editor__back btn btn-secondary btn-small"
|
||||
/>
|
||||
) : null}
|
||||
<h1 className="page-form-editor__title">{title}</h1>
|
||||
</header>
|
||||
<div className="page-form-editor__body">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import { useNavReturn } from '../hooks/useNavReturn'
|
||||
|
||||
/**
|
||||
* App-typischer Zurück-Schalter (kein Router-Link) — nutzt appReturn / History / Fallback.
|
||||
*/
|
||||
export default function PageReturnButton({
|
||||
fallbackPath,
|
||||
fallbackLabel,
|
||||
className = 'page-return-btn btn btn-secondary btn-small',
|
||||
}) {
|
||||
const fallback = useMemo(
|
||||
() =>
|
||||
fallbackPath && fallbackLabel
|
||||
? { path: fallbackPath, label: fallbackLabel }
|
||||
: null,
|
||||
[fallbackPath, fallbackLabel]
|
||||
)
|
||||
const { goBack, target } = useNavReturn(fallback)
|
||||
|
||||
if (!target?.label) return null
|
||||
|
||||
return (
|
||||
<button type="button" className={className} onClick={goBack} aria-label={target.label}>
|
||||
<ArrowLeft size={16} strokeWidth={2.25} className="page-return-btn__icon" aria-hidden />
|
||||
<span>{target.label}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { collectSkillLeavesFromTree, buildSkillCatalogTree } from '../utils/skillCatalogTree'
|
||||
import SkillTreePickerPanel from './SkillTreePickerPanel'
|
||||
|
||||
const PANEL_MAX_HEIGHT = 360
|
||||
const PANEL_MIN_HEIGHT = 140
|
||||
const PANEL_Z_INDEX = 1100
|
||||
|
||||
function normId(id) {
|
||||
return String(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mehrfachauswahl Fähigkeiten mit hierarchischer Treeview („Alle“) und Pfad-Suche.
|
||||
*/
|
||||
export default function SkillTreeMultiSelect({
|
||||
value = [],
|
||||
onChange,
|
||||
skills = [],
|
||||
placeholder = 'Fähigkeit suchen …',
|
||||
browseLabel = '▼ Katalog',
|
||||
emptyHint = 'Keine Treffer',
|
||||
className = '',
|
||||
usePortal = true,
|
||||
}) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [open, setOpen] = useState(false)
|
||||
const [browseTree, setBrowseTree] = useState(false)
|
||||
const [panelStyle, setPanelStyle] = useState(null)
|
||||
const rootRef = useRef(null)
|
||||
const fieldRef = useRef(null)
|
||||
const panelRef = useRef(null)
|
||||
|
||||
const tree = useMemo(() => buildSkillCatalogTree(skills), [skills])
|
||||
const selectedSet = useMemo(() => new Set(value.map(normId)), [value])
|
||||
|
||||
const leaves = useMemo(() => collectSkillLeavesFromTree(tree, value), [tree, value])
|
||||
|
||||
const selectedLabels = useMemo(() => {
|
||||
return value.map((id) => {
|
||||
const leaf = leaves.find((l) => normId(l.id) === normId(id)) || leaves.find(() => false)
|
||||
const fromSkills = skills.find((s) => normId(s.id) === normId(id))
|
||||
return leaf?.pathLabel || fromSkills?.name || `#${id}`
|
||||
})
|
||||
}, [value, leaves, skills])
|
||||
|
||||
const addId = useCallback(
|
||||
(id) => {
|
||||
const sid = normId(id)
|
||||
if (selectedSet.has(sid)) return
|
||||
onChange([...value, id])
|
||||
setQuery('')
|
||||
setBrowseTree(false)
|
||||
},
|
||||
[value, onChange, selectedSet]
|
||||
)
|
||||
|
||||
const removeAt = useCallback(
|
||||
(idx) => {
|
||||
onChange(value.filter((_, i) => i !== idx))
|
||||
},
|
||||
[value, onChange]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const onDoc = (e) => {
|
||||
const t = e.target
|
||||
if (rootRef.current?.contains(t) || panelRef.current?.contains(t)) return
|
||||
setOpen(false)
|
||||
setBrowseTree(false)
|
||||
}
|
||||
document.addEventListener('mousedown', onDoc)
|
||||
return () => document.removeEventListener('mousedown', onDoc)
|
||||
}, [])
|
||||
|
||||
const updatePanelPosition = useCallback(() => {
|
||||
const anchor = fieldRef.current
|
||||
if (!anchor) return
|
||||
const rect = anchor.getBoundingClientRect()
|
||||
const gap = 4
|
||||
const margin = 12
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gap - margin
|
||||
const spaceAbove = rect.top - gap - margin
|
||||
const openUp = spaceBelow < PANEL_MIN_HEIGHT && spaceAbove > spaceBelow
|
||||
const available = Math.max(0, openUp ? spaceAbove : spaceBelow)
|
||||
const maxHeight = Math.min(PANEL_MAX_HEIGHT, Math.max(PANEL_MIN_HEIGHT, available))
|
||||
const top = openUp ? Math.max(margin, rect.top - gap - maxHeight) : rect.bottom + gap
|
||||
|
||||
setPanelStyle({
|
||||
position: 'fixed',
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
top,
|
||||
maxHeight,
|
||||
zIndex: PANEL_Z_INDEX,
|
||||
})
|
||||
}, [])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !usePortal) {
|
||||
setPanelStyle(null)
|
||||
return undefined
|
||||
}
|
||||
updatePanelPosition()
|
||||
window.addEventListener('resize', updatePanelPosition)
|
||||
window.addEventListener('scroll', updatePanelPosition, true)
|
||||
return () => {
|
||||
window.removeEventListener('resize', updatePanelPosition)
|
||||
window.removeEventListener('scroll', updatePanelPosition, true)
|
||||
}
|
||||
}, [open, usePortal, updatePanelPosition, query, browseTree, value.length])
|
||||
|
||||
const showTree = browseTree || !query.trim()
|
||||
|
||||
const panelContent = showTree ? (
|
||||
<SkillTreePickerPanel
|
||||
skills={skills}
|
||||
excludeIds={value}
|
||||
searchQuery={query}
|
||||
onPickSkill={(id) => addId(id)}
|
||||
pickMode="multi"
|
||||
/>
|
||||
) : (
|
||||
<ul className="multiselect-combo__list" role="listbox">
|
||||
{leaves.filter((l) => l.pathLabel.toLowerCase().includes(query.trim().toLowerCase())).length === 0 ? (
|
||||
<li className="multiselect-combo__empty">{emptyHint}</li>
|
||||
) : (
|
||||
leaves
|
||||
.filter((l) => l.pathLabel.toLowerCase().includes(query.trim().toLowerCase()))
|
||||
.map((l) => (
|
||||
<li key={normId(l.id)}>
|
||||
<button
|
||||
type="button"
|
||||
className="multiselect-combo__opt skill-tree__pick--path"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => addId(l.id)}
|
||||
>
|
||||
<span className="skill-tree__pick-name">{l.label}</span>
|
||||
<span className="skill-tree__pick-path">{l.pathLabel}</span>
|
||||
</button>
|
||||
</li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
|
||||
const dropdownPanel =
|
||||
open && (usePortal ? panelStyle : true) ? (
|
||||
<div
|
||||
ref={panelRef}
|
||||
className={
|
||||
'skill-tree-multiselect__panel' + (usePortal ? ' skill-tree-multiselect__panel--portal' : '')
|
||||
}
|
||||
style={usePortal ? panelStyle : undefined}
|
||||
>
|
||||
{panelContent}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<div className={`multiselect-combo skill-tree-multiselect ${className}`.trim()} ref={rootRef}>
|
||||
<div className="multiselect-combo__chips">
|
||||
{value.map((id, idx) => (
|
||||
<button
|
||||
key={`${normId(id)}-${idx}`}
|
||||
type="button"
|
||||
className="multiselect-combo__chip"
|
||||
onClick={() => removeAt(idx)}
|
||||
title="Entfernen"
|
||||
>
|
||||
<span>{selectedLabels[idx]}</span>
|
||||
<span className="multiselect-combo__chip-x" aria-hidden>
|
||||
×
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="multiselect-combo__field" ref={fieldRef}>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input multiselect-combo__input"
|
||||
placeholder={placeholder}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setOpen(true)
|
||||
setBrowseTree(false)
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
autoComplete="off"
|
||||
aria-expanded={open}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn multiselect-combo__browse"
|
||||
title="Katalog als Baum"
|
||||
onClick={() => {
|
||||
setOpen(true)
|
||||
setBrowseTree(true)
|
||||
setQuery('')
|
||||
}}
|
||||
>
|
||||
{browseLabel}
|
||||
</button>
|
||||
</div>
|
||||
{!usePortal && dropdownPanel}
|
||||
{usePortal && dropdownPanel ? createPortal(dropdownPanel, document.body) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import {
|
||||
allExpandableKeys,
|
||||
buildSkillCatalogTree,
|
||||
collectSkillLeavesFromTree,
|
||||
defaultExpandedKeysForSkillTree,
|
||||
filterSkillTreeByQuery,
|
||||
} from '../utils/skillCatalogTree'
|
||||
|
||||
function normExclude(excludeIds) {
|
||||
return new Set(
|
||||
(excludeIds instanceof Set ? [...excludeIds] : excludeIds || [])
|
||||
.map((x) => Number(x))
|
||||
.filter((n) => Number.isFinite(n))
|
||||
)
|
||||
}
|
||||
|
||||
function SkillTreeNodes({ nodes, depth, expanded, exclude, onToggle, onPickSkill, pickMode }) {
|
||||
if (!nodes?.length) {
|
||||
return <li className="skill-tree__empty">Keine Fähigkeiten</li>
|
||||
}
|
||||
|
||||
return nodes.map((node) => {
|
||||
if (node.type === 'skill') {
|
||||
if (exclude.has(node.skillId)) return null
|
||||
return (
|
||||
<li key={node.key} className="skill-tree__leaf" style={{ paddingLeft: `${8 + depth * 14}px` }}>
|
||||
<button
|
||||
type="button"
|
||||
className="skill-tree__pick"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onPickSkill(node.skillId, node.skill)}
|
||||
>
|
||||
{node.label}
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
const hasKids = node.children?.length > 0
|
||||
const isOpen = expanded.has(node.key)
|
||||
return (
|
||||
<li key={node.key} className="skill-tree__branch">
|
||||
<div className="skill-tree__branch-head" style={{ paddingLeft: `${4 + depth * 14}px` }}>
|
||||
{hasKids ? (
|
||||
<button
|
||||
type="button"
|
||||
className="skill-tree__toggle"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => onToggle(node.key)}
|
||||
>
|
||||
{isOpen ? <ChevronDown size={16} aria-hidden /> : <ChevronRight size={16} aria-hidden />}
|
||||
</button>
|
||||
) : (
|
||||
<span className="skill-tree__toggle-spacer" aria-hidden />
|
||||
)}
|
||||
<span className={`skill-tree__group-label skill-tree__group-label--${node.type}`}>
|
||||
{node.label}
|
||||
</span>
|
||||
</div>
|
||||
{hasKids && isOpen ? (
|
||||
<ul className="skill-tree__children" role={pickMode === 'multi' ? 'group' : 'tree'}>
|
||||
<SkillTreeNodes
|
||||
nodes={node.children}
|
||||
depth={depth + 1}
|
||||
expanded={expanded}
|
||||
exclude={exclude}
|
||||
onToggle={onToggle}
|
||||
onPickSkill={onPickSkill}
|
||||
pickMode={pickMode}
|
||||
/>
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausklappbare Baumliste: Hauptgruppe → Kategorie → Fähigkeit (nur Hauptgruppe standard offen).
|
||||
*/
|
||||
export default function SkillTreePickerPanel({
|
||||
skills = [],
|
||||
excludeIds,
|
||||
searchQuery = '',
|
||||
onPickSkill,
|
||||
pickMode = 'single',
|
||||
className = '',
|
||||
}) {
|
||||
const exclude = useMemo(() => normExclude(excludeIds), [excludeIds])
|
||||
const fullTree = useMemo(() => buildSkillCatalogTree(skills), [skills])
|
||||
const displayTree = useMemo(
|
||||
() => filterSkillTreeByQuery(fullTree, searchQuery),
|
||||
[fullTree, searchQuery]
|
||||
)
|
||||
const [expanded, setExpanded] = useState(() => new Set())
|
||||
|
||||
useEffect(() => {
|
||||
if (searchQuery.trim()) {
|
||||
setExpanded(new Set(allExpandableKeys(displayTree)))
|
||||
} else {
|
||||
setExpanded(new Set(defaultExpandedKeysForSkillTree(displayTree)))
|
||||
}
|
||||
}, [searchQuery, displayTree])
|
||||
|
||||
useEffect(() => {
|
||||
if (!searchQuery.trim()) {
|
||||
setExpanded(new Set(defaultExpandedKeysForSkillTree(fullTree)))
|
||||
}
|
||||
}, [fullTree, searchQuery])
|
||||
|
||||
const onToggle = useCallback((key) => {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(key)) next.delete(key)
|
||||
else next.add(key)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
const flatSearchHits = useMemo(() => {
|
||||
const q = searchQuery.trim()
|
||||
if (!q) return []
|
||||
return collectSkillLeavesFromTree(fullTree, exclude).filter((leaf) =>
|
||||
leaf.pathLabel.toLowerCase().includes(q.toLowerCase())
|
||||
)
|
||||
}, [fullTree, exclude, searchQuery])
|
||||
|
||||
if (searchQuery.trim() && flatSearchHits.length > 0) {
|
||||
return (
|
||||
<ul className={`skill-tree skill-tree--flat-hits ${className}`.trim()} role="listbox">
|
||||
{flatSearchHits.map((leaf) => (
|
||||
<li key={leaf.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="skill-tree__pick skill-tree__pick--path"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onPickSkill(leaf.id, leaf.skill)}
|
||||
>
|
||||
<span className="skill-tree__pick-name">{leaf.label}</span>
|
||||
<span className="skill-tree__pick-path">{leaf.pathLabel}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className={`skill-tree ${className}`.trim()} role="tree">
|
||||
<SkillTreeNodes
|
||||
nodes={displayTree}
|
||||
depth={0}
|
||||
expanded={expanded}
|
||||
exclude={exclude}
|
||||
onToggle={onToggle}
|
||||
onPickSkill={onPickSkill}
|
||||
pickMode={pickMode}
|
||||
/>
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { skillCatalogPathLabel } from '../utils/skillCatalogTree'
|
||||
import SkillTreePickerPanel from './SkillTreePickerPanel'
|
||||
|
||||
/**
|
||||
* Einzelauswahl einer Fähigkeit als hierarchische Treeview.
|
||||
*/
|
||||
export default function SkillTreeSelect({
|
||||
value = '',
|
||||
onChange,
|
||||
skills = [],
|
||||
excludeIds,
|
||||
placeholder = 'Fähigkeit wählen…',
|
||||
disabled = false,
|
||||
className = '',
|
||||
searchPlaceholder = 'Fähigkeit suchen…',
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const rootRef = useRef(null)
|
||||
|
||||
const selected = useMemo(() => {
|
||||
const id = value ? Number(value) : NaN
|
||||
if (!Number.isFinite(id)) return null
|
||||
return skills.find((s) => Number(s.id) === id) || null
|
||||
}, [value, skills])
|
||||
|
||||
const displayLabel = selected ? skillCatalogPathLabel(selected) : ''
|
||||
|
||||
useEffect(() => {
|
||||
const onDoc = (e) => {
|
||||
if (!rootRef.current?.contains(e.target)) {
|
||||
setOpen(false)
|
||||
setQuery('')
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', onDoc)
|
||||
return () => document.removeEventListener('mousedown', onDoc)
|
||||
}, [])
|
||||
|
||||
const pick = (skillId) => {
|
||||
onChange(String(skillId))
|
||||
setOpen(false)
|
||||
setQuery('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`skill-tree-select ${className}`.trim()} ref={rootRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="form-input skill-tree-select__trigger"
|
||||
disabled={disabled}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
onClick={() => !disabled && setOpen((o) => !o)}
|
||||
>
|
||||
<span className={displayLabel ? '' : 'skill-tree-select__placeholder'}>
|
||||
{displayLabel || placeholder}
|
||||
</span>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="skill-tree-select__panel">
|
||||
<input
|
||||
type="search"
|
||||
className="form-input skill-tree-select__search"
|
||||
placeholder={searchPlaceholder}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<div className="skill-tree-select__tree-wrap">
|
||||
<SkillTreePickerPanel
|
||||
skills={skills}
|
||||
excludeIds={excludeIds}
|
||||
searchQuery={query}
|
||||
onPickSkill={pick}
|
||||
pickMode="single"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import api from '../../utils/api'
|
||||
import SkillTreeSelect from '../SkillTreeSelect'
|
||||
|
||||
export default function MaturityModelsAdminPanel() {
|
||||
const { user } = useAuth()
|
||||
@@ -25,6 +26,13 @@ export default function MaturityModelsAdminPanel() {
|
||||
const [levelsForm, setLevelsForm] = useState([])
|
||||
const [cellDraft, setCellDraft] = useState({})
|
||||
const [skillToAdd, setSkillToAdd] = useState('')
|
||||
/** Modal: Stammdaten Fähigkeit (Wiki-Felder) aus Matrix-Kontext */
|
||||
const [skillWikiModal, setSkillWikiModal] = useState(null)
|
||||
const [skillWikiForm, setSkillWikiForm] = useState({
|
||||
karate_relevance: '',
|
||||
relevance_level: ''
|
||||
})
|
||||
const [skillWikiLoading, setSkillWikiLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -32,7 +40,7 @@ export default function MaturityModelsAdminPanel() {
|
||||
try {
|
||||
const [m, sk] = await Promise.all([
|
||||
api.listMaturityModels({}),
|
||||
api.listSkills({ status: 'active' })
|
||||
api.listSkillsCatalog({ status: 'active' })
|
||||
])
|
||||
if (!cancelled) {
|
||||
setModels(m)
|
||||
@@ -219,6 +227,57 @@ export default function MaturityModelsAdminPanel() {
|
||||
}
|
||||
}
|
||||
|
||||
async function openSkillWikiModal(skillId, skillName) {
|
||||
setSkillWikiModal({ skill_id: skillId, skill_name: skillName })
|
||||
setSkillWikiLoading(true)
|
||||
setSkillWikiForm({ karate_relevance: '', relevance_level: '' })
|
||||
try {
|
||||
const s = await api.getSkill(skillId)
|
||||
setSkillWikiForm({
|
||||
karate_relevance: s.karate_relevance || '',
|
||||
relevance_level:
|
||||
s.relevance_level != null && s.relevance_level !== ''
|
||||
? String(s.relevance_level)
|
||||
: ''
|
||||
})
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
setSkillWikiModal(null)
|
||||
} finally {
|
||||
setSkillWikiLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
function closeSkillWikiModal() {
|
||||
setSkillWikiModal(null)
|
||||
}
|
||||
|
||||
async function handleSaveSkillWikiFields(e) {
|
||||
e.preventDefault()
|
||||
if (!skillWikiModal) return
|
||||
setError('')
|
||||
setSkillWikiLoading(true)
|
||||
try {
|
||||
await api.updateSkill(skillWikiModal.skill_id, {
|
||||
karate_relevance:
|
||||
skillWikiForm.karate_relevance && skillWikiForm.karate_relevance.trim()
|
||||
? skillWikiForm.karate_relevance.trim()
|
||||
: null,
|
||||
relevance_level:
|
||||
skillWikiForm.relevance_level === '' || skillWikiForm.relevance_level == null
|
||||
? null
|
||||
: Number(skillWikiForm.relevance_level)
|
||||
})
|
||||
const sk = await api.listSkillsCatalog({ status: 'active' })
|
||||
setAllSkills(sk)
|
||||
closeSkillWikiModal()
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setSkillWikiLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteModel() {
|
||||
if (!selectedId || !isSuperadmin) return
|
||||
if (!confirm('Reifegradmodell dauerhaft löschen?')) return
|
||||
@@ -527,16 +586,13 @@ export default function MaturityModelsAdminPanel() {
|
||||
<div className="admin-matrix-skill-add">
|
||||
<div className="admin-matrix-skill-add__select">
|
||||
<label className="form-label">Fähigkeit hinzufügen</label>
|
||||
<select
|
||||
className="form-input"
|
||||
<SkillTreeSelect
|
||||
value={skillToAdd}
|
||||
onChange={(e) => setSkillToAdd(e.target.value)}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{allSkills.map((s) => (
|
||||
<option key={s.id} value={s.id}>{s.name}</option>
|
||||
))}
|
||||
</select>
|
||||
onChange={setSkillToAdd}
|
||||
skills={allSkills}
|
||||
excludeIds={(detail.model_skills || []).map((ms) => ms.skill_id)}
|
||||
placeholder="— wählen —"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -552,13 +608,24 @@ export default function MaturityModelsAdminPanel() {
|
||||
<li key={ms.skill_id} className="admin-matrix-skill-list__item">
|
||||
<div className="admin-matrix-skill-list__row">
|
||||
<strong className="admin-matrix-skill-list__name">{ms.skill_name}</strong>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
onClick={() => handleRemoveSkill(ms.skill_id)}
|
||||
>
|
||||
Entfernen
|
||||
</button>
|
||||
<span className="admin-matrix-skill-list__buttons">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
disabled={saving || skillWikiLoading}
|
||||
title="Karate-Relevanz und Relevanzgrad bearbeiten"
|
||||
onClick={() => openSkillWikiModal(ms.skill_id, ms.skill_name)}
|
||||
>
|
||||
Wiki-Felder
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
onClick={() => handleRemoveSkill(ms.skill_id)}
|
||||
>
|
||||
Entfernen
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
||||
<div className="admin-matrix-skill-list__path muted">
|
||||
@@ -595,13 +662,26 @@ export default function MaturityModelsAdminPanel() {
|
||||
{(detail.model_skills || []).map((ms) => (
|
||||
<tr key={ms.skill_id}>
|
||||
<td className="admin-matrix-matrix__skill-cell">
|
||||
<div>{ms.skill_name}</div>
|
||||
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
||||
<div className="admin-matrix-matrix__skill-path muted">
|
||||
{ms.skill_main_category_name || '—'}
|
||||
{ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
|
||||
<div className="admin-matrix-matrix__skill-head">
|
||||
<div>
|
||||
<div>{ms.skill_name}</div>
|
||||
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
||||
<div className="admin-matrix-matrix__skill-path muted">
|
||||
{ms.skill_main_category_name || '—'}
|
||||
{ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-tiny"
|
||||
title="Karate-Relevanz und Relevanzgrad bearbeiten"
|
||||
disabled={saving || skillWikiLoading}
|
||||
onClick={() => openSkillWikiModal(ms.skill_id, ms.skill_name)}
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
{(detail.levels || []).map((l) => {
|
||||
const key = `${ms.skill_id}-${l.level_number}`
|
||||
@@ -643,6 +723,90 @@ export default function MaturityModelsAdminPanel() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{skillWikiModal ? (
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={closeSkillWikiModal}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-sheet"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="matrix-skill-wiki-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="matrix-skill-wiki-title" className="admin-modal-sheet__title">
|
||||
Fähigkeit: {skillWikiModal.skill_name}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary admin-modal-sheet__close"
|
||||
disabled={skillWikiLoading}
|
||||
onClick={closeSkillWikiModal}
|
||||
aria-label="Schließen"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-modal-sheet__body">
|
||||
{skillWikiLoading ? (
|
||||
<p className="muted">Lade Daten…</p>
|
||||
) : (
|
||||
<form className="skills-catalog-form" onSubmit={handleSaveSkillWikiFields}>
|
||||
<label className="form-label">Karate-Relevanz (Wiki)</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={4}
|
||||
value={skillWikiForm.karate_relevance}
|
||||
onChange={(e) =>
|
||||
setSkillWikiForm((f) => ({ ...f, karate_relevance: e.target.value }))
|
||||
}
|
||||
disabled={skillWikiLoading}
|
||||
placeholder="Freitext (Wiki-Eigenschaft KarateRelevanz)"
|
||||
/>
|
||||
<label className="form-label">Relevanzgrad (Wiki, 1–3)</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={
|
||||
skillWikiForm.relevance_level === ''
|
||||
? ''
|
||||
: String(skillWikiForm.relevance_level)
|
||||
}
|
||||
onChange={(e) =>
|
||||
setSkillWikiForm((f) => ({ ...f, relevance_level: e.target.value }))
|
||||
}
|
||||
disabled={skillWikiLoading}
|
||||
>
|
||||
<option value="">– nicht gesetzt –</option>
|
||||
<option value="1">1</option>
|
||||
<option value="2">2</option>
|
||||
<option value="3">3</option>
|
||||
</select>
|
||||
<p className="muted admin-matrix-hint">
|
||||
Änderungen gelten für die Fähigkeit im gesamten Katalog (gemeinsame Stammdaten).
|
||||
</p>
|
||||
<div className="skills-catalog-form__actions">
|
||||
<button type="submit" className="btn btn-primary" disabled={skillWikiLoading}>
|
||||
Speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={skillWikiLoading}
|
||||
onClick={closeSkillWikiModal}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import api from '../../utils/api'
|
||||
import {
|
||||
catalogSkillsForSelection,
|
||||
countCatalogSkillsWithoutCategory,
|
||||
countCatalogSkillsWithoutMain,
|
||||
SKILL_CATEGORY_UNASSIGNED_KEY,
|
||||
SKILL_MAIN_UNASSIGNED_KEY,
|
||||
SKILL_UNASSIGNED_CATEGORY_LABEL,
|
||||
SKILL_UNASSIGNED_MAIN_LABEL,
|
||||
} from '../../utils/skillCatalogTree'
|
||||
|
||||
function bySortThenName(a, b) {
|
||||
const sa = a.sort_order != null ? Number(a.sort_order) : 99999
|
||||
@@ -71,7 +80,10 @@ export default function SkillsCatalogAdmin() {
|
||||
keywords: '',
|
||||
status: 'active',
|
||||
sort_order: '',
|
||||
category_id: ''
|
||||
category_id: '',
|
||||
main_category_id: '',
|
||||
karate_relevance: '',
|
||||
relevance_level: ''
|
||||
})
|
||||
|
||||
const [newMainName, setNewMainName] = useState('')
|
||||
@@ -82,7 +94,7 @@ export default function SkillsCatalogAdmin() {
|
||||
const [editDialog, setEditDialog] = useState(null)
|
||||
|
||||
const refreshCategories = useCallback(async (mainId) => {
|
||||
if (mainId == null) {
|
||||
if (mainId == null || mainId === SKILL_MAIN_UNASSIGNED_KEY || typeof mainId !== 'number') {
|
||||
setCategories([])
|
||||
return
|
||||
}
|
||||
@@ -126,12 +138,19 @@ export default function SkillsCatalogAdmin() {
|
||||
|
||||
const sortedCategories = useMemo(() => [...categories].sort(bySortThenName), [categories])
|
||||
|
||||
const skillsInCategory = useMemo(() => {
|
||||
const unassignedMainCount = useMemo(() => countCatalogSkillsWithoutMain(catalog), [catalog])
|
||||
|
||||
const unassignedCategoryCount = useMemo(
|
||||
() => countCatalogSkillsWithoutCategory(catalog, selectedMainId),
|
||||
[catalog, selectedMainId]
|
||||
)
|
||||
|
||||
const skillsInSelection = useMemo(() => {
|
||||
if (selectedCategoryId == null) return []
|
||||
return catalog
|
||||
.filter((s) => s.category_id === selectedCategoryId)
|
||||
.sort(bySortThenName)
|
||||
}, [catalog, selectedCategoryId])
|
||||
return [...catalogSkillsForSelection(catalog, selectedMainId, selectedCategoryId)].sort(
|
||||
bySortThenName
|
||||
)
|
||||
}, [catalog, selectedMainId, selectedCategoryId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!editDialog) return
|
||||
@@ -176,7 +195,13 @@ export default function SkillsCatalogAdmin() {
|
||||
keywords: s.keywords || '',
|
||||
status: s.status || 'active',
|
||||
sort_order: s.sort_order ?? '',
|
||||
category_id: s.category_id ?? ''
|
||||
category_id: s.category_id ?? '',
|
||||
main_category_id: s.main_category_id ?? '',
|
||||
karate_relevance: s.karate_relevance || '',
|
||||
relevance_level:
|
||||
s.relevance_level != null && s.relevance_level !== ''
|
||||
? String(s.relevance_level)
|
||||
: ''
|
||||
})
|
||||
setEditDialog({ type: 'skill', id: s.id })
|
||||
}
|
||||
@@ -192,7 +217,7 @@ export default function SkillsCatalogAdmin() {
|
||||
try {
|
||||
await op()
|
||||
await bootstrap()
|
||||
if (selectedMainId) await refreshCategories(selectedMainId)
|
||||
if (typeof selectedMainId === 'number') await refreshCategories(selectedMainId)
|
||||
setMessage('Gespeichert.')
|
||||
return true
|
||||
} catch (e) {
|
||||
@@ -231,7 +256,7 @@ export default function SkillsCatalogAdmin() {
|
||||
}
|
||||
|
||||
async function handleSwapSkill(rowId, delta) {
|
||||
const sorted = [...skillsInCategory].sort(bySortThenName)
|
||||
const sorted = [...skillsInSelection].sort(bySortThenName)
|
||||
await run(async () => {
|
||||
await swapNeighborSortById(sorted, rowId, delta, (id, data) => api.updateSkill(id, data))
|
||||
})
|
||||
@@ -285,16 +310,18 @@ export default function SkillsCatalogAdmin() {
|
||||
async function handleSaveSkill(e) {
|
||||
e.preventDefault()
|
||||
if (!editDialog || editDialog.type !== 'skill') return
|
||||
let cid =
|
||||
const cid =
|
||||
skillForm.category_id === '' || skillForm.category_id == null
|
||||
? null
|
||||
: Number(skillForm.category_id)
|
||||
const skillRow = catalog.find((s) => s.id === editDialog.id)
|
||||
if (cid == null && skillRow?.category_id) {
|
||||
cid = skillRow.category_id
|
||||
}
|
||||
const mid =
|
||||
cid == null &&
|
||||
skillForm.main_category_id !== '' &&
|
||||
skillForm.main_category_id != null
|
||||
? Number(skillForm.main_category_id)
|
||||
: null
|
||||
const ok = await run(async () => {
|
||||
await api.updateSkill(editDialog.id, {
|
||||
const payload = {
|
||||
name: skillForm.name.trim(),
|
||||
description: skillForm.description || null,
|
||||
category: skillForm.category || null,
|
||||
@@ -304,16 +331,34 @@ export default function SkillsCatalogAdmin() {
|
||||
skillForm.sort_order === '' || skillForm.sort_order == null
|
||||
? null
|
||||
: Number(skillForm.sort_order),
|
||||
category_id: cid
|
||||
})
|
||||
category_id: cid,
|
||||
karate_relevance:
|
||||
typeof skillForm.karate_relevance === 'string' && skillForm.karate_relevance.trim()
|
||||
? skillForm.karate_relevance.trim()
|
||||
: null,
|
||||
relevance_level:
|
||||
skillForm.relevance_level === '' || skillForm.relevance_level == null
|
||||
? null
|
||||
: Number(skillForm.relevance_level),
|
||||
}
|
||||
if (cid == null) {
|
||||
payload.main_category_id = mid
|
||||
}
|
||||
await api.updateSkill(editDialog.id, payload)
|
||||
})
|
||||
if (ok) {
|
||||
if (cid != null && cid !== selectedCategoryId) {
|
||||
if (cid != null) {
|
||||
const cat = allCategories.find((c) => c.id === cid)
|
||||
if (cat?.main_category_id) {
|
||||
setSelectedMainId(cat.main_category_id)
|
||||
setSelectedCategoryId(cid)
|
||||
}
|
||||
} else if (mid == null) {
|
||||
setSelectedMainId(SKILL_MAIN_UNASSIGNED_KEY)
|
||||
setSelectedCategoryId(SKILL_CATEGORY_UNASSIGNED_KEY)
|
||||
} else {
|
||||
setSelectedMainId(mid)
|
||||
setSelectedCategoryId(SKILL_CATEGORY_UNASSIGNED_KEY)
|
||||
}
|
||||
closeEditDialog()
|
||||
}
|
||||
@@ -332,7 +377,7 @@ export default function SkillsCatalogAdmin() {
|
||||
|
||||
async function handleCreateCategory(e) {
|
||||
e.preventDefault()
|
||||
if (selectedMainId == null) return
|
||||
if (selectedMainId == null || selectedMainId === SKILL_MAIN_UNASSIGNED_KEY) return
|
||||
const name = newCategoryName.trim()
|
||||
if (!name) return
|
||||
await run(async () => {
|
||||
@@ -352,11 +397,17 @@ export default function SkillsCatalogAdmin() {
|
||||
const name = newSkillName.trim()
|
||||
if (!name) return
|
||||
await run(async () => {
|
||||
const created = await api.createSkill({
|
||||
name,
|
||||
category_id: selectedCategoryId,
|
||||
status: 'active'
|
||||
})
|
||||
const body = { name, status: 'active' }
|
||||
if (typeof selectedCategoryId === 'number') {
|
||||
body.category_id = selectedCategoryId
|
||||
} else if (selectedCategoryId === SKILL_CATEGORY_UNASSIGNED_KEY) {
|
||||
body.category_id = null
|
||||
body.main_category_id =
|
||||
typeof selectedMainId === 'number' ? selectedMainId : null
|
||||
} else {
|
||||
return
|
||||
}
|
||||
const created = await api.createSkill(body)
|
||||
setNewSkillName('')
|
||||
setSelectedSkillId(created.id)
|
||||
})
|
||||
@@ -414,8 +465,9 @@ export default function SkillsCatalogAdmin() {
|
||||
<div className="skills-catalog-admin">
|
||||
<p className="skills-catalog-admin__intro muted">
|
||||
Struktur: <strong>Hauptkategorie</strong> → <strong>Kategorie</strong> →{' '}
|
||||
<strong>Fähigkeit</strong>. Reihenfolge mit Pfeilen; Details über das Stift-Symbol (öffnet
|
||||
ein Fenster — auf dem iPhone nach unten scrollen, falls nötig).
|
||||
<strong>Fähigkeit</strong>. Fähigkeiten ohne Zuordnung finden Sie unter{' '}
|
||||
<strong>{SKILL_UNASSIGNED_MAIN_LABEL}</strong> bzw. <strong>{SKILL_UNASSIGNED_CATEGORY_LABEL}</strong>{' '}
|
||||
(wie in der Auswahlbox). Reihenfolge mit Pfeilen; Details über das Stift-Symbol.
|
||||
</p>
|
||||
|
||||
{error ? (
|
||||
@@ -440,6 +492,26 @@ export default function SkillsCatalogAdmin() {
|
||||
<section className="skills-catalog-column" aria-label="Hauptkategorien">
|
||||
<h3 className="skills-catalog-column__title">Hauptkategorien</h3>
|
||||
<ul className="skills-catalog-list">
|
||||
{unassignedMainCount > 0 ? (
|
||||
<li>
|
||||
<div
|
||||
className={
|
||||
'skills-catalog-row' +
|
||||
(selectedMainId === SKILL_MAIN_UNASSIGNED_KEY
|
||||
? ' skills-catalog-row--active'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="skills-catalog-row__label"
|
||||
onClick={() => selectMain(SKILL_MAIN_UNASSIGNED_KEY)}
|
||||
>
|
||||
{SKILL_UNASSIGNED_MAIN_LABEL} ({unassignedMainCount})
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
) : null}
|
||||
{sortedMains.map((m) => (
|
||||
<li key={m.id}>
|
||||
<div
|
||||
@@ -519,9 +591,57 @@ export default function SkillsCatalogAdmin() {
|
||||
<h3 className="skills-catalog-column__title">Kategorien</h3>
|
||||
{selectedMainId == null ? (
|
||||
<p className="muted skills-catalog-placeholder">Zuerst eine Hauptkategorie wählen.</p>
|
||||
) : selectedMainId === SKILL_MAIN_UNASSIGNED_KEY ? (
|
||||
<>
|
||||
<ul className="skills-catalog-list">
|
||||
{unassignedCategoryCount > 0 ? (
|
||||
<li>
|
||||
<div
|
||||
className={
|
||||
'skills-catalog-row' +
|
||||
(selectedCategoryId === SKILL_CATEGORY_UNASSIGNED_KEY
|
||||
? ' skills-catalog-row--active'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="skills-catalog-row__label"
|
||||
onClick={() => selectCategory(SKILL_CATEGORY_UNASSIGNED_KEY)}
|
||||
>
|
||||
{SKILL_UNASSIGNED_CATEGORY_LABEL} ({unassignedCategoryCount})
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
<p className="muted skills-catalog-placeholder">
|
||||
Unter {SKILL_UNASSIGNED_MAIN_LABEL} gibt es keine Unterkategorien.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ul className="skills-catalog-list">
|
||||
{unassignedCategoryCount > 0 ? (
|
||||
<li>
|
||||
<div
|
||||
className={
|
||||
'skills-catalog-row' +
|
||||
(selectedCategoryId === SKILL_CATEGORY_UNASSIGNED_KEY
|
||||
? ' skills-catalog-row--active'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="skills-catalog-row__label"
|
||||
onClick={() => selectCategory(SKILL_CATEGORY_UNASSIGNED_KEY)}
|
||||
>
|
||||
{SKILL_UNASSIGNED_CATEGORY_LABEL} ({unassignedCategoryCount})
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
) : null}
|
||||
{sortedCategories.map((c) => (
|
||||
<li key={c.id}>
|
||||
<div
|
||||
@@ -602,11 +722,13 @@ export default function SkillsCatalogAdmin() {
|
||||
<section className="skills-catalog-column" aria-label="Fähigkeiten">
|
||||
<h3 className="skills-catalog-column__title">Fähigkeiten</h3>
|
||||
{selectedCategoryId == null ? (
|
||||
<p className="muted skills-catalog-placeholder">Zuerst eine Kategorie wählen.</p>
|
||||
<p className="muted skills-catalog-placeholder">
|
||||
Zuerst eine Kategorie oder „{SKILL_UNASSIGNED_CATEGORY_LABEL}“ wählen.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="skills-catalog-list">
|
||||
{skillsInCategory.map((s) => (
|
||||
{skillsInSelection.map((s) => (
|
||||
<li key={s.id}>
|
||||
<div
|
||||
className={
|
||||
@@ -882,14 +1004,41 @@ export default function SkillsCatalogAdmin() {
|
||||
}))
|
||||
}
|
||||
disabled={busy}
|
||||
required
|
||||
>
|
||||
<option value="">{SKILL_UNASSIGNED_CATEGORY_LABEL}</option>
|
||||
{allCategories.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{(c.main_category_name ? c.main_category_name + ' · ' : '') + c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{skillForm.category_id === '' || skillForm.category_id == null ? (
|
||||
<>
|
||||
<label className="form-label">Hauptkategorie</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={
|
||||
skillForm.main_category_id === '' || skillForm.main_category_id == null
|
||||
? ''
|
||||
: String(skillForm.main_category_id)
|
||||
}
|
||||
onChange={(e) =>
|
||||
setSkillForm((f) => ({
|
||||
...f,
|
||||
main_category_id: e.target.value === '' ? '' : e.target.value
|
||||
}))
|
||||
}
|
||||
disabled={busy}
|
||||
>
|
||||
<option value="">{SKILL_UNASSIGNED_MAIN_LABEL}</option>
|
||||
{sortedMains.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</>
|
||||
) : null}
|
||||
<label className="form-label">Legacy-Kurzlabel „category“ (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
@@ -922,6 +1071,31 @@ export default function SkillsCatalogAdmin() {
|
||||
onChange={(e) => setSkillForm((f) => ({ ...f, description: e.target.value }))}
|
||||
disabled={busy}
|
||||
/>
|
||||
<label className="form-label">Karate-Relevanz (Wiki)</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={3}
|
||||
value={skillForm.karate_relevance}
|
||||
onChange={(e) =>
|
||||
setSkillForm((f) => ({ ...f, karate_relevance: e.target.value }))
|
||||
}
|
||||
disabled={busy}
|
||||
placeholder="Freitext aus Wiki / eigene Erläuterung"
|
||||
/>
|
||||
<label className="form-label">Relevanzgrad (Wiki, 1–3)</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={skillForm.relevance_level === '' ? '' : String(skillForm.relevance_level)}
|
||||
onChange={(e) =>
|
||||
setSkillForm((f) => ({ ...f, relevance_level: e.target.value }))
|
||||
}
|
||||
disabled={busy}
|
||||
>
|
||||
<option value="">– nicht gesetzt –</option>
|
||||
<option value="1">1</option>
|
||||
<option value="2">2</option>
|
||||
<option value="3">3</option>
|
||||
</select>
|
||||
<label className="form-label">Sortierung (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import React from 'react'
|
||||
|
||||
/**
|
||||
* Kompakte Katalog-Zuordnung (Fokus, Stile, Zielgruppen …) als Chip-Zeilen.
|
||||
*/
|
||||
export default function ExerciseCatalogAssocEditor({
|
||||
title,
|
||||
rows,
|
||||
setRows,
|
||||
options,
|
||||
idKey,
|
||||
emptyLabel,
|
||||
showPrimary = true,
|
||||
}) {
|
||||
const setPrimary = (idx) => {
|
||||
setRows(rows.map((r, i) => ({ ...r, is_primary: i === idx })))
|
||||
}
|
||||
const updateRow = (idx, patch) => {
|
||||
const next = rows.map((r, i) => (i === idx ? { ...r, ...patch } : r))
|
||||
if (patch.is_primary === true) {
|
||||
next.forEach((r, i) => {
|
||||
if (i !== idx) r.is_primary = false
|
||||
})
|
||||
}
|
||||
setRows(next)
|
||||
}
|
||||
const addRow = () => setRows([...rows, { [idKey]: '', is_primary: rows.length === 0 }])
|
||||
const removeRow = (idx) => {
|
||||
const next = rows.filter((_, i) => i !== idx)
|
||||
if (next.length && showPrimary && !next.some((r) => r.is_primary)) next[0].is_primary = true
|
||||
setRows(next)
|
||||
}
|
||||
|
||||
const optionLabel = (o) => {
|
||||
const parts = []
|
||||
if (o.icon) parts.push(o.icon)
|
||||
parts.push(o.name)
|
||||
if (o.abbreviation) parts.push(`(${o.abbreviation})`)
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="exercise-meta-block">
|
||||
<div className="exercise-meta-block__head">
|
||||
<h4 className="exercise-meta-block__title">{title}</h4>
|
||||
<button type="button" className="btn btn-secondary exercise-meta-block__add" onClick={addRow}>
|
||||
+ Eintrag
|
||||
</button>
|
||||
</div>
|
||||
{rows.length === 0 ? (
|
||||
<p className="exercise-meta-block__empty">{emptyLabel}</p>
|
||||
) : (
|
||||
<div className="exercise-meta-block__chips" role="list">
|
||||
{rows.map((row, idx) => (
|
||||
<div key={idx} className="exercise-catalog-chip" role="listitem">
|
||||
<select
|
||||
className="exercise-catalog-chip__select"
|
||||
value={row[idKey] || ''}
|
||||
aria-label={`${title} wählen`}
|
||||
onChange={(e) =>
|
||||
updateRow(idx, { [idKey]: e.target.value ? parseInt(e.target.value, 10) : '' })
|
||||
}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{optionLabel(o)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{showPrimary ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`exercise-catalog-chip__primary${row.is_primary ? ' exercise-catalog-chip__primary--on' : ''}`}
|
||||
title={row.is_primary ? 'Primär' : 'Als primär markieren'}
|
||||
aria-pressed={!!row.is_primary}
|
||||
onClick={() => setPrimary(idx)}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="exercise-catalog-chip__remove"
|
||||
aria-label="Entfernen"
|
||||
title="Entfernen"
|
||||
onClick={() => removeRow(idx)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import React from 'react'
|
||||
import PageSectionNav from '../PageSectionNav'
|
||||
|
||||
export function ExerciseFormTabBar({ activeTab, onChange, items }) {
|
||||
return (
|
||||
<div className="exercise-form-edit__tabbar">
|
||||
<PageSectionNav
|
||||
ariaLabel="Übungsbereiche"
|
||||
value={activeTab}
|
||||
onChange={onChange}
|
||||
items={items}
|
||||
className="page-section-nav--embedded exercise-form-edit__section-nav"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ExerciseFormPanel({ tab, activeTab, tone = 'default', title, hint, children }) {
|
||||
if (activeTab !== tab) return null
|
||||
return (
|
||||
<section
|
||||
id={`exercise-form-panel-${tab}`}
|
||||
className={`exercise-form-panel exercise-form-panel--${tone}`}
|
||||
role="tabpanel"
|
||||
aria-labelledby={`exercise-form-tab-${tab}`}
|
||||
>
|
||||
{title ? <h3 className="exercise-form-panel__title">{title}</h3> : null}
|
||||
{hint ? <p className="exercise-form-panel__hint">{hint}</p> : null}
|
||||
<div className="exercise-form-panel__body">{children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,241 @@
|
||||
import React from 'react'
|
||||
import { activeClubMemberships } from '../../utils/activeClub'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
import MultiSelectCombo from '../MultiSelectCombo'
|
||||
|
||||
/**
|
||||
* Massenänderung für ausgewählte Übungen in der Liste.
|
||||
*/
|
||||
export default function ExerciseListBulkModal({
|
||||
open,
|
||||
onClose,
|
||||
onSubmit,
|
||||
bulkSubmitting,
|
||||
selectedCount,
|
||||
bulkMaxIds,
|
||||
user,
|
||||
isPlatformAdmin,
|
||||
statusOptions,
|
||||
bulkVisibilityOptions,
|
||||
focusOptions,
|
||||
styleOptions,
|
||||
trainingTypeOptions,
|
||||
targetGroupOptions,
|
||||
bulkVisibility,
|
||||
setBulkVisibility,
|
||||
bulkStatus,
|
||||
setBulkStatus,
|
||||
bulkClubSelect,
|
||||
setBulkClubSelect,
|
||||
bulkClubManual,
|
||||
setBulkClubManual,
|
||||
bulkPatchFocusAreas,
|
||||
setBulkPatchFocusAreas,
|
||||
bulkFocusAreaIds,
|
||||
setBulkFocusAreaIds,
|
||||
bulkPatchStyleDirections,
|
||||
setBulkPatchStyleDirections,
|
||||
bulkStyleDirectionIds,
|
||||
setBulkStyleDirectionIds,
|
||||
bulkPatchTrainingTypes,
|
||||
setBulkPatchTrainingTypes,
|
||||
bulkTrainingTypeIds,
|
||||
setBulkTrainingTypeIds,
|
||||
bulkPatchTargetGroups,
|
||||
setBulkPatchTargetGroups,
|
||||
bulkTargetGroupIds,
|
||||
setBulkTargetGroupIds,
|
||||
}) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-sheet exercise-filter-modal"
|
||||
data-testid="exercise-list-bulk-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="exercise-bulk-modal-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="exercise-bulk-modal-title" className="admin-modal-sheet__title">
|
||||
Massenänderung
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-modal-sheet__body exercise-filter-modal__scroll">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
Es werden <strong>{selectedCount}</strong> Übung(en) aus der aktuellen Auswahl bearbeitet. Pro Durchlauf
|
||||
höchstens {bulkMaxIds}. Ohne Berechtigung bleiben Einzelübungen unverändert (siehe Hinweis nach dem
|
||||
Speichern).
|
||||
</p>
|
||||
<p className="form-sub" style={{ marginTop: 0, marginBottom: '14px' }}>
|
||||
Unter „Zuordnung ersetzen“: die gewählte Liste ersetzt die bisherige Zuordnung bei allen betroffenen Übungen
|
||||
vollständig (leere Auswahl = alle Zuordnungen dieser Kategorie entfernen). Die erste Auswahl gilt als
|
||||
Primärzuordnung.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">{EXERCISE_VISIBILITY_FIELD_LABEL}</label>
|
||||
<select className="form-input" value={bulkVisibility} onChange={(e) => setBulkVisibility(e.target.value)}>
|
||||
{bulkVisibilityOptions.map((o) => (
|
||||
<option key={o.id === '' ? '_unchanged' : o.id} value={o.id}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{bulkVisibility === 'club' ? (
|
||||
<div className="form-row">
|
||||
<label className="form-label">Verein zuordnen</label>
|
||||
<select className="form-input" value={bulkClubSelect} onChange={(e) => setBulkClubSelect(e.target.value)}>
|
||||
<option value="">Aktiver Verein (Vereins-Umschalter / Header)</option>
|
||||
{activeClubMemberships(user?.clubs).map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name || `#${c.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{isPlatformAdmin ? (
|
||||
<>
|
||||
<label className="form-label" style={{ marginTop: '10px' }}>
|
||||
Oder Vereins-ID (Plattform-Admin)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
className="form-input"
|
||||
placeholder="Leer = wie Dropdown / aktiver Verein"
|
||||
value={bulkClubManual}
|
||||
onChange={(e) => setBulkClubManual(e.target.value)}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="form-row">
|
||||
<label className="form-label">Status</label>
|
||||
<select className="form-input" value={bulkStatus} onChange={(e) => setBulkStatus(e.target.value)}>
|
||||
<option value="">— nicht ändern —</option>
|
||||
{statusOptions.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<section className="exercise-filter-section" style={{ marginTop: '8px', paddingTop: '12px' }}>
|
||||
<h4 className="exercise-filter-section-title">Zuordnung (optional)</h4>
|
||||
<div className="exercise-filters-modal-grid">
|
||||
<div>
|
||||
<label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={bulkPatchFocusAreas}
|
||||
onChange={(e) => {
|
||||
const on = e.target.checked
|
||||
setBulkPatchFocusAreas(on)
|
||||
if (!on) setBulkFocusAreaIds([])
|
||||
}}
|
||||
/>
|
||||
Fokusbereiche ersetzen
|
||||
</label>
|
||||
{bulkPatchFocusAreas ? (
|
||||
<MultiSelectCombo
|
||||
value={bulkFocusAreaIds}
|
||||
onChange={setBulkFocusAreaIds}
|
||||
options={focusOptions}
|
||||
placeholder="Fokusbereiche wählen …"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={bulkPatchStyleDirections}
|
||||
onChange={(e) => {
|
||||
const on = e.target.checked
|
||||
setBulkPatchStyleDirections(on)
|
||||
if (!on) setBulkStyleDirectionIds([])
|
||||
}}
|
||||
/>
|
||||
Stilrichtungen ersetzen
|
||||
</label>
|
||||
{bulkPatchStyleDirections ? (
|
||||
<MultiSelectCombo
|
||||
value={bulkStyleDirectionIds}
|
||||
onChange={setBulkStyleDirectionIds}
|
||||
options={styleOptions}
|
||||
placeholder="Stilrichtungen wählen …"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={bulkPatchTrainingTypes}
|
||||
onChange={(e) => {
|
||||
const on = e.target.checked
|
||||
setBulkPatchTrainingTypes(on)
|
||||
if (!on) setBulkTrainingTypeIds([])
|
||||
}}
|
||||
/>
|
||||
Trainingsstile ersetzen
|
||||
</label>
|
||||
{bulkPatchTrainingTypes ? (
|
||||
<MultiSelectCombo
|
||||
value={bulkTrainingTypeIds}
|
||||
onChange={setBulkTrainingTypeIds}
|
||||
options={trainingTypeOptions}
|
||||
placeholder="Trainingsstile wählen …"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={bulkPatchTargetGroups}
|
||||
onChange={(e) => {
|
||||
const on = e.target.checked
|
||||
setBulkPatchTargetGroups(on)
|
||||
if (!on) setBulkTargetGroupIds([])
|
||||
}}
|
||||
/>
|
||||
Zielgruppen ersetzen
|
||||
</label>
|
||||
{bulkPatchTargetGroups ? (
|
||||
<MultiSelectCombo
|
||||
value={bulkTargetGroupIds}
|
||||
onChange={setBulkTargetGroupIds}
|
||||
options={targetGroupOptions}
|
||||
placeholder="Zielgruppen wählen …"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div className="exercise-filter-modal__footer">
|
||||
<button type="button" className="btn" disabled={bulkSubmitting} onClick={onClose}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={bulkSubmitting} onClick={onSubmit}>
|
||||
{bulkSubmitting ? 'Speichern…' : 'Anwenden'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import React from 'react'
|
||||
|
||||
export default function ExerciseListBulkToolbar({
|
||||
selectedCount,
|
||||
bulkMaxIds,
|
||||
onClearSelection,
|
||||
onOpenBulkModal,
|
||||
onOpenSaveModuleModal,
|
||||
}) {
|
||||
if (selectedCount < 1) return null
|
||||
|
||||
return (
|
||||
<div className="card exercise-bulk-toolbar" data-testid="exercise-list-bulk-toolbar">
|
||||
<strong>{selectedCount} ausgewählt</strong>
|
||||
<button type="button" className="btn btn-secondary btn-small" onClick={onClearSelection}>
|
||||
Auswahl aufheben
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary btn-small" onClick={onOpenSaveModuleModal}>
|
||||
Als Modul speichern…
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary btn-small" onClick={onOpenBulkModal}>
|
||||
Massenänderung…
|
||||
</button>
|
||||
<span className="exercise-bulk-toolbar__meta">
|
||||
Bis zu {bulkMaxIds} pro Anfrage. Für „Verein“ ohne Auswahl: aktiver Vereinskontext (
|
||||
<code>X-Active-Club-Id</code>
|
||||
).
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import NavStateLink from '../NavStateLink'
|
||||
import {
|
||||
buildExercisesListReturnContext,
|
||||
navigateWithAppReturn,
|
||||
} from '../../utils/navReturnContext'
|
||||
import {
|
||||
Eye,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Globe,
|
||||
Users,
|
||||
Lock,
|
||||
CheckCircle2,
|
||||
Archive,
|
||||
CircleDot,
|
||||
FilePenLine,
|
||||
Image,
|
||||
Layers,
|
||||
} from 'lucide-react'
|
||||
import ExerciseRichTextBlock from '../ExerciseRichTextBlock'
|
||||
import { coerceApiNameList } from '../../utils/sanitizeHtml'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
import { canUserRequestExerciseDelete } from '../../utils/exercisePermissions'
|
||||
|
||||
const VIS_LABELS = { official: 'Global', club: 'Verein', private: 'Privat' }
|
||||
const STATUS_LABELS = {
|
||||
draft: 'Entwurf',
|
||||
in_review: 'In Prüfung',
|
||||
approved: 'Freigegeben',
|
||||
archived: 'Archiv',
|
||||
}
|
||||
|
||||
function visibilityLabel(v) {
|
||||
return VIS_LABELS[v] || v || '—'
|
||||
}
|
||||
|
||||
function statusLabel(s) {
|
||||
return STATUS_LABELS[s] || s || '—'
|
||||
}
|
||||
|
||||
function exerciseFocusNames(ex) {
|
||||
const fromApi = coerceApiNameList(ex.focus_area_names)
|
||||
if (fromApi.length) return fromApi
|
||||
if (ex.focus_area) return [ex.focus_area]
|
||||
return []
|
||||
}
|
||||
|
||||
function exerciseCardClassName(exercise, userId) {
|
||||
const vis = exercise.visibility || 'private'
|
||||
const visKey = vis === 'official' || vis === 'club' || vis === 'private' ? vis : 'private'
|
||||
const mine = userId != null && Number(exercise.created_by) === Number(userId)
|
||||
return ['card', 'exercise-card', `exercise-card--scope-${visKey}`, mine ? 'exercise-card--mine' : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
function exerciseVariantCount(exercise) {
|
||||
if (typeof exercise?.variant_count === 'number' && Number.isFinite(exercise.variant_count)) {
|
||||
return Math.max(0, exercise.variant_count)
|
||||
}
|
||||
return Array.isArray(exercise?.variants) ? exercise.variants.length : 0
|
||||
}
|
||||
|
||||
function exerciseMediaCount(exercise) {
|
||||
if (typeof exercise?.media_count === 'number' && Number.isFinite(exercise.media_count)) {
|
||||
return Math.max(0, exercise.media_count)
|
||||
}
|
||||
return Array.isArray(exercise?.media) ? exercise.media.length : 0
|
||||
}
|
||||
|
||||
function ExerciseCardContentStats({ exercise }) {
|
||||
const mediaCount = exerciseMediaCount(exercise)
|
||||
const variantCount = exerciseVariantCount(exercise)
|
||||
if (mediaCount <= 0 && variantCount <= 0) return null
|
||||
|
||||
const mediaLabel =
|
||||
mediaCount === 1 ? '1 Medium hinterlegt' : `${mediaCount} Medien hinterlegt`
|
||||
const variantLabel =
|
||||
variantCount === 1 ? '1 Variante' : `${variantCount} Varianten`
|
||||
|
||||
return (
|
||||
<div className="exercise-card__content-stats">
|
||||
{mediaCount > 0 ? (
|
||||
<span className="exercise-card__stat" title={mediaLabel} aria-label={mediaLabel}>
|
||||
<Image size={15} strokeWidth={2} aria-hidden />
|
||||
<span className="exercise-card__stat-num" aria-hidden>
|
||||
{mediaCount}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
{variantCount > 0 ? (
|
||||
<span className="exercise-card__stat" title={variantLabel} aria-label={variantLabel}>
|
||||
<Layers size={15} strokeWidth={2} aria-hidden />
|
||||
<span className="exercise-card__stat-num" aria-hidden>
|
||||
{variantCount}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ExerciseCardScopeStatus({ exercise }) {
|
||||
const v = exercise.visibility || 'private'
|
||||
const s = exercise.status || 'draft'
|
||||
const visLabel = visibilityLabel(v)
|
||||
const stLabel = statusLabel(s)
|
||||
const tip = `${visLabel} · ${stLabel}`
|
||||
let VisIcon = Lock
|
||||
if (v === 'official') VisIcon = Globe
|
||||
else if (v === 'club') VisIcon = Users
|
||||
let StatIcon = FilePenLine
|
||||
if (s === 'approved') StatIcon = CheckCircle2
|
||||
else if (s === 'archived') StatIcon = Archive
|
||||
else if (s === 'in_review') StatIcon = CircleDot
|
||||
return (
|
||||
<div
|
||||
className="exercise-card__meta-compact"
|
||||
title={tip}
|
||||
aria-label={`${EXERCISE_VISIBILITY_FIELD_LABEL}: ${visLabel}. Status: ${stLabel}.`}
|
||||
>
|
||||
<span className="exercise-card__meta-glyph">
|
||||
<VisIcon size={15} strokeWidth={2} aria-hidden />
|
||||
</span>
|
||||
<span className="exercise-card__meta-sep" aria-hidden>
|
||||
·
|
||||
</span>
|
||||
<span className="exercise-card__meta-glyph">
|
||||
<StatIcon size={15} strokeWidth={2} aria-hidden />
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Kartenzeile in der Übungsliste (Fokus/Planung — keine Virtualisierung im Grid, dafür content-visibility in app.css).
|
||||
*/
|
||||
export default function ExerciseListCard({
|
||||
exercise,
|
||||
user,
|
||||
selectedIds,
|
||||
toggleSelect,
|
||||
onDelete,
|
||||
onPeek,
|
||||
selectionPinned = false,
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const listReturn = useMemo(() => buildExercisesListReturnContext(), [])
|
||||
const focusNames = exerciseFocusNames(exercise)
|
||||
const styleNames = coerceApiNameList(exercise.style_direction_names)
|
||||
const typeNames = coerceApiNameList(exercise.training_type_names)
|
||||
const titleText = (exercise.title || 'Übung').replace(/"/g, '')
|
||||
|
||||
const openExercisePage = () =>
|
||||
navigateWithAppReturn(navigate, `/exercises/${exercise.id}`, listReturn)
|
||||
|
||||
const handleBodyClick = (e) => {
|
||||
if (e.target.closest('a, button, input, textarea, select, label, [role="button"]')) return
|
||||
openExercisePage()
|
||||
}
|
||||
|
||||
const handleBodyKeyDown = (e) => {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return
|
||||
if (e.target.closest('a, button, input, textarea, select, label, [role="button"]')) return
|
||||
e.preventDefault()
|
||||
openExercisePage()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
exerciseCardClassName(exercise, user?.id),
|
||||
selectionPinned ? 'exercise-card--selection-pinned' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
>
|
||||
<div className="exercise-card-layout exercise-card-layout--grow">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.has(Number(exercise.id))}
|
||||
onChange={() => toggleSelect(exercise)}
|
||||
aria-label={`„${titleText}“ auswählen`}
|
||||
className="exercise-card-layout__check"
|
||||
/>
|
||||
<div
|
||||
className="exercise-card__body exercise-card-body-flex exercise-card__body--clickable"
|
||||
role="link"
|
||||
tabIndex={0}
|
||||
onClick={handleBodyClick}
|
||||
onKeyDown={handleBodyKeyDown}
|
||||
aria-label={`„${titleText}“ öffnen`}
|
||||
>
|
||||
<h3 className="exercise-card-title">
|
||||
<NavStateLink
|
||||
to={`/exercises/${exercise.id}`}
|
||||
returnContext={listReturn}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{exercise.title}
|
||||
</NavStateLink>
|
||||
{selectionPinned ? (
|
||||
<span className="exercise-card__selection-badge" title="In Modul-Auswahl">
|
||||
Auswahl
|
||||
</span>
|
||||
) : null}
|
||||
</h3>
|
||||
<div className="exercise-card-tags">
|
||||
{focusNames.map((name) => (
|
||||
<span key={`fa:${name}`} className="exercise-tag exercise-tag--accent">
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
{styleNames.map((name) => (
|
||||
<span key={`sd:${name}`} className="exercise-tag exercise-tag--style">
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
{typeNames.map((name) => (
|
||||
<span key={`tt:${name}`} className="exercise-tag exercise-tag--training">
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
{(exercise.exercise_kind || '').toLowerCase().trim() === 'combination' ? (
|
||||
<span
|
||||
className="exercise-tag"
|
||||
style={{ background: 'var(--accent-soft)', color: 'var(--accent-dark)' }}
|
||||
>
|
||||
Kombination
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{exercise.summary && String(exercise.summary).trim() ? (
|
||||
<div className="exercise-card-summary exercise-card-summary--rich">
|
||||
<ExerciseRichTextBlock
|
||||
html={exercise.summary}
|
||||
exerciseId={exercise.id}
|
||||
media={exercise.media || []}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="exercise-card__footer">
|
||||
<div className="exercise-card__footer-meta">
|
||||
<ExerciseCardScopeStatus exercise={exercise} />
|
||||
<ExerciseCardContentStats exercise={exercise} />
|
||||
</div>
|
||||
<div className="exercise-card__actions exercise-card__actions--icons">
|
||||
<button
|
||||
type="button"
|
||||
className="exercise-card__icon-btn"
|
||||
title="Vorschau"
|
||||
aria-label={`„${titleText}“ in Vorschau anzeigen`}
|
||||
onClick={() => onPeek?.(exercise)}
|
||||
>
|
||||
<Eye size={18} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
<NavStateLink
|
||||
to={`/exercises/${exercise.id}/edit`}
|
||||
returnContext={listReturn}
|
||||
className="exercise-card__icon-btn"
|
||||
title="Bearbeiten"
|
||||
aria-label={`„${titleText}“ bearbeiten`}
|
||||
>
|
||||
<Pencil size={18} strokeWidth={2} aria-hidden />
|
||||
</NavStateLink>
|
||||
{canUserRequestExerciseDelete(user, exercise) ? (
|
||||
<button
|
||||
type="button"
|
||||
className="exercise-card__icon-btn exercise-card__icon-btn--danger"
|
||||
title="Löschen"
|
||||
aria-label={`„${(exercise.title || 'Übung').replace(/"/g, '')}“ löschen`}
|
||||
onClick={() => onDelete(exercise)}
|
||||
>
|
||||
<Trash2 size={18} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import React from 'react'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../../constants/skillLevels'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
import SkillTreeMultiSelect from '../SkillTreeMultiSelect'
|
||||
import ExerciseFocusRulePicker from '../ExerciseFocusRulePicker'
|
||||
import CatalogRulePicker from '../CatalogRulePicker'
|
||||
|
||||
const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)
|
||||
|
||||
/**
|
||||
* Filter-Dialog für die Übungsliste (gleiche Logik wie zuvor inline in ExercisesListPage).
|
||||
*/
|
||||
export default function ExerciseListFilterModal({
|
||||
open,
|
||||
onClose,
|
||||
filters,
|
||||
setFilters,
|
||||
focusOptions,
|
||||
styleOptions,
|
||||
trainingTypeOptions,
|
||||
targetGroupOptions,
|
||||
skillsCatalog = [],
|
||||
visibilityOptions,
|
||||
statusOptions,
|
||||
savingExercisePrefs,
|
||||
onSaveStandard,
|
||||
onResetAll,
|
||||
}) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-sheet exercise-filter-modal"
|
||||
data-testid="exercise-list-filter-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="exercise-filter-modal-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="exercise-filter-modal-title" className="admin-modal-sheet__title">
|
||||
Übungen filtern
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-modal-sheet__body exercise-filter-modal__scroll">
|
||||
<p className="muted" style={{ marginTop: 0, marginBottom: '14px' }}>
|
||||
Zwischen den Bereichen gilt <strong>UND</strong>. Fokusbereiche: mehrere „+ mit“ bedeuten alle müssen
|
||||
gesetzt sein; „− ohne“ schließt Übungen aus, die diesen Fokus zusätzlich haben. Stilrichtung /
|
||||
Trainingsstil / Zielgruppe: mehrere „+“ = alle zutreffend (UND); „−“ verbietet die Zuordnung. Unter
|
||||
„Freigabe“: Freigabelevel / Status mit „+“ = eine davon (ODER); „−“ blendet aus.
|
||||
</p>
|
||||
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Zuordnung</h4>
|
||||
<ExerciseFocusRulePicker
|
||||
focusOptions={focusOptions}
|
||||
focusRules={filters.focus_rules}
|
||||
focusOnlyWithout={filters.focus_only_without}
|
||||
legacyFocusAreaIds={filters.focus_area_ids}
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--catalog" style={{ marginTop: '12px' }}>
|
||||
<CatalogRulePicker
|
||||
label="Stilrichtung"
|
||||
hint="+ alle nötig (UND). − verbietet Zuordnung."
|
||||
options={styleOptions}
|
||||
rules={filters.style_direction_rules}
|
||||
rulesFieldName="style_direction_rules"
|
||||
placeholder="Stil …"
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
<CatalogRulePicker
|
||||
label="Trainingsstil"
|
||||
hint="+ alle nötig (UND). − verbietet Zuordnung."
|
||||
options={trainingTypeOptions}
|
||||
rules={filters.training_type_rules}
|
||||
rulesFieldName="training_type_rules"
|
||||
placeholder="Trainingsstil …"
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
<CatalogRulePicker
|
||||
label="Zielgruppe"
|
||||
hint="+ alle nötig (UND). − verbietet Zuordnung."
|
||||
options={targetGroupOptions}
|
||||
rules={filters.target_group_rules}
|
||||
rulesFieldName="target_group_rules"
|
||||
placeholder="Gruppe …"
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Fähigkeit und zugehörige Stufe</h4>
|
||||
<div className="exercise-filter-skill-block">
|
||||
<label className="form-label">Fähigkeit</label>
|
||||
<SkillTreeMultiSelect
|
||||
value={filters.skill_ids}
|
||||
onChange={(v) => setFilters({ ...filters, skill_ids: v })}
|
||||
skills={skillsCatalog}
|
||||
placeholder="Fähigkeit suchen …"
|
||||
/>
|
||||
<p className="exercise-filter-skill-hint">
|
||||
Die Stufen filtern nach dem Niveau der Zuordnung Übung ↔ Fähigkeit (von–bis).
|
||||
</p>
|
||||
<div className="exercise-filter-skill-levels-row">
|
||||
<label className="exercise-filter-skill-level-field">
|
||||
<span className="exercise-filter-skill-level-caption">von</span>
|
||||
<select
|
||||
className="form-input exercise-filter-level-select"
|
||||
title="Mindest-Stufe"
|
||||
value={filters.skill_min_level}
|
||||
onChange={(e) => setFilters({ ...filters, skill_min_level: e.target.value })}
|
||||
>
|
||||
<option value="">–</option>
|
||||
{LEVEL_FILTER_OPTS.map((o) => (
|
||||
<option key={o.value} value={String(o.level)} title={o.label}>
|
||||
{o.level}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<span className="exercise-filter-skill-dash" aria-hidden>
|
||||
–
|
||||
</span>
|
||||
<label className="exercise-filter-skill-level-field">
|
||||
<span className="exercise-filter-skill-level-caption">bis</span>
|
||||
<select
|
||||
className="form-input exercise-filter-level-select"
|
||||
title="Höchst-Stufe"
|
||||
value={filters.skill_max_level}
|
||||
onChange={(e) => setFilters({ ...filters, skill_max_level: e.target.value })}
|
||||
>
|
||||
<option value="">–</option>
|
||||
{LEVEL_FILTER_OPTS.map((o) => (
|
||||
<option key={`m-${o.value}`} value={String(o.level)} title={o.label}>
|
||||
{o.level}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Ausblenden / Liste</h4>
|
||||
<p className="muted" style={{ marginTop: 0, marginBottom: '12px', fontSize: '13px' }}>
|
||||
Freigabelevel und Status steuern Sie unter „Freigabe“ mit + und −. Hier nur globale Listen-Optionen.
|
||||
</p>
|
||||
<div style={{ marginTop: '6px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '10px',
|
||||
cursor: filters.focus_only_without ? 'not-allowed' : 'pointer',
|
||||
opacity: filters.focus_only_without ? 0.55 : 1,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={!!filters.focus_only_without}
|
||||
checked={!!filters.exclude_without_focus}
|
||||
onChange={(e) =>
|
||||
setFilters((prev) => ({
|
||||
...prev,
|
||||
exclude_without_focus: e.target.checked,
|
||||
...(e.target.checked ? { focus_only_without: false } : {}),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span>Übungen ohne Fokusbereich ausblenden</span>
|
||||
</label>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!filters.include_archived}
|
||||
onChange={(e) => setFilters({ ...filters, include_archived: e.target.checked })}
|
||||
/>
|
||||
<span>Archivierte Übungen einblenden (ohne Haken werden sie standardmäßig ausgeblendet)</span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="exercise-filter-section exercise-filter-section--last">
|
||||
<h4 className="exercise-filter-section-title">Freigabe</h4>
|
||||
<p className="muted" style={{ marginTop: 0, marginBottom: '10px', fontSize: '12px' }}>
|
||||
Pro Übung nur ein Wert: mehrere „+“ bedeuten „eine davon“ (ODER). „−“ blendet Werte aus.
|
||||
</p>
|
||||
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--two exercise-filters-modal-grid--catalog">
|
||||
<CatalogRulePicker
|
||||
label={EXERCISE_VISIBILITY_FIELD_LABEL}
|
||||
options={visibilityOptions}
|
||||
rules={filters.visibility_rules}
|
||||
rulesFieldName="visibility_rules"
|
||||
idKind="string"
|
||||
placeholder="Freigabelevel …"
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
<CatalogRulePicker
|
||||
label="Status"
|
||||
options={statusOptions}
|
||||
rules={filters.status_rules}
|
||||
rulesFieldName="status_rules"
|
||||
idKind="string"
|
||||
placeholder="Status …"
|
||||
onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div className="exercise-filter-modal__footer">
|
||||
<button type="button" className="btn btn-secondary" disabled={savingExercisePrefs} onClick={onSaveStandard}>
|
||||
{savingExercisePrefs ? 'Speichern…' : 'Als Standard speichern'}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={onResetAll}>
|
||||
Alle Filter zurücksetzen
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={onClose}>
|
||||
Fertig
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import React from 'react'
|
||||
|
||||
export default function ExerciseListSearchBar({
|
||||
searchTitleSuggestions,
|
||||
searchInput,
|
||||
onSearchInputChange,
|
||||
aiSearchInput,
|
||||
onAiSearchInputChange,
|
||||
mineOnly,
|
||||
onToggleMineOnly,
|
||||
onOpenFilter,
|
||||
filterChips,
|
||||
onResetAllFilters,
|
||||
exerciseCount,
|
||||
allOnPageSelected,
|
||||
onToggleSelectAllPage,
|
||||
}) {
|
||||
return (
|
||||
<div className="card exercise-search-bar">
|
||||
<label className="form-label">Volltextsuche (Titel, Ziel, …)</label>
|
||||
<datalist id="exercise-search-titles">
|
||||
{searchTitleSuggestions.map((t) => (
|
||||
<option key={t} value={t} />
|
||||
))}
|
||||
</datalist>
|
||||
<input
|
||||
type="search"
|
||||
className="form-input exercise-search-bar__primary"
|
||||
placeholder="Suchbegriffe…"
|
||||
value={searchInput}
|
||||
onChange={(e) => onSearchInputChange(e.target.value)}
|
||||
autoComplete="on"
|
||||
name="exercise-fulltext-search"
|
||||
list="exercise-search-titles"
|
||||
enterKeyHint="search"
|
||||
/>
|
||||
<label className="form-label">Ergänzende Suche / KI-Vorbereitung (Beta)</label>
|
||||
<input
|
||||
type="search"
|
||||
className="form-input"
|
||||
placeholder="zweiter Begriff — zusätzliche Volltextsuche (ODER)"
|
||||
value={aiSearchInput}
|
||||
onChange={(e) => onAiSearchInputChange(e.target.value)}
|
||||
autoComplete="on"
|
||||
name="exercise-ai-search"
|
||||
list="exercise-search-titles"
|
||||
enterKeyHint="search"
|
||||
/>
|
||||
<div className="exercise-search-bar__actions exercise-search-bar__actions--split">
|
||||
<div className="exercise-search-bar__actions-main">
|
||||
<button
|
||||
type="button"
|
||||
className={'btn btn-secondary exercise-mine-toggle' + (mineOnly ? ' exercise-mine-toggle--active' : '')}
|
||||
onClick={onToggleMineOnly}
|
||||
title="Nur Übungen, die mit deinem Profil als Ersteller gespeichert sind"
|
||||
>
|
||||
Meine Übungen
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary exercise-filter-trigger" onClick={onOpenFilter}>
|
||||
Filter
|
||||
{filterChips.length > 0 ? (
|
||||
<span className="exercise-filter-badge" aria-hidden>
|
||||
{filterChips.length}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
{filterChips.length > 0 ? (
|
||||
<button type="button" className="btn" onClick={onResetAllFilters}>
|
||||
Alle entfernen
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{filterChips.length > 0 ? (
|
||||
<div className="exercise-filter-chips-row" role="list" aria-label="Aktive Filter">
|
||||
{filterChips.map((c) => (
|
||||
<button
|
||||
key={c.key}
|
||||
type="button"
|
||||
role="listitem"
|
||||
className="exercise-filter-chip"
|
||||
title="Filter entfernen"
|
||||
onClick={() => c.onRemove()}
|
||||
>
|
||||
<span className="exercise-filter-chip__text">{c.label}</span>
|
||||
<span className="exercise-filter-chip__x" aria-hidden>
|
||||
×
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<p className="exercise-search-hint">
|
||||
Trefferliste aktualisiert sich kurz nach Eingabe. Titel der aktuellen Liste erscheinen als Vorschläge (Pfeil im
|
||||
Feld). Fachliche Filter über „Filter“ – zwischen Feldern UND, Auswahl mehrerer Werte je Feld mit ODER.
|
||||
{exerciseCount > 0 ? (
|
||||
<>
|
||||
{' '}
|
||||
<button type="button" className="btn btn-secondary btn-small" onClick={onToggleSelectAllPage}>
|
||||
{allOnPageSelected ? 'Auswahl auf dieser Seite aufheben' : 'Alle auf dieser Seite auswählen'}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import React from 'react'
|
||||
import SkillTreeSelect from '../SkillTreeSelect'
|
||||
import { skillCatalogPathLabel } from '../../utils/skillCatalogTree'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../../constants/skillLevels'
|
||||
import {
|
||||
EXERCISE_SKILL_INTENSITY_DEFAULT,
|
||||
EXERCISE_SKILL_INTENSITY_OPTIONS,
|
||||
normalizeExerciseSkillIntensity,
|
||||
} from '../../constants/exerciseSkillIntensity'
|
||||
|
||||
export default function ExerciseSkillsEditor({
|
||||
rows,
|
||||
skillsCatalog,
|
||||
skillPick,
|
||||
onSkillPickChange,
|
||||
onAdd,
|
||||
onRemove,
|
||||
onUpdateField,
|
||||
}) {
|
||||
return (
|
||||
<div className="exercise-meta-block exercise-meta-block--skills">
|
||||
<div className="exercise-meta-block__head">
|
||||
<h4 className="exercise-meta-block__title">Fähigkeiten</h4>
|
||||
</div>
|
||||
<p className="exercise-meta-block__hint">Je Übung mehrere Fähigkeiten mit Intensität und Niveau (von–bis).</p>
|
||||
|
||||
<div className="exercise-skills-add">
|
||||
<SkillTreeSelect
|
||||
value={skillPick}
|
||||
onChange={onSkillPickChange}
|
||||
skills={skillsCatalog}
|
||||
excludeIds={rows.map((s) => s.skill_id)}
|
||||
placeholder="Fähigkeit wählen…"
|
||||
/>
|
||||
<button type="button" className="btn btn-secondary" onClick={onAdd}>
|
||||
Hinzufügen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<p className="exercise-meta-block__empty">Noch keine Fähigkeit zugeordnet.</p>
|
||||
) : (
|
||||
<ul className="exercise-skills-list">
|
||||
{rows.map((row, idx) => {
|
||||
const sk = skillsCatalog.find((s) => s.id === row.skill_id)
|
||||
const intensity = normalizeExerciseSkillIntensity(row.intensity)
|
||||
return (
|
||||
<li key={`${row.skill_id}-${idx}`} className="exercise-skill-chip">
|
||||
<div className="exercise-skill-chip__identity">
|
||||
<span className="exercise-skill-chip__name">{sk?.name || `Skill #${row.skill_id}`}</span>
|
||||
{sk ? (
|
||||
<span className="exercise-skill-chip__path" title={skillCatalogPathLabel(sk)}>
|
||||
{skillCatalogPathLabel(sk)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="exercise-skill-chip__controls">
|
||||
<div className="exercise-skill-chip__field">
|
||||
<span className="exercise-skill-chip__caption">Intensität</span>
|
||||
<div className="exercise-intensity-segment" role="radiogroup" aria-label="Intensität">
|
||||
{EXERCISE_SKILL_INTENSITY_OPTIONS.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={intensity === o.value}
|
||||
className={`exercise-intensity-segment__btn${
|
||||
intensity === o.value ? ' exercise-intensity-segment__btn--active' : ''
|
||||
}`}
|
||||
onClick={() => onUpdateField(idx, 'intensity', o.value)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="exercise-skill-chip__levels">
|
||||
<label className="exercise-skill-chip__field">
|
||||
<span className="exercise-skill-chip__caption">von</span>
|
||||
<select
|
||||
className="form-input exercise-skill-level-select"
|
||||
value={row.required_level || ''}
|
||||
title="Mindest-Niveau"
|
||||
onChange={(e) => onUpdateField(idx, 'required_level', e.target.value)}
|
||||
>
|
||||
{SKILL_LEVEL_OPTIONS.map((o) => (
|
||||
<option key={`r-${o.value}`} value={o.value} title={o.label}>
|
||||
{o.level != null ? o.level : '–'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<span className="exercise-skill-chip__dash" aria-hidden>
|
||||
→
|
||||
</span>
|
||||
<label className="exercise-skill-chip__field">
|
||||
<span className="exercise-skill-chip__caption">bis</span>
|
||||
<select
|
||||
className="form-input exercise-skill-level-select"
|
||||
value={row.target_level || ''}
|
||||
title="Ziel-Niveau"
|
||||
onChange={(e) => onUpdateField(idx, 'target_level', e.target.value)}
|
||||
>
|
||||
{SKILL_LEVEL_OPTIONS.map((o) => (
|
||||
<option key={`t-${o.value}`} value={o.value} title={o.label}>
|
||||
{o.level != null ? o.level : '–'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="exercise-skill-chip__remove"
|
||||
aria-label="Fähigkeit entfernen"
|
||||
title="Entfernen"
|
||||
onClick={() => onRemove(idx)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { EXERCISE_SKILL_INTENSITY_DEFAULT }
|
||||
@@ -0,0 +1,705 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef, lazy, Suspense } from 'react'
|
||||
import api from '../../utils/api'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import { activeClubMemberships, getTenantClubDependencyKey } from '../../utils/activeClub'
|
||||
import PageSectionNav from '../PageSectionNav'
|
||||
import ExerciseListCard from './ExerciseListCard'
|
||||
import ExerciseListFilterModal from './ExerciseListFilterModal'
|
||||
import ExerciseListBulkModal from './ExerciseListBulkModal'
|
||||
import ExerciseListSearchBar from './ExerciseListSearchBar'
|
||||
import ExerciseListBulkToolbar from './ExerciseListBulkToolbar'
|
||||
import SaveSelectedExercisesAsModuleModal from './SaveSelectedExercisesAsModuleModal'
|
||||
import ExercisePeekModal from '../ExercisePeekModal'
|
||||
import NavStateLink from '../NavStateLink'
|
||||
import { buildExercisesListReturnContext } from '../../utils/navReturnContext'
|
||||
import { buildExerciseListFilterChips } from '../../utils/exerciseListFilterChips'
|
||||
import { skillCatalogPathLabel } from '../../utils/skillCatalogTree'
|
||||
import { applyDashboardExerciseListUrl, buildExerciseListQueryBase } from '../../utils/exerciseListQuery'
|
||||
import { readExerciseListSessionState, writeExerciseListSessionState } from '../../utils/exerciseListSessionState'
|
||||
import {
|
||||
mergeSelectedWithListEntries,
|
||||
normalizeSelectedEntries,
|
||||
snapshotExerciseForSelection,
|
||||
} from '../../utils/exerciseListSelection'
|
||||
import { useExerciseListCatalogsAndQuery } from '../../hooks/useExerciseListCatalogsAndQuery'
|
||||
import {
|
||||
INITIAL_EXERCISE_LIST_FILTERS,
|
||||
mergeExerciseListPrefsFromApi,
|
||||
compactExerciseListPrefsPayload,
|
||||
} from '../../constants/exerciseListFilters'
|
||||
|
||||
const ExerciseProgressionGraphPanel = lazy(() => import('../ExerciseProgressionGraphPanel'))
|
||||
|
||||
const BULK_MAX_IDS = 500
|
||||
const EXERCISES_PAGE_TABS = [
|
||||
{ id: 'list', label: 'Liste' },
|
||||
{ id: 'progression', label: 'Progressionsgraphen' },
|
||||
]
|
||||
|
||||
function ExercisesListPageRoot() {
|
||||
const { user, checkAuth } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
|
||||
const [mineOnly, setMineOnly] = useState(() => {
|
||||
try {
|
||||
const sp = new URLSearchParams(window.location.search)
|
||||
return sp.get('mine') === '1' || sp.get('created_by_me') === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [aiSearchInput, setAiSearchInput] = useState('')
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('')
|
||||
const [debouncedAiSearch, setDebouncedAiSearch] = useState('')
|
||||
const [filters, setFilters] = useState(() => ({ ...INITIAL_EXERCISE_LIST_FILTERS }))
|
||||
const [filterModalOpen, setFilterModalOpen] = useState(false)
|
||||
const [savingExercisePrefs, setSavingExercisePrefs] = useState(false)
|
||||
const [pageTab, setPageTab] = useState('list')
|
||||
const prefsAppliedRef = useRef(false)
|
||||
|
||||
const [selectedEntries, setSelectedEntries] = useState(() => [])
|
||||
const [bulkModalOpen, setBulkModalOpen] = useState(false)
|
||||
const [bulkVisibility, setBulkVisibility] = useState('')
|
||||
const [bulkStatus, setBulkStatus] = useState('')
|
||||
const [bulkClubSelect, setBulkClubSelect] = useState('')
|
||||
const [bulkClubManual, setBulkClubManual] = useState('')
|
||||
const [bulkSubmitting, setBulkSubmitting] = useState(false)
|
||||
const [bulkPatchFocusAreas, setBulkPatchFocusAreas] = useState(false)
|
||||
const [bulkFocusAreaIds, setBulkFocusAreaIds] = useState([])
|
||||
const [bulkPatchStyleDirections, setBulkPatchStyleDirections] = useState(false)
|
||||
const [bulkStyleDirectionIds, setBulkStyleDirectionIds] = useState([])
|
||||
const [bulkPatchTrainingTypes, setBulkPatchTrainingTypes] = useState(false)
|
||||
const [bulkTrainingTypeIds, setBulkTrainingTypeIds] = useState([])
|
||||
const [bulkPatchTargetGroups, setBulkPatchTargetGroups] = useState(false)
|
||||
const [bulkTargetGroupIds, setBulkTargetGroupIds] = useState([])
|
||||
const [peekExercise, setPeekExercise] = useState(null)
|
||||
const [saveModuleModalOpen, setSaveModuleModalOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!user?.id) return
|
||||
if (prefsAppliedRef.current) return
|
||||
const session = readExerciseListSessionState()
|
||||
const merged = mergeExerciseListPrefsFromApi(user.exercise_list_prefs)
|
||||
const filtersFromSession = session?.filters
|
||||
setFilters(applyDashboardExerciseListUrl(filtersFromSession ?? merged))
|
||||
if (session) {
|
||||
setSearchInput(session.searchInput || '')
|
||||
setAiSearchInput(session.aiSearchInput || '')
|
||||
setMineOnly(session.mineOnly)
|
||||
setSelectedEntries(normalizeSelectedEntries(session.selectedEntries))
|
||||
}
|
||||
try {
|
||||
const sp = new URLSearchParams(window.location.search)
|
||||
if (sp.get('mine') === '1' || sp.get('created_by_me') === '1') setMineOnly(true)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
prefsAppliedRef.current = true
|
||||
}, [user?.id, user?.exercise_list_prefs])
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefsAppliedRef.current) return
|
||||
writeExerciseListSessionState({
|
||||
filters,
|
||||
searchInput,
|
||||
aiSearchInput,
|
||||
mineOnly,
|
||||
selectedEntries,
|
||||
})
|
||||
}, [filters, searchInput, aiSearchInput, mineOnly, selectedEntries])
|
||||
|
||||
useEffect(() => {
|
||||
if (!user?.id) prefsAppliedRef.current = false
|
||||
}, [user?.id])
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebouncedSearch(searchInput.trim()), 400)
|
||||
return () => clearTimeout(t)
|
||||
}, [searchInput])
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebouncedAiSearch(aiSearchInput.trim()), 400)
|
||||
return () => clearTimeout(t)
|
||||
}, [aiSearchInput])
|
||||
|
||||
useEffect(() => {
|
||||
if (!filterModalOpen) return
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') setFilterModalOpen(false)
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [filterModalOpen])
|
||||
|
||||
const queryBase = useMemo(
|
||||
() => buildExerciseListQueryBase(filters, debouncedSearch, debouncedAiSearch, mineOnly),
|
||||
[filters, debouncedSearch, debouncedAiSearch, mineOnly]
|
||||
)
|
||||
|
||||
const {
|
||||
catalogs,
|
||||
catalogsReady,
|
||||
exercises,
|
||||
setExercises,
|
||||
listFetching,
|
||||
loadingMore,
|
||||
hasMore,
|
||||
loadMore,
|
||||
} = useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey })
|
||||
|
||||
const selectedIds = useMemo(
|
||||
() => new Set(selectedEntries.map((e) => Number(e.id)).filter((id) => Number.isFinite(id) && id > 0)),
|
||||
[selectedEntries]
|
||||
)
|
||||
|
||||
const selectedExercisesDisplay = useMemo(
|
||||
() => mergeSelectedWithListEntries(selectedEntries, exercises),
|
||||
[selectedEntries, exercises]
|
||||
)
|
||||
|
||||
const filterResultExercises = useMemo(
|
||||
() => exercises.filter((e) => !selectedIds.has(Number(e.id))),
|
||||
[exercises, selectedIds]
|
||||
)
|
||||
|
||||
const focusOptions = useMemo(
|
||||
() =>
|
||||
catalogs.focusAreas.map((fa) => ({
|
||||
id: fa.id,
|
||||
label: `${fa.icon || ''} ${fa.name || ''}`.trim(),
|
||||
})),
|
||||
[catalogs.focusAreas]
|
||||
)
|
||||
const styleOptions = useMemo(
|
||||
() => catalogs.styleDirections.map((s) => ({ id: s.id, label: s.name || String(s.id) })),
|
||||
[catalogs.styleDirections]
|
||||
)
|
||||
const trainingTypeOptions = useMemo(
|
||||
() => catalogs.trainingTypes.map((t) => ({ id: t.id, label: t.name || String(t.id) })),
|
||||
[catalogs.trainingTypes]
|
||||
)
|
||||
const targetGroupOptions = useMemo(
|
||||
() => catalogs.targetGroups.map((g) => ({ id: g.id, label: g.name || String(g.id) })),
|
||||
[catalogs.targetGroups]
|
||||
)
|
||||
const skillOptions = useMemo(
|
||||
() =>
|
||||
catalogs.skills.map((s) => ({
|
||||
id: s.id,
|
||||
label: skillCatalogPathLabel(s) || s.name || String(s.id),
|
||||
})),
|
||||
[catalogs.skills]
|
||||
)
|
||||
const visibilityOptions = useMemo(
|
||||
() => [
|
||||
{ id: 'private', label: 'Privat' },
|
||||
{ id: 'club', label: 'Verein' },
|
||||
{ id: 'official', label: 'Offiziell' },
|
||||
],
|
||||
[]
|
||||
)
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ id: 'draft', label: 'Entwurf' },
|
||||
{ id: 'in_review', label: 'In Prüfung' },
|
||||
{ id: 'approved', label: 'Freigegeben' },
|
||||
{ id: 'archived', label: 'Archiviert' },
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const filterChips = useMemo(
|
||||
() =>
|
||||
buildExerciseListFilterChips({
|
||||
mineOnly,
|
||||
setMineOnly,
|
||||
filters,
|
||||
setFilters,
|
||||
focusOptions,
|
||||
styleOptions,
|
||||
trainingTypeOptions,
|
||||
targetGroupOptions,
|
||||
skillOptions,
|
||||
visibilityOptions,
|
||||
statusOptions,
|
||||
}),
|
||||
[
|
||||
mineOnly,
|
||||
filters,
|
||||
focusOptions,
|
||||
styleOptions,
|
||||
trainingTypeOptions,
|
||||
targetGroupOptions,
|
||||
skillOptions,
|
||||
visibilityOptions,
|
||||
statusOptions,
|
||||
]
|
||||
)
|
||||
|
||||
/** Für Browser-/datalist-Vorschläge (aktuelle Treffer-Titel, begrenzt) */
|
||||
const searchTitleSuggestions = useMemo(() => {
|
||||
const titles = exercises.map((e) => (e.title || '').trim()).filter(Boolean)
|
||||
return [...new Set(titles)].slice(0, 80)
|
||||
}, [exercises])
|
||||
|
||||
const clubNameById = useMemo(() => {
|
||||
const m = {}
|
||||
for (const c of activeClubMemberships(user?.clubs)) {
|
||||
if (c?.id != null) m[Number(c.id)] = c.name || `#${c.id}`
|
||||
}
|
||||
return m
|
||||
}, [user?.clubs])
|
||||
|
||||
const effectiveClubId =
|
||||
user?.effective_club_id != null && user.effective_club_id !== ''
|
||||
? Number(user.effective_club_id)
|
||||
: user?.active_club_id != null && user.active_club_id !== ''
|
||||
? Number(user.active_club_id)
|
||||
: null
|
||||
|
||||
const toggleSelect = useCallback((exercise) => {
|
||||
const snap = snapshotExerciseForSelection(exercise)
|
||||
if (!snap) return
|
||||
setSelectedEntries((prev) => {
|
||||
const idx = prev.findIndex((e) => Number(e.id) === snap.id)
|
||||
if (idx >= 0) return prev.filter((_, i) => i !== idx)
|
||||
return [...prev, snap]
|
||||
})
|
||||
}, [])
|
||||
|
||||
const clearSelection = useCallback(() => setSelectedEntries([]), [])
|
||||
|
||||
const toggleSelectAllPage = useCallback(() => {
|
||||
setSelectedEntries((prev) => {
|
||||
const ids = new Set(prev.map((e) => Number(e.id)))
|
||||
const pageIds = filterResultExercises.map((e) => Number(e.id))
|
||||
const allSel = pageIds.length > 0 && pageIds.every((id) => ids.has(id))
|
||||
if (allSel) {
|
||||
const remove = new Set(pageIds)
|
||||
return prev.filter((e) => !remove.has(Number(e.id)))
|
||||
}
|
||||
const next = [...prev]
|
||||
for (const ex of filterResultExercises) {
|
||||
const snap = snapshotExerciseForSelection(ex)
|
||||
if (!snap || ids.has(snap.id)) continue
|
||||
ids.add(snap.id)
|
||||
next.push(snap)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, [filterResultExercises])
|
||||
|
||||
const allOnPageSelected = useMemo(
|
||||
() =>
|
||||
filterResultExercises.length > 0 &&
|
||||
filterResultExercises.every((e) => selectedIds.has(Number(e.id))),
|
||||
[filterResultExercises, selectedIds]
|
||||
)
|
||||
|
||||
const selectedExercisesInListOrder = selectedExercisesDisplay
|
||||
|
||||
const exercisesModuleReturnContext = useMemo(() => buildExercisesListReturnContext(), [])
|
||||
|
||||
const bulkVisibilityOptions = useMemo(() => {
|
||||
const base = [
|
||||
{ id: '', label: '— nicht ändern —' },
|
||||
{ id: 'private', label: 'Privat' },
|
||||
{ id: 'club', label: 'Verein' },
|
||||
]
|
||||
if (isSuperadmin) base.push({ id: 'official', label: 'Offiziell (global)' })
|
||||
return base
|
||||
}, [isSuperadmin])
|
||||
|
||||
const handleDelete = async (exercise) => {
|
||||
if (!confirm(`Übung "${exercise.title}" wirklich löschen?`)) return
|
||||
try {
|
||||
await api.deleteExercise(exercise.id)
|
||||
setExercises((prev) => prev.filter((e) => e.id !== exercise.id))
|
||||
setSelectedEntries((prev) => prev.filter((e) => Number(e.id) !== Number(exercise.id)))
|
||||
} catch (err) {
|
||||
alert('Fehler beim Löschen: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const resetAllFilters = useCallback(() => {
|
||||
setMineOnly(false)
|
||||
setFilters({ ...INITIAL_EXERCISE_LIST_FILTERS })
|
||||
}, [])
|
||||
|
||||
const handleSaveExerciseFilterPrefs = useCallback(async () => {
|
||||
const uid = user?.id
|
||||
if (!uid) {
|
||||
alert('Nicht angemeldet.')
|
||||
return
|
||||
}
|
||||
setSavingExercisePrefs(true)
|
||||
try {
|
||||
const payload = compactExerciseListPrefsPayload(filters)
|
||||
await api.updateProfile(uid, { exercise_list_prefs: payload })
|
||||
await checkAuth()
|
||||
alert('Standardfilter für die Übungsliste gespeichert.')
|
||||
} catch (e) {
|
||||
alert('Speichern fehlgeschlagen: ' + (e.message || String(e)))
|
||||
} finally {
|
||||
setSavingExercisePrefs(false)
|
||||
}
|
||||
}, [user?.id, filters, checkAuth])
|
||||
|
||||
const openBulkModal = () => {
|
||||
setBulkVisibility('')
|
||||
setBulkStatus('')
|
||||
setBulkClubSelect('')
|
||||
setBulkClubManual('')
|
||||
setBulkPatchFocusAreas(false)
|
||||
setBulkFocusAreaIds([])
|
||||
setBulkPatchStyleDirections(false)
|
||||
setBulkStyleDirectionIds([])
|
||||
setBulkPatchTrainingTypes(false)
|
||||
setBulkTrainingTypeIds([])
|
||||
setBulkPatchTargetGroups(false)
|
||||
setBulkTargetGroupIds([])
|
||||
setBulkModalOpen(true)
|
||||
}
|
||||
|
||||
const handleBulkSubmit = async () => {
|
||||
const anyRelationPatch =
|
||||
bulkPatchFocusAreas ||
|
||||
bulkPatchStyleDirections ||
|
||||
bulkPatchTrainingTypes ||
|
||||
bulkPatchTargetGroups
|
||||
if (!bulkVisibility && !bulkStatus && !anyRelationPatch) {
|
||||
alert(
|
||||
'Bitte mindestens eine Änderung wählen (Freigabelevel, Status oder eine der Zuordnungen mit gesetztem Häkchen „ersetzen“).'
|
||||
)
|
||||
return
|
||||
}
|
||||
const ids = Array.from(selectedIds).filter((x) => Number.isFinite(x) && x > 0)
|
||||
if (ids.length === 0) {
|
||||
alert('Keine Übungen ausgewählt.')
|
||||
return
|
||||
}
|
||||
if (ids.length > BULK_MAX_IDS) {
|
||||
alert(`Maximal ${BULK_MAX_IDS} Übungen pro Vorgang. Bitte Auswahl oder mehrere Durchläufe verwenden.`)
|
||||
return
|
||||
}
|
||||
const payload = { exercise_ids: ids }
|
||||
if (bulkVisibility) payload.visibility = bulkVisibility
|
||||
if (bulkStatus) payload.status = bulkStatus
|
||||
if (bulkPatchFocusAreas) {
|
||||
payload.focus_area_ids = bulkFocusAreaIds.map((x) => Number(x)).filter((n) => Number.isFinite(n) && n > 0)
|
||||
}
|
||||
if (bulkPatchStyleDirections) {
|
||||
payload.style_direction_ids = bulkStyleDirectionIds.map((x) => Number(x)).filter((n) => Number.isFinite(n) && n > 0)
|
||||
}
|
||||
if (bulkPatchTrainingTypes) {
|
||||
payload.training_type_ids = bulkTrainingTypeIds.map((x) => Number(x)).filter((n) => Number.isFinite(n) && n > 0)
|
||||
}
|
||||
if (bulkPatchTargetGroups) {
|
||||
payload.target_group_ids = bulkTargetGroupIds.map((x) => Number(x)).filter((n) => Number.isFinite(n) && n > 0)
|
||||
}
|
||||
if (bulkVisibility === 'club') {
|
||||
const manual = String(bulkClubManual || '').trim()
|
||||
if (manual && /^\d+$/.test(manual)) payload.club_id = Number(manual)
|
||||
else if (bulkClubSelect && /^\d+$/.test(String(bulkClubSelect))) {
|
||||
payload.club_id = Number(bulkClubSelect)
|
||||
}
|
||||
}
|
||||
setBulkSubmitting(true)
|
||||
try {
|
||||
const res = await api.bulkPatchExercisesMetadata(payload)
|
||||
const updatedSet = new Set((res.updated || []).map((x) => Number(x)))
|
||||
let resolvedClubId = null
|
||||
if (bulkVisibility === 'club') {
|
||||
if (payload.club_id != null) resolvedClubId = payload.club_id
|
||||
else if (effectiveClubId != null && !Number.isNaN(effectiveClubId)) resolvedClubId = effectiveClubId
|
||||
}
|
||||
const clubLabel =
|
||||
resolvedClubId != null ? clubNameById[resolvedClubId] || `Verein #${resolvedClubId}` : null
|
||||
|
||||
let nextPrimaryFocusName = null
|
||||
if (bulkPatchFocusAreas) {
|
||||
const faNums = bulkFocusAreaIds.map((x) => Number(x)).filter((n) => Number.isFinite(n) && n > 0)
|
||||
if (faNums.length > 0) {
|
||||
const opt = focusOptions.find((o) => Number(o.id) === Number(faNums[0]))
|
||||
nextPrimaryFocusName = String(opt?.label ?? '').trim() || String(faNums[0])
|
||||
}
|
||||
}
|
||||
|
||||
setExercises((prev) =>
|
||||
prev.map((e) => {
|
||||
if (!updatedSet.has(Number(e.id))) return e
|
||||
const next = { ...e }
|
||||
if (bulkVisibility) {
|
||||
next.visibility = bulkVisibility
|
||||
next.club_id = bulkVisibility === 'club' ? resolvedClubId : null
|
||||
next.club_name = bulkVisibility === 'club' ? clubLabel : null
|
||||
}
|
||||
if (bulkStatus) next.status = bulkStatus
|
||||
if (bulkPatchFocusAreas) {
|
||||
if (nextPrimaryFocusName == null) delete next.focus_area
|
||||
else next.focus_area = nextPrimaryFocusName
|
||||
}
|
||||
return next
|
||||
})
|
||||
)
|
||||
|
||||
let msg = `${res.updated_count ?? updatedSet.size} Übung(en) aktualisiert.`
|
||||
if (res.failed_count) msg += `\n${res.failed_count} nicht geändert (siehe Details).`
|
||||
if (Array.isArray(res.failed) && res.failed.length) {
|
||||
msg +=
|
||||
'\n\n' +
|
||||
res.failed
|
||||
.slice(0, 12)
|
||||
.map((f) => `#${f.id}: ${f.detail}`)
|
||||
.join('\n')
|
||||
if (res.failed.length > 12) msg += '\n…'
|
||||
}
|
||||
alert(msg)
|
||||
setBulkModalOpen(false)
|
||||
clearSelection()
|
||||
} catch (err) {
|
||||
alert('Massenänderung fehlgeschlagen: ' + (err.message || String(err)))
|
||||
} finally {
|
||||
setBulkSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!catalogsReady && pageTab === 'list') {
|
||||
return (
|
||||
<div className="app-page">
|
||||
<div className="empty-state" style={{ padding: '2.5rem 1rem' }}>
|
||||
<div className="spinner" />
|
||||
<p className="muted" style={{ marginTop: '12px' }}>
|
||||
Lade Kataloge…
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<div className="exercises-page__header">
|
||||
<h1 className="page-title exercises-page__title">Übungen</h1>
|
||||
{pageTab === 'list' ? (
|
||||
<NavStateLink
|
||||
to="/exercises/new"
|
||||
returnContext={exercisesModuleReturnContext}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
+ Neu
|
||||
</NavStateLink>
|
||||
) : (
|
||||
<span aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<PageSectionNav
|
||||
ariaLabel="Übungen Bereiche"
|
||||
value={pageTab}
|
||||
onChange={setPageTab}
|
||||
items={EXERCISES_PAGE_TABS}
|
||||
className="exercises-page-toolbar-tabs"
|
||||
/>
|
||||
|
||||
{pageTab === 'progression' ? (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="card empty-state" style={{ padding: '2rem 1rem' }}>
|
||||
<div className="spinner" />
|
||||
<p className="muted" style={{ marginTop: '12px' }}>
|
||||
Lade Progressionsgraphen…
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ExerciseProgressionGraphPanel />
|
||||
</Suspense>
|
||||
) : (
|
||||
<>
|
||||
<ExerciseListSearchBar
|
||||
searchTitleSuggestions={searchTitleSuggestions}
|
||||
searchInput={searchInput}
|
||||
onSearchInputChange={setSearchInput}
|
||||
aiSearchInput={aiSearchInput}
|
||||
onAiSearchInputChange={setAiSearchInput}
|
||||
mineOnly={mineOnly}
|
||||
onToggleMineOnly={() => setMineOnly((v) => !v)}
|
||||
onOpenFilter={() => setFilterModalOpen(true)}
|
||||
filterChips={filterChips}
|
||||
onResetAllFilters={resetAllFilters}
|
||||
exerciseCount={exercises.length}
|
||||
allOnPageSelected={allOnPageSelected}
|
||||
onToggleSelectAllPage={toggleSelectAllPage}
|
||||
/>
|
||||
|
||||
<ExerciseListBulkToolbar
|
||||
selectedCount={selectedIds.size}
|
||||
bulkMaxIds={BULK_MAX_IDS}
|
||||
onClearSelection={clearSelection}
|
||||
onOpenBulkModal={openBulkModal}
|
||||
onOpenSaveModuleModal={() => setSaveModuleModalOpen(true)}
|
||||
/>
|
||||
|
||||
<ExerciseListFilterModal
|
||||
open={filterModalOpen}
|
||||
onClose={() => setFilterModalOpen(false)}
|
||||
filters={filters}
|
||||
setFilters={setFilters}
|
||||
focusOptions={focusOptions}
|
||||
styleOptions={styleOptions}
|
||||
trainingTypeOptions={trainingTypeOptions}
|
||||
targetGroupOptions={targetGroupOptions}
|
||||
skillsCatalog={catalogs.skills}
|
||||
visibilityOptions={visibilityOptions}
|
||||
statusOptions={statusOptions}
|
||||
savingExercisePrefs={savingExercisePrefs}
|
||||
onSaveStandard={handleSaveExerciseFilterPrefs}
|
||||
onResetAll={resetAllFilters}
|
||||
/>
|
||||
|
||||
<ExerciseListBulkModal
|
||||
open={bulkModalOpen}
|
||||
onClose={() => setBulkModalOpen(false)}
|
||||
onSubmit={handleBulkSubmit}
|
||||
bulkSubmitting={bulkSubmitting}
|
||||
selectedCount={selectedIds.size}
|
||||
bulkMaxIds={BULK_MAX_IDS}
|
||||
user={user}
|
||||
isPlatformAdmin={isPlatformAdmin}
|
||||
statusOptions={statusOptions}
|
||||
bulkVisibilityOptions={bulkVisibilityOptions}
|
||||
focusOptions={focusOptions}
|
||||
styleOptions={styleOptions}
|
||||
trainingTypeOptions={trainingTypeOptions}
|
||||
targetGroupOptions={targetGroupOptions}
|
||||
bulkVisibility={bulkVisibility}
|
||||
setBulkVisibility={setBulkVisibility}
|
||||
bulkStatus={bulkStatus}
|
||||
setBulkStatus={setBulkStatus}
|
||||
bulkClubSelect={bulkClubSelect}
|
||||
setBulkClubSelect={setBulkClubSelect}
|
||||
bulkClubManual={bulkClubManual}
|
||||
setBulkClubManual={setBulkClubManual}
|
||||
bulkPatchFocusAreas={bulkPatchFocusAreas}
|
||||
setBulkPatchFocusAreas={setBulkPatchFocusAreas}
|
||||
bulkFocusAreaIds={bulkFocusAreaIds}
|
||||
setBulkFocusAreaIds={setBulkFocusAreaIds}
|
||||
bulkPatchStyleDirections={bulkPatchStyleDirections}
|
||||
setBulkPatchStyleDirections={setBulkPatchStyleDirections}
|
||||
bulkStyleDirectionIds={bulkStyleDirectionIds}
|
||||
setBulkStyleDirectionIds={setBulkStyleDirectionIds}
|
||||
bulkPatchTrainingTypes={bulkPatchTrainingTypes}
|
||||
setBulkPatchTrainingTypes={setBulkPatchTrainingTypes}
|
||||
bulkTrainingTypeIds={bulkTrainingTypeIds}
|
||||
setBulkTrainingTypeIds={setBulkTrainingTypeIds}
|
||||
bulkPatchTargetGroups={bulkPatchTargetGroups}
|
||||
setBulkPatchTargetGroups={setBulkPatchTargetGroups}
|
||||
bulkTargetGroupIds={bulkTargetGroupIds}
|
||||
setBulkTargetGroupIds={setBulkTargetGroupIds}
|
||||
/>
|
||||
|
||||
<SaveSelectedExercisesAsModuleModal
|
||||
open={saveModuleModalOpen}
|
||||
onClose={() => setSaveModuleModalOpen(false)}
|
||||
selectedExercises={selectedExercisesInListOrder}
|
||||
returnContext={exercisesModuleReturnContext}
|
||||
onSuccess={clearSelection}
|
||||
/>
|
||||
|
||||
<ExercisePeekModal
|
||||
open={peekExercise != null}
|
||||
exerciseId={peekExercise?.id}
|
||||
titleFallback={peekExercise?.title}
|
||||
onClose={() => setPeekExercise(null)}
|
||||
/>
|
||||
|
||||
{listFetching && exercises.length === 0 && selectedEntries.length === 0 ? (
|
||||
<div className="card empty-state" style={{ padding: '2rem 1rem' }}>
|
||||
<div className="spinner" />
|
||||
<p className="muted" style={{ marginTop: '12px' }}>
|
||||
Lade Übungen…
|
||||
</p>
|
||||
</div>
|
||||
) : exercises.length === 0 && selectedEntries.length === 0 ? (
|
||||
<div className="card">
|
||||
<p className="exercises-empty-text">Keine Übungen gefunden.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{selectedEntries.length > 0 ? (
|
||||
<section className="exercises-selection-section" data-testid="exercises-selection-section">
|
||||
<div className="exercises-selection-section__head">
|
||||
<h2 className="exercises-selection-section__title">Auswahl ({selectedEntries.length})</h2>
|
||||
<p className="exercises-selection-section__hint">
|
||||
Bleibt sichtbar, auch wenn du den Filter wechselst — ideal für die Modul-Zusammenstellung.
|
||||
</p>
|
||||
</div>
|
||||
<div className="exercises-list-grid exercises-list-grid--selection">
|
||||
{selectedExercisesDisplay.map((exercise) => (
|
||||
<ExerciseListCard
|
||||
key={`sel-${exercise.id}`}
|
||||
exercise={exercise}
|
||||
user={user}
|
||||
selectedIds={selectedIds}
|
||||
toggleSelect={toggleSelect}
|
||||
onDelete={handleDelete}
|
||||
onPeek={(ex) => setPeekExercise({ id: ex.id, title: ex.title })}
|
||||
selectionPinned
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{filterResultExercises.length === 0 ? (
|
||||
selectedEntries.length > 0 ? (
|
||||
<p className="exercises-meta-line exercises-meta-line--muted">
|
||||
Keine weiteren Treffer für den aktuellen Filter.
|
||||
</p>
|
||||
) : null
|
||||
) : (
|
||||
<>
|
||||
{listFetching ? (
|
||||
<p className="exercises-meta-line exercises-meta-line--muted">Aktualisiere Treffer…</p>
|
||||
) : null}
|
||||
<p className="exercises-meta-line">
|
||||
{filterResultExercises.length} Treffer
|
||||
{selectedEntries.length > 0 ? ' (ohne bereits Ausgewählte)' : ''}
|
||||
{hasMore ? ' · es gibt weitere Einträge' : ''}
|
||||
</p>
|
||||
<div className="exercises-list-grid" data-testid="exercises-list-grid">
|
||||
{filterResultExercises.map((exercise) => (
|
||||
<ExerciseListCard
|
||||
key={exercise.id}
|
||||
exercise={exercise}
|
||||
user={user}
|
||||
selectedIds={selectedIds}
|
||||
toggleSelect={toggleSelect}
|
||||
onDelete={handleDelete}
|
||||
onPeek={(ex) => setPeekExercise({ id: ex.id, title: ex.title })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{hasMore && (
|
||||
<div className="exercises-load-more">
|
||||
<button type="button" className="btn btn-secondary" disabled={loadingMore} onClick={loadMore}>
|
||||
{loadingMore ? 'Laden…' : 'Mehr laden'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ExercisesListPageRoot
|
||||
@@ -0,0 +1,409 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import FormActionBar from '../FormActionBar'
|
||||
import FormModalOverlay from '../FormModalOverlay'
|
||||
import api from '../../utils/api'
|
||||
import { useToast } from '../../context/ToastContext'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import { activeClubMemberships, getDefaultClubIdForGovernanceForms } from '../../utils/activeClub'
|
||||
import { hydrateExercisePlanningRow } from '../../utils/trainingUnitSectionsForm'
|
||||
import { buildRowsPayload, moduleItemToPayload } from '../../utils/exerciseListSelection'
|
||||
import { navigateWithAppReturn } from '../../utils/navReturnContext'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
|
||||
/**
|
||||
* Erstellt ein Trainingsmodul aus per Checkbox ausgewählten Übungen (Reihenfolge = Auswahlreihenfolge).
|
||||
* Optional: Positionen an ein bestehendes Modul anfügen.
|
||||
*/
|
||||
export default function SaveSelectedExercisesAsModuleModal({
|
||||
open,
|
||||
onClose,
|
||||
/** @type {Array<{ id: number, title?: string }>} */
|
||||
selectedExercises,
|
||||
/** Return-Kontext für Modul-Editor (z. B. Übungsliste) */
|
||||
returnContext,
|
||||
onSuccess,
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { user } = useAuth()
|
||||
const memberClubs = useMemo(() => activeClubMemberships(user?.clubs), [user?.clubs])
|
||||
const roleLc = String(user?.role || '').toLowerCase()
|
||||
const isSuperadmin = roleLc === 'superadmin'
|
||||
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [loadErr, setLoadErr] = useState('')
|
||||
/** @type {[Array<object>, Function]} */
|
||||
const [rows, setRows] = useState([])
|
||||
const [moduleOptions, setModuleOptions] = useState([])
|
||||
const [modulesLoading, setModulesLoading] = useState(false)
|
||||
|
||||
const [targetMode, setTargetMode] = useState('new')
|
||||
const [existingModuleId, setExistingModuleId] = useState('')
|
||||
|
||||
const [title, setTitle] = useState('')
|
||||
const [visibility, setVisibility] = useState('club')
|
||||
const [clubId, setClubId] = useState('')
|
||||
|
||||
const resetLocal = useCallback(() => {
|
||||
setLoadErr('')
|
||||
setRows([])
|
||||
setModuleOptions([])
|
||||
setTargetMode('new')
|
||||
setExistingModuleId('')
|
||||
setTitle('')
|
||||
setVisibility('club')
|
||||
setClubId('')
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
resetLocal()
|
||||
return
|
||||
}
|
||||
const defaultClub = getDefaultClubIdForGovernanceForms(user)
|
||||
if (defaultClub != null) setClubId(String(defaultClub))
|
||||
else if (memberClubs.length === 1) setClubId(String(memberClubs[0].id))
|
||||
|
||||
const count = selectedExercises?.length || 0
|
||||
setTitle(count > 0 ? `Modul · ${count} Übung${count === 1 ? '' : 'en'}` : '')
|
||||
|
||||
if (!count) {
|
||||
setRows([])
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
setLoadErr('')
|
||||
;(async () => {
|
||||
try {
|
||||
const hydrated = []
|
||||
for (const ex of selectedExercises) {
|
||||
const row = await hydrateExercisePlanningRow({ id: ex.id, title: ex.title })
|
||||
if (row) hydrated.push(row)
|
||||
}
|
||||
if (cancelled) return
|
||||
if (!hydrated.length) {
|
||||
setLoadErr('Ausgewählte Übungen konnten nicht geladen werden.')
|
||||
setRows([])
|
||||
return
|
||||
}
|
||||
setRows(hydrated)
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setLoadErr(e.message || 'Übungen konnten nicht geladen werden')
|
||||
setRows([])
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, selectedExercises, user, memberClubs.length, resetLocal])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
setModulesLoading(true)
|
||||
api
|
||||
.listTrainingModules()
|
||||
.then((list) => {
|
||||
if (cancelled) return
|
||||
setModuleOptions(Array.isArray(list) ? list : [])
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setModuleOptions([])
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setModulesLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const updateRow = (idx, patch) => {
|
||||
setRows((prev) => prev.map((row, i) => (i === idx ? { ...row, ...patch } : row)))
|
||||
}
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
if (submitting || !rows.length) return
|
||||
|
||||
const newItemsPayload = buildRowsPayload(rows)
|
||||
if (!newItemsPayload.length) {
|
||||
toast.error('Keine gültigen Übungspositionen.')
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
if (targetMode === 'append') {
|
||||
const mid = parseInt(existingModuleId, 10)
|
||||
if (!Number.isFinite(mid) || mid < 1) {
|
||||
toast.error('Bitte ein bestehendes Modul wählen.')
|
||||
return
|
||||
}
|
||||
const existing = await api.getTrainingModule(mid)
|
||||
const existingItems = Array.isArray(existing?.items) ? existing.items : []
|
||||
const merged = [
|
||||
...existingItems.map((row, idx) => moduleItemToPayload(row, idx)).filter(Boolean),
|
||||
...newItemsPayload.map((row, idx) => ({ ...row, order_index: existingItems.length + idx })),
|
||||
]
|
||||
await api.updateTrainingModule(mid, { items: merged })
|
||||
toast.success(`${newItemsPayload.length} Übung(en) an Modul angefügt.`)
|
||||
navigateWithAppReturn(navigate, `/planning/training-modules/${mid}`, returnContext)
|
||||
onSuccess?.()
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
const tit = (title || '').trim()
|
||||
if (!tit) {
|
||||
toast.error('Bitte einen Modultitel angeben.')
|
||||
return
|
||||
}
|
||||
|
||||
let cid = visibility === 'club' && clubId ? parseInt(clubId, 10) : null
|
||||
if (visibility === 'club' && (!Number.isFinite(cid) || cid < 1)) {
|
||||
const fallback = getDefaultClubIdForGovernanceForms(user)
|
||||
if (Number.isFinite(fallback) && fallback > 0) cid = fallback
|
||||
}
|
||||
if (visibility === 'club' && (!Number.isFinite(cid) || cid < 1)) {
|
||||
toast.error('Bitte einen Verein wählen (Freigabelevel „Verein“).')
|
||||
return
|
||||
}
|
||||
if (visibility !== 'club') cid = null
|
||||
|
||||
const created = await api.createTrainingModule({
|
||||
title: tit,
|
||||
visibility,
|
||||
club_id: cid,
|
||||
items: newItemsPayload,
|
||||
})
|
||||
toast.success('Trainingsmodul gespeichert.')
|
||||
if (created?.id) {
|
||||
navigateWithAppReturn(navigate, `/planning/training-modules/${created.id}`, returnContext)
|
||||
}
|
||||
onSuccess?.()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.error(err.message || 'Speichern fehlgeschlagen')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const saveLabel = targetMode === 'append' ? 'An Modul anfügen' : 'Modul anlegen'
|
||||
|
||||
return (
|
||||
<FormModalOverlay open={open} raised onBackdropClick={onClose}>
|
||||
<div className="card modal-panel--form modal-panel--narrow">
|
||||
<h2 className="modal-panel__title">Auswahl als Trainingsmodul</h2>
|
||||
<p className="modal-panel__intro">
|
||||
Die gewählten Übungen werden in der <strong>Reihenfolge der Auswahl</strong> übernommen. Pro Übung kann
|
||||
optional eine Variante gesetzt werden.
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Laden …</p>
|
||||
) : loadErr ? (
|
||||
<p style={{ color: 'var(--danger)' }}>{loadErr}</p>
|
||||
) : rows.length === 0 ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Keine Übungen ausgewählt.</p>
|
||||
) : (
|
||||
<form id="save-selected-module-form" className="modal-form-shell" onSubmit={handleSubmit}>
|
||||
<div className="modal-form-shell__body">
|
||||
<div className="form-row" style={{ marginBottom: '1rem' }}>
|
||||
<label className="form-label">Ziel</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={targetMode}
|
||||
onChange={(e) => setTargetMode(e.target.value)}
|
||||
>
|
||||
<option value="new">Neues Modul anlegen</option>
|
||||
<option value="append">Bestehendes Modul erweitern</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{targetMode === 'append' ? (
|
||||
<div className="form-row" style={{ marginBottom: '1rem' }}>
|
||||
<label className="form-label">Bestehendes Modul</label>
|
||||
{modulesLoading ? (
|
||||
<p style={{ color: 'var(--text2)', margin: 0 }}>Module laden …</p>
|
||||
) : moduleOptions.length === 0 ? (
|
||||
<p style={{ color: 'var(--text2)', margin: 0 }}>
|
||||
Keine bearbeitbaren Module gefunden. Lege zuerst ein neues Modul an.
|
||||
</p>
|
||||
) : (
|
||||
<select
|
||||
className="form-input"
|
||||
value={existingModuleId}
|
||||
onChange={(e) => setExistingModuleId(e.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="">— Modul wählen —</option>
|
||||
{moduleOptions.map((m) => (
|
||||
<option key={m.id} value={String(m.id)}>
|
||||
{(m.title || '').trim() || `Modul #${m.id}`}
|
||||
{m.items_count != null ? ` (${m.items_count} Pos.)` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<p style={{ margin: '6px 0 0', fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.45 }}>
|
||||
Die neuen Übungen werden <strong>ans Ende</strong> des gewählten Moduls angefügt.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div style={{ marginBottom: '1rem' }}>
|
||||
<label className="form-label">Modultitel</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
required
|
||||
placeholder="z. B. Technikblock Grundlagen"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">{EXERCISE_VISIBILITY_FIELD_LABEL}</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={visibility}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
setVisibility(v)
|
||||
if (v === 'club' && !clubId) {
|
||||
const fallback = getDefaultClubIdForGovernanceForms(user)
|
||||
if (fallback != null) setClubId(String(fallback))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="private">Privat</option>
|
||||
<option value="club">Verein</option>
|
||||
{isSuperadmin ? <option value="official">Offiziell</option> : null}
|
||||
</select>
|
||||
</div>
|
||||
{visibility === 'club' ? (
|
||||
<div className="form-row" style={{ marginBottom: '1rem' }}>
|
||||
<label className="form-label">Verein</label>
|
||||
<select className="form-input" value={clubId} onChange={(e) => setClubId(e.target.value)}>
|
||||
<option value="">— Verein wählen —</option>
|
||||
{memberClubs.map((cl) => (
|
||||
<option key={cl.id} value={String(cl.id)}>
|
||||
{cl.name || `Verein #${cl.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1rem',
|
||||
padding: '10px 12px',
|
||||
maxHeight: 'min(320px, 45vh)',
|
||||
overflowY: 'auto',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||
{rows.map((row, idx) => {
|
||||
const isCombo = row.exercise_kind === 'combination'
|
||||
const variants = Array.isArray(row.variants) ? row.variants : []
|
||||
return (
|
||||
<li
|
||||
key={`${row.exercise_id}-${idx}`}
|
||||
style={{
|
||||
padding: '10px 0',
|
||||
borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontWeight: 600, color: 'var(--text1)', fontSize: '0.92rem', marginBottom: 8 }}>
|
||||
{idx + 1}. {(row.exercise_title || '').trim() || `Übung #${row.exercise_id}`}
|
||||
{isCombo ? (
|
||||
<span
|
||||
style={{
|
||||
marginLeft: 8,
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 600,
|
||||
color: 'var(--accent-dark)',
|
||||
}}
|
||||
>
|
||||
Kombination
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{!isCombo && variants.length > 0 ? (
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label" style={{ fontSize: '0.78rem' }}>
|
||||
Variante
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={String(row.exercise_variant_id ?? '')}
|
||||
onChange={(e) => updateRow(idx, { exercise_variant_id: e.target.value })}
|
||||
>
|
||||
<option value="">Standard (keine Variante)</option>
|
||||
{variants.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{(v.variant_name || v.name || '').trim() || `Variante #${v.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : !isCombo ? (
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text3)' }}>Keine Varianten hinterlegt</div>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormActionBar
|
||||
placement="bottom"
|
||||
variant="modal"
|
||||
formId="save-selected-module-form"
|
||||
saving={submitting}
|
||||
showSave={false}
|
||||
saveAndCloseLabel={saveLabel}
|
||||
saveAndCloseShortLabel={targetMode === 'append' ? 'Anfügen' : 'Anlegen'}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1rem' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={onClose}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!loading && (loadErr || rows.length === 0) ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1rem' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</FormModalOverlay>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import React from 'react'
|
||||
import NavStateLink from '../NavStateLink'
|
||||
import SkillProfileCompact from '../skills/SkillProfileCompact'
|
||||
import {
|
||||
frameworkSessionDurationLabel,
|
||||
splitFrameworkCommaAgg,
|
||||
splitFrameworkGoalsAgg,
|
||||
frameworkProgramHasCatalogMeta,
|
||||
} from '../../utils/frameworkProgramListHelpers'
|
||||
|
||||
function CatalogGroup({ label, items, variant }) {
|
||||
if (!items.length) return null
|
||||
return (
|
||||
<div className={`fw-prog-card__catalog-group fw-prog-card__catalog-group--${variant}`}>
|
||||
<span className="fw-prog-card__catalog-label">{label}</span>
|
||||
<ul className="fw-prog-card__chip-list" aria-label={label}>
|
||||
{items.map((name) => (
|
||||
<li key={name} className="fw-prog-card__chip">
|
||||
{name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelkarte für die Rahmenprogramm-Bibliothek.
|
||||
*/
|
||||
export default function FrameworkProgramListCard({
|
||||
row,
|
||||
returnContext,
|
||||
onDelete,
|
||||
skillSummary = null,
|
||||
skillSummaryLoading = false,
|
||||
skillFilterIds = [],
|
||||
skillDisplayLimit = 6,
|
||||
onShowSkillProfile,
|
||||
}) {
|
||||
const title = (row.title || '').trim() || `Rahmen #${row.id}`
|
||||
const description = (row.description || '').trim()
|
||||
const durationLabel = frameworkSessionDurationLabel(row)
|
||||
const hasDuration = durationLabel !== 'Dauer nicht angegeben'
|
||||
const goals = splitFrameworkGoalsAgg(row.goal_titles_agg)
|
||||
const focusAreas = splitFrameworkCommaAgg(row.focus_area_names_agg)
|
||||
const styleDirs = splitFrameworkCommaAgg(
|
||||
row.style_direction_names_agg || row.style_direction_name
|
||||
)
|
||||
const trainingTypes = splitFrameworkCommaAgg(row.training_type_names_agg)
|
||||
const targetGroups = splitFrameworkCommaAgg(row.target_group_names_agg)
|
||||
const goalsCount = Number(row.goals_count)
|
||||
const slotsCount = Number(row.slots_count)
|
||||
const showCatalog = frameworkProgramHasCatalogMeta(row)
|
||||
|
||||
return (
|
||||
<article className="fw-prog-card card">
|
||||
<div className="fw-prog-card__accent" aria-hidden="true" />
|
||||
<div className="fw-prog-card__inner">
|
||||
<header className="fw-prog-card__head">
|
||||
<div className="fw-prog-card__title-block">
|
||||
<h2 className="fw-prog-card__title">
|
||||
<NavStateLink
|
||||
to={`/planning/framework-programs/${row.id}`}
|
||||
returnContext={returnContext}
|
||||
className="fw-prog-card__title-link"
|
||||
>
|
||||
{title}
|
||||
</NavStateLink>
|
||||
</h2>
|
||||
{description ? (
|
||||
<p className="fw-prog-card__desc">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ul className="fw-prog-card__stats" aria-label="Kennzahlen">
|
||||
<li
|
||||
className={
|
||||
'fw-prog-card__stat' +
|
||||
(hasDuration ? ' fw-prog-card__stat--duration' : ' fw-prog-card__stat--muted')
|
||||
}
|
||||
>
|
||||
<span className="fw-prog-card__stat-label">Session</span>
|
||||
<span className="fw-prog-card__stat-value">{durationLabel}</span>
|
||||
</li>
|
||||
<li className="fw-prog-card__stat">
|
||||
<span className="fw-prog-card__stat-label">Ziele</span>
|
||||
<span className="fw-prog-card__stat-value">
|
||||
{Number.isFinite(goalsCount) ? goalsCount : '—'}
|
||||
</span>
|
||||
</li>
|
||||
<li className="fw-prog-card__stat">
|
||||
<span className="fw-prog-card__stat-label">Sessions</span>
|
||||
<span className="fw-prog-card__stat-value">
|
||||
{Number.isFinite(slotsCount) ? slotsCount : '—'}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</header>
|
||||
|
||||
{goals.length > 0 ? (
|
||||
<section className="fw-prog-card__section fw-prog-card__section--goals">
|
||||
<h3 className="fw-prog-card__section-title">Entwicklungsziele</h3>
|
||||
<ul className="fw-prog-card__goal-list" aria-label="Entwicklungsziele">
|
||||
{goals.map((g) => (
|
||||
<li key={g} className="fw-prog-card__goal">
|
||||
{g}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{showCatalog ? (
|
||||
<section className="fw-prog-card__section fw-prog-card__section--catalog">
|
||||
<h3 className="fw-prog-card__section-title">Einordnung</h3>
|
||||
<div className="fw-prog-card__catalog">
|
||||
<CatalogGroup label="Fokus" items={focusAreas} variant="focus" />
|
||||
<CatalogGroup label="Stil" items={styleDirs} variant="style" />
|
||||
<CatalogGroup label="Trainingsart" items={trainingTypes} variant="type" />
|
||||
<CatalogGroup label="Zielgruppe" items={targetGroups} variant="target" />
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="fw-prog-card__section fw-prog-card__section--skills">
|
||||
<div className="fw-prog-card__section-head">
|
||||
<h3 className="fw-prog-card__section-title">Fähigkeiten</h3>
|
||||
{onShowSkillProfile ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small fw-prog-card__skills-btn"
|
||||
onClick={() => onShowSkillProfile(row)}
|
||||
>
|
||||
Alle anzeigen
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<SkillProfileCompact
|
||||
summary={skillSummary}
|
||||
artifactType="framework_program"
|
||||
loading={skillSummaryLoading}
|
||||
displayLimit={skillDisplayLimit}
|
||||
highlightSkillIds={skillFilterIds}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<footer className="fw-prog-card__actions">
|
||||
<NavStateLink
|
||||
to={`/planning/framework-programs/${row.id}`}
|
||||
returnContext={returnContext}
|
||||
className="btn btn-primary fw-prog-card__btn-primary"
|
||||
>
|
||||
Öffnen
|
||||
</NavStateLink>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary fw-prog-card__btn-danger"
|
||||
onClick={() => onDelete(row.id, row.title)}
|
||||
>
|
||||
Löschen
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user