Compare commits
59
Commits
55d87d8d17
...
MVP1.5
| 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 |
No files matched your search
@@ -104,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:**
|
||||
|
||||
|
||||
@@ -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,6 +473,34 @@ 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.
|
||||
@@ -648,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
|
||||
@@ -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/`.
|
||||
@@ -169,11 +169,35 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
||||
|
||||
---
|
||||
|
||||
## 15. 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` |
|
||||
|
||||
@@ -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,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 |
|
||||
@@ -16,6 +16,7 @@
|
||||
| `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).
|
||||
|
||||
|
||||
@@ -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`?
|
||||
@@ -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) |
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
> | 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`** |
|
||||
@@ -90,6 +91,7 @@ Kurz (Stand 2026-05-14): App- und DB-Version siehe **`backend/version.py`**; Ker
|
||||
|
||||
### 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`.
|
||||
|
||||
+2
-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, dashboard, 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,6 +208,7 @@ 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)
|
||||
|
||||
@@ -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;
|
||||
@@ -113,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
|
||||
@@ -1102,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(
|
||||
@@ -1223,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),
|
||||
@@ -2095,7 +2116,17 @@ 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
|
||||
@@ -2118,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):
|
||||
|
||||
@@ -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__)
|
||||
|
||||
@@ -615,14 +616,16 @@ 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()
|
||||
|
||||
@@ -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
|
||||
@@ -99,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(
|
||||
@@ -136,6 +162,14 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
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", [])
|
||||
@@ -143,6 +177,8 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
||||
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
|
||||
|
||||
|
||||
@@ -209,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")
|
||||
@@ -277,22 +360,25 @@ 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"]
|
||||
|
||||
@@ -327,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)
|
||||
@@ -337,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
|
||||
@@ -348,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",
|
||||
@@ -403,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)
|
||||
@@ -418,19 +552,17 @@ 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"]
|
||||
@@ -438,6 +570,8 @@ def create_training_framework_program(
|
||||
_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)
|
||||
@@ -489,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)
|
||||
@@ -503,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()")
|
||||
@@ -555,7 +690,17 @@ def update_training_framework_program(
|
||||
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,),
|
||||
|
||||
@@ -648,6 +648,7 @@ def _ensure_default_whole_group_phase(cur, unit_id: int, *, order_index: int = 0
|
||||
|
||||
_SECTION_ROWS_SQL = """
|
||||
SELECT tus.id, tus.training_unit_id, tus.order_index, tus.title, tus.guidance_notes,
|
||||
tus.planned_duration_min,
|
||||
tus.source_template_section_id, tus.phase_id, tus.parallel_stream_id
|
||||
FROM training_unit_sections tus
|
||||
LEFT JOIN training_unit_phases ph ON ph.id = tus.phase_id
|
||||
@@ -740,7 +741,7 @@ def _fetch_phases_nested(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, title, guidance_notes,
|
||||
source_template_section_id, phase_id, parallel_stream_id
|
||||
planned_duration_min, source_template_section_id, phase_id, parallel_stream_id
|
||||
FROM training_unit_sections
|
||||
WHERE phase_id = %s
|
||||
ORDER BY order_index
|
||||
@@ -771,7 +772,7 @@ def _fetch_phases_nested(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, training_unit_id, order_index, title, guidance_notes,
|
||||
source_template_section_id, phase_id, parallel_stream_id
|
||||
planned_duration_min, source_template_section_id, phase_id, parallel_stream_id
|
||||
FROM training_unit_sections
|
||||
WHERE parallel_stream_id = %s
|
||||
ORDER BY order_index
|
||||
@@ -831,6 +832,7 @@ def _clone_section_payload_dict(sec: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"title": sec.get("title"),
|
||||
"order_index": sec.get("order_index"),
|
||||
"guidance_notes": sec.get("guidance_notes"),
|
||||
"planned_duration_min": sec.get("planned_duration_min"),
|
||||
"items": items_clean,
|
||||
}
|
||||
stid = sec.get("source_template_section_id")
|
||||
@@ -878,6 +880,86 @@ def _phases_clone_payload(cur, unit_id: int) -> List[Dict[str, Any]]:
|
||||
return out
|
||||
|
||||
|
||||
def _copy_scheduled_unit_plan_to_blueprint(
|
||||
cur,
|
||||
source_unit_id: int,
|
||||
blueprint_unit_id: int,
|
||||
profile_id: int,
|
||||
role: str,
|
||||
) -> None:
|
||||
"""Übernimmt Phasen/Sektionen einer geplanten Einheit in eine Rahmen-Blueprint-Einheit."""
|
||||
cloned_phases = _phases_clone_payload(cur, source_unit_id)
|
||||
if cloned_phases:
|
||||
_replace_unit_phases(cur, blueprint_unit_id, cloned_phases, profile_id, role, profile_id)
|
||||
return
|
||||
secs = _fetch_sections(cur, source_unit_id)
|
||||
sections_payload = [_clone_section_payload_dict(s) for s in secs]
|
||||
if not sections_payload:
|
||||
_replace_unit_sections(
|
||||
cur,
|
||||
blueprint_unit_id,
|
||||
[{"title": "Ablauf", "order_index": 0, "guidance_notes": None, "items": []}],
|
||||
)
|
||||
return
|
||||
_replace_unit_sections(cur, blueprint_unit_id, sections_payload)
|
||||
|
||||
|
||||
def _shift_framework_slots_sort_orders_from(cur, framework_program_id: int, from_sort_order: int) -> None:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE training_framework_slots
|
||||
SET sort_order = sort_order + 1
|
||||
WHERE framework_program_id = %s AND sort_order >= %s
|
||||
""",
|
||||
(framework_program_id, int(from_sort_order)),
|
||||
)
|
||||
|
||||
|
||||
def _insert_framework_slot_and_blueprint_unit(
|
||||
cur,
|
||||
framework_program_id: int,
|
||||
sort_order: int,
|
||||
title: Optional[str],
|
||||
notes: Optional[Any],
|
||||
profile_id: int,
|
||||
) -> Tuple[int, int]:
|
||||
"""Legt Slot-Zeile + Blueprint-`training_units`-Zeile an; gibt (slot_id, blueprint_unit_id) zurück."""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_slots (
|
||||
framework_program_id, sort_order, title, notes, training_unit_id
|
||||
) VALUES (%s, %s, %s, %s, NULL)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
framework_program_id,
|
||||
int(sort_order),
|
||||
title,
|
||||
notes,
|
||||
),
|
||||
)
|
||||
sid = int(cur.fetchone()["id"])
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date,
|
||||
planned_time_start, planned_time_end, planned_focus,
|
||||
status, notes, trainer_notes,
|
||||
created_by, plan_template_id, framework_slot_id
|
||||
) VALUES (
|
||||
NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
'planned', NULL, NULL,
|
||||
%s, NULL, %s
|
||||
)
|
||||
RETURNING id
|
||||
""",
|
||||
(profile_id, sid),
|
||||
)
|
||||
bid = int(cur.fetchone()["id"])
|
||||
return sid, bid
|
||||
|
||||
|
||||
def _copy_blueprint_into_scheduled_unit(
|
||||
cur,
|
||||
blueprint_unit_id: int,
|
||||
@@ -894,6 +976,7 @@ def _copy_blueprint_into_scheduled_unit(
|
||||
planned_date,
|
||||
planned_time_start,
|
||||
planned_time_end,
|
||||
planned_duration_min,
|
||||
planned_focus,
|
||||
actual_date,
|
||||
actual_time_start,
|
||||
@@ -912,6 +995,7 @@ def _copy_blueprint_into_scheduled_unit(
|
||||
%s,
|
||||
planned_time_start,
|
||||
planned_time_end,
|
||||
planned_duration_min,
|
||||
planned_focus,
|
||||
NULL::DATE,
|
||||
NULL::TIME WITHOUT TIME ZONE,
|
||||
@@ -1201,8 +1285,9 @@ def _insert_one_replacement_section(
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_unit_sections (
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes, source_template_section_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes,
|
||||
planned_duration_min, source_template_section_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
@@ -1212,6 +1297,7 @@ def _insert_one_replacement_section(
|
||||
order_ix,
|
||||
title,
|
||||
sec.get("guidance_notes"),
|
||||
sec.get("planned_duration_min"),
|
||||
src_tsec,
|
||||
),
|
||||
)
|
||||
@@ -1549,10 +1635,12 @@ def _normalize_training_plan_template_section_payload(sec: Any, si: int) -> Dict
|
||||
p_so = int(raw_so) if raw_so is not None and raw_so != "" else 0
|
||||
except (TypeError, ValueError):
|
||||
p_so = 0
|
||||
pdur = _optional_positive_int(sec.get("planned_duration_min"), "planned_duration_min")
|
||||
return {
|
||||
"title": title,
|
||||
"order_index": order_ix,
|
||||
"guidance_text": sec.get("guidance_text"),
|
||||
"planned_duration_min": pdur,
|
||||
"phase_kind": pk,
|
||||
"phase_order_index": p_oi,
|
||||
"parallel_stream_order_index": p_so,
|
||||
@@ -1565,15 +1653,16 @@ def _insert_training_plan_template_sections(cur, template_id: int, sections_in:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_plan_template_sections (
|
||||
template_id, order_index, title, guidance_text,
|
||||
template_id, order_index, title, guidance_text, planned_duration_min,
|
||||
phase_kind, phase_order_index, parallel_stream_order_index
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
template_id,
|
||||
row["order_index"],
|
||||
row["title"],
|
||||
row["guidance_text"],
|
||||
row["planned_duration_min"],
|
||||
row["phase_kind"],
|
||||
row["phase_order_index"],
|
||||
row["parallel_stream_order_index"],
|
||||
@@ -1620,6 +1709,7 @@ def _template_rows_to_phases_payload(rows: List[Dict[str, Any]]) -> List[Dict[st
|
||||
"title": rr.get("title"),
|
||||
"order_index": j,
|
||||
"guidance_notes": rr.get("guidance_text"),
|
||||
"planned_duration_min": rr.get("planned_duration_min"),
|
||||
"items": [],
|
||||
**(
|
||||
{"source_template_section_id": int(tid)}
|
||||
@@ -1663,6 +1753,7 @@ def _template_rows_to_phases_payload(rows: List[Dict[str, Any]]) -> List[Dict[st
|
||||
"title": rr.get("title"),
|
||||
"order_index": j,
|
||||
"guidance_notes": rr.get("guidance_text"),
|
||||
"planned_duration_min": rr.get("planned_duration_min"),
|
||||
"items": [],
|
||||
**(
|
||||
{"source_template_section_id": int(tid)}
|
||||
@@ -1695,7 +1786,7 @@ def _instantiate_from_template(
|
||||
) -> None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, title, guidance_text, order_index, phase_kind, phase_order_index, parallel_stream_order_index
|
||||
SELECT id, title, guidance_text, planned_duration_min, order_index, phase_kind, phase_order_index, parallel_stream_order_index
|
||||
FROM training_plan_template_sections
|
||||
WHERE template_id = %s
|
||||
ORDER BY order_index
|
||||
@@ -1777,7 +1868,26 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
|
||||
f"""
|
||||
SELECT t.*,
|
||||
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
|
||||
AS sections_count
|
||||
AS sections_count,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT json_agg(
|
||||
json_build_object(
|
||||
'id', s.id,
|
||||
'order_index', s.order_index,
|
||||
'title', s.title,
|
||||
'guidance_text', s.guidance_text,
|
||||
'phase_kind', s.phase_kind,
|
||||
'phase_order_index', s.phase_order_index,
|
||||
'parallel_stream_order_index', s.parallel_stream_order_index
|
||||
)
|
||||
ORDER BY s.order_index
|
||||
)
|
||||
FROM training_plan_template_sections s
|
||||
WHERE s.template_id = t.id
|
||||
),
|
||||
'[]'::json
|
||||
) AS sections
|
||||
FROM training_plan_templates t
|
||||
WHERE ({vis_clause})
|
||||
ORDER BY t.updated_at DESC NULLS LAST, t.name
|
||||
@@ -2492,11 +2602,13 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
|
||||
eff_lead_for_co,
|
||||
)
|
||||
|
||||
pdur = _optional_positive_int(data.get("planned_duration_min"), "planned_duration_min")
|
||||
base_params = (
|
||||
group_id,
|
||||
planned_date,
|
||||
data.get("planned_time_start"),
|
||||
data.get("planned_time_end"),
|
||||
pdur,
|
||||
data.get("planned_focus"),
|
||||
data.get("status", "planned"),
|
||||
data.get("notes"),
|
||||
@@ -2511,11 +2623,11 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date, planned_time_start, planned_time_end,
|
||||
planned_focus, status, notes, trainer_notes, created_by,
|
||||
planned_duration_min, planned_focus, status, notes, trainer_notes, created_by,
|
||||
plan_template_id,
|
||||
lead_trainer_profile_id,
|
||||
assistant_trainer_profile_ids
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
base_params + (av_db,),
|
||||
@@ -2525,10 +2637,10 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
|
||||
"""
|
||||
INSERT INTO training_units (
|
||||
group_id, planned_date, planned_time_start, planned_time_end,
|
||||
planned_focus, status, notes, trainer_notes, created_by,
|
||||
planned_duration_min, planned_focus, status, notes, trainer_notes, created_by,
|
||||
plan_template_id,
|
||||
lead_trainer_profile_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
base_params,
|
||||
@@ -2618,6 +2730,11 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
if "planned_time_end" in data:
|
||||
blueprint_fields.append("planned_time_end = %s")
|
||||
blueprint_params.append(data.get("planned_time_end"))
|
||||
if "planned_duration_min" in data:
|
||||
blueprint_fields.append("planned_duration_min = %s")
|
||||
blueprint_params.append(
|
||||
_optional_positive_int(data.get("planned_duration_min"), "planned_duration_min")
|
||||
)
|
||||
if "notes" in data:
|
||||
blueprint_fields.append("notes = %s")
|
||||
blueprint_params.append(data.get("notes"))
|
||||
@@ -2683,6 +2800,7 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
planned_date = COALESCE(%s, planned_date),
|
||||
planned_time_start = %s,
|
||||
planned_time_end = %s,
|
||||
planned_duration_min = %s,
|
||||
planned_focus = %s,
|
||||
actual_date = %s,
|
||||
actual_time_start = %s,
|
||||
@@ -2702,6 +2820,9 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
|
||||
data.get("planned_date"),
|
||||
data.get("planned_time_start"),
|
||||
data.get("planned_time_end"),
|
||||
_optional_positive_int(data.get("planned_duration_min"), "planned_duration_min")
|
||||
if "planned_duration_min" in data
|
||||
else unit_row.get("planned_duration_min"),
|
||||
data.get("planned_focus"),
|
||||
data.get("actual_date"),
|
||||
data.get("actual_time_start"),
|
||||
@@ -2877,6 +2998,234 @@ def create_training_unit_from_framework_slot(data: dict, tenant: TenantContext =
|
||||
return get_training_unit(new_id, tenant)
|
||||
|
||||
|
||||
@router.post("/training-units/{unit_id}/publish-to-framework")
|
||||
def publish_training_unit_to_framework(
|
||||
unit_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
|
||||
):
|
||||
"""Geplanten Ablauf einer Einheit als Session-Blueprint in ein Rahmenprogramm übernehmen (neu / bestehend, Slot wählbar)."""
|
||||
from routers.training_framework_programs import ( # noqa: WPS433 — zyklischer Import
|
||||
_assert_visibility,
|
||||
_fetch_framework_row,
|
||||
_insert_goal_rows,
|
||||
_parse_positive_int_ids,
|
||||
_replace_target_groups,
|
||||
_replace_training_types,
|
||||
_response_framework_detail,
|
||||
)
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Planungsberechtigte dürfen Rahmenprogramme bearbeiten")
|
||||
|
||||
mode = (data.get("mode") or "").strip().lower()
|
||||
if mode not in ("new_slot", "existing_slot"):
|
||||
raise HTTPException(status_code=400, detail="mode muss new_slot oder existing_slot sein")
|
||||
|
||||
fw_new = data.get("new_framework")
|
||||
fw_id_raw = data.get("framework_program_id")
|
||||
has_new = isinstance(fw_new, dict) and len(fw_new) > 0
|
||||
has_id = fw_id_raw not in (None, "")
|
||||
|
||||
if has_new == has_id:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Entweder new_framework ODER framework_program_id angeben (nicht beides, nicht keines)",
|
||||
)
|
||||
|
||||
framework_id: int = 0
|
||||
slot_title_o: Optional[str] = None
|
||||
notes_o = data.get("slot_notes")
|
||||
st = data.get("slot_title")
|
||||
if st is not None:
|
||||
st = str(st).strip()
|
||||
slot_title_o = st or None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
unit_row = _training_unit_guard_row(cur, unit_id)
|
||||
if unit_row.get("framework_slot_id"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Nur geplante Einheiten (Kalender) können in einen Rahmen übernommen werden, keine Blueprint-Einheit",
|
||||
)
|
||||
_assert_training_unit_permission(cur, unit_row, profile_id, role)
|
||||
|
||||
if has_new:
|
||||
title = (fw_new.get("title") or "").strip()
|
||||
if not title:
|
||||
raise HTTPException(status_code=400, detail="new_framework.title ist Pflicht")
|
||||
|
||||
vis = _assert_visibility(fw_new.get("visibility") or "private")
|
||||
club_nf = fw_new.get("club_id")
|
||||
if club_nf in ("", []):
|
||||
club_nf = None
|
||||
if vis == "club" and club_nf is None:
|
||||
club_nf = tenant.effective_club_id
|
||||
|
||||
goals_in = fw_new.get("goals")
|
||||
if not isinstance(goals_in, list) or not goals_in:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="new_framework.goals als Liste mit mindestens einem Eintrag ist Pflicht",
|
||||
)
|
||||
|
||||
fa_id = _optional_positive_int(fw_new.get("focus_area_id"), "focus_area_id")
|
||||
sd_id = _optional_positive_int(fw_new.get("style_direction_id"), "style_direction_id")
|
||||
tt_ids = _parse_positive_int_ids(fw_new.get("training_type_ids"), "training_type_ids")
|
||||
tg_ids = _parse_positive_int_ids(fw_new.get("target_group_ids"), "target_group_ids")
|
||||
|
||||
assert_valid_governance_visibility(cur, profile_id, role, vis, club_nf)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_framework_programs (
|
||||
title, description,
|
||||
planned_period_start, planned_period_end,
|
||||
visibility, club_id, created_by,
|
||||
focus_area_id, style_direction_id
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
title[:200],
|
||||
fw_new.get("description"),
|
||||
fw_new.get("planned_period_start"),
|
||||
fw_new.get("planned_period_end"),
|
||||
vis,
|
||||
club_nf,
|
||||
profile_id,
|
||||
fa_id,
|
||||
sd_id,
|
||||
),
|
||||
)
|
||||
framework_id = int(cur.fetchone()["id"])
|
||||
_insert_goal_rows(cur, framework_id, goals_in)
|
||||
_replace_training_types(cur, framework_id, tt_ids)
|
||||
_replace_target_groups(cur, framework_id, tg_ids)
|
||||
else:
|
||||
try:
|
||||
framework_id = int(fw_id_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="framework_program_id ungültig") from None
|
||||
if framework_id < 1:
|
||||
raise HTTPException(status_code=400, detail="framework_program_id ungültig")
|
||||
|
||||
row_fw = _fetch_framework_row(cur, framework_id)
|
||||
assert_library_content_editable(cur, profile_id, role, row_fw)
|
||||
|
||||
ins_raw = data.get("insert_at_index")
|
||||
slot_id_out: int = 0
|
||||
|
||||
if mode == "new_slot":
|
||||
pos: Optional[int] = None
|
||||
if ins_raw is not None and ins_raw != "":
|
||||
try:
|
||||
pos = int(ins_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="insert_at_index ungültig") from None
|
||||
if pos < 0:
|
||||
raise HTTPException(status_code=400, detail="insert_at_index ungültig")
|
||||
|
||||
if pos is None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(sort_order), -1) + 1 AS n
|
||||
FROM training_framework_slots
|
||||
WHERE framework_program_id = %s
|
||||
""",
|
||||
(framework_id,),
|
||||
)
|
||||
pos = int(cur.fetchone()["n"])
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT COUNT(*)::int AS c FROM training_framework_slots WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
cmax = int(cur.fetchone()["c"])
|
||||
if pos > cmax:
|
||||
pos = cmax
|
||||
_shift_framework_slots_sort_orders_from(cur, framework_id, pos)
|
||||
|
||||
sid, bid = _insert_framework_slot_and_blueprint_unit(
|
||||
cur,
|
||||
framework_id,
|
||||
pos,
|
||||
slot_title_o,
|
||||
notes_o,
|
||||
profile_id,
|
||||
)
|
||||
slot_id_out = sid
|
||||
_copy_scheduled_unit_plan_to_blueprint(cur, unit_id, bid, profile_id, role)
|
||||
_promote_private_exercises_used_in_unit(cur, bid, profile_id, role)
|
||||
|
||||
else:
|
||||
raw_existing = data.get("framework_slot_id")
|
||||
try:
|
||||
slot_id_out = int(raw_existing)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail="framework_slot_id ist Pflicht und muss eine Zahl sein") from None
|
||||
if slot_id_out < 1:
|
||||
raise HTTPException(status_code=400, detail="framework_slot_id ist ungültig")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, framework_program_id, sort_order, title, notes
|
||||
FROM training_framework_slots
|
||||
WHERE id = %s
|
||||
""",
|
||||
(slot_id_out,),
|
||||
)
|
||||
slot_row = cur.fetchone()
|
||||
if not slot_row:
|
||||
raise HTTPException(status_code=404, detail="Rahmen-Slot nicht gefunden")
|
||||
if int(slot_row["framework_program_id"]) != framework_id:
|
||||
raise HTTPException(status_code=400, detail="Slot gehört nicht zu diesem Rahmenprogramm")
|
||||
|
||||
cur.execute(
|
||||
"SELECT id FROM training_units WHERE framework_slot_id = %s",
|
||||
(slot_id_out,),
|
||||
)
|
||||
bp = cur.fetchone()
|
||||
if not bp:
|
||||
raise HTTPException(status_code=404, detail="Keine Blueprint-Einheit für diesen Slot")
|
||||
|
||||
meta_fields: List[str] = []
|
||||
meta_params: List[Any] = []
|
||||
if "slot_title" in data:
|
||||
stn = data.get("slot_title")
|
||||
title_v = (str(stn).strip() or None) if stn is not None else None
|
||||
meta_fields.append("title = %s")
|
||||
meta_params.append(title_v)
|
||||
if "slot_notes" in data:
|
||||
meta_fields.append("notes = %s")
|
||||
meta_params.append(data.get("slot_notes"))
|
||||
if meta_fields:
|
||||
meta_params.append(slot_id_out)
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE training_framework_slots
|
||||
SET {", ".join(meta_fields)}
|
||||
WHERE id = %s
|
||||
""",
|
||||
tuple(meta_params),
|
||||
)
|
||||
|
||||
bid = int(bp["id"])
|
||||
_copy_scheduled_unit_plan_to_blueprint(cur, unit_id, bid, profile_id, role)
|
||||
_promote_private_exercises_used_in_unit(cur, bid, profile_id, role)
|
||||
|
||||
cur.execute(
|
||||
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
return _response_framework_detail(framework_id, profile_id, role)
|
||||
|
||||
|
||||
@router.post("/training-units/quick-create")
|
||||
def quick_create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
profile_id = tenant.profile_id
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -377,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
|
||||
|
||||
|
||||
@@ -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,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,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]
|
||||
+44
-5
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.145"
|
||||
BUILD_DATE = "2026-05-16"
|
||||
DB_SCHEMA_VERSION = "20260516065"
|
||||
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)
|
||||
@@ -20,11 +20,12 @@ MODULE_VERSIONS = {
|
||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||
"groups": "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.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
||||
"training_units": "0.3.0", # GET /api/training-units Keyset cursor_planned_date + cursor_id (+ optional cursor_planned_time); Sort mit id-Tiebreak
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.13.0", # Vorlagen/Framework/Module/Graphs: RBAC wie Übungen (edit/delete/governance transition); Planungs-UI Sichtbarkeit neue Vorlage
|
||||
"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
|
||||
@@ -36,6 +37,44 @@ 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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -78,6 +80,8 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
||||
- **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 („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).
|
||||
@@ -129,6 +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`. |
|
||||
+19
-2
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-14
|
||||
**App-Version / DB-Schema:** App **`0.8.140`** (u. a. Planungs-Breakout-UI), DB-Schema **`20260515063`** — maßgeblich **`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**.
|
||||
|
||||
@@ -35,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`** |
|
||||
|
||||
@@ -69,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)
|
||||
@@ -76,6 +86,13 @@ 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`.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -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.
|
||||
@@ -5,7 +5,9 @@
|
||||
"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",
|
||||
@@ -20,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',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
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. */
|
||||
@@ -89,8 +90,7 @@ export function buildExerciseApiPayload(formData, extras = {}) {
|
||||
age_groups: [],
|
||||
skills: (formData.skills || []).map((s) => ({
|
||||
skill_id: s.skill_id,
|
||||
is_primary: !!s.is_primary,
|
||||
intensity: s.intensity || null,
|
||||
intensity: normalizeExerciseSkillIntensity(s.intensity),
|
||||
required_level: s.required_level || null,
|
||||
target_level: s.target_level || null,
|
||||
})),
|
||||
|
||||
@@ -144,6 +144,14 @@ export async function applyTrainingModuleToTrainingUnit(unitId, 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')
|
||||
}
|
||||
|
||||
@@ -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 || [],
|
||||
}),
|
||||
})
|
||||
}
|
||||
+2167
-1
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
|
||||
@@ -7,13 +7,14 @@ 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'
|
||||
|
||||
@@ -88,7 +89,7 @@ export default function ExercisePickerModal({
|
||||
api.listStyleDirections(),
|
||||
api.listTrainingTypes(),
|
||||
api.listTargetGroups(),
|
||||
api.listSkills(),
|
||||
api.listSkillsCatalog(),
|
||||
])
|
||||
if (!cancelled) {
|
||||
setCatalogs({
|
||||
@@ -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' },
|
||||
@@ -377,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>
|
||||
@@ -466,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}
|
||||
@@ -506,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 }}>
|
||||
@@ -543,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
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
swapAdjacentPhaseRuns,
|
||||
reorderBlocksImmutableWithPlanLoc,
|
||||
reorderSectionBeforeParallelRunAsWholeGroup,
|
||||
reorderSectionAfterParallelRunAsWholeGroup,
|
||||
reorderSectionAsFirstInParallelStream,
|
||||
reorderBlockIntoParallelStreamEnd,
|
||||
globalInsertBeforeIndexForParallelStreamEnd,
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
noteRow,
|
||||
sectionPlannedMinutes,
|
||||
} from '../utils/trainingUnitSectionsForm'
|
||||
import { formatDurationDisplay, parseDurationInput } from '../utils/trainingDurationUtils'
|
||||
import api from '../utils/api'
|
||||
import { isCompactTagLegendMode } from '../config/planningModuleUx'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
@@ -266,12 +268,27 @@ export default function TrainingUnitSectionsEditor({
|
||||
betweenInsertMenus = true,
|
||||
/** Trainingsplanung: Phasen/Streams anlegen und Abschnitte zuordnen */
|
||||
enableParallelPhaseControls = false,
|
||||
/** Nur Abschnitts-Gliederung (Vorlagen): keine Übungen/Anmerkungen */
|
||||
structureOnly = false,
|
||||
}) {
|
||||
const { user } = useAuth()
|
||||
const planningCompactLegend = isCompactTagLegendMode(
|
||||
user?.training_planning_prefs?.module_display_mode
|
||||
)
|
||||
|
||||
const [useCompactPhaseMoves, setUseCompactPhaseMoves] = useState(() =>
|
||||
typeof window !== 'undefined'
|
||||
? window.matchMedia('(max-width: 768px)').matches
|
||||
: false
|
||||
)
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia('(max-width: 768px)')
|
||||
const apply = () => setUseCompactPhaseMoves(!!mq.matches)
|
||||
apply()
|
||||
mq.addEventListener('change', apply)
|
||||
return () => mq.removeEventListener('change', apply)
|
||||
}, [])
|
||||
|
||||
const ensure = (prev) =>
|
||||
prev && prev.length ? prev : [defaultSection()]
|
||||
|
||||
@@ -1297,6 +1314,47 @@ export default function TrainingUnitSectionsEditor({
|
||||
return sIdx === 0
|
||||
}
|
||||
|
||||
const moveSectionToPlanTarget = (sIdx, rawKey) => {
|
||||
if (!rawKey) return
|
||||
patch((prev) => {
|
||||
const opts = planSelectOptionsForSection(prev, sIdx, buildPlanTargetOptions(prev))
|
||||
const hit = opts.find((o) => o.key === rawKey)
|
||||
if (!hit) return prev
|
||||
const tpl = { ...hit.template }
|
||||
let next = prev.map((s, i) => (i === sIdx ? { ...s, planLoc: tpl } : s))
|
||||
if (enableParallelPhaseControls) next = afterSectionReorderParallelGuard(prev, next)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const moveSectionToWholeGroupAbove = (sIdx) => {
|
||||
const sec = list[sIdx]
|
||||
const po = sec?.planLoc?.phaseOrderIndex ?? 0
|
||||
if (sec?.planLoc?.phaseKind === 'parallel') {
|
||||
patch((prev) => {
|
||||
let next = reorderSectionBeforeParallelRunAsWholeGroup(prev, sIdx, po)
|
||||
if (enableParallelPhaseControls) next = afterSectionReorderParallelGuard(prev, next)
|
||||
return next
|
||||
})
|
||||
} else {
|
||||
moveSection(sIdx, -1)
|
||||
}
|
||||
}
|
||||
|
||||
const moveSectionToWholeGroupBelow = (sIdx) => {
|
||||
const sec = list[sIdx]
|
||||
const po = sec?.planLoc?.phaseOrderIndex ?? 0
|
||||
if (sec?.planLoc?.phaseKind === 'parallel') {
|
||||
patch((prev) => {
|
||||
let next = reorderSectionAfterParallelRunAsWholeGroup(prev, sIdx, po)
|
||||
if (enableParallelPhaseControls) next = afterSectionReorderParallelGuard(prev, next)
|
||||
return next
|
||||
})
|
||||
} else {
|
||||
moveSection(sIdx, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const sectionMoveDisabledDown = (sIdx) => {
|
||||
const sec = list[sIdx]
|
||||
const L = sec?.planLoc
|
||||
@@ -2002,34 +2060,82 @@ export default function TrainingUnitSectionsEditor({
|
||||
}
|
||||
placeholder="Hinweise zum Abschnitt (Material, Zeit, Zielrichtung …)"
|
||||
/>
|
||||
{enableParallelPhaseControls ? (
|
||||
<div className="form-row" style={{ marginTop: '10px', marginBottom: '2px' }}>
|
||||
{!structureOnly ? (
|
||||
<div
|
||||
className="form-row"
|
||||
style={{ marginTop: '10px', marginBottom: '2px', maxWidth: '220px' }}
|
||||
>
|
||||
<label className="form-label" style={{ fontSize: '0.78rem' }}>
|
||||
Zuordnung
|
||||
Geplante Abschnittsdauer
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={planLocKey(sec.planLoc)}
|
||||
onChange={(e) => applySectionPlanTarget(sIdx, e.target.value)}
|
||||
>
|
||||
<option value="">Standard — eine Ganzgruppe (klassischer Ablauf)</option>
|
||||
{planSelectOptionsForSection(list, sIdx, buildPlanTargetOptions(list)).map((o) => (
|
||||
<option key={o.key} value={o.key}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input tu-ex-duration"
|
||||
inputMode="decimal"
|
||||
value={sec.planned_duration_min ?? ''}
|
||||
onChange={(e) =>
|
||||
updateSectionField(sIdx, 'planned_duration_min', e.target.value)
|
||||
}
|
||||
placeholder="z. B. 15 oder 0,25 h"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{planMin > 0 && (
|
||||
{enableParallelPhaseControls && useCompactPhaseMoves ? (
|
||||
<div className="tu-section-phase-moves" style={{ marginTop: '8px' }}>
|
||||
<span
|
||||
className="form-label"
|
||||
style={{ fontSize: '0.75rem', display: 'block', marginBottom: '6px' }}
|
||||
>
|
||||
Phase / Gruppe
|
||||
</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary framework-ctrl framework-ctrl--xs"
|
||||
title="In Ganzgruppe darüber"
|
||||
onClick={() => moveSectionToWholeGroupAbove(sIdx)}
|
||||
>
|
||||
Ganz ↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary framework-ctrl framework-ctrl--xs"
|
||||
title="In Ganzgruppe darunter"
|
||||
onClick={() => moveSectionToWholeGroupBelow(sIdx)}
|
||||
>
|
||||
Ganz ↓
|
||||
</button>
|
||||
{planSelectOptionsForSection(list, sIdx, buildPlanTargetOptions(list))
|
||||
.filter((o) => o.key.startsWith('par:'))
|
||||
.map((o) => (
|
||||
<button
|
||||
key={o.key}
|
||||
type="button"
|
||||
className="btn btn-secondary framework-ctrl framework-ctrl--xs"
|
||||
title={o.label}
|
||||
onClick={() => moveSectionToPlanTarget(sIdx, o.key)}
|
||||
>
|
||||
{o.label.length > 14 ? `${o.label.slice(0, 12)}…` : o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{!structureOnly && planMin > 0 && (
|
||||
<p style={{ fontSize: '0.78rem', color: 'var(--text2)', marginTop: '0.35rem' }}>
|
||||
Geplant in diesem Abschnitt: ca. {planMin} Min. (Übungen)
|
||||
Geplant in diesem Abschnitt:{' '}
|
||||
<strong>{formatDurationDisplay(planMin)}</strong>
|
||||
{parseDurationInput(sec.planned_duration_min) != null
|
||||
? ' (Abschnittsangabe)'
|
||||
: ' (Summe Übungen)'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{betweenInsertMenus ? renderBetweenInsertBand(sIdx, 0, itemCount) : null}
|
||||
{!structureOnly ? (
|
||||
<>
|
||||
{betweenInsertMenus ? renderBetweenInsertBand(sIdx, 0, itemCount) : null}
|
||||
|
||||
{(sec.items || []).map((it, iIdx) => {
|
||||
{(sec.items || []).map((it, iIdx) => {
|
||||
const dropHere =
|
||||
enableItemDragReorder &&
|
||||
dropTargetPos?.sIdx === sIdx &&
|
||||
@@ -2541,6 +2647,8 @@ export default function TrainingUnitSectionsEditor({
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
{useStreamTagDropUx && pl?.phaseKind === 'parallel' && parallelPhaseOrder != null
|
||||
? (() => {
|
||||
|
||||
@@ -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()
|
||||
@@ -39,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)
|
||||
@@ -267,7 +268,7 @@ export default function MaturityModelsAdminPanel() {
|
||||
? null
|
||||
: Number(skillWikiForm.relevance_level)
|
||||
})
|
||||
const sk = await api.listSkills({ status: 'active' })
|
||||
const sk = await api.listSkillsCatalog({ status: 'active' })
|
||||
setAllSkills(sk)
|
||||
closeSkillWikiModal()
|
||||
} catch (e) {
|
||||
@@ -585,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"
|
||||
|
||||
@@ -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
|
||||
@@ -72,6 +81,7 @@ export default function SkillsCatalogAdmin() {
|
||||
status: 'active',
|
||||
sort_order: '',
|
||||
category_id: '',
|
||||
main_category_id: '',
|
||||
karate_relevance: '',
|
||||
relevance_level: ''
|
||||
})
|
||||
@@ -84,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
|
||||
}
|
||||
@@ -128,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
|
||||
@@ -179,6 +196,7 @@ export default function SkillsCatalogAdmin() {
|
||||
status: s.status || 'active',
|
||||
sort_order: s.sort_order ?? '',
|
||||
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 !== ''
|
||||
@@ -199,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) {
|
||||
@@ -238,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))
|
||||
})
|
||||
@@ -292,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,
|
||||
@@ -319,16 +339,26 @@ export default function SkillsCatalogAdmin() {
|
||||
relevance_level:
|
||||
skillForm.relevance_level === '' || skillForm.relevance_level == null
|
||||
? null
|
||||
: Number(skillForm.relevance_level)
|
||||
})
|
||||
: 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()
|
||||
}
|
||||
@@ -347,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 () => {
|
||||
@@ -367,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)
|
||||
})
|
||||
@@ -429,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 ? (
|
||||
@@ -455,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
|
||||
@@ -534,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
|
||||
@@ -617,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={
|
||||
@@ -897,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"
|
||||
|
||||
@@ -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
@@ -1,5 +1,6 @@
|
||||
import React from 'react'
|
||||
import { activeClubMemberships } from '../../utils/activeClub'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
import MultiSelectCombo from '../MultiSelectCombo'
|
||||
|
||||
/**
|
||||
@@ -83,7 +84,7 @@ export default function ExerciseListBulkModal({
|
||||
Primärzuordnung.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<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}>
|
||||
|
||||
@@ -5,6 +5,7 @@ export default function ExerciseListBulkToolbar({
|
||||
bulkMaxIds,
|
||||
onClearSelection,
|
||||
onOpenBulkModal,
|
||||
onOpenSaveModuleModal,
|
||||
}) {
|
||||
if (selectedCount < 1) return null
|
||||
|
||||
@@ -14,6 +15,9 @@ export default function ExerciseListBulkToolbar({
|
||||
<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>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import React, { useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import NavStateLink from '../NavStateLink'
|
||||
import {
|
||||
buildExercisesListReturnContext,
|
||||
navigateWithAppReturn,
|
||||
} from '../../utils/navReturnContext'
|
||||
import {
|
||||
Eye,
|
||||
Pencil,
|
||||
@@ -11,9 +16,12 @@ import {
|
||||
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' }
|
||||
@@ -48,6 +56,52 @@ function exerciseCardClassName(exercise, userId) {
|
||||
.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'
|
||||
@@ -65,7 +119,7 @@ function ExerciseCardScopeStatus({ exercise }) {
|
||||
<div
|
||||
className="exercise-card__meta-compact"
|
||||
title={tip}
|
||||
aria-label={`Sichtbarkeit: ${visLabel}. Status: ${stLabel}.`}
|
||||
aria-label={`${EXERCISE_VISIBILITY_FIELD_LABEL}: ${visLabel}. Status: ${stLabel}.`}
|
||||
>
|
||||
<span className="exercise-card__meta-glyph">
|
||||
<VisIcon size={15} strokeWidth={2} aria-hidden />
|
||||
@@ -83,23 +137,75 @@ function ExerciseCardScopeStatus({ exercise }) {
|
||||
/**
|
||||
* 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 }) {
|
||||
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)}>
|
||||
<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.id)}
|
||||
aria-label={`„${(exercise.title || 'Übung').replace(/"/g, '')}“ auswählen`}
|
||||
onChange={() => toggleSelect(exercise)}
|
||||
aria-label={`„${titleText}“ auswählen`}
|
||||
className="exercise-card-layout__check"
|
||||
/>
|
||||
<div className="exercise-card__body exercise-card-body-flex">
|
||||
<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">
|
||||
<Link to={`/exercises/${exercise.id}`}>{exercise.title}</Link>
|
||||
<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) => (
|
||||
@@ -138,24 +244,29 @@ export default function ExerciseListCard({ exercise, user, selectedIds, toggleSe
|
||||
</div>
|
||||
</div>
|
||||
<div className="exercise-card__footer">
|
||||
<ExerciseCardScopeStatus exercise={exercise} />
|
||||
<div className="exercise-card__footer-meta">
|
||||
<ExerciseCardScopeStatus exercise={exercise} />
|
||||
<ExerciseCardContentStats exercise={exercise} />
|
||||
</div>
|
||||
<div className="exercise-card__actions exercise-card__actions--icons">
|
||||
<Link
|
||||
to={`/exercises/${exercise.id}`}
|
||||
<button
|
||||
type="button"
|
||||
className="exercise-card__icon-btn"
|
||||
title="Ansehen"
|
||||
aria-label={`„${(exercise.title || 'Übung').replace(/"/g, '')}“ ansehen`}
|
||||
title="Vorschau"
|
||||
aria-label={`„${titleText}“ in Vorschau anzeigen`}
|
||||
onClick={() => onPeek?.(exercise)}
|
||||
>
|
||||
<Eye size={18} strokeWidth={2} aria-hidden />
|
||||
</Link>
|
||||
<Link
|
||||
</button>
|
||||
<NavStateLink
|
||||
to={`/exercises/${exercise.id}/edit`}
|
||||
returnContext={listReturn}
|
||||
className="exercise-card__icon-btn"
|
||||
title="Bearbeiten"
|
||||
aria-label={`„${(exercise.title || 'Übung').replace(/"/g, '')}“ bearbeiten`}
|
||||
aria-label={`„${titleText}“ bearbeiten`}
|
||||
>
|
||||
<Pencil size={18} strokeWidth={2} aria-hidden />
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
{canUserRequestExerciseDelete(user, exercise) ? (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react'
|
||||
import { SKILL_LEVEL_OPTIONS } from '../../constants/skillLevels'
|
||||
import MultiSelectCombo from '../MultiSelectCombo'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../../constants/exerciseGovernanceLabels'
|
||||
import SkillTreeMultiSelect from '../SkillTreeMultiSelect'
|
||||
import ExerciseFocusRulePicker from '../ExerciseFocusRulePicker'
|
||||
import CatalogRulePicker from '../CatalogRulePicker'
|
||||
|
||||
@@ -18,7 +19,7 @@ export default function ExerciseListFilterModal({
|
||||
styleOptions,
|
||||
trainingTypeOptions,
|
||||
targetGroupOptions,
|
||||
skillOptions,
|
||||
skillsCatalog = [],
|
||||
visibilityOptions,
|
||||
statusOptions,
|
||||
savingExercisePrefs,
|
||||
@@ -56,7 +57,7 @@ export default function ExerciseListFilterModal({
|
||||
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“: Sichtbarkeit / Status mit „+“ = eine davon (ODER); „−“ blendet aus.
|
||||
„Freigabe“: Freigabelevel / Status mit „+“ = eine davon (ODER); „−“ blendet aus.
|
||||
</p>
|
||||
|
||||
<section className="exercise-filter-section">
|
||||
@@ -103,10 +104,10 @@ export default function ExerciseListFilterModal({
|
||||
<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>
|
||||
<MultiSelectCombo
|
||||
<SkillTreeMultiSelect
|
||||
value={filters.skill_ids}
|
||||
onChange={(v) => setFilters({ ...filters, skill_ids: v })}
|
||||
options={skillOptions}
|
||||
skills={skillsCatalog}
|
||||
placeholder="Fähigkeit suchen …"
|
||||
/>
|
||||
<p className="exercise-filter-skill-hint">
|
||||
@@ -155,7 +156,7 @@ export default function ExerciseListFilterModal({
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Ausblenden / Liste</h4>
|
||||
<p className="muted" style={{ marginTop: 0, marginBottom: '12px', fontSize: '13px' }}>
|
||||
Sichtbarkeit und Status steuern Sie unter „Freigabe“ mit + und −. Hier nur globale Listen-Optionen.
|
||||
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
|
||||
@@ -199,12 +200,12 @@ export default function ExerciseListFilterModal({
|
||||
</p>
|
||||
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--two exercise-filters-modal-grid--catalog">
|
||||
<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((prev) => ({ ...prev, ...patch }))}
|
||||
/>
|
||||
<CatalogRulePicker
|
||||
|
||||
@@ -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 }
|
||||
@@ -1,5 +1,4 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef, lazy, Suspense } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../../utils/api'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import { activeClubMemberships, getTenantClubDependencyKey } from '../../utils/activeClub'
|
||||
@@ -9,8 +8,19 @@ 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,
|
||||
@@ -51,7 +61,7 @@ function ExercisesListPageRoot() {
|
||||
const [pageTab, setPageTab] = useState('list')
|
||||
const prefsAppliedRef = useRef(false)
|
||||
|
||||
const [selectedIds, setSelectedIds] = useState(() => new Set())
|
||||
const [selectedEntries, setSelectedEntries] = useState(() => [])
|
||||
const [bulkModalOpen, setBulkModalOpen] = useState(false)
|
||||
const [bulkVisibility, setBulkVisibility] = useState('')
|
||||
const [bulkStatus, setBulkStatus] = useState('')
|
||||
@@ -66,12 +76,22 @@ function ExercisesListPageRoot() {
|
||||
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)
|
||||
setFilters(applyDashboardExerciseListUrl(merged))
|
||||
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)
|
||||
@@ -81,6 +101,17 @@ function ExercisesListPageRoot() {
|
||||
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])
|
||||
@@ -120,9 +151,20 @@ function ExercisesListPageRoot() {
|
||||
loadMore,
|
||||
} = useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey })
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedIds(new Set())
|
||||
}, [queryBase])
|
||||
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(
|
||||
() =>
|
||||
@@ -145,7 +187,11 @@ function ExercisesListPageRoot() {
|
||||
[catalogs.targetGroups]
|
||||
)
|
||||
const skillOptions = useMemo(
|
||||
() => catalogs.skills.map((s) => ({ id: s.id, label: s.name || String(s.id) })),
|
||||
() =>
|
||||
catalogs.skills.map((s) => ({
|
||||
id: s.id,
|
||||
label: skillCatalogPathLabel(s) || s.name || String(s.id),
|
||||
})),
|
||||
[catalogs.skills]
|
||||
)
|
||||
const visibilityOptions = useMemo(
|
||||
@@ -215,38 +261,49 @@ function ExercisesListPageRoot() {
|
||||
? Number(user.active_club_id)
|
||||
: null
|
||||
|
||||
const toggleSelect = useCallback((id) => {
|
||||
setSelectedIds((prev) => {
|
||||
const n = new Set(prev)
|
||||
const nid = Number(id)
|
||||
if (Number.isNaN(nid)) return prev
|
||||
if (n.has(nid)) n.delete(nid)
|
||||
else n.add(nid)
|
||||
return n
|
||||
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(() => setSelectedIds(new Set()), [])
|
||||
const clearSelection = useCallback(() => setSelectedEntries([]), [])
|
||||
|
||||
const toggleSelectAllPage = useCallback(() => {
|
||||
setSelectedIds((prev) => {
|
||||
const n = new Set(prev)
|
||||
const allSel =
|
||||
exercises.length > 0 && exercises.every((e) => n.has(Number(e.id)))
|
||||
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) {
|
||||
exercises.forEach((e) => n.delete(Number(e.id)))
|
||||
} else {
|
||||
exercises.forEach((e) => n.add(Number(e.id)))
|
||||
const remove = new Set(pageIds)
|
||||
return prev.filter((e) => !remove.has(Number(e.id)))
|
||||
}
|
||||
return n
|
||||
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
|
||||
})
|
||||
}, [exercises])
|
||||
}, [filterResultExercises])
|
||||
|
||||
const allOnPageSelected = useMemo(
|
||||
() => exercises.length > 0 && exercises.every((e) => selectedIds.has(Number(e.id))),
|
||||
[exercises, selectedIds]
|
||||
() =>
|
||||
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 —' },
|
||||
@@ -262,6 +319,7 @@ function ExercisesListPageRoot() {
|
||||
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)
|
||||
}
|
||||
@@ -315,7 +373,7 @@ function ExercisesListPageRoot() {
|
||||
bulkPatchTargetGroups
|
||||
if (!bulkVisibility && !bulkStatus && !anyRelationPatch) {
|
||||
alert(
|
||||
'Bitte mindestens eine Änderung wählen (Sichtbarkeit, Status oder eine der Zuordnungen mit gesetztem Häkchen „ersetzen“).'
|
||||
'Bitte mindestens eine Änderung wählen (Freigabelevel, Status oder eine der Zuordnungen mit gesetztem Häkchen „ersetzen“).'
|
||||
)
|
||||
return
|
||||
}
|
||||
@@ -428,9 +486,13 @@ function ExercisesListPageRoot() {
|
||||
<div className="exercises-page__header">
|
||||
<h1 className="page-title exercises-page__title">Übungen</h1>
|
||||
{pageTab === 'list' ? (
|
||||
<Link to="/exercises/new" className="btn btn-primary">
|
||||
<NavStateLink
|
||||
to="/exercises/new"
|
||||
returnContext={exercisesModuleReturnContext}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
+ Neu
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
) : (
|
||||
<span aria-hidden="true" />
|
||||
)}
|
||||
@@ -480,6 +542,7 @@ function ExercisesListPageRoot() {
|
||||
bulkMaxIds={BULK_MAX_IDS}
|
||||
onClearSelection={clearSelection}
|
||||
onOpenBulkModal={openBulkModal}
|
||||
onOpenSaveModuleModal={() => setSaveModuleModalOpen(true)}
|
||||
/>
|
||||
|
||||
<ExerciseListFilterModal
|
||||
@@ -491,7 +554,7 @@ function ExercisesListPageRoot() {
|
||||
styleOptions={styleOptions}
|
||||
trainingTypeOptions={trainingTypeOptions}
|
||||
targetGroupOptions={targetGroupOptions}
|
||||
skillOptions={skillOptions}
|
||||
skillsCatalog={catalogs.skills}
|
||||
visibilityOptions={visibilityOptions}
|
||||
statusOptions={statusOptions}
|
||||
savingExercisePrefs={savingExercisePrefs}
|
||||
@@ -540,44 +603,96 @@ function ExercisesListPageRoot() {
|
||||
setBulkTargetGroupIds={setBulkTargetGroupIds}
|
||||
/>
|
||||
|
||||
{listFetching && exercises.length === 0 ? (
|
||||
<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 ? (
|
||||
) : exercises.length === 0 && selectedEntries.length === 0 ? (
|
||||
<div className="card">
|
||||
<p className="exercises-empty-text">Keine Übungen gefunden.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{listFetching ? (
|
||||
<p className="exercises-meta-line exercises-meta-line--muted">Aktualisiere Treffer…</p>
|
||||
{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}
|
||||
<p className="exercises-meta-line">
|
||||
{exercises.length} angezeigt
|
||||
{hasMore ? ' · es gibt weitere Einträge' : ''}
|
||||
</p>
|
||||
<div className="exercises-list-grid" data-testid="exercises-list-grid">
|
||||
{exercises.map((exercise) => (
|
||||
<ExerciseListCard
|
||||
key={exercise.id}
|
||||
exercise={exercise}
|
||||
user={user}
|
||||
selectedIds={selectedIds}
|
||||
toggleSelect={toggleSelect}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{hasMore && (
|
||||
<div className="exercises-load-more">
|
||||
<button type="button" className="btn btn-secondary" disabled={loadingMore} onClick={loadMore}>
|
||||
{loadingMore ? 'Laden…' : 'Mehr laden'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
collectDistinctSessionDurationsMinutes,
|
||||
EMPTY_FRAMEWORK_IMPORT_FILTERS,
|
||||
filterFrameworkPrograms,
|
||||
hasActiveFrameworkImportFilters,
|
||||
} from '../../utils/frameworkProgramListHelpers'
|
||||
import { buildPlanningArtifactFilterChips } from '../../utils/planningArtifactFilterChips'
|
||||
import PlanningArtifactFilterModal from './PlanningArtifactFilterModal'
|
||||
|
||||
/**
|
||||
* Filter-Leiste für Rahmenprogramm-Liste und Import-Dialog (UX wie Übungsliste).
|
||||
*/
|
||||
export default function FrameworkProgramsFilterBlock({
|
||||
programs = [],
|
||||
filters,
|
||||
onFiltersChange,
|
||||
catalogFocusAreas = [],
|
||||
catalogTrainingTypes = [],
|
||||
catalogTargetGroups = [],
|
||||
catalogSkills = [],
|
||||
skillSummaries = null,
|
||||
disabled = false,
|
||||
durationRadioName = 'fw-duration-mode',
|
||||
showHint = true,
|
||||
className = '',
|
||||
searchPlaceholder = 'Suche (Titel, Ziele, Katalog) …',
|
||||
filterModalTitle = 'Rahmenprogramme filtern',
|
||||
resultLabel = 'Rahmenprogramm',
|
||||
}) {
|
||||
const [filterModalOpen, setFilterModalOpen] = useState(false)
|
||||
|
||||
const matchCount = useMemo(
|
||||
() => filterFrameworkPrograms(programs, filters, skillSummaries).length,
|
||||
[programs, filters, skillSummaries]
|
||||
)
|
||||
|
||||
const totalCount = (programs || []).length
|
||||
const filterActive = hasActiveFrameworkImportFilters(filters)
|
||||
|
||||
const filterChips = useMemo(
|
||||
() =>
|
||||
buildPlanningArtifactFilterChips({
|
||||
filters,
|
||||
setFilters: onFiltersChange,
|
||||
catalogs: {
|
||||
focusAreas: catalogFocusAreas,
|
||||
trainingTypes: catalogTrainingTypes,
|
||||
targetGroups: catalogTargetGroups,
|
||||
skills: catalogSkills,
|
||||
},
|
||||
artifactType: 'framework_program',
|
||||
emptyFilters: EMPTY_FRAMEWORK_IMPORT_FILTERS,
|
||||
}),
|
||||
[
|
||||
filters,
|
||||
onFiltersChange,
|
||||
catalogFocusAreas,
|
||||
catalogTrainingTypes,
|
||||
catalogTargetGroups,
|
||||
catalogSkills,
|
||||
]
|
||||
)
|
||||
|
||||
const clearFilters = () => onFiltersChange({ ...EMPTY_FRAMEWORK_IMPORT_FILTERS })
|
||||
|
||||
useEffect(() => {
|
||||
if (!filterModalOpen) return undefined
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') setFilterModalOpen(false)
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [filterModalOpen])
|
||||
|
||||
const resultPlural = totalCount === 1 ? resultLabel : `${resultLabel}e`
|
||||
|
||||
return (
|
||||
<div className={'fw-prog-filter-block planning-list-filter-bar' + (className ? ` ${className}` : '')}>
|
||||
<div className="card exercise-search-bar planning-list-filter-bar__search">
|
||||
<label className="form-label">Suche</label>
|
||||
<input
|
||||
type="search"
|
||||
className="form-input exercise-search-bar__primary"
|
||||
value={filters.query}
|
||||
onChange={(e) => onFiltersChange((prev) => ({ ...prev, query: e.target.value }))}
|
||||
placeholder={searchPlaceholder}
|
||||
disabled={disabled}
|
||||
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-filter-trigger"
|
||||
disabled={disabled}
|
||||
onClick={() => setFilterModalOpen(true)}
|
||||
>
|
||||
Filter
|
||||
{filterChips.length > 0 ? (
|
||||
<span className="exercise-filter-badge" aria-hidden>
|
||||
{filterChips.length}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
{filterChips.length > 0 ? (
|
||||
<button type="button" className="btn" disabled={disabled} onClick={clearFilters}>
|
||||
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"
|
||||
disabled={disabled}
|
||||
onClick={() => c.onRemove()}
|
||||
>
|
||||
<span className="exercise-filter-chip__text">{c.label}</span>
|
||||
<span className="exercise-filter-chip__x" aria-hidden>
|
||||
×
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{showHint ? (
|
||||
<p className="exercise-search-hint form-sub" style={{ marginBottom: 0 }}>
|
||||
Fachliche Filter über „Filter“ — zwischen Feldern UND. Fähigkeiten vergleichen nur unter
|
||||
Rahmenprogrammen.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="fw-import-results-bar">
|
||||
<div className="fw-import-results-bar__count">
|
||||
<strong className="fw-import-results-bar__num">{matchCount}</strong>
|
||||
<span>
|
||||
{' '}
|
||||
von {totalCount} {resultPlural}
|
||||
</span>
|
||||
{matchCount === 0 && totalCount > 0 ? (
|
||||
<span className="fw-import-results-bar__warn"> — kein Treffer</span>
|
||||
) : null}
|
||||
</div>
|
||||
{filterActive ? (
|
||||
<div className="fw-import-results-bar__actions">
|
||||
<span className="fw-import-filter-badge">Filter aktiv</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<PlanningArtifactFilterModal
|
||||
open={filterModalOpen}
|
||||
onClose={() => setFilterModalOpen(false)}
|
||||
filters={filters}
|
||||
onFiltersChange={onFiltersChange}
|
||||
artifactType="framework_program"
|
||||
programs={programs}
|
||||
catalogFocusAreas={catalogFocusAreas}
|
||||
catalogTrainingTypes={catalogTrainingTypes}
|
||||
catalogTargetGroups={catalogTargetGroups}
|
||||
catalogSkills={catalogSkills}
|
||||
durationRadioName={durationRadioName}
|
||||
onResetAll={clearFilters}
|
||||
disabled={disabled}
|
||||
title={filterModalTitle}
|
||||
showCatalogFilters
|
||||
showDurationFilters
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { formatPlanTemplateStructurePreview } from '../../utils/trainingUnitSectionsForm'
|
||||
|
||||
export default function PlanTemplateStructurePreview({ sections, compact = false }) {
|
||||
const preview = useMemo(() => formatPlanTemplateStructurePreview(sections), [sections])
|
||||
|
||||
if (preview.isEmpty) {
|
||||
return (
|
||||
<p style={{ margin: 0, fontSize: compact ? '0.82rem' : '0.88rem', color: 'var(--text3)' }}>
|
||||
Noch keine Abschnitte definiert.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul
|
||||
className="plan-template-structure-preview"
|
||||
style={{
|
||||
listStyle: 'none',
|
||||
margin: compact ? '0.35rem 0 0' : '0.5rem 0 0',
|
||||
padding: 0,
|
||||
display: 'grid',
|
||||
gap: compact ? '0.35rem' : '0.45rem',
|
||||
}}
|
||||
>
|
||||
{preview.lines.map((line, idx) => (
|
||||
<li
|
||||
key={`${line.kind}-${line.label}-${idx}`}
|
||||
style={{
|
||||
fontSize: compact ? '0.82rem' : '0.88rem',
|
||||
lineHeight: 1.45,
|
||||
color: 'var(--text2)',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
fontSize: '0.72rem',
|
||||
fontWeight: 700,
|
||||
letterSpacing: '0.02em',
|
||||
textTransform: 'uppercase',
|
||||
color: line.kind === 'parallel' ? 'var(--accent-dark)' : 'var(--text3)',
|
||||
marginRight: '0.45rem',
|
||||
}}
|
||||
>
|
||||
{line.label}
|
||||
</span>
|
||||
<span style={{ color: 'var(--text1)' }}>{line.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { collectDistinctSessionDurationsMinutes } from '../../utils/frameworkProgramListHelpers'
|
||||
import { formatDurationDisplay } from '../../utils/trainingDurationUtils'
|
||||
import PlanningSkillFilterSection from './PlanningSkillFilterSection'
|
||||
|
||||
/**
|
||||
* Filter-Modal für Rahmenprogramme / Trainingsmodule (UX wie ExerciseListFilterModal).
|
||||
*/
|
||||
export default function PlanningArtifactFilterModal({
|
||||
open,
|
||||
onClose,
|
||||
filters,
|
||||
onFiltersChange,
|
||||
artifactType = 'framework_program',
|
||||
programs = [],
|
||||
catalogFocusAreas = [],
|
||||
catalogTrainingTypes = [],
|
||||
catalogTargetGroups = [],
|
||||
catalogSkills = [],
|
||||
durationRadioName = 'planning-duration-mode',
|
||||
onResetAll,
|
||||
disabled = false,
|
||||
showCatalogFilters = true,
|
||||
showDurationFilters = true,
|
||||
title = 'Filtern',
|
||||
}) {
|
||||
const distinctDurations = useMemo(
|
||||
() => (showDurationFilters ? collectDistinctSessionDurationsMinutes(programs) : []),
|
||||
[programs, showDurationFilters]
|
||||
)
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const updateFilter = (patch) => onFiltersChange((prev) => ({ ...prev, ...patch }))
|
||||
|
||||
const toggleId = (key, id) => {
|
||||
const s = String(id)
|
||||
onFiltersChange((prev) => {
|
||||
const cur = prev[key] || []
|
||||
const next = cur.includes(s) ? cur.filter((x) => x !== s) : [...cur, s]
|
||||
return { ...prev, [key]: next }
|
||||
})
|
||||
}
|
||||
|
||||
const artifactLabel =
|
||||
artifactType === 'training_module'
|
||||
? 'Trainingsmodule'
|
||||
: artifactType === 'framework_program'
|
||||
? 'Rahmenprogramme'
|
||||
: 'Einträge'
|
||||
|
||||
return (
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-sheet exercise-filter-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="planning-filter-modal-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="planning-filter-modal-title" className="admin-modal-sheet__title">
|
||||
{title}
|
||||
</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>. Mehrere Katalog-Werte innerhalb eines Feldes
|
||||
bedeuten <strong>ODER</strong>. Fähigkeiten filtern nach Trainingsgewicht — nur unter sichtbaren{' '}
|
||||
{artifactLabel}.
|
||||
</p>
|
||||
|
||||
{showCatalogFilters ? (
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Katalog</h4>
|
||||
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--catalog">
|
||||
{catalogFocusAreas.length > 0 ? (
|
||||
<div className="fw-import-catalog-block">
|
||||
<span className="form-label">Fokusbereich</span>
|
||||
<div className="framework-catalog-checkgrid">
|
||||
{catalogFocusAreas.map((fa) => (
|
||||
<label key={fa.id} className="framework-catalog-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(filters.focusAreaIds || []).includes(String(fa.id))}
|
||||
onChange={() => toggleId('focusAreaIds', fa.id)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span>{fa.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{catalogTrainingTypes.length > 0 ? (
|
||||
<div className="fw-import-catalog-block">
|
||||
<span className="form-label">Trainingsart</span>
|
||||
<div className="framework-catalog-checkgrid">
|
||||
{catalogTrainingTypes.map((t) => (
|
||||
<label key={t.id} className="framework-catalog-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(filters.trainingTypeIds || []).includes(String(t.id))}
|
||||
onChange={() => toggleId('trainingTypeIds', t.id)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span>{t.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{catalogTargetGroups.length > 0 ? (
|
||||
<div className="fw-import-catalog-block">
|
||||
<span className="form-label">Zielgruppe</span>
|
||||
<div className="framework-catalog-checkgrid">
|
||||
{catalogTargetGroups.map((tg) => (
|
||||
<label key={tg.id} className="framework-catalog-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(filters.targetGroupIds || []).includes(String(tg.id))}
|
||||
onChange={() => toggleId('targetGroupIds', tg.id)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span>{tg.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{showDurationFilters ? (
|
||||
<section className="exercise-filter-section">
|
||||
<h4 className="exercise-filter-section-title">Session-Dauer</h4>
|
||||
<fieldset className="fw-import-duration-fieldset" style={{ border: 0, padding: 0, margin: 0 }}>
|
||||
<div className="fw-import-duration-mode" role="radiogroup" aria-label="Dauer-Filtermodus">
|
||||
{[
|
||||
{ id: 'any', label: 'Alle' },
|
||||
{ id: 'range', label: 'Zeitspanne' },
|
||||
{ id: 'preset', label: 'Vorhandene Zeiten' },
|
||||
].map((opt) => (
|
||||
<label key={opt.id} className="fw-import-duration-mode__opt">
|
||||
<input
|
||||
type="radio"
|
||||
name={durationRadioName}
|
||||
checked={filters.durationMode === opt.id}
|
||||
disabled={disabled || (opt.id === 'preset' && distinctDurations.length === 0)}
|
||||
onChange={() =>
|
||||
updateFilter({
|
||||
durationMode: opt.id,
|
||||
...(opt.id === 'any'
|
||||
? { durationRangeFrom: '', durationRangeTo: '', durationPresetMin: null }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>{opt.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{filters.durationMode === 'range' ? (
|
||||
<div className="responsive-grid-2 fw-import-duration-range" style={{ marginTop: 10 }}>
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label">Von (Minuten)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
className="form-input"
|
||||
value={filters.durationRangeFrom}
|
||||
onChange={(e) =>
|
||||
updateFilter({ durationMode: 'range', durationRangeFrom: e.target.value })
|
||||
}
|
||||
placeholder="z. B. 60"
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label">Bis (Minuten)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
className="form-input"
|
||||
value={filters.durationRangeTo}
|
||||
onChange={(e) =>
|
||||
updateFilter({ durationMode: 'range', durationRangeTo: e.target.value })
|
||||
}
|
||||
placeholder="z. B. 90"
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{filters.durationMode === 'preset' ? (
|
||||
distinctDurations.length === 0 ? (
|
||||
<p className="form-sub" style={{ margin: '8px 0 0' }}>
|
||||
Noch keine Session-Dauern hinterlegt.
|
||||
</p>
|
||||
) : (
|
||||
<div className="fw-import-duration-presets" style={{ marginTop: 10 }}>
|
||||
{distinctDurations.map((min) => {
|
||||
const on = filters.durationPresetMin === min
|
||||
return (
|
||||
<button
|
||||
key={min}
|
||||
type="button"
|
||||
className={
|
||||
'btn framework-ctrl framework-ctrl--xs' +
|
||||
(on ? ' fw-import-duration-preset--on' : ' btn-secondary')
|
||||
}
|
||||
disabled={disabled}
|
||||
onClick={() =>
|
||||
updateFilter({
|
||||
durationMode: 'preset',
|
||||
durationPresetMin: on ? null : min,
|
||||
durationRangeFrom: '',
|
||||
durationRangeTo: '',
|
||||
})
|
||||
}
|
||||
>
|
||||
{formatDurationDisplay(min)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
</fieldset>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{catalogSkills.length > 0 ? (
|
||||
<section className="exercise-filter-section exercise-filter-section--last">
|
||||
<h4 className="exercise-filter-section-title">Fähigkeit und Trainingsgewicht</h4>
|
||||
<PlanningSkillFilterSection
|
||||
artifactType={artifactType}
|
||||
skillIds={filters.skillIds || []}
|
||||
onSkillIdsChange={(v) => updateFilter({ skillIds: v })}
|
||||
skillMinClubPercent={filters.skillMinClubPercent ?? 0}
|
||||
onSkillMinClubPercentChange={(v) => updateFilter({ skillMinClubPercent: v })}
|
||||
skillSort={filters.skillSort || 'title'}
|
||||
onSkillSortChange={(v) => updateFilter({ skillSort: v })}
|
||||
skillsCatalog={catalogSkills}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="exercise-filter-modal__footer">
|
||||
<button type="button" className="btn" onClick={onResetAll} disabled={disabled}>
|
||||
Alle Filter zurücksetzen
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={onClose}>
|
||||
Fertig
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
|
||||
const ITEMS = [
|
||||
{ to: '/planning', label: 'Trainingsplanung', end: true },
|
||||
{ to: '/planning/framework-programs', label: 'Rahmenprogramme' },
|
||||
{ to: '/planning/training-modules', label: 'Trainingsmodule' },
|
||||
{ to: '/planning/plan-templates', label: 'Vorlagen' },
|
||||
]
|
||||
|
||||
/** Oberste Planungs-Navigation (Chip-Register). */
|
||||
export default function PlanningRouteNav() {
|
||||
return (
|
||||
<nav
|
||||
className="admin-page-subtabs page-section-nav page-section-nav--wrap planning-route-nav"
|
||||
aria-label="Planung"
|
||||
>
|
||||
{ITEMS.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.end}
|
||||
className={({ isActive }) =>
|
||||
'admin-page-subtabs__btn' + (isActive ? ' admin-page-subtabs__btn--active' : '')
|
||||
}
|
||||
>
|
||||
<span>{item.label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import React from 'react'
|
||||
import SkillTreeMultiSelect from '../SkillTreeMultiSelect'
|
||||
import { peerCorpusCountLabel } from '../../utils/skillProfileListHelpers'
|
||||
|
||||
/**
|
||||
* Fähigkeiten-Filter für Planungsartefakte (Rahmenprogramme, Module).
|
||||
* Semantik wie Übungsliste (SkillTreeMultiSelect), aber mit Peer-Prozent statt Stufen.
|
||||
*/
|
||||
export default function PlanningSkillFilterSection({
|
||||
artifactType = 'framework_program',
|
||||
skillIds = [],
|
||||
onSkillIdsChange,
|
||||
skillMinClubPercent = 0,
|
||||
onSkillMinClubPercentChange,
|
||||
skillSort = 'title',
|
||||
onSkillSortChange,
|
||||
skillsCatalog = [],
|
||||
disabled = false,
|
||||
}) {
|
||||
const peerLabel = peerCorpusCountLabel(artifactType)
|
||||
const peerMaxLabel =
|
||||
artifactType === 'framework_program' ? 'Rahmenprogramm-Maximum' : `${peerLabel}-Maximum`
|
||||
|
||||
return (
|
||||
<div className="exercise-filter-skill-block">
|
||||
<label className="form-label">Fähigkeit</label>
|
||||
<SkillTreeMultiSelect
|
||||
value={skillIds}
|
||||
onChange={onSkillIdsChange}
|
||||
skills={skillsCatalog}
|
||||
placeholder="Fähigkeit suchen …"
|
||||
/>
|
||||
<p className="exercise-filter-skill-hint">
|
||||
Trainingsgewicht relativ zum stärksten sichtbaren Eintrag unter {peerLabel} — nicht gemischt mit
|
||||
anderen Planungs-Artefakttypen.
|
||||
</p>
|
||||
{(skillIds || []).length > 0 ? (
|
||||
<div className="fw-import-skill-options" style={{ marginTop: 10 }}>
|
||||
<div className="form-row" style={{ marginBottom: 8 }}>
|
||||
<label className="form-label">Mindest-Anteil am {peerMaxLabel}</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={String(skillMinClubPercent ?? 0)}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onSkillMinClubPercentChange(Number(e.target.value) || 0)}
|
||||
>
|
||||
<option value="0">Kein Minimum (nur markieren)</option>
|
||||
<option value="25">mind. 25%</option>
|
||||
<option value="50">mind. 50%</option>
|
||||
<option value="75">mind. 75%</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label">Sortierung</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={skillSort || 'title'}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onSkillSortChange(e.target.value)}
|
||||
>
|
||||
<option value="title">Bibliotheks-Reihenfolge</option>
|
||||
<option value="skill_strength">Stärkste gewählte Fähigkeit zuerst</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
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 } from '../../utils/activeClub'
|
||||
import { collectExercisePlacementsForModule } from '../../utils/trainingPlanModuleFromUnit'
|
||||
import { navigateWithAppReturn } from '../../utils/navReturnContext'
|
||||
|
||||
/**
|
||||
* Erstellt ein Trainingsmodul aus den Übungen einer gespeicherten Trainingseinheit (Mehrfachauswahl).
|
||||
*/
|
||||
export default function SaveExercisesAsModuleModal({
|
||||
open,
|
||||
onClose,
|
||||
unitId,
|
||||
planningModalClubId,
|
||||
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('')
|
||||
const [unitLabel, setUnitLabel] = useState('')
|
||||
const [candidates, setCandidates] = useState([])
|
||||
const [selected, setSelected] = useState(() => [])
|
||||
|
||||
const [title, setTitle] = useState('')
|
||||
const [visibility, setVisibility] = useState('club')
|
||||
const [clubId, setClubId] = useState('')
|
||||
|
||||
const resetLocal = useCallback(() => {
|
||||
setLoadErr('')
|
||||
setUnitLabel('')
|
||||
setCandidates([])
|
||||
setSelected([])
|
||||
setTitle('')
|
||||
setVisibility('club')
|
||||
setClubId('')
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !unitId) {
|
||||
resetLocal()
|
||||
return
|
||||
}
|
||||
if (planningModalClubId != null && planningModalClubId !== '') {
|
||||
setClubId(String(planningModalClubId))
|
||||
} else if (memberClubs.length === 1) {
|
||||
setClubId(String(memberClubs[0].id))
|
||||
}
|
||||
setLoading(true)
|
||||
setLoadErr('')
|
||||
api
|
||||
.getTrainingUnit(unitId)
|
||||
.then((u) => {
|
||||
const dateStr = (u.planned_date || '').trim() || 'Training'
|
||||
setUnitLabel(dateStr)
|
||||
setTitle(`Modul · ${dateStr}`)
|
||||
const c = collectExercisePlacementsForModule(u)
|
||||
setCandidates(c)
|
||||
setSelected(c.map(() => true))
|
||||
})
|
||||
.catch((e) => {
|
||||
setLoadErr(e.message || 'Einheit konnte nicht geladen werden')
|
||||
setCandidates([])
|
||||
setSelected([])
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [open, unitId, planningModalClubId, memberClubs.length, resetLocal])
|
||||
|
||||
const toggleOne = (idx) => {
|
||||
setSelected((prev) => {
|
||||
const next = [...prev]
|
||||
next[idx] = !next[idx]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const setAll = (on) => {
|
||||
setSelected(candidates.map(() => on))
|
||||
}
|
||||
|
||||
const selectedCount = selected.filter(Boolean).length
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
if (!unitId || submitting) return
|
||||
const itemsPayload = []
|
||||
let oi = 0
|
||||
for (let i = 0; i < candidates.length; i += 1) {
|
||||
if (!selected[i]) continue
|
||||
const c = candidates[i]
|
||||
itemsPayload.push({
|
||||
item_type: 'exercise',
|
||||
order_index: oi,
|
||||
exercise_id: c.exercise_id,
|
||||
exercise_variant_id: c.exercise_variant_id,
|
||||
planned_duration_min: c.planned_duration_min,
|
||||
notes: c.notes,
|
||||
})
|
||||
oi += 1
|
||||
}
|
||||
if (!itemsPayload.length) {
|
||||
toast.error('Mindestens eine Übung auswählen.')
|
||||
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)) {
|
||||
toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
|
||||
return
|
||||
}
|
||||
if (visibility !== 'club') cid = null
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const created = await api.createTrainingModule({
|
||||
title: tit,
|
||||
visibility,
|
||||
club_id: cid,
|
||||
items: itemsPayload,
|
||||
})
|
||||
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
|
||||
|
||||
return (
|
||||
<FormModalOverlay open={open} raised onBackdropClick={onClose}>
|
||||
<div className="card modal-panel--form modal-panel--narrow">
|
||||
<h2 className="modal-panel__title">Übungen als Trainingsmodul</h2>
|
||||
<p className="modal-panel__intro">
|
||||
Es werden die <strong>gespeicherten</strong> Übungspositionen der Einheit vom{' '}
|
||||
<strong>{unitLabel || '…'}</strong> verwendet. Speichere die Planung vorher, wenn du den aktuellen Stand
|
||||
brauchst.
|
||||
</p>
|
||||
|
||||
{loading ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Laden …</p>
|
||||
) : loadErr ? (
|
||||
<p style={{ color: 'var(--danger)' }}>{loadErr}</p>
|
||||
) : candidates.length === 0 ? (
|
||||
<p style={{ color: 'var(--text2)' }}>In dieser Einheit sind keine Übungen im Ablauf hinterlegt.</p>
|
||||
) : (
|
||||
<form id="save-module-form" className="modal-form-shell" onSubmit={handleSubmit}>
|
||||
<div className="modal-form-shell__body">
|
||||
<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. Aufwärmsequenz"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', marginBottom: '0.75rem' }}>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => setAll(true)}>
|
||||
Alle
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary framework-ctrl framework-ctrl--xs" onClick={() => setAll(false)}>
|
||||
Keine
|
||||
</button>
|
||||
<span style={{ fontSize: '0.82rem', color: 'var(--text3)', alignSelf: 'center' }}>
|
||||
{selectedCount} von {candidates.length} gewählt (Reihenfolge wie im Plan)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1rem',
|
||||
padding: '10px 12px',
|
||||
maxHeight: 'min(240px, 40vh)',
|
||||
overflowY: 'auto',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||
{candidates.map((c, idx) => (
|
||||
<li
|
||||
key={`${c.exercise_id}-${idx}`}
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
alignItems: 'flex-start',
|
||||
padding: '8px 0',
|
||||
borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!selected[idx]}
|
||||
onChange={() => toggleOne(idx)}
|
||||
style={{ marginTop: 4 }}
|
||||
/>
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{ fontWeight: 600, color: 'var(--text1)', fontSize: '0.92rem' }}>
|
||||
{c.exercise_title}
|
||||
</div>
|
||||
{c.contextLabel ? (
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginTop: 2 }}>{c.contextLabel}</div>
|
||||
) : null}
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text2)', marginTop: 2 }}>
|
||||
{c.exercise_variant_id ? `Variante #${c.exercise_variant_id}` : 'Standard-Variante'}
|
||||
{c.planned_duration_min != null && Number.isFinite(Number(c.planned_duration_min))
|
||||
? ` · ${c.planned_duration_min} Min (Plan)`
|
||||
: ''}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={visibility}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
setVisibility(v)
|
||||
if (v === 'club' && !clubId && planningModalClubId != null) {
|
||||
setClubId(String(planningModalClubId))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
|
||||
<FormActionBar
|
||||
placement="bottom"
|
||||
variant="modal"
|
||||
formId="save-module-form"
|
||||
saving={submitting}
|
||||
showSave={false}
|
||||
saveAndCloseLabel="Modul anlegen"
|
||||
saveAndCloseShortLabel="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 ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1rem' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!loading && !loadErr && candidates.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,148 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
EMPTY_TRAINING_MODULE_FILTERS,
|
||||
filterTrainingModules,
|
||||
hasActiveTrainingModuleFilters,
|
||||
} from '../../utils/trainingModuleListHelpers'
|
||||
import { buildPlanningArtifactFilterChips } from '../../utils/planningArtifactFilterChips'
|
||||
import PlanningArtifactFilterModal from './PlanningArtifactFilterModal'
|
||||
|
||||
/**
|
||||
* Filter-Leiste für Trainingsmodule (UX wie Übungsliste / Rahmenprogramme).
|
||||
*/
|
||||
export default function TrainingModulesFilterBlock({
|
||||
modules = [],
|
||||
filters,
|
||||
onFiltersChange,
|
||||
catalogSkills = [],
|
||||
skillSummaries = null,
|
||||
disabled = false,
|
||||
className = '',
|
||||
}) {
|
||||
const [filterModalOpen, setFilterModalOpen] = useState(false)
|
||||
|
||||
const matchCount = useMemo(
|
||||
() => filterTrainingModules(modules, filters, skillSummaries).length,
|
||||
[modules, filters, skillSummaries]
|
||||
)
|
||||
|
||||
const totalCount = (modules || []).length
|
||||
const filterActive = hasActiveTrainingModuleFilters(filters)
|
||||
|
||||
const filterChips = useMemo(
|
||||
() =>
|
||||
buildPlanningArtifactFilterChips({
|
||||
filters,
|
||||
setFilters: onFiltersChange,
|
||||
catalogs: { skills: catalogSkills },
|
||||
artifactType: 'training_module',
|
||||
emptyFilters: EMPTY_TRAINING_MODULE_FILTERS,
|
||||
}),
|
||||
[filters, onFiltersChange, catalogSkills]
|
||||
)
|
||||
|
||||
const clearFilters = () => onFiltersChange({ ...EMPTY_TRAINING_MODULE_FILTERS })
|
||||
|
||||
useEffect(() => {
|
||||
if (!filterModalOpen) return undefined
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') setFilterModalOpen(false)
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [filterModalOpen])
|
||||
|
||||
return (
|
||||
<div className={'planning-list-filter-bar' + (className ? ` ${className}` : '')}>
|
||||
<div className="card exercise-search-bar planning-list-filter-bar__search">
|
||||
<label className="form-label">Suche</label>
|
||||
<input
|
||||
type="search"
|
||||
className="form-input exercise-search-bar__primary"
|
||||
value={filters.query}
|
||||
onChange={(e) => onFiltersChange((prev) => ({ ...prev, query: e.target.value }))}
|
||||
placeholder="Titel oder Kurzbeschreibung …"
|
||||
disabled={disabled}
|
||||
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-filter-trigger"
|
||||
disabled={disabled}
|
||||
onClick={() => setFilterModalOpen(true)}
|
||||
>
|
||||
Filter
|
||||
{filterChips.length > 0 ? (
|
||||
<span className="exercise-filter-badge" aria-hidden>
|
||||
{filterChips.length}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
{filterChips.length > 0 ? (
|
||||
<button type="button" className="btn" disabled={disabled} onClick={clearFilters}>
|
||||
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"
|
||||
disabled={disabled}
|
||||
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 form-sub" style={{ marginBottom: 0 }}>
|
||||
Fachliche Filter über „Filter“. Fähigkeiten vergleichen nur unter sichtbaren Modulen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="fw-import-results-bar">
|
||||
<div className="fw-import-results-bar__count">
|
||||
<strong className="fw-import-results-bar__num">{matchCount}</strong>
|
||||
<span>
|
||||
{' '}
|
||||
von {totalCount} Modul{totalCount === 1 ? '' : 'en'}
|
||||
</span>
|
||||
{matchCount === 0 && totalCount > 0 ? (
|
||||
<span className="fw-import-results-bar__warn"> — kein Treffer</span>
|
||||
) : null}
|
||||
</div>
|
||||
{filterActive ? (
|
||||
<div className="fw-import-results-bar__actions">
|
||||
<span className="fw-import-filter-badge">Filter aktiv</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<PlanningArtifactFilterModal
|
||||
open={filterModalOpen}
|
||||
onClose={() => setFilterModalOpen(false)}
|
||||
filters={filters}
|
||||
onFiltersChange={onFiltersChange}
|
||||
artifactType="training_module"
|
||||
catalogSkills={catalogSkills}
|
||||
onResetAll={clearFilters}
|
||||
disabled={disabled}
|
||||
title="Trainingsmodule filtern"
|
||||
showCatalogFilters={false}
|
||||
showDurationFilters={false}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
import React from 'react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import FrameworkProgramsFilterBlock from './FrameworkProgramsFilterBlock'
|
||||
import {
|
||||
EMPTY_FRAMEWORK_IMPORT_FILTERS,
|
||||
filterFrameworkPrograms,
|
||||
frameworkProgramOptionLabel,
|
||||
frameworkSessionDurationLabel,
|
||||
} from '../../utils/frameworkProgramListHelpers'
|
||||
import { formatDurationDisplay } from '../../utils/trainingDurationUtils'
|
||||
|
||||
/**
|
||||
* Modal: geplante Einheiten aus einem Trainingsrahmenprogramm (Blueprint-Slots) erzeugen.
|
||||
@@ -6,6 +14,9 @@ import React from 'react'
|
||||
export default function TrainingPlanningFrameworkImportModal({
|
||||
open,
|
||||
frameworkProgramsList,
|
||||
catalogFocusAreas = [],
|
||||
catalogTrainingTypes = [],
|
||||
catalogTargetGroups = [],
|
||||
fwImportProgramId,
|
||||
onProgramChange,
|
||||
fwImportLoading,
|
||||
@@ -23,72 +34,103 @@ export default function TrainingPlanningFrameworkImportModal({
|
||||
onSubmit,
|
||||
onClose,
|
||||
}) {
|
||||
const [filters, setFilters] = useState(() => ({ ...EMPTY_FRAMEWORK_IMPORT_FILTERS }))
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setFilters({ ...EMPTY_FRAMEWORK_IMPORT_FILTERS })
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const filteredPrograms = useMemo(
|
||||
() => filterFrameworkPrograms(frameworkProgramsList, filters),
|
||||
[frameworkProgramsList, filters]
|
||||
)
|
||||
|
||||
const matchCount = filteredPrograms.length
|
||||
|
||||
useEffect(() => {
|
||||
if (!fwImportProgramId) return
|
||||
const stillVisible = filteredPrograms.some((p) => String(p.id) === String(fwImportProgramId))
|
||||
if (!stillVisible) onProgramChange('')
|
||||
}, [filteredPrograms, fwImportProgramId, onProgramChange])
|
||||
|
||||
const selectedProgramSummary = useMemo(() => {
|
||||
if (!fwImportProgramId) return null
|
||||
return (frameworkProgramsList || []).find((p) => String(p.id) === String(fwImportProgramId))
|
||||
}, [frameworkProgramsList, fwImportProgramId])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fw-import-modal-backdrop"
|
||||
data-testid="planning-framework-import-modal"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1010,
|
||||
padding: '1rem',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: 'clamp(14px, 3vw, 1.75rem)',
|
||||
maxWidth: 'min(620px, 100%)',
|
||||
width: '100%',
|
||||
maxHeight: '90vh',
|
||||
overflowY: 'auto',
|
||||
boxSizing: 'border-box',
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginBottom: '0.65rem' }}>Sessions aus Rahmen übernehmen</h2>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem', marginBottom: '1rem', lineHeight: 1.5 }}>
|
||||
<div className="fw-import-modal-panel">
|
||||
<h2 className="fw-import-modal-panel__title">Sessions aus Rahmen übernehmen</h2>
|
||||
<p className="fw-import-modal-panel__lead">
|
||||
Wähle ein Trainingsrahmenprogramm und eine oder mehrere Sessions. Pro Session entsteht eine{' '}
|
||||
<strong>eigene geplante Einheit</strong> in der aktuellen Gruppe (Kopie des Ablaufs). Die{' '}
|
||||
<strong>Verknüpfung zum Rahmen-Slot</strong> wird gespeichert, damit die Herkunft sichtbar bleibt.
|
||||
<strong>eigene geplante Einheit</strong> in der aktuellen Gruppe (Kopie des Ablaufs).
|
||||
</p>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label">Rahmenprogramm</label>
|
||||
<FrameworkProgramsFilterBlock
|
||||
programs={frameworkProgramsList}
|
||||
filters={filters}
|
||||
onFiltersChange={setFilters}
|
||||
catalogFocusAreas={catalogFocusAreas}
|
||||
catalogTrainingTypes={catalogTrainingTypes}
|
||||
catalogTargetGroups={catalogTargetGroups}
|
||||
disabled={fwImportSubmitting}
|
||||
durationRadioName="fw-duration-mode"
|
||||
showHint={false}
|
||||
searchPlaceholder="Rahmenprogramm suchen …"
|
||||
filterModalTitle="Rahmenprogramme filtern"
|
||||
/>
|
||||
|
||||
<div className="form-row fw-import-program-select">
|
||||
<label className="form-label">
|
||||
Rahmenprogramm
|
||||
<span className="fw-import-program-select__count">
|
||||
{' '}
|
||||
({matchCount} {matchCount === 1 ? 'Treffer' : 'Treffer'})
|
||||
</span>
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={fwImportProgramId}
|
||||
onChange={(e) => onProgramChange(e.target.value)}
|
||||
disabled={fwImportLoading || fwImportSubmitting}
|
||||
disabled={fwImportLoading || fwImportSubmitting || matchCount === 0}
|
||||
>
|
||||
<option value="">Bitte wählen…</option>
|
||||
{frameworkProgramsList.map((fp) => (
|
||||
<option value="">
|
||||
{matchCount === 0 ? 'Kein Rahmenprogramm passt zum Filter' : 'Bitte wählen…'}
|
||||
</option>
|
||||
{filteredPrograms.map((fp) => (
|
||||
<option key={fp.id} value={String(fp.id)}>
|
||||
{(fp.title || '').trim() || `Rahmen #${fp.id}`}
|
||||
{frameworkProgramOptionLabel(fp)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedProgramSummary ? (
|
||||
<p className="form-sub" style={{ marginTop: '6px' }}>
|
||||
Session-Dauer: <strong>{frameworkSessionDurationLabel(selectedProgramSummary)}</strong>
|
||||
{selectedProgramSummary.goal_titles_agg ? (
|
||||
<>
|
||||
{' '}
|
||||
· Ziele: {selectedProgramSummary.goal_titles_agg}
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{fwImportLoading ? (
|
||||
<p style={{ color: 'var(--text2)', marginTop: '1rem' }}>Laden der Sessions…</p>
|
||||
<p className="fw-import-muted">Laden der Sessions…</p>
|
||||
) : fwImportDetail?.slots?.length ? (
|
||||
<>
|
||||
<fieldset style={{ border: 'none', margin: '1rem 0', padding: 0 }}>
|
||||
<legend className="form-label" style={{ padding: 0, marginBottom: '0.5rem' }}>
|
||||
Sessions (mit Ablauf)
|
||||
</legend>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
<fieldset className="fw-import-sessions">
|
||||
<legend className="form-label">Sessions (mit Ablauf)</legend>
|
||||
<ul className="fw-import-sessions__list">
|
||||
{[...fwImportDetail.slots]
|
||||
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
|
||||
.map((slot) => {
|
||||
@@ -96,40 +138,46 @@ export default function TrainingPlanningFrameworkImportModal({
|
||||
const checked = fwImportSelectedSlots.has(slot.id)
|
||||
const label =
|
||||
(slot.title || '').trim() || `Session ${(slot.sort_order ?? 0) + 1}`
|
||||
const slotDur =
|
||||
slot.planned_duration_min != null
|
||||
? formatDurationDisplay(slot.planned_duration_min)
|
||||
: null
|
||||
return (
|
||||
<li key={slot.id} style={{ marginBottom: '10px' }}>
|
||||
<li key={slot.id} className="fw-import-sessions__item">
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
alignItems: 'flex-start',
|
||||
cursor: hasBp ? 'pointer' : 'not-allowed',
|
||||
opacity: hasBp ? 1 : 0.55,
|
||||
}}
|
||||
className={
|
||||
'fw-import-sessions__label' + (hasBp ? '' : ' fw-import-sessions__label--disabled')
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="fw-import-sessions__check"
|
||||
checked={checked}
|
||||
disabled={!hasBp || fwImportSubmitting}
|
||||
onChange={() => onToggleSlot(slot)}
|
||||
style={{ marginTop: '0.2rem', flexShrink: 0 }}
|
||||
/>
|
||||
<span style={{ flex: 1, minWidth: 0 }}>
|
||||
<strong>{label}</strong>
|
||||
<span className="fw-import-sessions__body">
|
||||
<span className="fw-import-sessions__title-row">
|
||||
<strong>{label}</strong>
|
||||
{slotDur ? (
|
||||
<span className="fw-import-sessions__dur">{slotDur}</span>
|
||||
) : (
|
||||
<span className="fw-import-sessions__dur fw-import-sessions__dur--muted">
|
||||
Dauer offen
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{!hasBp ? (
|
||||
<span style={{ display: 'block', fontSize: '0.82rem', color: 'var(--danger)' }}>
|
||||
<span className="fw-import-sessions__warn">
|
||||
Ohne Session-Ablauf — Übernahme nicht möglich.
|
||||
</span>
|
||||
) : null}
|
||||
{hasBp && checked ? (
|
||||
<span style={{ display: 'block', marginTop: '6px' }}>
|
||||
<span className="form-label" style={{ fontSize: '0.78rem' }}>
|
||||
Termin (Datum)
|
||||
</span>
|
||||
<span className="fw-import-sessions__date">
|
||||
<span className="form-label">Termin (Datum)</span>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
style={{ maxWidth: '200px', marginTop: '4px' }}
|
||||
value={fwImportSlotDates[String(slot.id)] || ''}
|
||||
onChange={(e) => onSlotDateChange(String(slot.id), e.target.value)}
|
||||
disabled={fwImportSubmitting}
|
||||
@@ -144,15 +192,7 @@ export default function TrainingPlanningFrameworkImportModal({
|
||||
</ul>
|
||||
</fieldset>
|
||||
|
||||
<div
|
||||
className="responsive-grid-3"
|
||||
style={{
|
||||
marginBottom: '0.75rem',
|
||||
padding: '12px',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: '8px',
|
||||
}}
|
||||
>
|
||||
<div className="fw-import-dates-panel responsive-grid-3">
|
||||
<div className="form-row">
|
||||
<label className="form-label">Startdatum (Vorschlag)</label>
|
||||
<input
|
||||
@@ -174,11 +214,10 @@ export default function TrainingPlanningFrameworkImportModal({
|
||||
disabled={fwImportSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ alignSelf: 'end' }}>
|
||||
<div className="form-row fw-import-dates-panel__action">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ width: '100%' }}
|
||||
disabled={fwImportSubmitting}
|
||||
onClick={onApplyDateSuggestions}
|
||||
>
|
||||
@@ -188,10 +227,10 @@ export default function TrainingPlanningFrameworkImportModal({
|
||||
</div>
|
||||
</>
|
||||
) : fwImportProgramId ? (
|
||||
<p style={{ color: 'var(--text2)', marginTop: '0.75rem' }}>Keine Sessions in diesem Programm.</p>
|
||||
<p className="fw-import-muted">Keine Sessions in diesem Programm.</p>
|
||||
) : null}
|
||||
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '1.25rem' }}>
|
||||
<div className="fw-import-modal-panel__footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,10 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import FormActionBar from '../FormActionBar'
|
||||
import FormModalOverlay from '../FormModalOverlay'
|
||||
import TrainingPlanExerciseVisibilityPanel from '../TrainingPlanExerciseVisibilityPanel'
|
||||
import TrainingUnitSectionsEditor from '../TrainingUnitSectionsEditor'
|
||||
import { activeClubMemberships } from '../../utils/activeClub'
|
||||
import { canDeleteLibraryContent } from '../../utils/libraryContentPermissions'
|
||||
import { frameworkLineageText } from '../../utils/trainingPlanningPageHelpers'
|
||||
|
||||
/**
|
||||
@@ -16,11 +17,12 @@ export default function TrainingPlanningUnitFormModal({
|
||||
updateFormField,
|
||||
setFormData,
|
||||
onSubmit,
|
||||
onSaveOnly,
|
||||
onSaveAndClose,
|
||||
onCancel,
|
||||
draftPlanTemplateId,
|
||||
onDraftTemplateSelect,
|
||||
planTemplates,
|
||||
onDeletePlanTemplate,
|
||||
clubDirectory,
|
||||
clubDirectoryForCo,
|
||||
planningModalClubId,
|
||||
@@ -29,6 +31,8 @@ export default function TrainingPlanningUnitFormModal({
|
||||
sectionsEditMode,
|
||||
setSectionsEditMode,
|
||||
onSaveAsTemplate,
|
||||
onRequestPublishToFramework,
|
||||
onRequestSaveAsModule,
|
||||
onRequestTrainingModulePick,
|
||||
onRequestExercisePick,
|
||||
onPeekExercise,
|
||||
@@ -51,42 +55,21 @@ export default function TrainingPlanningUnitFormModal({
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const formId = 'planning-unit-form'
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="planning-unit-form-modal"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
padding: '1rem',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: 'clamp(12px, 3vw, 2rem)',
|
||||
maxWidth: 'min(1100px, 100%)',
|
||||
width: '100%',
|
||||
maxHeight: '92vh',
|
||||
overflowY: 'auto',
|
||||
margin: 'max(0px, env(safe-area-inset-top, 0px)) auto',
|
||||
boxSizing: 'border-box',
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginBottom: '1rem' }}>
|
||||
<FormModalOverlay open={open} data-testid="planning-unit-form-modal" onBackdropClick={onCancel}>
|
||||
<div className="modal-panel--form">
|
||||
<h2 className="modal-panel__title">
|
||||
{editingUnit ? 'Trainingseinheit bearbeiten' : 'Neue Trainingseinheit'}
|
||||
</h2>
|
||||
|
||||
<form
|
||||
id={formId}
|
||||
className="modal-form-shell"
|
||||
onSubmit={(e) => (onSaveAndClose ? onSaveAndClose(e) : onSubmit?.(e))}
|
||||
>
|
||||
<div className="modal-form-shell__body">
|
||||
{editingUnit?.origin_framework_slot_id
|
||||
? (() => {
|
||||
const L = frameworkLineageText(editingUnit)
|
||||
@@ -148,80 +131,11 @@ export default function TrainingPlanningUnitFormModal({
|
||||
</select>
|
||||
<p className="training-planning-template-panel__help">
|
||||
Übernimmt nur die <strong>Sektionsstruktur</strong> aus der Bibliothek; Übungen trägst du unten bei den
|
||||
Abschnitten ein. Gespeicherte Vorlagen kannst du unter Planung später erweitern.
|
||||
Abschnitten ein. Vorlagen verwaltest du unter <Link to="/planning/plan-templates">Planung → Vorlagen</Link>.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{planTemplates.length > 0 && typeof onDeletePlanTemplate === 'function' ? (
|
||||
<details
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1.35rem',
|
||||
padding: '12px 14px',
|
||||
background: 'var(--surface2)',
|
||||
border: '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 600, color: 'var(--text1)' }}>
|
||||
Gespeicherte Vorlagen löschen
|
||||
</summary>
|
||||
<p style={{ margin: '0.65rem 0 0.75rem', fontSize: '0.82rem', color: 'var(--text2)', lineHeight: 1.45 }}>
|
||||
Entfernen nach Rolle: eigene private Vorlagen; Vereinsinhalte als Vereinsadmin; offizielle nur als
|
||||
Plattform‑Admin. Einheiten mit Verweis behalten den Ablauf; die Vorlage wird entkoppelt.
|
||||
</p>
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||
{planTemplates.map((t, ti) => {
|
||||
const canDel = user && canDeleteLibraryContent(user, t)
|
||||
return (
|
||||
<li
|
||||
key={t.id}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '10px',
|
||||
padding: '8px 0',
|
||||
borderTop: ti === 0 ? 'none' : '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<span style={{ minWidth: 0, flex: 1, fontSize: '0.9rem' }}>
|
||||
<strong style={{ color: 'var(--text1)' }}>{t.name}</strong>
|
||||
<span style={{ fontSize: '0.78rem', color: 'var(--text3)', marginLeft: '6px' }}>
|
||||
(
|
||||
{String(t.visibility || 'club').toLowerCase() === 'private'
|
||||
? 'Privat'
|
||||
: String(t.visibility || 'club').toLowerCase() === 'official'
|
||||
? 'Offiziell'
|
||||
: 'Verein'}
|
||||
)
|
||||
</span>
|
||||
{typeof t.sections_count === 'number' ? (
|
||||
<span style={{ fontSize: '0.82rem', color: 'var(--text2)', marginLeft: '6px' }}>
|
||||
· {t.sections_count} Abschn.
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{canDel ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
style={{ flexShrink: 0, padding: '6px 12px', fontSize: '0.82rem' }}
|
||||
onClick={() => onDeletePlanTemplate(t)}
|
||||
>
|
||||
Löschen
|
||||
</button>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.78rem', color: 'var(--text3)', flexShrink: 0 }}>nur Lesen</span>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</details>
|
||||
) : null}
|
||||
|
||||
<form onSubmit={onSubmit}>
|
||||
<h3 style={{ marginBottom: '1rem' }}>Planung</h3>
|
||||
|
||||
<div className="responsive-grid-3" style={{ marginBottom: '1rem' }}>
|
||||
@@ -492,6 +406,28 @@ export default function TrainingPlanningUnitFormModal({
|
||||
>
|
||||
Vorlage aus Aufbau speichern
|
||||
</button>
|
||||
{editingUnit?.id && !editingUnit?.framework_slot_id ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ marginBottom: '2px' }}
|
||||
onClick={() => onRequestPublishToFramework?.()}
|
||||
title="Letzten gespeicherten Ablauf ins Rahmenprogramm übernehmen"
|
||||
>
|
||||
Als Rahmen-Session speichern…
|
||||
</button>
|
||||
) : null}
|
||||
{editingUnit?.id && !editingUnit?.framework_slot_id ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ marginBottom: '2px' }}
|
||||
onClick={() => onRequestSaveAsModule?.()}
|
||||
title="Gespeicherte Übungen als Trainingsmodul sichern"
|
||||
>
|
||||
Übungen als Modul…
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -625,16 +561,21 @@ export default function TrainingPlanningUnitFormModal({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1.5rem' }}>
|
||||
<button type="submit" className="btn btn-primary" style={{ flex: 1 }}>
|
||||
{editingUnit ? 'Speichern' : 'Erstellen'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={onCancel}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<FormActionBar
|
||||
placement="bottom"
|
||||
variant="modal"
|
||||
formId={formId}
|
||||
isNew={!editingUnit}
|
||||
onSave={onSaveOnly ? () => onSaveOnly() : undefined}
|
||||
onSaveAndClose={onSaveAndClose ? () => onSaveAndClose() : undefined}
|
||||
onCancel={onCancel}
|
||||
showSave={Boolean(onSaveOnly)}
|
||||
showSaveAndClose
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</FormModalOverlay>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import React, { useEffect, useState, useMemo } 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 } from '../../utils/activeClub'
|
||||
import { navigateWithAppReturn } from '../../utils/navReturnContext'
|
||||
|
||||
/**
|
||||
* Übernimmt den gespeicherten Ablauf einer geplanten Trainingseinheit in ein Rahmenprogramm (neu oder bestehend, Slot wählbar).
|
||||
*/
|
||||
export default function TrainingPublishToFrameworkModal({
|
||||
open,
|
||||
onClose,
|
||||
unitId,
|
||||
planningModalClubId,
|
||||
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 [scope, setScope] = useState('existing')
|
||||
const [programs, setPrograms] = useState([])
|
||||
const [programsLoading, setProgramsLoading] = useState(false)
|
||||
const [fwProgramId, setFwProgramId] = useState('')
|
||||
const [fwDetail, setFwDetail] = useState(null)
|
||||
const [fwDetailLoading, setFwDetailLoading] = useState(false)
|
||||
|
||||
const [slotMode, setSlotMode] = useState('new_slot')
|
||||
const [insertAt, setInsertAt] = useState('')
|
||||
const [existingSlotId, setExistingSlotId] = useState('')
|
||||
|
||||
const [newTitle, setNewTitle] = useState('')
|
||||
const [newVisibility, setNewVisibility] = useState('private')
|
||||
const [newClubId, setNewClubId] = useState('')
|
||||
const [newGoalTitle, setNewGoalTitle] = useState('Aus geplanter Einheit')
|
||||
|
||||
const [slotTitle, setSlotTitle] = useState('')
|
||||
const [slotNotes, setSlotNotes] = useState('')
|
||||
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
return
|
||||
}
|
||||
if (planningModalClubId != null && planningModalClubId !== '') {
|
||||
setNewClubId(String(planningModalClubId))
|
||||
} else if (memberClubs.length === 1) {
|
||||
setNewClubId(String(memberClubs[0].id))
|
||||
}
|
||||
setProgramsLoading(true)
|
||||
api
|
||||
.listTrainingFrameworkPrograms()
|
||||
.then((list) => {
|
||||
setPrograms(Array.isArray(list) ? list : [])
|
||||
})
|
||||
.catch(() => setPrograms([]))
|
||||
.finally(() => setProgramsLoading(false))
|
||||
}, [open, planningModalClubId, memberClubs])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || scope !== 'existing' || !fwProgramId) {
|
||||
setFwDetail(null)
|
||||
return
|
||||
}
|
||||
const id = parseInt(fwProgramId, 10)
|
||||
if (!Number.isFinite(id) || id < 1) {
|
||||
setFwDetail(null)
|
||||
return
|
||||
}
|
||||
setFwDetailLoading(true)
|
||||
api
|
||||
.getTrainingFrameworkProgram(id)
|
||||
.then(setFwDetail)
|
||||
.catch(() => setFwDetail(null))
|
||||
.finally(() => setFwDetailLoading(false))
|
||||
}, [open, scope, fwProgramId])
|
||||
|
||||
const sortedSlots = useMemo(() => {
|
||||
const sl = fwDetail?.slots
|
||||
if (!Array.isArray(sl)) return []
|
||||
return [...sl].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
|
||||
}, [fwDetail])
|
||||
|
||||
const resetAndClose = () => {
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
if (!unitId || submitting) return
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
if (scope === 'new') {
|
||||
const tit = (newTitle || '').trim()
|
||||
if (!tit) {
|
||||
toast.error('Bitte einen Titel für das neue Rahmenprogramm angeben.')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
const gt = (newGoalTitle || '').trim() || 'Entwicklungsziel'
|
||||
let club_id =
|
||||
newVisibility === 'club' && newClubId ? parseInt(newClubId, 10) : null
|
||||
if (newVisibility === 'club' && (!Number.isFinite(club_id) || club_id < 1)) {
|
||||
toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
if (newVisibility !== 'club') club_id = null
|
||||
|
||||
const st = (slotTitle || '').trim()
|
||||
const sn = (slotNotes || '').trim()
|
||||
const created = await api.publishTrainingUnitToFramework(unitId, {
|
||||
new_framework: {
|
||||
title: tit,
|
||||
visibility: newVisibility,
|
||||
club_id,
|
||||
goals: [{ sort_order: 0, title: gt, notes: null }],
|
||||
},
|
||||
mode: 'new_slot',
|
||||
insert_at_index: null,
|
||||
...(st ? { slot_title: st } : {}),
|
||||
...(sn ? { slot_notes: slotNotes } : {}),
|
||||
})
|
||||
toast.success('Ablauf wurde im Rahmenprogramm gespeichert.')
|
||||
if (created?.id) {
|
||||
navigateWithAppReturn(navigate, `/planning/framework-programs/${created.id}`, returnContext)
|
||||
}
|
||||
onSuccess?.()
|
||||
resetAndClose()
|
||||
return
|
||||
} else {
|
||||
const fid = parseInt(fwProgramId, 10)
|
||||
if (!Number.isFinite(fid) || fid < 1) {
|
||||
toast.error('Bitte ein Rahmenprogramm auswählen.')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
framework_program_id: fid,
|
||||
mode: slotMode,
|
||||
}
|
||||
const st = (slotTitle || '').trim()
|
||||
const sn = (slotNotes || '').trim()
|
||||
if (st) payload.slot_title = st
|
||||
if (sn) payload.slot_notes = slotNotes
|
||||
if (slotMode === 'new_slot') {
|
||||
if (insertAt.trim() === '') {
|
||||
payload.insert_at_index = null
|
||||
} else {
|
||||
const n = parseInt(insertAt, 10)
|
||||
if (!Number.isFinite(n) || n < 0) {
|
||||
toast.error('Position: nicht negative Ganzzahl oder leer (anhängen).')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
payload.insert_at_index = n
|
||||
}
|
||||
} else {
|
||||
const sid = parseInt(existingSlotId, 10)
|
||||
if (!Number.isFinite(sid) || sid < 1) {
|
||||
toast.error('Bitte einen Session-Slot zum Überschreiben wählen.')
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
payload.framework_slot_id = sid
|
||||
}
|
||||
|
||||
const updated = await api.publishTrainingUnitToFramework(unitId, payload)
|
||||
toast.success('Ablauf wurde im Rahmenprogramm gespeichert.')
|
||||
if (updated?.id) {
|
||||
navigateWithAppReturn(navigate, `/planning/framework-programs/${updated.id}`, returnContext)
|
||||
}
|
||||
onSuccess?.()
|
||||
resetAndClose()
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(err.message || 'Speichern fehlgeschlagen')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<FormModalOverlay open={open} raised onBackdropClick={resetAndClose}>
|
||||
<div className="card modal-panel--form modal-panel--narrow">
|
||||
<h2 className="modal-panel__title">Ablauf ins Rahmenprogramm übernehmen</h2>
|
||||
<p className="modal-panel__intro">
|
||||
Es wird der <strong>zuletzt gespeicherte</strong> Ablauf dieser Einheit aus der Datenbank übernommen.
|
||||
Nicht gespeicherte Änderungen im Formular sind nicht enthalten — bitte vorher die Einheit speichern.
|
||||
</p>
|
||||
|
||||
<form id="publish-framework-form" className="modal-form-shell" onSubmit={handleSubmit}>
|
||||
<div className="modal-form-shell__body">
|
||||
<div style={{ marginBottom: '1rem' }}>
|
||||
<span className="form-label">Ziel</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', marginTop: '0.35rem' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name="pf_scope"
|
||||
checked={scope === 'existing'}
|
||||
onChange={() => setScope('existing')}
|
||||
/>
|
||||
Bestehendes Rahmenprogramm
|
||||
</label>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name="pf_scope"
|
||||
checked={scope === 'new'}
|
||||
onChange={() => setScope('new')}
|
||||
/>
|
||||
Neues Rahmenprogramm
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{scope === 'existing' ? (
|
||||
<>
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Rahmenprogramm</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={fwProgramId}
|
||||
onChange={(e) => {
|
||||
setFwProgramId(e.target.value)
|
||||
setExistingSlotId('')
|
||||
}}
|
||||
required
|
||||
>
|
||||
<option value="">{programsLoading ? 'Laden…' : '— Wählen —'}</option>
|
||||
{programs.map((p) => (
|
||||
<option key={p.id} value={String(p.id)}>
|
||||
{(p.title || '').trim() || `Rahmen #${p.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '0.85rem' }}>
|
||||
<span className="form-label">Session-Platz</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: '0.35rem' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name="pf_slot"
|
||||
checked={slotMode === 'new_slot'}
|
||||
onChange={() => setSlotMode('new_slot')}
|
||||
/>
|
||||
Neuen Session-Slot anlegen
|
||||
</label>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name="pf_slot"
|
||||
checked={slotMode === 'existing_slot'}
|
||||
onChange={() => setSlotMode('existing_slot')}
|
||||
/>
|
||||
Bestehenden Slot überschreiben (Ablauf ersetzen)
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{slotMode === 'new_slot' ? (
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Position (0 = erste Stelle)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
placeholder="Leer = ans Ende anhängen"
|
||||
value={insertAt}
|
||||
onChange={(e) => setInsertAt(e.target.value)}
|
||||
/>
|
||||
<p style={{ fontSize: '0.78rem', color: 'var(--text3)', margin: '0.35rem 0 0' }}>
|
||||
Die Reihenfolge der Slots kannst du in der Rahmen-Bearbeitung jederzeit ändern (Ziehen oder
|
||||
Pfeile).
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Slot</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={existingSlotId}
|
||||
onChange={(e) => setExistingSlotId(e.target.value)}
|
||||
required={slotMode === 'existing_slot'}
|
||||
>
|
||||
<option value="">
|
||||
{fwDetailLoading ? 'Laden…' : '— Session wählen —'}
|
||||
</option>
|
||||
{sortedSlots.map((s, i) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{(s.title || '').trim() || `Session ${i + 1}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Titel Rahmenprogramm</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={newTitle}
|
||||
onChange={(e) => setNewTitle(e.target.value)}
|
||||
placeholder="z. B. Saisonvorbereitung"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Erstes Entwicklungsziel (Pflichtfeld Rahmen)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={newGoalTitle}
|
||||
onChange={(e) => setNewGoalTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={newVisibility}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
setNewVisibility(v)
|
||||
if (v === 'club' && !newClubId && planningModalClubId != null) {
|
||||
setNewClubId(String(planningModalClubId))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="private">Privat</option>
|
||||
<option value="club">Verein</option>
|
||||
{isSuperadmin ? <option value="official">Offiziell</option> : null}
|
||||
</select>
|
||||
</div>
|
||||
{newVisibility === 'club' ? (
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Verein</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={newClubId}
|
||||
onChange={(e) => setNewClubId(e.target.value)}
|
||||
>
|
||||
<option value="">— Verein wählen —</option>
|
||||
{memberClubs.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name || `Verein #${c.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="form-row" style={{ marginBottom: '0.85rem' }}>
|
||||
<label className="form-label">Session-Titel (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={slotTitle}
|
||||
onChange={(e) => setSlotTitle(e.target.value)}
|
||||
placeholder="z. B. Woche 3 — Technik"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginBottom: '1.1rem' }}>
|
||||
<label className="form-label">Notizen zur Session (optional)</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={2}
|
||||
value={slotNotes}
|
||||
onChange={(e) => setSlotNotes(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<FormActionBar
|
||||
placement="bottom"
|
||||
variant="modal"
|
||||
formId="publish-framework-form"
|
||||
saving={submitting}
|
||||
showSave={false}
|
||||
saveAndCloseLabel="In Rahmen übernehmen"
|
||||
saveAndCloseShortLabel="Übernehmen"
|
||||
onCancel={resetAndClose}
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</FormModalOverlay>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import TrainingPlanExerciseVisibilityPanel from '../TrainingPlanExerciseVisibilityPanel'
|
||||
import TrainingUnitSectionsEditor from '../TrainingUnitSectionsEditor'
|
||||
import { activeClubMemberships } from '../../utils/activeClub'
|
||||
import { frameworkLineageText } from '../../utils/trainingPlanningPageHelpers'
|
||||
import {
|
||||
formatDurationDisplay,
|
||||
minutesToDurationFieldValue,
|
||||
parseDurationInput,
|
||||
sumExercisePlannedMinutes,
|
||||
sumSectionPlannedMinutes,
|
||||
} from '../../utils/trainingDurationUtils'
|
||||
|
||||
/**
|
||||
* Vollseiten-Formular: Trainingseinheit planen / nachbereiten (ohne Modal-Overlay).
|
||||
*/
|
||||
export default function TrainingUnitFormShell({
|
||||
editingUnit,
|
||||
formData,
|
||||
updateFormField,
|
||||
setFormData,
|
||||
onSaveOnly,
|
||||
onSaveAndClose,
|
||||
draftPlanTemplateId,
|
||||
onDraftTemplateSelect,
|
||||
planTemplates,
|
||||
clubDirectory,
|
||||
clubDirectoryForCo,
|
||||
planningClubId,
|
||||
user,
|
||||
onMetaRefresh,
|
||||
sectionsEditMode,
|
||||
setSectionsEditMode,
|
||||
onSaveAsTemplate,
|
||||
onRequestPublishToFramework,
|
||||
onRequestSaveAsModule,
|
||||
onRequestTrainingModulePick,
|
||||
onRequestExercisePick,
|
||||
onPeekExercise,
|
||||
formId = 'planning-unit-form',
|
||||
}) {
|
||||
const [newTplVisibility, setNewTplVisibility] = useState('private')
|
||||
const [newTplClubId, setNewTplClubId] = useState('')
|
||||
|
||||
const memberClubs = useMemo(() => activeClubMemberships(user?.clubs), [user?.clubs])
|
||||
const roleLc = String(user?.role || '').toLowerCase()
|
||||
const isSuperadmin = roleLc === 'superadmin'
|
||||
|
||||
const plannedTotalParsed = parseDurationInput(formData.planned_duration_min)
|
||||
const sumFromSections = sumSectionPlannedMinutes(formData.sections)
|
||||
const sumFromExercises = sumExercisePlannedMinutes(formData.sections)
|
||||
|
||||
useEffect(() => {
|
||||
if (planningClubId != null && planningClubId !== '') {
|
||||
setNewTplClubId(String(planningClubId))
|
||||
} else if (memberClubs.length === 1) {
|
||||
setNewTplClubId(String(memberClubs[0].id))
|
||||
}
|
||||
}, [planningClubId, memberClubs])
|
||||
|
||||
return (
|
||||
<form
|
||||
id={formId}
|
||||
className="card page-form-shell"
|
||||
style={{ padding: 'clamp(14px, 3vw, 1.75rem)' }}
|
||||
onSubmit={(e) => (onSaveAndClose ? onSaveAndClose(e) : onSaveOnly?.(e))}
|
||||
>
|
||||
<div className="page-form-shell__scroll">
|
||||
{editingUnit?.origin_framework_slot_id
|
||||
? (() => {
|
||||
const L = frameworkLineageText(editingUnit)
|
||||
return (
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginBottom: '1.1rem',
|
||||
padding: '12px 14px',
|
||||
background: 'var(--surface2)',
|
||||
fontSize: '0.9rem',
|
||||
lineHeight: 1.5,
|
||||
}}
|
||||
>
|
||||
<strong style={{ color: 'var(--text1)' }}>Herkunft:</strong>{' '}
|
||||
{editingUnit.origin_framework_program_id ? (
|
||||
<Link
|
||||
to={`/planning/framework-programs/${editingUnit.origin_framework_program_id}`}
|
||||
style={{ color: 'var(--accent-dark)' }}
|
||||
>
|
||||
{L.fpTitle}
|
||||
</Link>
|
||||
) : (
|
||||
L.fpTitle
|
||||
)}
|
||||
<span style={{ color: 'var(--text2)' }}> · {L.slotBit}</span>
|
||||
<p style={{ margin: '0.5rem 0 0', fontSize: '0.82rem', color: 'var(--text2)' }}>
|
||||
Inhalt stammt aus dem Session-Blueprint des Rahmenprogramms. Änderungen gelten nur für diese
|
||||
geplante Einheit; die Zuordnung zum Rahmen bleibt zur Nachverfolgung erhalten.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
})()
|
||||
: null}
|
||||
|
||||
{!editingUnit && (
|
||||
<div className="training-planning-template-panel" style={{ marginBottom: '1.35rem' }}>
|
||||
<label className="form-label training-planning-template-panel__label" htmlFor="planning-draft-template">
|
||||
Vorlage für den Ablauf
|
||||
</label>
|
||||
<select
|
||||
id="planning-draft-template"
|
||||
className="form-input training-planning-template-panel__select"
|
||||
value={draftPlanTemplateId}
|
||||
onChange={(e) => onDraftTemplateSelect(e.target.value)}
|
||||
>
|
||||
<option value="">Ohne Vorlage — leere Gliederung (ein Abschnitt)</option>
|
||||
{planTemplates.map((t) => {
|
||||
const v = String(t.visibility || 'club').toLowerCase()
|
||||
const vLabel = v === 'private' ? 'Privat' : v === 'official' ? 'Offiziell' : 'Verein'
|
||||
return (
|
||||
<option key={t.id} value={String(t.id)}>
|
||||
{t.name}
|
||||
{typeof t.sections_count === 'number' ? ` · ${t.sections_count} Abschn.` : ''} · {vLabel}
|
||||
</option>
|
||||
)
|
||||
})}
|
||||
</select>
|
||||
<p className="training-planning-template-panel__help">
|
||||
Übernimmt nur die <strong>Sektionsstruktur</strong> aus der Bibliothek; Übungen trägst du unten bei den
|
||||
Abschnitten ein. Vorlagen verwaltest du unter{' '}
|
||||
<Link to="/planning/plan-templates">Planung → Vorlagen</Link>.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h3 style={{ marginBottom: '1rem' }}>Planung</h3>
|
||||
|
||||
<div className="responsive-grid-3" style={{ marginBottom: '1rem' }}>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Datum *</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={formData.planned_date}
|
||||
onChange={(e) => updateFormField('planned_date', e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Von</label>
|
||||
<input
|
||||
type="time"
|
||||
className="form-input"
|
||||
value={formData.planned_time_start}
|
||||
onChange={(e) => updateFormField('planned_time_start', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Bis</label>
|
||||
<input
|
||||
type="time"
|
||||
className="form-input"
|
||||
value={formData.planned_time_end}
|
||||
onChange={(e) => updateFormField('planned_time_end', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-row" style={{ marginBottom: '1rem' }}>
|
||||
<label className="form-label">Geplante Gesamtdauer</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
inputMode="decimal"
|
||||
value={formData.planned_duration_min}
|
||||
onChange={(e) => updateFormField('planned_duration_min', e.target.value)}
|
||||
placeholder="z. B. 1,5 oder 90 (Minuten)"
|
||||
/>
|
||||
<p className="form-sub" style={{ marginTop: '0.35rem' }}>
|
||||
{plannedTotalParsed != null ? (
|
||||
<>
|
||||
Eingabe: <strong>{formatDurationDisplay(plannedTotalParsed)}</strong>
|
||||
</>
|
||||
) : (
|
||||
'Stunden mit Komma/Punkt (1,5 = 90 Min) oder Minuten ab 8.'
|
||||
)}
|
||||
{sumFromSections > 0 || sumFromExercises > 0 ? (
|
||||
<>
|
||||
{' '}
|
||||
· Summe Abschnitte: <strong>{formatDurationDisplay(sumFromSections)}</strong>
|
||||
{sumFromExercises > 0 && sumFromExercises !== sumFromSections ? (
|
||||
<>
|
||||
{' '}
|
||||
· Übungen: <strong>{formatDurationDisplay(sumFromExercises)}</strong>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label">Trainingsfokus</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={formData.planned_focus}
|
||||
onChange={(e) => updateFormField('planned_focus', e.target.value)}
|
||||
placeholder="z.B. Grundlagen, Kinder altersgerecht"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
marginTop: '1.25rem',
|
||||
marginBottom: '0.25rem',
|
||||
padding: '12px 14px',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<h3 style={{ margin: '0 0 10px', fontSize: '1rem' }}>Trainerzuordnung (diese Einheit)</h3>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Leitung</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.lead_trainer_profile_id}
|
||||
onChange={(e) => updateFormField('lead_trainer_profile_id', e.target.value)}
|
||||
disabled={!editingUnit && !formData.group_id}
|
||||
>
|
||||
<option value="">Standard (Haupttrainer der Gruppe)</option>
|
||||
{clubDirectory.map((m) => (
|
||||
<option key={String(m.id)} value={String(m.id)}>
|
||||
{(m.name || '').trim() || m.email || `Profil ${m.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginTop: '0.75rem' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.session_assistants_inherit}
|
||||
onChange={(e) => updateFormField('session_assistants_inherit', e.target.checked)}
|
||||
/>
|
||||
<span style={{ fontSize: '0.9rem', color: 'var(--text1)' }}>
|
||||
Co-Trainer wie in der Trainingsgruppe (Standard)
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{!formData.session_assistants_inherit ? (
|
||||
<div style={{ marginTop: '10px', maxHeight: '200px', overflowY: 'auto' }}>
|
||||
{clubDirectoryForCo.map((m) => {
|
||||
const mid = typeof m.id === 'number' ? m.id : parseInt(String(m.id), 10)
|
||||
const isOn =
|
||||
Number.isFinite(mid) && formData.session_assistant_profile_ids.includes(mid)
|
||||
return (
|
||||
<label
|
||||
key={`co-${mid}`}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
fontSize: '0.875rem',
|
||||
marginBottom: '6px',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isOn}
|
||||
onChange={() => {
|
||||
setFormData((prev) => {
|
||||
const was = prev.session_assistant_profile_ids.includes(mid)
|
||||
const nextIds = was
|
||||
? prev.session_assistant_profile_ids.filter((x) => x !== mid)
|
||||
: [...prev.session_assistant_profile_ids, mid].sort((a, b) => a - b)
|
||||
return { ...prev, session_assistant_profile_ids: nextIds }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<span>{(m.name || '').trim() || m.email || `Profil ${mid}`}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<TrainingPlanExerciseVisibilityPanel
|
||||
sections={formData.sections}
|
||||
targetClubId={planningClubId}
|
||||
user={user}
|
||||
onMetaRefresh={onMetaRefresh}
|
||||
/>
|
||||
|
||||
<div style={{ marginTop: '2rem' }}>
|
||||
{editingUnit ? (
|
||||
<div style={{ marginBottom: '1rem' }}>
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label="Modus für Abschnitte und Übungen"
|
||||
style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '10px' }}
|
||||
>
|
||||
<span className="form-label" style={{ marginBottom: 0, fontSize: '0.82rem' }}>
|
||||
Ablauf bearbeiten als
|
||||
</span>
|
||||
<div
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
borderRadius: '10px',
|
||||
border: '1.5px solid var(--border2)',
|
||||
overflow: 'hidden',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
{[
|
||||
{ id: 'planning', label: 'Planung' },
|
||||
{ id: 'debrief', label: 'Nachbereitung' },
|
||||
].map((opt, i) => (
|
||||
<button
|
||||
key={opt.id}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={sectionsEditMode === opt.id}
|
||||
onClick={() => setSectionsEditMode(opt.id)}
|
||||
style={{
|
||||
border: 'none',
|
||||
padding: '8px 14px',
|
||||
fontWeight: 600,
|
||||
fontSize: '0.85rem',
|
||||
cursor: 'pointer',
|
||||
background: sectionsEditMode === opt.id ? 'var(--accent-dark)' : 'transparent',
|
||||
color: sectionsEditMode === opt.id ? '#fff' : 'var(--text1)',
|
||||
...(i > 0 ? { borderLeft: '1.5px solid var(--border2)' } : {}),
|
||||
}}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<TrainingUnitSectionsEditor
|
||||
heading="Abschnitte & Übungen"
|
||||
headingAccessory={
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'flex-end',
|
||||
gap: '10px',
|
||||
marginBottom: '10px',
|
||||
}}
|
||||
>
|
||||
<div className="form-row" style={{ marginBottom: 0, minWidth: 'min(160px, 100%)' }}>
|
||||
<label className="form-label" style={{ fontSize: '0.82rem' }}>
|
||||
Neue Vorlage: Sichtbarkeit
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={newTplVisibility}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
setNewTplVisibility(v)
|
||||
if (v === 'club' && !newTplClubId && planningClubId != null) {
|
||||
setNewTplClubId(String(planningClubId))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="private">Privat (nur du)</option>
|
||||
<option value="club">Verein</option>
|
||||
{isSuperadmin ? <option value="official">Offiziell (global)</option> : null}
|
||||
</select>
|
||||
</div>
|
||||
{newTplVisibility === 'club' ? (
|
||||
<div className="form-row" style={{ marginBottom: 0, flex: '1 1 200px' }}>
|
||||
<label className="form-label" style={{ fontSize: '0.82rem' }}>
|
||||
Verein
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={newTplClubId}
|
||||
onChange={(e) => setNewTplClubId(e.target.value)}
|
||||
>
|
||||
<option value="">— Verein wählen —</option>
|
||||
{memberClubs.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name || `Verein #${c.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() =>
|
||||
onSaveAsTemplate?.({
|
||||
visibility: newTplVisibility,
|
||||
club_id:
|
||||
newTplVisibility === 'club' && newTplClubId
|
||||
? parseInt(newTplClubId, 10)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
>
|
||||
Vorlage aus Aufbau speichern
|
||||
</button>
|
||||
{editingUnit?.id && !editingUnit?.framework_slot_id ? (
|
||||
<>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => onRequestPublishToFramework?.()}>
|
||||
Als Rahmen-Session speichern…
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => onRequestSaveAsModule?.()}>
|
||||
Übungen als Modul…
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
sections={formData.sections}
|
||||
wideExerciseGrid
|
||||
onSectionsChange={(updater) =>
|
||||
setFormData((prev) => ({ ...prev, sections: updater(prev.sections) }))
|
||||
}
|
||||
onRequestTrainingModulePick={onRequestTrainingModulePick}
|
||||
onRequestExercisePick={onRequestExercisePick}
|
||||
onPeekExercise={onPeekExercise}
|
||||
showExecutionExtras={Boolean(editingUnit) && sectionsEditMode === 'debrief'}
|
||||
enableParallelPhaseControls
|
||||
/>
|
||||
</div>
|
||||
|
||||
{editingUnit ? (
|
||||
<>
|
||||
<h3 style={{ marginTop: '2rem', marginBottom: '1rem' }}>Durchführung</h3>
|
||||
<div className="responsive-grid-4" style={{ marginBottom: '1rem' }}>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Tatsächliches Datum</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={formData.actual_date}
|
||||
onChange={(e) => updateFormField('actual_date', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Von</label>
|
||||
<input
|
||||
type="time"
|
||||
className="form-input"
|
||||
value={formData.actual_time_start}
|
||||
onChange={(e) => updateFormField('actual_time_start', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Bis</label>
|
||||
<input
|
||||
type="time"
|
||||
className="form-input"
|
||||
value={formData.actual_time_end}
|
||||
onChange={(e) => updateFormField('actual_time_end', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Teilnehmer</label>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
value={formData.attendance_count}
|
||||
onChange={(e) => updateFormField('attendance_count', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Status</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.status}
|
||||
onChange={(e) => updateFormField('status', e.target.value)}
|
||||
>
|
||||
<option value="planned">Geplant</option>
|
||||
<option value="completed">Durchgeführt</option>
|
||||
<option value="cancelled">Abgesagt</option>
|
||||
</select>
|
||||
</div>
|
||||
{formData.status === 'completed' ? (
|
||||
<div className="form-row" style={{ marginTop: '0.75rem' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'flex-start', gap: '10px', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!formData.debrief_completed}
|
||||
onChange={(e) => updateFormField('debrief_completed', e.target.checked)}
|
||||
style={{ marginTop: '3px' }}
|
||||
/>
|
||||
<span>
|
||||
<strong>Rückschau erledigt</strong>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<h3 style={{ marginTop: '2rem', marginBottom: '1rem' }}>Notizen</h3>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Öffentliche Notizen</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={3}
|
||||
value={formData.notes}
|
||||
onChange={(e) => updateFormField('notes', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Trainernotizen</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={3}
|
||||
value={formData.trainer_notes}
|
||||
onChange={(e) => updateFormField('trainer_notes', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../../utils/api'
|
||||
|
||||
const ARTIFACT_LABELS = {
|
||||
framework_program: 'Rahmenprogramm',
|
||||
training_module: 'Trainingsmodul',
|
||||
progression_graph: 'Regressionspfad',
|
||||
}
|
||||
|
||||
function formatScore(value) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return '0'
|
||||
return n % 1 === 0 ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschläge für Planungsartefakte anhand gewählter Fähigkeiten (Phase 3).
|
||||
*/
|
||||
export default function SkillDiscoveryPanel({ skills = [] }) {
|
||||
const [selectedIds, setSelectedIds] = useState([])
|
||||
const [query, setQuery] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [result, setResult] = useState(null)
|
||||
|
||||
const filteredSkills = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
const list = (skills || []).filter((s) => s.status !== 'inactive')
|
||||
if (!q) return list
|
||||
return list.filter(
|
||||
(s) =>
|
||||
(s.name || '').toLowerCase().includes(q) ||
|
||||
(s.category || '').toLowerCase().includes(q)
|
||||
)
|
||||
}, [skills, query])
|
||||
|
||||
const toggleSkill = (id) => {
|
||||
const s = String(id)
|
||||
setSelectedIds((prev) =>
|
||||
prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s]
|
||||
)
|
||||
}
|
||||
|
||||
async function handleSearch() {
|
||||
const ids = selectedIds.map((x) => parseInt(x, 10)).filter((n) => n > 0)
|
||||
if (!ids.length) {
|
||||
setError('Wähle mindestens eine Fähigkeit.')
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setResult(null)
|
||||
try {
|
||||
const data = await api.getSkillDiscoverySuggestions(ids, { limit: 25 })
|
||||
setResult(data)
|
||||
} catch (e) {
|
||||
setError(e.message || 'Suche fehlgeschlagen')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="skill-discovery card">
|
||||
<h2 className="skill-discovery__title">Planungs-Vorschläge</h2>
|
||||
<p className="form-sub skill-discovery__lead">
|
||||
Wähle Fähigkeiten, die du schwerpunktmäßig entwickeln willst — Shinkan schlägt passende
|
||||
Rahmenprogramme, Trainingsmodule und Regressionspfade vor. Sortierung nach absolutem
|
||||
Trainingsgewicht (nicht nach Anteil innerhalb des Plans).
|
||||
</p>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label">Fähigkeiten filtern</label>
|
||||
<input
|
||||
className="form-input"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Name oder Kategorie …"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="skill-discovery__pick-grid" role="group" aria-label="Fähigkeiten auswählen">
|
||||
{filteredSkills.length === 0 ? (
|
||||
<p className="form-sub">Keine Fähigkeiten gefunden.</p>
|
||||
) : (
|
||||
filteredSkills.map((sk) => (
|
||||
<label key={sk.id} className="skill-discovery__pick">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.includes(String(sk.id))}
|
||||
onChange={() => toggleSkill(sk.id)}
|
||||
/>
|
||||
<span className="skill-discovery__pick-name">{sk.name}</span>
|
||||
{sk.category ? (
|
||||
<span className="skill-discovery__pick-cat">{sk.category}</span>
|
||||
) : null}
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="skill-discovery__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={loading || selectedIds.length === 0}
|
||||
onClick={handleSearch}
|
||||
>
|
||||
{loading ? 'Suche …' : 'Bibliothek durchsuchen'}
|
||||
</button>
|
||||
{selectedIds.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => {
|
||||
setSelectedIds([])
|
||||
setResult(null)
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
Auswahl leeren
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{error ? <p className="skill-discovery__error">{error}</p> : null}
|
||||
|
||||
{result?.suggestions?.length > 0 ? (
|
||||
<ul className="skill-discovery__results">
|
||||
{result.suggestions.map((item) => {
|
||||
const matchScore = item.match?.match_score ?? item.match?.match_weight ?? 0
|
||||
const focusPct = item.match?.artifact_focus_percent ?? item.match?.match_percent
|
||||
const topByCat = item.skill_profile_summary?.top_by_category || []
|
||||
return (
|
||||
<li key={`${item.artifact_type}-${item.artifact_id}`} className="skill-discovery__result card">
|
||||
<div className="skill-discovery__result-head">
|
||||
<span className="skill-discovery__result-type">
|
||||
{ARTIFACT_LABELS[item.artifact_type] || item.artifact_type}
|
||||
</span>
|
||||
<span className="skill-discovery__result-match" title="Summe der Trainingsgewichte der gewählten Fähigkeiten">
|
||||
Gewicht {formatScore(matchScore)}
|
||||
</span>
|
||||
</div>
|
||||
<strong className="skill-discovery__result-title">
|
||||
{item.artifact_title || `#${item.artifact_id}`}
|
||||
</strong>
|
||||
{item.match?.matched_skills?.length > 0 ? (
|
||||
<p className="skill-discovery__result-skills">
|
||||
{item.match.matched_skills.map((m) => m.skill_name).join(' · ')}
|
||||
{focusPct != null ? ` (${formatScore(focusPct)}% des Plans)` : null}
|
||||
</p>
|
||||
) : null}
|
||||
{topByCat.length > 0 ? (
|
||||
<ul className="skill-discovery__result-cats">
|
||||
{topByCat.slice(0, 4).map((row) => (
|
||||
<li key={`${row.category_name}-${row.skill_id}`}>
|
||||
<span className="skill-discovery__result-cat-name">{row.category_name}</span>
|
||||
<span>{row.skill_name}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{item.path ? (
|
||||
<Link to={item.path} className="btn btn-secondary btn-small skill-discovery__result-link">
|
||||
Öffnen
|
||||
</Link>
|
||||
) : item.artifact_type === 'progression_graph' ? (
|
||||
<p className="form-sub" style={{ margin: '8px 0 0' }}>
|
||||
Regressionspfad in der Übungsliste unter „Progressionsgraph“ bearbeiten.
|
||||
</p>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
) : result && !loading ? (
|
||||
<p className="form-sub skill-discovery__no-hit">
|
||||
Keine passenden Artefakte in deiner sichtbaren Bibliothek — prüfe Fähigkeiten-Verknüpfungen an
|
||||
den Übungen oder erweitere die Auswahl.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
formatClubPercent,
|
||||
formatSkillWeight,
|
||||
kpiRowsFromSummary,
|
||||
peerPercentSuffix,
|
||||
} from '../../utils/skillProfileListHelpers'
|
||||
|
||||
/**
|
||||
* Kleine KPI-Kacheln: je Unterkategorie die Top-Fähigkeit (Listen/Karten).
|
||||
*/
|
||||
export default function SkillProfileCompact({
|
||||
summary,
|
||||
artifactType = 'training_module',
|
||||
loading = false,
|
||||
emptyText = 'Keine Fähigkeiten',
|
||||
displayLimit = 24,
|
||||
highlightSkillIds = [],
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="skill-kpi-grid skill-kpi-grid--loading" aria-busy="true">
|
||||
<span className="form-sub">…</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const rows = kpiRowsFromSummary(summary, { limit: displayLimit })
|
||||
const highlight = new Set((highlightSkillIds || []).map(String))
|
||||
const peerLabel = peerPercentSuffix(artifactType)
|
||||
|
||||
if (!rows.length) {
|
||||
return summary ? <p className="form-sub skill-kpi-grid--empty">{emptyText}</p> : null
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="skill-kpi-grid" aria-label="Fähigkeiten je Kategorie">
|
||||
{rows.map((row) => {
|
||||
const highlighted = highlight.has(String(row.skill_id))
|
||||
const isBest = row.is_club_best_for_skill || row.universal_percent >= 100
|
||||
return (
|
||||
<li
|
||||
key={`${row.category_name}-${row.skill_id}`}
|
||||
className={
|
||||
'skill-kpi-tile' +
|
||||
(highlighted ? ' skill-kpi-tile--highlight' : '') +
|
||||
(isBest ? ' skill-kpi-tile--best' : '')
|
||||
}
|
||||
title={`${row.category_name}: ${row.skill_name} — Gewicht ${formatSkillWeight(row.weight ?? row.score)}, ${formatClubPercent(row.universal_percent)} unter ${peerLabel}`}
|
||||
>
|
||||
<span className="skill-kpi-tile__cat">{row.category_name}</span>
|
||||
<span className="skill-kpi-tile__name">{row.skill_name}</span>
|
||||
<span className="skill-kpi-tile__score">{formatSkillWeight(row.weight ?? row.score)}</span>
|
||||
<span className="skill-kpi-tile__pct">
|
||||
{isBest ? '★ ' : ''}
|
||||
{formatClubPercent(row.universal_percent)} {peerLabel}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import api from '../../utils/api'
|
||||
import { peerCorpusCountLabel } from '../../utils/skillProfileListHelpers'
|
||||
import SkillProfilePanel from './SkillProfilePanel'
|
||||
|
||||
/**
|
||||
* Vollständiges Fähigkeiten-Profil in einem Modal (Listen-Kontext).
|
||||
*/
|
||||
export default function SkillProfileFullModal({
|
||||
open,
|
||||
onClose,
|
||||
artifactType = 'framework_program',
|
||||
artifactId,
|
||||
title = 'Fähigkeiten-Profil',
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [data, setData] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !artifactId) return undefined
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setData(null)
|
||||
const load =
|
||||
artifactType === 'training_module'
|
||||
? api.getTrainingModuleSkillProfile(artifactId)
|
||||
: artifactType === 'progression_graph'
|
||||
? api.getProgressionGraphSkillProfile(artifactId)
|
||||
: api.getFrameworkProgramSkillProfile(artifactId)
|
||||
load
|
||||
.then((res) => {
|
||||
if (!cancelled) setData(res)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message || 'Profil konnte nicht geladen werden')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, artifactId, artifactType])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const peerCountLabel = peerCorpusCountLabel(artifactType)
|
||||
const scale = data?.reference_scale
|
||||
|
||||
return (
|
||||
<div className="skill-profile-modal" role="dialog" aria-modal="true" aria-labelledby="skill-profile-modal-title">
|
||||
<button type="button" className="skill-profile-modal__backdrop" aria-label="Schließen" onClick={onClose} />
|
||||
<div className="skill-profile-modal__panel card">
|
||||
<header className="skill-profile-modal__head">
|
||||
<h2 id="skill-profile-modal-title" className="skill-profile-modal__title">
|
||||
{title}
|
||||
</h2>
|
||||
<button type="button" className="btn btn-secondary btn-small" onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</header>
|
||||
<SkillProfilePanel
|
||||
profile={data?.overall}
|
||||
slots={artifactType === 'framework_program' ? data?.slots : null}
|
||||
loading={loading}
|
||||
error={error}
|
||||
title="Vollständiges Profil"
|
||||
displayMode="full"
|
||||
embedded
|
||||
defaultExpanded
|
||||
artifactType={artifactType}
|
||||
/>
|
||||
{scale && !loading ? (
|
||||
<p className="form-sub skill-profile-modal__scale">
|
||||
Vergleichsbasis: {scale.artifacts_scanned ?? 0} sichtbare {peerCountLabel} (
|
||||
{scale.skills_in_corpus ?? 0} Fähigkeiten mit Referenz).
|
||||
{scale.description ? ` ${scale.description}` : null}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import {
|
||||
formatClubPercent,
|
||||
peerPercentSuffix,
|
||||
} from '../../utils/skillProfileListHelpers'
|
||||
|
||||
function skillWeight(skill) {
|
||||
return Number(skill?.weight ?? skill?.score ?? 0)
|
||||
}
|
||||
|
||||
function formatWeight(value) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return '0'
|
||||
return n % 1 === 0 ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
function barFillPercent(skill, maxWeight, hasReferenceScale) {
|
||||
if (hasReferenceScale && skill?.universal_percent != null) {
|
||||
return Math.min(100, Number(skill.universal_percent))
|
||||
}
|
||||
const w = skillWeight(skill)
|
||||
return maxWeight > 0 ? Math.min(100, (w / maxWeight) * 100) : 0
|
||||
}
|
||||
|
||||
function metricLabel(skill, hasReferenceScale, peerLabel) {
|
||||
if (hasReferenceScale && skill?.universal_percent != null) {
|
||||
const best = skill.is_club_best_for_skill ? ' ★' : ''
|
||||
return `${formatClubPercent(skill.universal_percent)} ${peerLabel}${best}`
|
||||
}
|
||||
return formatWeight(skillWeight(skill))
|
||||
}
|
||||
|
||||
function SkillRow({ skill, maxWeight, hasReferenceScale, peerLabel }) {
|
||||
if (!skill) return null
|
||||
const pct = barFillPercent(skill, maxWeight, hasReferenceScale)
|
||||
return (
|
||||
<li className="skill-profile__row">
|
||||
<div className="skill-profile__row-head">
|
||||
<span className="skill-profile__name" title={skill.skill_name}>
|
||||
{skill.category_name ? (
|
||||
<span className="skill-profile__name-cat">{skill.category_name} · </span>
|
||||
) : null}
|
||||
{skill.skill_name}
|
||||
</span>
|
||||
<span className="skill-profile__pct" title="Trainingsgewicht (gewichtete Minuten)">
|
||||
{metricLabel(skill, hasReferenceScale, peerLabel)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="skill-profile__bar-track" aria-hidden="true">
|
||||
<div className="skill-profile__bar-fill" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
{hasReferenceScale ? (
|
||||
<span className="skill-profile__meta-hint">
|
||||
Gewicht {formatWeight(skillWeight(skill))}
|
||||
{skill.club_best ? (
|
||||
<>
|
||||
{' '}
|
||||
· Top unter {peerLabel}: {skill.club_best.artifact_title || skill.club_best.artifact_id} (
|
||||
{formatWeight(skill.club_best.weight)})
|
||||
</>
|
||||
) : skill.is_club_best_for_skill ? (
|
||||
' · Stärkster unter ' + peerLabel
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function CategoryTopSkill({ skill, maxWeight, hasReferenceScale, peerLabel }) {
|
||||
if (!skill) return null
|
||||
return (
|
||||
<SkillRow
|
||||
skill={skill}
|
||||
maxWeight={maxWeight}
|
||||
hasReferenceScale={hasReferenceScale}
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CategoryGroupedProfile({ profile, ariaLabel, peerLabel }) {
|
||||
const groups = profile?.by_main_category || []
|
||||
const hasReferenceScale = Boolean(profile?.has_reference_scale)
|
||||
const maxWeight = useMemo(() => {
|
||||
let max = 1
|
||||
for (const mc of groups) {
|
||||
for (const cat of mc.categories || []) {
|
||||
const w = skillWeight(cat.top_skill)
|
||||
if (w > max) max = w
|
||||
}
|
||||
}
|
||||
return max
|
||||
}, [groups])
|
||||
|
||||
if (!groups.length) return null
|
||||
|
||||
return (
|
||||
<div className="skill-profile__by-category" aria-label={ariaLabel}>
|
||||
{groups.map((mc) => (
|
||||
<section key={mc.main_category_id ?? mc.main_category_name} className="skill-profile__main-cat">
|
||||
<h4 className="skill-profile__main-cat-title">{mc.main_category_name}</h4>
|
||||
<ul className="skill-profile__cat-list">
|
||||
{(mc.categories || []).map((cat) => (
|
||||
<li key={cat.category_id ?? cat.category_name} className="skill-profile__cat-item">
|
||||
<span className="skill-profile__cat-label">{cat.category_name}</span>
|
||||
<div className="skill-profile__cat-row">
|
||||
<CategoryTopSkill
|
||||
skill={cat.top_skill}
|
||||
maxWeight={maxWeight}
|
||||
hasReferenceScale={hasReferenceScale}
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FullSkillsProfile({ profile, ariaLabel, peerLabel }) {
|
||||
const skills = profile?.skills || []
|
||||
const hasReferenceScale = Boolean(profile?.has_reference_scale)
|
||||
const maxWeight = useMemo(
|
||||
() => Math.max(...skills.map((s) => skillWeight(s)), 1),
|
||||
[skills]
|
||||
)
|
||||
|
||||
if (!skills.length) return null
|
||||
|
||||
return (
|
||||
<ul className="skill-profile__list" aria-label={ariaLabel}>
|
||||
{skills.map((sk) => (
|
||||
<SkillRow
|
||||
key={sk.skill_id}
|
||||
skill={sk}
|
||||
maxWeight={maxWeight}
|
||||
hasReferenceScale={hasReferenceScale}
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function topCategoryBadge(profile) {
|
||||
const parts = []
|
||||
for (const mc of profile?.by_main_category || []) {
|
||||
for (const cat of mc.categories || []) {
|
||||
const top = cat.top_skill
|
||||
if (!top) continue
|
||||
parts.push(`${cat.category_name}: ${top.skill_name}`)
|
||||
if (parts.length >= 2) return parts.join(' · ')
|
||||
}
|
||||
}
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Gewichtetes Fähigkeiten-Profil (Phase 3) — Anzeige für Planungsartefakte.
|
||||
* displayMode: 'summary' = Top je Kategorie (Editor), 'full' = alle Fähigkeiten (Modal).
|
||||
*/
|
||||
export default function SkillProfilePanel({
|
||||
profile,
|
||||
slots = null,
|
||||
loading = false,
|
||||
error = '',
|
||||
title = 'Fähigkeiten-Profil',
|
||||
hint = '',
|
||||
defaultExpanded = true,
|
||||
displayMode = 'summary',
|
||||
embedded = false,
|
||||
artifactType = 'framework_program',
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(defaultExpanded)
|
||||
const [slotOpenId, setSlotOpenId] = useState(null)
|
||||
|
||||
const peerLabel = peerPercentSuffix(artifactType)
|
||||
|
||||
const defaultHint =
|
||||
displayMode === 'full'
|
||||
? `Alle verknüpften Fähigkeiten nach Trainingsgewicht. Prozent = Anteil am stärksten sichtbaren Eintrag unter ${peerLabel} je Fähigkeit.`
|
||||
: `Trainingsgewicht aus Dauer, Häufigkeit, Intensität und Stufen-Spanne. Prozent vergleicht nur unter ${peerLabel}, nicht mit anderen Planungs-Artefakttypen.`
|
||||
|
||||
const hintText = hint || defaultHint
|
||||
const badge = useMemo(() => topCategoryBadge(profile), [profile])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className={'skill-profile skill-profile--loading' + (embedded ? '' : ' card')}>
|
||||
<p className="skill-profile__status">Fähigkeiten-Profil wird berechnet…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className={'skill-profile skill-profile--error' + (embedded ? '' : ' card')}>
|
||||
<p className="skill-profile__status">{error}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const noData =
|
||||
!profile ||
|
||||
(profile.exercise_occurrence_count === 0 && profile.distinct_exercise_count === 0)
|
||||
|
||||
const categoryCount = (profile?.by_main_category || []).reduce(
|
||||
(n, mc) => n + (mc.categories?.length || 0),
|
||||
0
|
||||
)
|
||||
|
||||
const body = (
|
||||
<div className="skill-profile__body">
|
||||
<p className="form-sub skill-profile__hint">{hintText}</p>
|
||||
|
||||
{noData ? (
|
||||
<p className="skill-profile__empty">
|
||||
Noch keine Übungen mit Fähigkeiten-Verknüpfung — lege Übungen im Ablauf an und verknüpfe
|
||||
Fähigkeiten in der Übungsbearbeitung.
|
||||
</p>
|
||||
) : profile.exercises_with_skills_count === 0 ? (
|
||||
<p className="skill-profile__empty">
|
||||
{profile.distinct_exercise_count} Übung{profile.distinct_exercise_count === 1 ? '' : 'en'} im
|
||||
Ablauf, aber keine Fähigkeiten an den Übungen hinterlegt.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="skill-profile__stats">
|
||||
<span>
|
||||
<strong>{profile.distinct_exercise_count}</strong> Übungen
|
||||
</span>
|
||||
<span>
|
||||
<strong>{profile.skills?.length ?? 0}</strong> Fähigkeiten
|
||||
</span>
|
||||
{displayMode === 'summary' ? (
|
||||
<span>
|
||||
<strong>{categoryCount}</strong> Kategorien
|
||||
</span>
|
||||
) : null}
|
||||
<span>
|
||||
<strong>{formatWeight(profile.total_score ?? profile.total_weight)}</strong> Gesamt-Gewicht
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{displayMode === 'full' ? (
|
||||
<FullSkillsProfile
|
||||
profile={profile}
|
||||
ariaLabel="Alle Fähigkeiten nach Gewicht"
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
) : (
|
||||
<CategoryGroupedProfile
|
||||
profile={profile}
|
||||
ariaLabel="Top-Fähigkeit je Kategorie"
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{slots && slots.length > 0 ? (
|
||||
<div className="skill-profile__slots">
|
||||
<span className="skill-profile__slots-label">Pro Session</span>
|
||||
<ul className="skill-profile__slot-list">
|
||||
{slots.map((sl) => {
|
||||
const open = slotOpenId === sl.slot_id
|
||||
const slotBadge = topCategoryBadge(sl.profile)
|
||||
return (
|
||||
<li key={sl.slot_id} className="skill-profile__slot-item">
|
||||
<button
|
||||
type="button"
|
||||
className="skill-profile__slot-btn"
|
||||
onClick={() => setSlotOpenId(open ? null : sl.slot_id)}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<span>
|
||||
{(sl.slot_title || '').trim() || `Session ${(sl.sort_order ?? 0) + 1}`}
|
||||
</span>
|
||||
{slotBadge ? (
|
||||
<span className="skill-profile__slot-top">{slotBadge}</span>
|
||||
) : (
|
||||
<span className="skill-profile__slot-top skill-profile__slot-top--muted">
|
||||
{sl.exercise_occurrence_count > 0 ? 'ohne Fähigkeiten' : 'kein Ablauf'}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{open && sl.profile?.skills?.length > 0 ? (
|
||||
displayMode === 'full' ? (
|
||||
<FullSkillsProfile
|
||||
profile={sl.profile}
|
||||
ariaLabel={`Alle Fähigkeiten Session ${(sl.sort_order ?? 0) + 1}`}
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
) : (
|
||||
<CategoryGroupedProfile
|
||||
profile={sl.profile}
|
||||
ariaLabel={`Fähigkeiten Session ${(sl.sort_order ?? 0) + 1}`}
|
||||
peerLabel={peerLabel}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
|
||||
if (embedded) {
|
||||
return <div className="skill-profile skill-profile--embedded">{body}</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card skill-profile">
|
||||
<button
|
||||
type="button"
|
||||
className="skill-profile__toggle"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
<span className="skill-profile__toggle-title">{title}</span>
|
||||
{!noData && badge ? (
|
||||
<span className="skill-profile__toggle-badge">{badge}</span>
|
||||
) : null}
|
||||
<span className="skill-profile__toggle-icon" aria-hidden="true">
|
||||
{expanded ? '▾' : '▸'}
|
||||
</span>
|
||||
</button>
|
||||
{expanded ? body : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** UI-Bezeichnung für `exercises.visibility` (API/DB-Feldname unverändert). */
|
||||
export const EXERCISE_VISIBILITY_FIELD_LABEL = 'Freigabelevel'
|
||||
|
||||
export const EXERCISE_VISIBILITY_CLUB_FIELD_LABEL = 'Verein (Freigabelevel)'
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Kanonische Intensität Übung ↔ Fähigkeit (Scoring + Formular). */
|
||||
|
||||
export const EXERCISE_SKILL_INTENSITY_DEFAULT = 'mittel'
|
||||
|
||||
export const EXERCISE_SKILL_INTENSITY_OPTIONS = [
|
||||
{ value: 'niedrig', label: 'niedrig' },
|
||||
{ value: 'mittel', label: 'mittel' },
|
||||
{ value: 'hoch', label: 'hoch' },
|
||||
]
|
||||
|
||||
export function normalizeExerciseSkillIntensity(value) {
|
||||
const key = String(value ?? '').trim().toLowerCase()
|
||||
if (key === 'niedrig' || key === 'low') return 'niedrig'
|
||||
if (key === 'hoch' || key === 'high') return 'hoch'
|
||||
return 'mittel'
|
||||
}
|
||||
|
||||
export function formatExerciseSkillIntensityLabel(value) {
|
||||
const n = normalizeExerciseSkillIntensity(value)
|
||||
return EXERCISE_SKILL_INTENSITY_OPTIONS.find((o) => o.value === n)?.label || n
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import FormActionBar from '../components/FormActionBar'
|
||||
|
||||
const FormEditorActionsContext = createContext(null)
|
||||
|
||||
export function FormEditorActionsProvider({ children }) {
|
||||
const [config, setConfig] = useState(null)
|
||||
const value = useMemo(() => ({ config, setConfig }), [config])
|
||||
|
||||
return <FormEditorActionsContext.Provider value={value}>{children}</FormEditorActionsContext.Provider>
|
||||
}
|
||||
|
||||
/** Mobile: FormActionBar statt Bottom-Nav; Desktop: Fallback (Nav ist ohnehin ausgeblendet). */
|
||||
export function FormEditorBottomSlot({ children }) {
|
||||
const ctx = useContext(FormEditorActionsContext)
|
||||
const config = ctx?.config
|
||||
|
||||
if (config) {
|
||||
return (
|
||||
<div className="form-editor-mobile-dock" data-testid="form-editor-mobile-dock">
|
||||
<FormActionBar {...config} placement="bottom" variant="page" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return children
|
||||
}
|
||||
|
||||
/** @param {Record<string, unknown> | null} config FormActionBar-Props */
|
||||
export function useFormEditorActions(config) {
|
||||
const setConfig = useContext(FormEditorActionsContext)?.setConfig
|
||||
|
||||
useEffect(() => {
|
||||
if (!setConfig) return undefined
|
||||
setConfig(config ?? null)
|
||||
return () => setConfig(null)
|
||||
}, [setConfig, config])
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClub
|
||||
api.listStyleDirections(),
|
||||
api.listTrainingTypes(),
|
||||
api.listTargetGroups(),
|
||||
api.listSkills(),
|
||||
api.listSkillsCatalog(),
|
||||
])
|
||||
if (!cancelled) {
|
||||
setCatalogs({
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
let lockDepth = 0
|
||||
const saved = {
|
||||
appMainScrollTop: 0,
|
||||
bodyScrollTop: 0,
|
||||
appMainOverflow: '',
|
||||
appMainTouchAction: '',
|
||||
}
|
||||
|
||||
function queryAppMain() {
|
||||
return document.querySelector('.app-main')
|
||||
}
|
||||
|
||||
function applyLock() {
|
||||
document.documentElement.classList.add('modal-scroll-locked')
|
||||
|
||||
const appMain = queryAppMain()
|
||||
if (appMain) {
|
||||
saved.appMainScrollTop = appMain.scrollTop
|
||||
saved.appMainOverflow = appMain.style.overflow
|
||||
saved.appMainTouchAction = appMain.style.touchAction
|
||||
appMain.style.overflow = 'hidden'
|
||||
appMain.style.touchAction = 'none'
|
||||
}
|
||||
|
||||
saved.bodyScrollTop = window.scrollY || document.documentElement.scrollTop || 0
|
||||
document.body.style.overflow = 'hidden'
|
||||
document.body.style.overscrollBehavior = 'none'
|
||||
}
|
||||
|
||||
function releaseLock() {
|
||||
document.documentElement.classList.remove('modal-scroll-locked')
|
||||
|
||||
const appMain = queryAppMain()
|
||||
if (appMain) {
|
||||
appMain.style.overflow = saved.appMainOverflow
|
||||
appMain.style.touchAction = saved.appMainTouchAction
|
||||
appMain.scrollTop = saved.appMainScrollTop
|
||||
}
|
||||
|
||||
document.body.style.overflow = ''
|
||||
document.body.style.overscrollBehavior = ''
|
||||
if (saved.bodyScrollTop) {
|
||||
window.scrollTo(0, saved.bodyScrollTop)
|
||||
}
|
||||
}
|
||||
|
||||
/** Hintergrund-Scroll sperren (.app-main + body), verschachtelte Modals via Zähler. */
|
||||
export function useModalScrollLock(active) {
|
||||
useEffect(() => {
|
||||
if (!active) return undefined
|
||||
lockDepth += 1
|
||||
if (lockDepth === 1) applyLock()
|
||||
return () => {
|
||||
lockDepth = Math.max(0, lockDepth - 1)
|
||||
if (lockDepth === 0) releaseLock()
|
||||
}
|
||||
}, [active])
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { goNavReturn, resolveNavReturnTarget } from '../utils/navReturnContext'
|
||||
|
||||
/**
|
||||
* @param {{ path: string, label: string } | null | undefined} fallback
|
||||
*/
|
||||
export function useNavReturn(fallback) {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const target = useMemo(
|
||||
() => resolveNavReturnTarget(location, fallback),
|
||||
[location, fallback]
|
||||
)
|
||||
const goBack = useCallback(() => {
|
||||
goNavReturn(navigate, location, fallback)
|
||||
}, [navigate, location, fallback])
|
||||
return { goBack, target }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Outlet, useLocation } from 'react-router-dom'
|
||||
import PlanningRouteNav from '../components/planning/PlanningRouteNav'
|
||||
import { isPlanningUnitEditorPath } from '../utils/planningUnitRoutes'
|
||||
|
||||
/** Gemeinsame Hülle für Planung, Rahmenprogramme, Module und Vorlagen. */
|
||||
export default function PlanningLayout() {
|
||||
const { pathname } = useLocation()
|
||||
const hideRouteNav = isPlanningUnitEditorPath(pathname)
|
||||
|
||||
return (
|
||||
<div className="app-page planning-layout">
|
||||
{!hideRouteNav ? <PlanningRouteNav /> : null}
|
||||
<div className="planning-layout__main">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { CalendarCheck, ClipboardList, FilePenLine, Library } from 'lucide-react'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import {
|
||||
buildDashboardReturnContext,
|
||||
buildTrainingRunReturnContext,
|
||||
} from '../utils/navReturnContext'
|
||||
import EmailVerificationBanner from '../components/EmailVerificationBanner'
|
||||
import DashboardTrainingVisibilityWidget from '../components/DashboardTrainingVisibilityWidget'
|
||||
import DashboardOrgInboxWidget from '../components/DashboardOrgInboxWidget'
|
||||
@@ -26,6 +31,7 @@ function Dashboard() {
|
||||
const [dashboardKpisErr, setDashboardKpisErr] = useState(null)
|
||||
const { user, loading: authLoading } = useAuth()
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
const dashboardReturn = useMemo(() => buildDashboardReturnContext(), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!user?.id) {
|
||||
@@ -166,14 +172,20 @@ function Dashboard() {
|
||||
<ul className="dashboard-preview-card__list">
|
||||
{phase0Stats.draftPreview.map((ex) => (
|
||||
<li key={ex.id}>
|
||||
<Link to={`/exercises/${ex.id}/edit`} className="dashboard-preview-card__link">
|
||||
<NavStateLink
|
||||
to={`/exercises/${ex.id}/edit`}
|
||||
returnContext={dashboardReturn}
|
||||
className="dashboard-preview-card__link"
|
||||
>
|
||||
{ex.title}
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p style={{ margin: '0.75rem 0 0', fontSize: '0.86rem' }}>
|
||||
<Link to={draftsHref}>Alle Entwürfe in der Übersicht</Link>
|
||||
<NavStateLink to={draftsHref} returnContext={dashboardReturn}>
|
||||
Alle Entwürfe in der Übersicht
|
||||
</NavStateLink>
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -205,9 +217,13 @@ function Dashboard() {
|
||||
<ul className="dashboard-preview-card__list">
|
||||
{trainingHome.upcoming.map((u) => (
|
||||
<li key={u.id}>
|
||||
<Link to={`/planning/run/${u.id}`} className="dashboard-preview-card__link">
|
||||
<NavStateLink
|
||||
to={`/planning/run/${u.id}`}
|
||||
returnContext={buildTrainingRunReturnContext(u.id) || dashboardReturn}
|
||||
className="dashboard-preview-card__link"
|
||||
>
|
||||
{unitWhenLabel(u)}
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
{u.group_name ? (
|
||||
<span className="dashboard-preview-card__meta">{` — ${u.group_name}`}</span>
|
||||
) : null}
|
||||
@@ -237,9 +253,13 @@ function Dashboard() {
|
||||
const snippet = (u.trainer_notes || u.notes || '').trim().slice(0, 120)
|
||||
return (
|
||||
<li key={`n-${u.id}`}>
|
||||
<Link to={`/planning/run/${u.id}`} className="dashboard-preview-card__link">
|
||||
<NavStateLink
|
||||
to={`/planning/run/${u.id}`}
|
||||
returnContext={buildTrainingRunReturnContext(u.id) || dashboardReturn}
|
||||
className="dashboard-preview-card__link"
|
||||
>
|
||||
{unitWhenLabel(u)}
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
{u.group_name ? (
|
||||
<span className="dashboard-preview-card__meta">{` · ${u.group_name}`}</span>
|
||||
) : null}
|
||||
@@ -266,9 +286,13 @@ function Dashboard() {
|
||||
<ul className="dashboard-preview-card__list">
|
||||
{trainingHome.reviewPending.map((u) => (
|
||||
<li key={`r-${u.id}`}>
|
||||
<Link to={`/planning?unit=${u.id}`} className="dashboard-preview-card__link">
|
||||
<NavStateLink
|
||||
to={`/planning/units/${u.id}/edit`}
|
||||
returnContext={dashboardReturn}
|
||||
className="dashboard-preview-card__link"
|
||||
>
|
||||
{(u.actual_date || u.planned_date || '').toString().slice(0, 10) || 'Datum'}
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
{u.group_name ? (
|
||||
<span className="dashboard-preview-card__meta">{` — ${u.group_name}`}</span>
|
||||
) : null}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Link, useNavigate, useParams, useLocation } from 'react-router-dom'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { useParams, useLocation } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import PageReturnButton from '../components/PageReturnButton'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import {
|
||||
EXERCISES_LIST_PATH,
|
||||
buildCurrentLocationReturnContext,
|
||||
} from '../utils/navReturnContext'
|
||||
import ExerciseRichTextBlock from '../components/ExerciseRichTextBlock'
|
||||
import ExerciseAttachmentMediaStrip from '../components/ExerciseAttachmentMediaStrip'
|
||||
import CombinationPlanBracket from '../components/CombinationPlanBracket'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import { formatSkillLevelSlug } from '../constants/skillLevels'
|
||||
import { formatExerciseSkillIntensityLabel } from '../constants/exerciseSkillIntensity'
|
||||
|
||||
function TagRow({ exercise }) {
|
||||
const tags = []
|
||||
@@ -54,8 +61,11 @@ function metaParts(exercise) {
|
||||
|
||||
function ExerciseDetailPage() {
|
||||
const { id } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const editReturnContext = useMemo(
|
||||
() => buildCurrentLocationReturnContext(location, 'Zurück zur Übung'),
|
||||
[location]
|
||||
)
|
||||
const [exercise, setExercise] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -98,9 +108,10 @@ function ExerciseDetailPage() {
|
||||
<div className="card">
|
||||
<h2>Übung</h2>
|
||||
<p style={{ color: 'var(--danger)' }}>{msg}</p>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/exercises')}>
|
||||
Zur Übersicht
|
||||
</button>
|
||||
<PageReturnButton
|
||||
fallbackPath={EXERCISES_LIST_PATH}
|
||||
fallbackLabel="Zurück zur Übungsliste"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -109,7 +120,6 @@ function ExerciseDetailPage() {
|
||||
if (!exercise) return null
|
||||
|
||||
const meta = metaParts(exercise)
|
||||
const fromExerciseEdit = location.state?.fromExerciseEdit === true
|
||||
|
||||
const isCombinationDetail =
|
||||
(exercise.exercise_kind || '').toLowerCase().trim() === 'combination' &&
|
||||
@@ -131,13 +141,19 @@ function ExerciseDetailPage() {
|
||||
onClose={() => setEmbeddedPeekExerciseId(null)}
|
||||
/>
|
||||
<div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/exercises')}>
|
||||
← Übersicht
|
||||
</button>
|
||||
<PageReturnButton
|
||||
fallbackPath={EXERCISES_LIST_PATH}
|
||||
fallbackLabel="Zurück zur Übungsliste"
|
||||
className="page-return-btn btn btn-secondary btn-small"
|
||||
/>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginLeft: 'auto' }}>
|
||||
<Link to={`/exercises/${exercise.id}/edit`} className="btn btn-primary">
|
||||
{fromExerciseEdit ? 'Zurück zur Bearbeitung' : 'Bearbeiten'}
|
||||
</Link>
|
||||
<NavStateLink
|
||||
to={`/exercises/${exercise.id}/edit`}
|
||||
returnContext={editReturnContext}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
Bearbeiten
|
||||
</NavStateLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -229,9 +245,9 @@ function ExerciseDetailPage() {
|
||||
const lvl =
|
||||
rl || tl ? ` (${[rl, tl].filter(Boolean).join(' → ')})` : ''
|
||||
return (
|
||||
<span key={s.id} className={`exercise-tag${s.is_primary ? ' exercise-tag--accent' : ''}`}>
|
||||
<span key={s.id} className="exercise-tag">
|
||||
{s.skill_name}
|
||||
{s.intensity ? ` · ${s.intensity}` : ''}
|
||||
{` · ${formatExerciseSkillIntensityLabel(s.intensity)}`}
|
||||
{lvl}
|
||||
</span>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useState, useCallback, useRef, useMemo } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import { buildMediaLibraryReturnContext } from '../utils/navReturnContext'
|
||||
import {
|
||||
LayoutGrid,
|
||||
List,
|
||||
@@ -108,21 +110,23 @@ function parseTagsInput(s) {
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function MediaUsageBlock({ usage, compact }) {
|
||||
function MediaUsageBlock({ usage, compact, returnContext }) {
|
||||
const u = usage || { exercises: [], training_units: [] }
|
||||
const ex = u.exercises || []
|
||||
const tus = u.training_units || []
|
||||
if (!ex.length && !tus.length)
|
||||
return <span className="media-library__hint">{compact ? '—' : 'Noch in keiner Übung / Einheit verknüpft.'}</span>
|
||||
const LinkOrNav = returnContext ? NavStateLink : Link
|
||||
const linkExtra = returnContext ? { returnContext } : {}
|
||||
return (
|
||||
<div className="media-library__usage-links">
|
||||
{ex.length ? (
|
||||
<div>
|
||||
<strong>Übungen</strong>{' '}
|
||||
{ex.map((e) => (
|
||||
<Link key={e.id} to={`/exercises/${e.id}`} title={e.title}>
|
||||
<LinkOrNav key={e.id} to={`/exercises/${e.id}`} title={e.title} {...linkExtra}>
|
||||
{e.title.length > (compact ? 18 : 40) ? `${e.title.slice(0, compact ? 18 : 40)}…` : e.title}
|
||||
</Link>
|
||||
</LinkOrNav>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
@@ -134,9 +138,9 @@ function MediaUsageBlock({ usage, compact }) {
|
||||
[t.planned_date, (t.group_name || '').trim()].filter(Boolean).join(' · ') || `Einheit #${t.id}`
|
||||
const short = label.length > (compact ? 20 : 36) ? `${label.slice(0, compact ? 20 : 36)}…` : label
|
||||
return (
|
||||
<Link key={t.id} to={`/planning?unit=${t.id}`} title={label}>
|
||||
<LinkOrNav key={t.id} to={`/planning/units/${t.id}/edit`} title={label} {...linkExtra}>
|
||||
{short}
|
||||
</Link>
|
||||
</LinkOrNav>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
@@ -297,6 +301,7 @@ export default function MediaLibraryPage() {
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
const hasClubOrgAdmin = activeClubMemberships(user?.clubs).some((c) => (c.roles || []).includes('club_admin'))
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
const mediaLibraryReturn = useMemo(() => buildMediaLibraryReturnContext(), [])
|
||||
|
||||
const archiveVisOptions = useMemo(
|
||||
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
|
||||
@@ -1004,7 +1009,7 @@ export default function MediaLibraryPage() {
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<MediaUsageBlock usage={it.usage} compact />
|
||||
<MediaUsageBlock usage={it.usage} compact returnContext={mediaLibraryReturn} />
|
||||
{(it.lifecycle_state || 'active') === 'active' && !it.legal_hold_active && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -1074,7 +1079,7 @@ export default function MediaLibraryPage() {
|
||||
{(it.tags || []).length ? (it.tags || []).join(', ') : '—'}
|
||||
</td>
|
||||
<td className="media-library__td-usage media-library__td-sub">
|
||||
<MediaUsageBlock usage={it.usage} compact />
|
||||
<MediaUsageBlock usage={it.usage} compact returnContext={mediaLibraryReturn} />
|
||||
</td>
|
||||
{viewer?.show_club_meta ? (
|
||||
<td className="media-library__td-sub">{it.club_name || it.club_id || '—'}</td>
|
||||
@@ -1333,7 +1338,7 @@ export default function MediaLibraryPage() {
|
||||
<div className="media-library__meta-block">
|
||||
<span className="media-library__meta-k">Verwendung</span>
|
||||
<div className="media-library__meta-v">
|
||||
<MediaUsageBlock usage={modal.usage} compact={false} />
|
||||
<MediaUsageBlock usage={modal.usage} compact={false} returnContext={mediaLibraryReturn} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Scale } from 'lucide-react'
|
||||
import PageReturnButton from '../components/PageReturnButton'
|
||||
import { SETTINGS_PATH } from '../utils/navReturnContext'
|
||||
|
||||
const LEGAL_LINKS = [
|
||||
{ to: '/impressum', label: 'Impressum', description: 'Angaben zum Betreiber und Verantwortlichen' },
|
||||
@@ -12,9 +14,7 @@ function SettingsLegalPage() {
|
||||
return (
|
||||
<div className="page-padding app-page" style={{ padding: '1rem' }}>
|
||||
<p style={{ marginBottom: '0.75rem' }}>
|
||||
<Link to="/settings" style={{ fontSize: '0.9rem' }}>
|
||||
← Zurück zu Einstellungen
|
||||
</Link>
|
||||
<PageReturnButton fallbackPath={SETTINGS_PATH} fallbackLabel="Zurück zu Einstellungen" />
|
||||
</p>
|
||||
|
||||
<h1 style={{ marginBottom: '0.35rem', fontSize: '1.5rem' }}>Rechtliches</h1>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import PageReturnButton from '../components/PageReturnButton'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import { SETTINGS_PATH } from '../utils/navReturnContext'
|
||||
|
||||
/**
|
||||
* Technische System- und Build-Infos (ehemals Dashboard) — unter Einstellungen für Betrieb/Diagnose.
|
||||
@@ -33,9 +34,7 @@ function SettingsSystemInfoPage() {
|
||||
return (
|
||||
<div className="page-padding app-page" style={{ padding: '1rem' }}>
|
||||
<p style={{ marginBottom: '0.75rem' }}>
|
||||
<Link to="/settings" style={{ fontSize: '0.9rem' }}>
|
||||
← Zurück zu Einstellungen
|
||||
</Link>
|
||||
<PageReturnButton fallbackPath={SETTINGS_PATH} fallbackLabel="Zurück zu Einstellungen" />
|
||||
</p>
|
||||
<h1 style={{ marginBottom: '0.35rem', fontSize: '1.5rem' }}>Systeminformationen</h1>
|
||||
<p
|
||||
|
||||
@@ -2,10 +2,12 @@ import React, { useState, useEffect } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import PageSectionNav from '../components/PageSectionNav'
|
||||
import SkillDiscoveryPanel from '../components/skills/SkillDiscoveryPanel'
|
||||
|
||||
const SKILLS_SECTION_TABS = [
|
||||
{ id: 'skills', label: 'Fähigkeiten' },
|
||||
{ id: 'methods', label: 'Trainingsmethoden' },
|
||||
{ id: 'discovery', label: 'Planungs-Vorschläge' },
|
||||
]
|
||||
|
||||
function SkillsPage() {
|
||||
@@ -243,6 +245,8 @@ function SkillsPage() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'discovery' && <SkillDiscoveryPanel skills={skills} />}
|
||||
|
||||
{/* Methods Tab */}
|
||||
{activeTab === 'methods' && (
|
||||
<>
|
||||
|
||||
@@ -6,6 +6,11 @@ import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import ExerciseFullContent from '../components/ExerciseFullContent'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import PageReturnButton from '../components/PageReturnButton'
|
||||
import {
|
||||
buildPlanningHubFallbackReturnContext,
|
||||
buildTrainingRunReturnContext,
|
||||
} from '../utils/navReturnContext'
|
||||
import {
|
||||
COACH_ENTRY_BRANCH_GATE,
|
||||
buildCoachSavePlanPayload,
|
||||
@@ -184,6 +189,8 @@ export default function TrainingCoachPage() {
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const idNum = unitId ? parseInt(unitId, 10) : NaN
|
||||
const planningReturn = useMemo(() => buildPlanningHubFallbackReturnContext(), [])
|
||||
const runReturn = useMemo(() => buildTrainingRunReturnContext(unitId), [unitId])
|
||||
|
||||
const coachFocusResetRef = useRef(null)
|
||||
|
||||
@@ -667,9 +674,11 @@ export default function TrainingCoachPage() {
|
||||
return (
|
||||
<div className="card" style={{ margin: '1rem', padding: '1.5rem' }}>
|
||||
<p style={{ marginBottom: '1rem' }}>{loadError || 'Nicht gefunden.'}</p>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||
Zur Planung
|
||||
</button>
|
||||
<PageReturnButton
|
||||
fallbackPath={planningReturn.path}
|
||||
fallbackLabel={planningReturn.label}
|
||||
className="page-return-btn btn btn-secondary btn-small"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -680,6 +689,7 @@ export default function TrainingCoachPage() {
|
||||
key={candidatePeekId != null ? String(candidatePeekId) : 'coach-peek-closed'}
|
||||
open={candidatePeekId != null}
|
||||
exerciseId={candidatePeekId}
|
||||
returnContext={runReturn}
|
||||
onClose={() => setCandidatePeekId(null)}
|
||||
/>
|
||||
<nav
|
||||
@@ -697,9 +707,11 @@ export default function TrainingCoachPage() {
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate(`/planning/run/${unitId}`)}>
|
||||
Zur Planansicht
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||
Planung
|
||||
</button>
|
||||
<PageReturnButton
|
||||
fallbackPath={planningReturn.path}
|
||||
fallbackLabel={planningReturn.label}
|
||||
className="page-return-btn btn btn-secondary btn-small"
|
||||
/>
|
||||
{streamFocusOptions.length > 0 ? (
|
||||
<label
|
||||
className="no-print"
|
||||
|
||||
@@ -5,7 +5,15 @@ import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
||||
import PageSectionNav from '../components/PageSectionNav'
|
||||
import PageFormEditorChrome from '../components/PageFormEditorChrome'
|
||||
import SkillProfilePanel from '../components/skills/SkillProfilePanel'
|
||||
import { useToast } from '../context/ToastContext'
|
||||
import { useNavReturn } from '../hooks/useNavReturn'
|
||||
import {
|
||||
FRAMEWORK_PROGRAMS_LIST_PATH,
|
||||
buildFrameworkProgramsListReturnContext,
|
||||
preserveAppReturnOnNavigate,
|
||||
} from '../utils/navReturnContext'
|
||||
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
||||
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
||||
import {
|
||||
@@ -19,6 +27,7 @@ import {
|
||||
reorderSectionBeforeParallelRunAsWholeGroup,
|
||||
reorderSectionAsFirstInParallelStream,
|
||||
} from '../utils/trainingUnitSectionsForm'
|
||||
import { parseDurationInput } from '../utils/trainingDurationUtils'
|
||||
|
||||
const DND_FW_SLOT = 'application/x-shinkan-framework-slot'
|
||||
|
||||
@@ -45,7 +54,7 @@ function emptyGoal() {
|
||||
|
||||
|
||||
function emptySlot() {
|
||||
return { title: '', notes: '', sections: [defaultSection('Ablauf')] }
|
||||
return { title: '', notes: '', planned_duration_min: '', sections: [defaultSection('Ablauf')] }
|
||||
}
|
||||
|
||||
async function enrichFrameworkSlotSections(slots) {
|
||||
@@ -72,12 +81,10 @@ function defaultForm() {
|
||||
return {
|
||||
title: '',
|
||||
description: '',
|
||||
focus_area_id: '',
|
||||
style_direction_id: '',
|
||||
focus_area_ids: [],
|
||||
style_direction_ids: [],
|
||||
training_type_ids: [],
|
||||
target_group_ids: [],
|
||||
planned_period_start: '',
|
||||
planned_period_end: '',
|
||||
visibility: 'private',
|
||||
club_id: '',
|
||||
goals: [emptyGoal()],
|
||||
@@ -98,12 +105,10 @@ function frameworkDraftSnapshot(fm) {
|
||||
return JSON.stringify({
|
||||
title: (fm.title || '').trim(),
|
||||
description: (fm.description || '').trim(),
|
||||
focus_area_id: fm.focus_area_id || '',
|
||||
style_direction_id: fm.style_direction_id || '',
|
||||
focus_area_ids: [...(fm.focus_area_ids || [])].map(String).sort(),
|
||||
style_direction_ids: [...(fm.style_direction_ids || [])].map(String).sort(),
|
||||
training_type_ids: [...(fm.training_type_ids || [])].map(String).sort(),
|
||||
target_group_ids: [...(fm.target_group_ids || [])].map(String).sort(),
|
||||
planned_period_start: fm.planned_period_start || '',
|
||||
planned_period_end: fm.planned_period_end || '',
|
||||
visibility: (fm.visibility || '').trim(),
|
||||
club_id: (fm.club_id || '').trim(),
|
||||
goals: goalsNorm,
|
||||
@@ -116,16 +121,22 @@ function serverFrameworkToForm(fw) {
|
||||
return {
|
||||
title: fw.title || '',
|
||||
description: fw.description || '',
|
||||
focus_area_id: fw.focus_area_id != null ? String(fw.focus_area_id) : '',
|
||||
style_direction_id: fw.style_direction_id != null ? String(fw.style_direction_id) : '',
|
||||
focus_area_ids: Array.isArray(fw.focus_area_ids)
|
||||
? fw.focus_area_ids.map((x) => String(x))
|
||||
: fw.focus_area_id != null
|
||||
? [String(fw.focus_area_id)]
|
||||
: [],
|
||||
style_direction_ids: Array.isArray(fw.style_direction_ids)
|
||||
? fw.style_direction_ids.map((x) => String(x))
|
||||
: fw.style_direction_id != null
|
||||
? [String(fw.style_direction_id)]
|
||||
: [],
|
||||
training_type_ids: Array.isArray(fw.training_type_ids)
|
||||
? fw.training_type_ids.map((x) => String(x))
|
||||
: [],
|
||||
target_group_ids: Array.isArray(fw.target_group_ids)
|
||||
? fw.target_group_ids.map((x) => String(x))
|
||||
: [],
|
||||
planned_period_start: fw.planned_period_start || '',
|
||||
planned_period_end: fw.planned_period_end || '',
|
||||
visibility: fw.visibility || 'private',
|
||||
club_id: fw.club_id != null ? String(fw.club_id) : '',
|
||||
goals: goalsIn.map((g) => ({
|
||||
@@ -135,6 +146,10 @@ function serverFrameworkToForm(fw) {
|
||||
slots: (fw.slots || []).map((s) => ({
|
||||
title: s.title || '',
|
||||
notes: s.notes || '',
|
||||
planned_duration_min:
|
||||
s.planned_duration_min != null && s.planned_duration_min !== undefined
|
||||
? String(s.planned_duration_min)
|
||||
: '',
|
||||
sections: normalizeUnitToForm({
|
||||
sections: s.sections,
|
||||
exercises: s.exercises,
|
||||
@@ -163,6 +178,7 @@ function buildApiPayload(form) {
|
||||
sort_order: si,
|
||||
title: (s.title || '').trim() || null,
|
||||
notes: (s.notes || '').trim() || null,
|
||||
planned_duration_min: parseDurationInput(s.planned_duration_min),
|
||||
}
|
||||
if (plan.phases) {
|
||||
return { ...base, phases: plan.phases }
|
||||
@@ -170,14 +186,12 @@ function buildApiPayload(form) {
|
||||
return { ...base, sections: plan.sections }
|
||||
})
|
||||
|
||||
const focusAreaId =
|
||||
form.focus_area_id && !Number.isNaN(parseInt(form.focus_area_id, 10))
|
||||
? parseInt(form.focus_area_id, 10)
|
||||
: null
|
||||
const styleDirectionId =
|
||||
form.style_direction_id && !Number.isNaN(parseInt(form.style_direction_id, 10))
|
||||
? parseInt(form.style_direction_id, 10)
|
||||
: null
|
||||
const focus_area_ids = (form.focus_area_ids || [])
|
||||
.map((x) => parseInt(String(x), 10))
|
||||
.filter((n) => !Number.isNaN(n) && n > 0)
|
||||
const style_direction_ids = (form.style_direction_ids || [])
|
||||
.map((x) => parseInt(String(x), 10))
|
||||
.filter((n) => !Number.isNaN(n) && n > 0)
|
||||
|
||||
const training_type_ids = (form.training_type_ids || [])
|
||||
.map((x) => parseInt(String(x), 10))
|
||||
@@ -194,12 +208,10 @@ function buildApiPayload(form) {
|
||||
return {
|
||||
title: (form.title || '').trim(),
|
||||
description: (form.description || '').trim() || null,
|
||||
focus_area_id: focusAreaId,
|
||||
style_direction_id: styleDirectionId,
|
||||
focus_area_ids,
|
||||
style_direction_ids,
|
||||
training_type_ids,
|
||||
target_group_ids,
|
||||
planned_period_start: form.planned_period_start || null,
|
||||
planned_period_end: form.planned_period_end || null,
|
||||
visibility: form.visibility || 'private',
|
||||
club_id: clubId,
|
||||
goals,
|
||||
@@ -211,6 +223,8 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
const { id: idParam } = useParams()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const frameworkListReturn = useMemo(() => buildFrameworkProgramsListReturnContext(), [])
|
||||
const { goBack } = useNavReturn(frameworkListReturn)
|
||||
/** Route `…/framework-programs/new` hat kein dynamisches `:id` — useParams ist dann leer. */
|
||||
const isNew = /\/framework-programs\/new\/?$/.test(location.pathname)
|
||||
|
||||
@@ -235,6 +249,10 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
)
|
||||
/** Schmale Ansicht: welcher Session-Slot gerade die volle Breite nutzt (Chip-Navigation) */
|
||||
const [mobileSlotIdx, setMobileSlotIdx] = useState(0)
|
||||
const [skillProfileData, setSkillProfileData] = useState(null)
|
||||
const [skillProfileLoading, setSkillProfileLoading] = useState(false)
|
||||
const [skillProfileError, setSkillProfileError] = useState('')
|
||||
const [skillProfileTick, setSkillProfileTick] = useState(0)
|
||||
|
||||
const toast = useToast()
|
||||
const baselineRef = useRef(null)
|
||||
@@ -288,6 +306,32 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
return () => document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (isNew || !idParam) {
|
||||
setSkillProfileData(null)
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setSkillProfileLoading(true)
|
||||
setSkillProfileError('')
|
||||
try {
|
||||
const data = await api.getFrameworkProgramSkillProfile(idParam)
|
||||
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
|
||||
}
|
||||
}, [isNew, idParam, skillProfileTick])
|
||||
|
||||
const loadMeta = useCallback(async () => {
|
||||
try {
|
||||
const [cl, fa, sd, tt, tg] = await Promise.all([
|
||||
@@ -327,7 +371,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
}
|
||||
const fid = parseInt(idParam, 10)
|
||||
if (Number.isNaN(fid)) {
|
||||
navigate('/planning/framework-programs', { replace: true })
|
||||
navigate(FRAMEWORK_PROGRAMS_LIST_PATH, { replace: true })
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
@@ -341,7 +385,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
setForm(next)
|
||||
} catch (e) {
|
||||
toast.error(e.message || 'Laden fehlgeschlagen')
|
||||
navigate('/planning/framework-programs')
|
||||
goBack()
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
@@ -427,7 +471,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
}))
|
||||
}
|
||||
|
||||
const performFrameworkSave = async ({ fromUnsavedDialog = false } = {}) => {
|
||||
const performFrameworkSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
|
||||
if (!(form.title || '').trim()) {
|
||||
toast.error('Titel ist Pflichtfeld.')
|
||||
return false
|
||||
@@ -448,8 +492,12 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
if (isNew) {
|
||||
const created = await api.createTrainingFrameworkProgram(payload)
|
||||
toast.success('Rahmenprogramm angelegt.')
|
||||
if (!fromUnsavedDialog) {
|
||||
navigate(`/planning/framework-programs/${created.id}`, { replace: true })
|
||||
if (closeAfter) {
|
||||
goBack()
|
||||
} else if (!fromUnsavedDialog) {
|
||||
preserveAppReturnOnNavigate(navigate, location, `/planning/framework-programs/${created.id}`, {
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -463,6 +511,8 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
setBypassDirty(false)
|
||||
setBaselineReady(true)
|
||||
toast.success('Gespeichert.')
|
||||
setSkillProfileTick((t) => t + 1)
|
||||
if (closeAfter) goBack()
|
||||
return true
|
||||
} catch (e) {
|
||||
toast.error(e.message || 'Speichern fehlgeschlagen')
|
||||
@@ -473,9 +523,29 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
await performFrameworkSave({ fromUnsavedDialog: false })
|
||||
await performFrameworkSave({ fromUnsavedDialog: false, closeAfter: false })
|
||||
}
|
||||
|
||||
const handleSaveAndClose = async () => {
|
||||
await performFrameworkSave({ fromUnsavedDialog: false, closeAfter: true })
|
||||
}
|
||||
|
||||
const actionConfig = useMemo(
|
||||
() => ({
|
||||
saving,
|
||||
isNew,
|
||||
onSave: handleSave,
|
||||
onSaveAndClose: handleSaveAndClose,
|
||||
onCancel: goBack,
|
||||
showSave: true,
|
||||
showSaveAndClose: true,
|
||||
cancelLabel: 'Abbrechen',
|
||||
}),
|
||||
[saving, isNew, goBack, handleSave, handleSaveAndClose]
|
||||
)
|
||||
|
||||
const pageTitle = isNew ? 'Neues Rahmenprogramm' : 'Rahmenprogramm bearbeiten'
|
||||
|
||||
const handleUnsavedDialogSave = async () => {
|
||||
const ok = await performFrameworkSave({ fromUnsavedDialog: true })
|
||||
if (ok) blocker.proceed()
|
||||
@@ -487,7 +557,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
if (!confirm('Dieses Rahmenprogramm wirklich löschen?')) return
|
||||
try {
|
||||
await api.deleteTrainingFrameworkProgram(fid)
|
||||
navigate('/planning/framework-programs')
|
||||
goBack()
|
||||
} catch (e) {
|
||||
toast.error(e.message || 'Löschen fehlgeschlagen')
|
||||
}
|
||||
@@ -526,14 +596,15 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
desktopLayout ? undefined : { display: panelActive(key) ? 'block' : 'none' }
|
||||
|
||||
const trainingTypesFiltered = useMemo(() => {
|
||||
if (!form.focus_area_id) return trainingTypesCatalog
|
||||
const faSet = new Set((form.focus_area_ids || []).map(String))
|
||||
if (!faSet.size) return trainingTypesCatalog
|
||||
return trainingTypesCatalog.filter(
|
||||
(t) => !t.focus_area_id || String(t.focus_area_id) === String(form.focus_area_id)
|
||||
(t) => !t.focus_area_id || faSet.has(String(t.focus_area_id))
|
||||
)
|
||||
}, [trainingTypesCatalog, form.focus_area_id])
|
||||
}, [trainingTypesCatalog, form.focus_area_ids])
|
||||
|
||||
useEffect(() => {
|
||||
if (!form.focus_area_id || trainingTypesCatalog.length === 0) return
|
||||
if (!(form.focus_area_ids || []).length || trainingTypesCatalog.length === 0) return
|
||||
const allowed = new Set(trainingTypesFiltered.map((t) => String(t.id)))
|
||||
setForm((prev) => {
|
||||
const cur = prev.training_type_ids || []
|
||||
@@ -541,7 +612,27 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
if (next.length === cur.length) return prev
|
||||
return { ...prev, training_type_ids: next }
|
||||
})
|
||||
}, [form.focus_area_id, trainingTypesCatalog.length, trainingTypesFiltered])
|
||||
}, [form.focus_area_ids, trainingTypesCatalog.length, trainingTypesFiltered])
|
||||
|
||||
const toggleFocusAreaId = (fid) => {
|
||||
const idStr = String(fid)
|
||||
setForm((prev) => {
|
||||
const s = new Set(prev.focus_area_ids || [])
|
||||
if (s.has(idStr)) s.delete(idStr)
|
||||
else s.add(idStr)
|
||||
return { ...prev, focus_area_ids: [...s].sort((a, b) => Number(a) - Number(b)) }
|
||||
})
|
||||
}
|
||||
|
||||
const toggleStyleDirectionId = (sid) => {
|
||||
const idStr = String(sid)
|
||||
setForm((prev) => {
|
||||
const s = new Set(prev.style_direction_ids || [])
|
||||
if (s.has(idStr)) s.delete(idStr)
|
||||
else s.add(idStr)
|
||||
return { ...prev, style_direction_ids: [...s].sort((a, b) => Number(a) - Number(b)) }
|
||||
})
|
||||
}
|
||||
|
||||
const toggleTrainingTypeId = (tid) => {
|
||||
const idStr = String(tid)
|
||||
@@ -768,6 +859,20 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-row" style={{ marginTop: '0.5rem', maxWidth: '220px' }}>
|
||||
<label className="form-label" style={{ fontSize: '0.82rem' }}>
|
||||
Geplante Session-Dauer
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
inputMode="decimal"
|
||||
value={slot.planned_duration_min ?? ''}
|
||||
onChange={(e) => slotField(si, 'planned_duration_min', e.target.value)}
|
||||
placeholder="z. B. 1,5 h"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<details className="framework-slot-details">
|
||||
<summary className="framework-slot-details__summary">Notizen (Session)</summary>
|
||||
<div className="form-row">
|
||||
@@ -836,16 +941,12 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<PageFormEditorChrome
|
||||
testId="framework-program-form"
|
||||
title={pageTitle}
|
||||
actionConfig={actionConfig}
|
||||
>
|
||||
<div className="framework-edit">
|
||||
<p style={{ marginBottom: '0.75rem' }}>
|
||||
<Link to="/planning/framework-programs" style={{ color: 'var(--accent-dark)' }}>
|
||||
← Alle Rahmenprogramme
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
<h1 style={{ marginBottom: '0.75rem' }}>{isNew ? 'Neues Rahmenprogramm' : 'Rahmenprogramm bearbeiten'}</h1>
|
||||
|
||||
<details className="framework-edit-intro">
|
||||
<summary className="framework-edit-intro__summary">
|
||||
Kurz erklärt: Was ist ein Rahmenprogramm?
|
||||
@@ -871,6 +972,17 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isNew ? (
|
||||
<SkillProfilePanel
|
||||
title="Fähigkeiten-Schwerpunkte (aus Übungen)"
|
||||
profile={skillProfileData?.overall}
|
||||
slots={skillProfileData?.slots}
|
||||
loading={skillProfileLoading}
|
||||
error={skillProfileError}
|
||||
artifactType="framework_program"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={
|
||||
'framework-edit__panel framework-edit__panel--meta card' +
|
||||
@@ -898,35 +1010,47 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Fokusbereich (optional)</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={form.focus_area_id}
|
||||
onChange={(e) => updateField('focus_area_id', e.target.value)}
|
||||
>
|
||||
<option value="">— keiner —</option>
|
||||
{focusAreas.map((fa) => (
|
||||
<option key={fa.id} value={String(fa.id)}>
|
||||
{fa.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="form-sub">Hilft beim Filtern der Trainingsarten und bei der späteren Zuordnung in der Planung.</p>
|
||||
<label className="form-label">Fokusbereiche (optional, Mehrfachwahl)</label>
|
||||
<div className="framework-catalog-checkgrid">
|
||||
{focusAreas.length === 0 ? (
|
||||
<p className="form-sub" style={{ marginTop: 0 }}>
|
||||
Keine Fokusbereiche im Katalog.
|
||||
</p>
|
||||
) : (
|
||||
focusAreas.map((fa) => (
|
||||
<label key={fa.id} className="framework-catalog-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(form.focus_area_ids || []).includes(String(fa.id))}
|
||||
onChange={() => toggleFocusAreaId(fa.id)}
|
||||
/>
|
||||
<span>{fa.name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<p className="form-sub">Aus dem Katalog; filtert die Trainingsarten unten.</p>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Stilrichtung (optional)</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={form.style_direction_id}
|
||||
onChange={(e) => updateField('style_direction_id', e.target.value)}
|
||||
>
|
||||
<option value="">— keine —</option>
|
||||
{styleDirections.map((sd) => (
|
||||
<option key={sd.id} value={String(sd.id)}>
|
||||
{sd.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="form-label">Stilrichtungen (optional, Mehrfachwahl)</label>
|
||||
<div className="framework-catalog-checkgrid">
|
||||
{styleDirections.length === 0 ? (
|
||||
<p className="form-sub" style={{ marginTop: 0 }}>
|
||||
Keine Stilrichtungen im Katalog.
|
||||
</p>
|
||||
) : (
|
||||
styleDirections.map((sd) => (
|
||||
<label key={sd.id} className="framework-catalog-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(form.style_direction_ids || []).includes(String(sd.id))}
|
||||
onChange={() => toggleStyleDirectionId(sd.id)}
|
||||
/>
|
||||
<span>{sd.name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Trainingsarten (optional, Mehrfachwahl)</label>
|
||||
@@ -971,27 +1095,6 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="responsive-grid-2" style={{ marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label className="form-label">Zeitraum von</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={form.planned_period_start}
|
||||
onChange={(e) => updateField('planned_period_start', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label">Zeitraum bis</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={form.planned_period_end}
|
||||
onChange={(e) => updateField('planned_period_end', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="responsive-grid-2" style={{ marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
@@ -1021,6 +1124,14 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isNew ? (
|
||||
<div className="framework-edit__danger-zone">
|
||||
<button type="button" className="btn btn-secondary framework-edit__delete-btn" onClick={handleDelete}>
|
||||
Rahmenprogramm löschen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -1249,20 +1360,6 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', alignItems: 'center' }}>
|
||||
<button type="button" className="btn btn-primary" disabled={saving} onClick={handleSave}>
|
||||
{saving ? 'Speichern…' : isNew ? 'Anlegen' : 'Speichern'}
|
||||
</button>
|
||||
<Link to="/planning/framework-programs" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
|
||||
Abbrechen
|
||||
</Link>
|
||||
{!isNew ? (
|
||||
<button type="button" className="btn btn-secondary" onClick={handleDelete}>
|
||||
Löschen
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ExercisePickerModal
|
||||
@@ -1331,6 +1428,6 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
onSave={handleUnsavedDialogSave}
|
||||
onDiscardWithoutSave={() => setBypassDirty(true)}
|
||||
/>
|
||||
</div>
|
||||
</PageFormEditorChrome>
|
||||
)
|
||||
}
|
||||
@@ -1,77 +1,63 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import FrameworkProgramsFilterBlock from '../components/planning/FrameworkProgramsFilterBlock'
|
||||
import FrameworkProgramListCard from '../components/planning/FrameworkProgramListCard'
|
||||
import SkillProfileFullModal from '../components/skills/SkillProfileFullModal'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
|
||||
function dashIfEmpty(val) {
|
||||
const s = (val ?? '').toString().trim()
|
||||
return s.length ? s : '—'
|
||||
}
|
||||
|
||||
function FrameworkSummaryMeta({ r }) {
|
||||
const trainingTypes =
|
||||
typeof r.training_type_names_agg === 'string' ? r.training_type_names_agg.trim() : ''
|
||||
const targetGroups =
|
||||
typeof r.target_group_names_agg === 'string' ? r.target_group_names_agg.trim() : ''
|
||||
const styleDir = typeof r.style_direction_name === 'string' ? r.style_direction_name.trim() : ''
|
||||
const focus = typeof r.focus_area_name === 'string' ? r.focus_area_name.trim() : ''
|
||||
|
||||
const rowStyle = {
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(6.5rem, 32%) 1fr',
|
||||
gap: '0.25rem 0.75rem',
|
||||
alignItems: 'start',
|
||||
marginTop: '0.35rem',
|
||||
lineHeight: 1.45,
|
||||
}
|
||||
|
||||
return (
|
||||
<dl style={{ margin: '0.5rem 0 0', padding: 0, fontSize: '0.875rem', color: 'var(--text2)' }}>
|
||||
<div style={rowStyle}>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>Fokusbereich</dt>
|
||||
<dd style={{ margin: 0 }}>{dashIfEmpty(focus)}</dd>
|
||||
</div>
|
||||
{styleDir ? (
|
||||
<div style={rowStyle}>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>Stilrichtung</dt>
|
||||
<dd style={{ margin: 0 }}>{styleDir}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
<div style={rowStyle}>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>Trainingsarten</dt>
|
||||
<dd style={{ margin: 0 }}>{trainingTypes.length ? trainingTypes : '—'}</dd>
|
||||
</div>
|
||||
<div style={rowStyle}>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>Zielgruppen</dt>
|
||||
<dd style={{ margin: 0 }}>{targetGroups.length ? targetGroups : '—'}</dd>
|
||||
</div>
|
||||
<div style={{ ...rowStyle, marginTop: '0.5rem' }}>
|
||||
<dt style={{ margin: 0, fontWeight: 600, color: 'var(--text3)' }}>Kurzbeschreibung</dt>
|
||||
<dd style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
|
||||
{(r.description && String(r.description).trim()) || '—'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)
|
||||
}
|
||||
import { buildFrameworkProgramsListReturnContext } from '../utils/navReturnContext'
|
||||
import {
|
||||
EMPTY_FRAMEWORK_IMPORT_FILTERS,
|
||||
filterFrameworkPrograms,
|
||||
hasActiveFrameworkImportFilters,
|
||||
} from '../utils/frameworkProgramListHelpers'
|
||||
|
||||
export default function TrainingFrameworkProgramsListPage() {
|
||||
const { user } = useAuth()
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
const frameworkListReturn = useMemo(() => buildFrameworkProgramsListReturnContext(), [])
|
||||
const [rows, setRows] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [catalogFocusAreas, setCatalogFocusAreas] = useState([])
|
||||
const [catalogTrainingTypes, setCatalogTrainingTypes] = useState([])
|
||||
const [catalogTargetGroups, setCatalogTargetGroups] = useState([])
|
||||
const [catalogSkills, setCatalogSkills] = useState([])
|
||||
const [filters, setFilters] = useState(() => ({ ...EMPTY_FRAMEWORK_IMPORT_FILTERS }))
|
||||
const [skillSummaries, setSkillSummaries] = useState({})
|
||||
const [summariesLoading, setSummariesLoading] = useState(false)
|
||||
const [profileModal, setProfileModal] = useState(null)
|
||||
|
||||
const filteredRows = useMemo(
|
||||
() => filterFrameworkPrograms(rows, filters, skillSummaries),
|
||||
[rows, filters, skillSummaries]
|
||||
)
|
||||
const filterActive = hasActiveFrameworkImportFilters(filters)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const list = await api.listTrainingFrameworkPrograms()
|
||||
const [list, fa, tt, tg, skills] = await Promise.all([
|
||||
api.listTrainingFrameworkPrograms(),
|
||||
api.listFocusAreas({ status: 'active' }),
|
||||
api.listTrainingTypes({ status: 'active' }),
|
||||
api.listTargetGroups({ status: 'active' }),
|
||||
api.listSkillsCatalog({ status: 'active' }),
|
||||
])
|
||||
setRows(Array.isArray(list) ? list : [])
|
||||
setCatalogFocusAreas(Array.isArray(fa) ? fa : [])
|
||||
setCatalogTrainingTypes(Array.isArray(tt) ? tt : [])
|
||||
setCatalogTargetGroups(Array.isArray(tg) ? tg : [])
|
||||
setCatalogSkills(Array.isArray(skills) ? skills : [])
|
||||
} catch (e) {
|
||||
setError(e.message || 'Laden fehlgeschlagen')
|
||||
setRows([])
|
||||
setCatalogFocusAreas([])
|
||||
setCatalogTrainingTypes([])
|
||||
setCatalogTargetGroups([])
|
||||
setCatalogSkills([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -81,6 +67,29 @@ export default function TrainingFrameworkProgramsListPage() {
|
||||
load()
|
||||
}, [load, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!rows.length) {
|
||||
setSkillSummaries({})
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
setSummariesLoading(true)
|
||||
api
|
||||
.batchSkillProfileSummaries({ frameworkProgramIds: rows.map((r) => r.id) })
|
||||
.then((data) => {
|
||||
if (!cancelled) setSkillSummaries(data?.summaries || {})
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSkillSummaries({})
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setSummariesLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [rows, tenantClubDepKey])
|
||||
|
||||
async function handleDelete(id, title) {
|
||||
if (!confirm(`Rahmenprogramm „${title || id}“ wirklich löschen?`)) return
|
||||
try {
|
||||
@@ -92,121 +101,118 @@ export default function TrainingFrameworkProgramsListPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'space-between',
|
||||
gap: '1rem',
|
||||
marginBottom: '1.25rem',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h1 className="page-title" style={{ marginBottom: '0.35rem' }}>
|
||||
Trainingsrahmenprogramme
|
||||
</h1>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '36rem', margin: 0 }}>
|
||||
Vorlagen für Ziele und Sessions — die Verknüpfung mit Gruppenterminen erfolgt in der{' '}
|
||||
<Link to="/planning" style={{ fontWeight: 600, color: 'var(--accent-dark)' }}>
|
||||
Trainingsplanung
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<details className="planning-filter-help" style={{ marginTop: '10px', maxWidth: '36rem' }}>
|
||||
<summary className="planning-filter-help__summary">Mehr zur Übernahme in die Planung</summary>
|
||||
<div className="planning-filter-help__body">
|
||||
Unter <strong>Planung</strong> wählst du eine Gruppe und übernimmst Slots aus einem Rahmenprogramm in
|
||||
echte Termine. So bleibt die Bibliothek wiederverwendbar, ohne dass Einzelgruppen fest verdrahtet sind.
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<Link
|
||||
to="/planning/framework-programs/new"
|
||||
className="btn btn-primary"
|
||||
style={{ textDecoration: 'none', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
Rahmenprogramm anlegen
|
||||
</Link>
|
||||
<div className="fw-prog-page">
|
||||
<header className="fw-prog-page__header">
|
||||
<div className="fw-prog-page__intro">
|
||||
<h1 className="page-title fw-prog-page__title">Trainingsrahmenprogramme</h1>
|
||||
<p className="fw-prog-page__lead">
|
||||
Vorlagen für Entwicklungsziele und Sessions — die Übernahme in Gruppentermine erfolgt in der
|
||||
Trainingsplanung.
|
||||
</p>
|
||||
<details className="planning-filter-help fw-prog-page__help">
|
||||
<summary className="planning-filter-help__summary">Mehr zur Übernahme in die Planung</summary>
|
||||
<div className="planning-filter-help__body">
|
||||
Unter <strong>Planung</strong> wählst du eine Gruppe und übernimmst Slots aus einem Rahmenprogramm in
|
||||
echte Termine. So bleibt die Bibliothek wiederverwendbar, ohne dass Einzelgruppen fest verdrahtet sind.
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<NavStateLink
|
||||
to="/planning/framework-programs/new"
|
||||
returnContext={frameworkListReturn}
|
||||
className="btn btn-primary fw-prog-page__cta"
|
||||
>
|
||||
Rahmenprogramm anlegen
|
||||
</NavStateLink>
|
||||
</header>
|
||||
|
||||
<p style={{ marginBottom: '1rem' }}>
|
||||
<Link to="/planning" style={{ color: 'var(--accent-dark)' }}>
|
||||
← Zurück zur Trainingsplanung
|
||||
</Link>
|
||||
</p>
|
||||
{error ? (
|
||||
<div className="card fw-prog-page__error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error && (
|
||||
<div className="card" style={{ borderLeft: '4px solid var(--danger)', marginBottom: '1rem' }}>
|
||||
{error}
|
||||
{loading ? (
|
||||
<div className="fw-prog-page__loading card">
|
||||
<div className="spinner" aria-hidden="true" />
|
||||
<p>Rahmenprogramme werden geladen…</p>
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="card fw-prog-page__empty">
|
||||
<div className="fw-prog-page__empty-icon" aria-hidden="true">
|
||||
📋
|
||||
</div>
|
||||
)}
|
||||
<h2 className="fw-prog-page__empty-title">Noch keine Rahmenprogramme</h2>
|
||||
<p className="fw-prog-page__empty-text">
|
||||
Lege ein neues Programm an — mit Titel, mindestens einem Entwicklungsziel und optional Sessions samt
|
||||
Übungsablauf.
|
||||
</p>
|
||||
<NavStateLink
|
||||
to="/planning/framework-programs/new"
|
||||
returnContext={frameworkListReturn}
|
||||
className="btn btn-primary btn-full"
|
||||
>
|
||||
Erstes Rahmenprogramm anlegen
|
||||
</NavStateLink>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FrameworkProgramsFilterBlock
|
||||
programs={rows}
|
||||
filters={filters}
|
||||
onFiltersChange={setFilters}
|
||||
catalogFocusAreas={catalogFocusAreas}
|
||||
catalogTrainingTypes={catalogTrainingTypes}
|
||||
catalogTargetGroups={catalogTargetGroups}
|
||||
catalogSkills={catalogSkills}
|
||||
skillSummaries={skillSummaries}
|
||||
durationRadioName="fw-list-duration-mode"
|
||||
className="fw-prog-filter-block--list"
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div style={{ textAlign: 'center', padding: '2rem' }}>
|
||||
<div className="spinner" />
|
||||
<p>Laden…</p>
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="card">
|
||||
<p style={{ color: 'var(--text2)', marginBottom: '1rem' }}>
|
||||
Noch kein Rahmenprogramm gespeichert. Lege ein neues an — mit Titel, mindestens einem Ziel und optional
|
||||
Slots samt Übungen.
|
||||
</p>
|
||||
<Link
|
||||
to="/planning/framework-programs/new"
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ textDecoration: 'none' }}
|
||||
>
|
||||
Rahmenprogramm anlegen
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="framework-programs-list">
|
||||
{rows.map((r) => (
|
||||
<li key={r.id} className="card">
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'space-between',
|
||||
gap: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ minWidth: 0, flex: '1 1 220px' }}>
|
||||
<Link
|
||||
to={`/planning/framework-programs/${r.id}`}
|
||||
style={{ fontWeight: 600, fontSize: '1.05rem', color: 'var(--text1)' }}
|
||||
>
|
||||
{r.title || `Rahmen #${r.id}`}
|
||||
</Link>
|
||||
<div style={{ fontSize: '0.85rem', color: 'var(--text2)', marginTop: '0.35rem' }}>
|
||||
<span>
|
||||
{(r.goals_count ?? '—') + ' Ziele · '}
|
||||
{(r.slots_count ?? '—') + ' Slots'}
|
||||
</span>
|
||||
</div>
|
||||
<FrameworkSummaryMeta r={r} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
|
||||
<Link
|
||||
to={`/planning/framework-programs/${r.id}`}
|
||||
className="btn btn-secondary"
|
||||
style={{ textDecoration: 'none' }}
|
||||
>
|
||||
Bearbeiten
|
||||
</Link>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => handleDelete(r.id, r.title)}>
|
||||
Löschen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{filteredRows.length === 0 ? (
|
||||
<div className="card fw-prog-page__empty fw-prog-page__empty--filter">
|
||||
<h2 className="fw-prog-page__empty-title">Kein Treffer</h2>
|
||||
<p className="fw-prog-page__empty-text">
|
||||
{filterActive
|
||||
? 'Kein Rahmenprogramm passt zu den gewählten Filtern. Passe die Kriterien an oder setze den Filter zurück.'
|
||||
: 'Keine Einträge.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="fw-prog-list" aria-label="Rahmenprogramme">
|
||||
{filteredRows.map((r) => (
|
||||
<li key={r.id}>
|
||||
<FrameworkProgramListCard
|
||||
row={r}
|
||||
returnContext={frameworkListReturn}
|
||||
onDelete={handleDelete}
|
||||
skillSummary={skillSummaries[`framework_program:${r.id}`]}
|
||||
skillSummaryLoading={summariesLoading}
|
||||
skillFilterIds={filters.skillIds || []}
|
||||
skillDisplayLimit={filters.skillDisplayLimit || 10}
|
||||
onShowSkillProfile={(row) =>
|
||||
setProfileModal({
|
||||
artifactType: 'framework_program',
|
||||
artifactId: row.id,
|
||||
title: (row.title || '').trim() || `Rahmen #${row.id}`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<SkillProfileFullModal
|
||||
open={Boolean(profileModal)}
|
||||
onClose={() => setProfileModal(null)}
|
||||
artifactType={profileModal?.artifactType}
|
||||
artifactId={profileModal?.artifactId}
|
||||
title={profileModal?.title}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,13 +1,20 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||
import FormActionBar from '../components/FormActionBar'
|
||||
import SkillProfilePanel from '../components/skills/SkillProfilePanel'
|
||||
import { hydrateExercisePlanningRow } from '../utils/trainingUnitSectionsForm'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { useToast } from '../context/ToastContext'
|
||||
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
||||
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
||||
import { activeClubMemberships, getDefaultClubIdForGovernanceForms, getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import {
|
||||
buildTrainingModulesListReturnContext,
|
||||
goNavReturn,
|
||||
preserveAppReturnOnNavigate,
|
||||
} from '../utils/navReturnContext'
|
||||
|
||||
function moduleFormSnapshot({
|
||||
title,
|
||||
@@ -61,6 +68,7 @@ function swapItems(arr, i, j) {
|
||||
export default function TrainingModuleEditPage() {
|
||||
const { id: routeId } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const isNew = !routeId || routeId === 'new'
|
||||
const moduleId = !isNew ? parseInt(routeId, 10) : NaN
|
||||
|
||||
@@ -69,6 +77,10 @@ export default function TrainingModuleEditPage() {
|
||||
const [methods, setMethods] = useState([])
|
||||
const [pickerOpen, setPickerOpen] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [skillProfileData, setSkillProfileData] = useState(null)
|
||||
const [skillProfileLoading, setSkillProfileLoading] = useState(false)
|
||||
const [skillProfileError, setSkillProfileError] = useState('')
|
||||
const [skillProfileTick, setSkillProfileTick] = useState(0)
|
||||
|
||||
const [title, setTitle] = useState('')
|
||||
const [summary, setSummary] = useState('')
|
||||
@@ -123,6 +135,32 @@ export default function TrainingModuleEditPage() {
|
||||
const blocker = useUnsavedChangesBlocker(Boolean(formDirtyEffective && !saving))
|
||||
useBeforeUnloadWhen(Boolean(formDirtyEffective && !saving))
|
||||
|
||||
useEffect(() => {
|
||||
if (isNew || !Number.isFinite(moduleId)) {
|
||||
setSkillProfileData(null)
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setSkillProfileLoading(true)
|
||||
setSkillProfileError('')
|
||||
try {
|
||||
const data = await api.getTrainingModuleSkillProfile(moduleId)
|
||||
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
|
||||
}
|
||||
}, [isNew, moduleId, skillProfileTick])
|
||||
|
||||
const { user } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
@@ -301,7 +339,13 @@ export default function TrainingModuleEditPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const performModuleSave = async ({ fromUnsavedDialog = false } = {}) => {
|
||||
const moduleListReturn = useMemo(() => buildTrainingModulesListReturnContext(), [])
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
goNavReturn(navigate, location, moduleListReturn)
|
||||
}, [navigate, location, moduleListReturn])
|
||||
|
||||
const performModuleSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
|
||||
if (!title.trim()) {
|
||||
toast.error('Titel ist Pflicht.')
|
||||
return false
|
||||
@@ -313,8 +357,12 @@ export default function TrainingModuleEditPage() {
|
||||
if (isNew) {
|
||||
const created = await api.createTrainingModule(body)
|
||||
toast.success('Trainingsmodul angelegt.')
|
||||
if (!fromUnsavedDialog) {
|
||||
navigate(`/planning/training-modules/${created.id}`, { replace: true })
|
||||
if (closeAfter) {
|
||||
goBack()
|
||||
} else if (!fromUnsavedDialog) {
|
||||
preserveAppReturnOnNavigate(navigate, location, `/planning/training-modules/${created.id}`, {
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -322,6 +370,8 @@ export default function TrainingModuleEditPage() {
|
||||
baselineRef.current = moduleFormSnapshot(latestFormRef.current)
|
||||
setBypassDirty(false)
|
||||
toast.success('Gespeichert.')
|
||||
setSkillProfileTick((t) => t + 1)
|
||||
if (closeAfter) goBack()
|
||||
return true
|
||||
} catch (err) {
|
||||
const msg = err.message || 'Speichern fehlgeschlagen'
|
||||
@@ -334,8 +384,12 @@ export default function TrainingModuleEditPage() {
|
||||
}
|
||||
|
||||
const handleSave = async (e) => {
|
||||
e.preventDefault()
|
||||
await performModuleSave({ fromUnsavedDialog: false })
|
||||
e?.preventDefault?.()
|
||||
await performModuleSave({ fromUnsavedDialog: false, closeAfter: false })
|
||||
}
|
||||
|
||||
const handleSaveAndClose = async () => {
|
||||
await performModuleSave({ fromUnsavedDialog: false, closeAfter: true })
|
||||
}
|
||||
|
||||
const handleUnsavedDialogSave = async () => {
|
||||
@@ -353,11 +407,6 @@ export default function TrainingModuleEditPage() {
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<p style={{ marginBottom: '0.75rem' }}>
|
||||
<Link to="/planning/training-modules" style={{ color: 'var(--accent-dark)', fontWeight: 600 }}>
|
||||
← Zurück zur Modul‑Bibliothek
|
||||
</Link>
|
||||
</p>
|
||||
<h1 className="page-title">{isNew ? 'Neues Trainingsmodul' : 'Trainingsmodul bearbeiten'}</h1>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', marginBottom: '1.25rem', maxWidth: '40rem' }}>
|
||||
Reihenfolge der Positionen entspricht der späteren Übernahme in einen Abschnitt der Einheit (Kopie).
|
||||
@@ -367,7 +416,22 @@ export default function TrainingModuleEditPage() {
|
||||
{loading ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Laden …</p>
|
||||
) : (
|
||||
<form className="card" style={{ padding: 'clamp(14px, 3vw, 1.75rem)', maxWidth: '720px' }} onSubmit={handleSave}>
|
||||
<form
|
||||
id="training-module-form"
|
||||
className="card page-form-shell"
|
||||
style={{ padding: 'clamp(14px, 3vw, 1.75rem)', maxWidth: '720px' }}
|
||||
onSubmit={handleSave}
|
||||
>
|
||||
<div className="page-form-shell__scroll">
|
||||
{!isNew ? (
|
||||
<SkillProfilePanel
|
||||
title="Fähigkeiten im Modul"
|
||||
profile={skillProfileData?.overall}
|
||||
loading={skillProfileLoading}
|
||||
error={skillProfileError}
|
||||
artifactType="training_module"
|
||||
/>
|
||||
) : null}
|
||||
<div className="form-row">
|
||||
<label className="form-label">Titel *</label>
|
||||
<input className="form-input" value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
@@ -648,14 +712,17 @@ export default function TrainingModuleEditPage() {
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div style={{ display: 'flex', gap: '10px', marginTop: '1.5rem', flexWrap: 'wrap' }}>
|
||||
<button type="submit" className="btn btn-primary" disabled={saving}>
|
||||
{saving ? 'Speichern …' : isNew ? 'Anlegen' : 'Speichern'}
|
||||
</button>
|
||||
<Link to="/planning/training-modules" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
|
||||
Abbrechen
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<FormActionBar
|
||||
formId="training-module-form"
|
||||
isNew={isNew}
|
||||
saving={saving}
|
||||
onSave={() => handleSave()}
|
||||
onSaveAndClose={handleSaveAndClose}
|
||||
onCancel={goBack}
|
||||
cancelLabel="Abbrechen"
|
||||
/>
|
||||
</form>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,25 +1,51 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import TrainingModulesFilterBlock from '../components/planning/TrainingModulesFilterBlock'
|
||||
import SkillProfileCompact from '../components/skills/SkillProfileCompact'
|
||||
import SkillProfileFullModal from '../components/skills/SkillProfileFullModal'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import { buildTrainingModulesListReturnContext } from '../utils/navReturnContext'
|
||||
import {
|
||||
EMPTY_TRAINING_MODULE_FILTERS,
|
||||
filterTrainingModules,
|
||||
hasActiveTrainingModuleFilters,
|
||||
} from '../utils/trainingModuleListHelpers'
|
||||
|
||||
export default function TrainingModulesListPage() {
|
||||
const { user } = useAuth()
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
const modulesListReturn = useMemo(() => buildTrainingModulesListReturnContext(), [])
|
||||
const [rows, setRows] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [catalogSkills, setCatalogSkills] = useState([])
|
||||
const [filters, setFilters] = useState(() => ({ ...EMPTY_TRAINING_MODULE_FILTERS }))
|
||||
const [skillSummaries, setSkillSummaries] = useState({})
|
||||
const [summariesLoading, setSummariesLoading] = useState(false)
|
||||
const [profileModal, setProfileModal] = useState(null)
|
||||
|
||||
const filteredRows = useMemo(
|
||||
() => filterTrainingModules(rows, filters, skillSummaries),
|
||||
[rows, filters, skillSummaries]
|
||||
)
|
||||
const filterActive = hasActiveTrainingModuleFilters(filters)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const list = await api.listTrainingModules()
|
||||
const [list, skills] = await Promise.all([
|
||||
api.listTrainingModules(),
|
||||
api.listSkillsCatalog({ status: 'active' }),
|
||||
])
|
||||
setRows(Array.isArray(list) ? list : [])
|
||||
setCatalogSkills(Array.isArray(skills) ? skills : [])
|
||||
} catch (e) {
|
||||
setError(e.message || 'Laden fehlgeschlagen')
|
||||
setRows([])
|
||||
setCatalogSkills([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -29,6 +55,29 @@ export default function TrainingModulesListPage() {
|
||||
load()
|
||||
}, [load, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!rows.length) {
|
||||
setSkillSummaries({})
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
setSummariesLoading(true)
|
||||
api
|
||||
.batchSkillProfileSummaries({ trainingModuleIds: rows.map((r) => r.id) })
|
||||
.then((data) => {
|
||||
if (!cancelled) setSkillSummaries(data?.summaries || {})
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSkillSummaries({})
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setSummariesLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [rows, tenantClubDepKey])
|
||||
|
||||
async function handleDelete(id, title) {
|
||||
if (!confirm(`Trainingsmodul „${title || id}“ wirklich löschen?`)) return
|
||||
try {
|
||||
@@ -40,7 +89,7 @@ export default function TrainingModulesListPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
@@ -56,16 +105,18 @@ export default function TrainingModulesListPage() {
|
||||
Trainingsmodule
|
||||
</h1>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '38rem', margin: 0 }}>
|
||||
Wiederverwendbare Übungsfolgen für die{' '}
|
||||
<Link to="/planning" style={{ fontWeight: 600, color: 'var(--accent-dark)' }}>
|
||||
Trainingsplanung
|
||||
</Link>
|
||||
. Übernahme in eine Einheit erfolgt dort als lokale Kopie (mit Herkunftsmarkierung).
|
||||
Wiederverwendbare Übungsfolgen für die Trainingsplanung. Prozentwerte vergleichen Module nur unter
|
||||
sichtbaren Modulen.
|
||||
</p>
|
||||
</div>
|
||||
<Link to="/planning/training-modules/new" className="btn btn-primary" style={{ textDecoration: 'none' }}>
|
||||
<NavStateLink
|
||||
to="/planning/training-modules/new"
|
||||
returnContext={modulesListReturn}
|
||||
className="btn btn-primary"
|
||||
style={{ textDecoration: 'none' }}
|
||||
>
|
||||
Neues Modul
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
@@ -78,58 +129,118 @@ export default function TrainingModulesListPage() {
|
||||
<p style={{ margin: 0, color: 'var(--text2)' }}>Noch keine Module angelegt.</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '10px' }}>
|
||||
{rows.map((r) => (
|
||||
<li key={r.id} className="card" style={{ padding: '1rem 1.15rem' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'space-between',
|
||||
gap: '10px',
|
||||
alignItems: 'flex-start',
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: '1 1 220px', minWidth: 0 }}>
|
||||
<Link
|
||||
to={`/planning/training-modules/${r.id}`}
|
||||
<>
|
||||
<TrainingModulesFilterBlock
|
||||
modules={rows}
|
||||
filters={filters}
|
||||
onFiltersChange={setFilters}
|
||||
catalogSkills={catalogSkills}
|
||||
skillSummaries={skillSummaries}
|
||||
className="fw-prog-filter-block--list"
|
||||
/>
|
||||
|
||||
{filteredRows.length === 0 ? (
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<h2 style={{ margin: '0 0 0.5rem', fontSize: '1.05rem' }}>Kein Treffer</h2>
|
||||
<p style={{ margin: 0, color: 'var(--text2)' }}>
|
||||
{filterActive
|
||||
? 'Kein Modul passt zu den gewählten Filtern. Passe die Kriterien an oder setze den Filter zurück.'
|
||||
: 'Keine Einträge.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul
|
||||
style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '10px' }}
|
||||
>
|
||||
{filteredRows.map((r) => (
|
||||
<li key={r.id} className="card" style={{ padding: '1rem 1.15rem' }}>
|
||||
<div
|
||||
style={{
|
||||
fontWeight: 700,
|
||||
fontSize: '1.05rem',
|
||||
color: 'var(--accent-dark)',
|
||||
textDecoration: 'none',
|
||||
wordBreak: 'break-word',
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'space-between',
|
||||
gap: '10px',
|
||||
alignItems: 'flex-start',
|
||||
}}
|
||||
>
|
||||
{(r.title || '').trim() || `Modul #${r.id}`}
|
||||
</Link>
|
||||
<p style={{ margin: '0.35rem 0 0', fontSize: '0.88rem', color: 'var(--text2)', lineHeight: 1.45 }}>
|
||||
{(r.summary || '').trim() || '—'}{' '}
|
||||
<span style={{ color: 'var(--text3)' }}>
|
||||
({Number(r.items_count) || 0} Position{r.items_count === 1 ? '' : 'en'})
|
||||
</span>
|
||||
</p>
|
||||
<p style={{ margin: '0.35rem 0 0', fontSize: '0.8rem', color: 'var(--text3)' }}>
|
||||
Sichtbarkeit: <strong>{r.visibility || '—'}</strong>
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
|
||||
<Link
|
||||
className="btn btn-secondary"
|
||||
style={{ textDecoration: 'none' }}
|
||||
to={`/planning/training-modules/${r.id}`}
|
||||
>
|
||||
Bearbeiten
|
||||
</Link>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => handleDelete(r.id, r.title)}>
|
||||
Löschen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div style={{ flex: '1 1 220px', minWidth: 0 }}>
|
||||
<NavStateLink
|
||||
to={`/planning/training-modules/${r.id}`}
|
||||
returnContext={modulesListReturn}
|
||||
style={{
|
||||
fontWeight: 700,
|
||||
fontSize: '1.05rem',
|
||||
color: 'var(--accent-dark)',
|
||||
textDecoration: 'none',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
{(r.title || '').trim() || `Modul #${r.id}`}
|
||||
</NavStateLink>
|
||||
<p
|
||||
style={{
|
||||
margin: '0.35rem 0 0',
|
||||
fontSize: '0.88rem',
|
||||
color: 'var(--text2)',
|
||||
lineHeight: 1.45,
|
||||
}}
|
||||
>
|
||||
{(r.summary || '').trim() || '—'}{' '}
|
||||
<span style={{ color: 'var(--text3)' }}>
|
||||
({Number(r.items_count) || 0} Position{r.items_count === 1 ? '' : 'en'})
|
||||
</span>
|
||||
</p>
|
||||
<div style={{ marginTop: '0.5rem' }}>
|
||||
<SkillProfileCompact
|
||||
summary={skillSummaries[`training_module:${r.id}`]}
|
||||
artifactType="training_module"
|
||||
loading={summariesLoading}
|
||||
displayLimit={filters.skillDisplayLimit || 12}
|
||||
highlightSkillIds={filters.skillIds || []}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-small"
|
||||
onClick={() =>
|
||||
setProfileModal({
|
||||
artifactType: 'training_module',
|
||||
artifactId: r.id,
|
||||
title: (r.title || '').trim() || `Modul #${r.id}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
Fähigkeiten-Profil
|
||||
</button>
|
||||
<NavStateLink
|
||||
to={`/planning/training-modules/${r.id}`}
|
||||
returnContext={modulesListReturn}
|
||||
className="btn btn-secondary"
|
||||
style={{ textDecoration: 'none' }}
|
||||
>
|
||||
Bearbeiten
|
||||
</NavStateLink>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => handleDelete(r.id, r.title)}>
|
||||
Löschen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SkillProfileFullModal
|
||||
open={Boolean(profileModal)}
|
||||
onClose={() => setProfileModal(null)}
|
||||
artifactType={profileModal?.artifactType}
|
||||
artifactId={profileModal?.artifactId}
|
||||
title={profileModal?.title}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
||||
import FormActionBar from '../components/FormActionBar'
|
||||
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
||||
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { useToast } from '../context/ToastContext'
|
||||
import { useNavReturn } from '../hooks/useNavReturn'
|
||||
import {
|
||||
buildPlanTemplatesListReturnContext,
|
||||
} from '../utils/navReturnContext'
|
||||
import {
|
||||
defaultSection,
|
||||
formSectionsFromPlanTemplateRows,
|
||||
templateSectionsPayloadFromFormSections,
|
||||
} from '../utils/trainingUnitSectionsForm'
|
||||
import {
|
||||
activeClubMemberships,
|
||||
getDefaultClubIdForGovernanceForms,
|
||||
getTenantClubDependencyKey,
|
||||
} from '../utils/activeClub'
|
||||
|
||||
function templateFormSnapshot({ name, description, visibility, clubIdField, sections }) {
|
||||
return JSON.stringify({
|
||||
name: (name || '').trim(),
|
||||
description: (description || '').trim(),
|
||||
visibility: visibility || '',
|
||||
clubIdField: (clubIdField || '').trim(),
|
||||
sections: templateSectionsPayloadFromFormSections(sections),
|
||||
})
|
||||
}
|
||||
|
||||
export default function TrainingPlanTemplateEditPage() {
|
||||
const { id: routeId } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const templatesListReturn = useMemo(() => buildPlanTemplatesListReturnContext(), [])
|
||||
const { goBack } = useNavReturn(templatesListReturn)
|
||||
const templateId = parseInt(routeId, 10)
|
||||
const toast = useToast()
|
||||
const { user } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [visibility, setVisibility] = useState('club')
|
||||
const [clubIdField, setClubIdField] = useState('')
|
||||
const [sections, setSections] = useState([defaultSection()])
|
||||
const [clubsForGovernanceForms, setClubsForGovernanceForms] = useState([])
|
||||
|
||||
const baselineRef = useRef(null)
|
||||
const latestFormRef = useRef({})
|
||||
const [baselineReady, setBaselineReady] = useState(false)
|
||||
const [bypassDirty, setBypassDirty] = useState(false)
|
||||
|
||||
latestFormRef.current = { name, description, visibility, clubIdField, sections }
|
||||
|
||||
const dirtySignature = templateFormSnapshot(latestFormRef.current)
|
||||
const formDirtyEffective =
|
||||
baselineReady && baselineRef.current != null && !bypassDirty && !loading && dirtySignature !== baselineRef.current
|
||||
|
||||
const blocker = useUnsavedChangesBlocker(Boolean(formDirtyEffective && !saving))
|
||||
useBeforeUnloadWhen(Boolean(formDirtyEffective && !saving))
|
||||
|
||||
const membershipClubRows = useMemo(() => activeClubMemberships(user?.clubs ?? []), [user?.clubs])
|
||||
|
||||
const visibilityClubChoices = useMemo(() => {
|
||||
if (isPlatformAdmin && clubsForGovernanceForms.length > 0) {
|
||||
return [...clubsForGovernanceForms].sort((a, b) =>
|
||||
String(a.name || '').localeCompare(String(b.name || ''), 'de')
|
||||
)
|
||||
}
|
||||
return [...membershipClubRows].sort((a, b) =>
|
||||
String(a.name || '').localeCompare(String(b.name || ''), 'de')
|
||||
)
|
||||
}, [isPlatformAdmin, clubsForGovernanceForms, membershipClubRows])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlatformAdmin) {
|
||||
setClubsForGovernanceForms([])
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const list = await api.listClubs()
|
||||
if (!cancelled) setClubsForGovernanceForms(Array.isArray(list) ? list : [])
|
||||
} catch {
|
||||
if (!cancelled) setClubsForGovernanceForms([])
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isPlatformAdmin, tenantClubDepKey])
|
||||
|
||||
useEffect(() => {
|
||||
baselineRef.current = null
|
||||
setBaselineReady(false)
|
||||
setBypassDirty(false)
|
||||
}, [templateId])
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return
|
||||
const handle = window.setTimeout(() => {
|
||||
baselineRef.current = templateFormSnapshot(latestFormRef.current)
|
||||
setBaselineReady(true)
|
||||
}, 120)
|
||||
return () => clearTimeout(handle)
|
||||
}, [loading, templateId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(templateId) || templateId < 1) {
|
||||
setError('Ungültige Vorlagen-ID')
|
||||
setLoading(false)
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const tpl = await api.getTrainingPlanTemplate(templateId)
|
||||
if (cancelled) return
|
||||
setName((tpl.name || '').trim())
|
||||
setDescription((tpl.description || '').trim())
|
||||
setVisibility((tpl.visibility || 'club').trim())
|
||||
setClubIdField(tpl.club_id != null ? String(tpl.club_id) : '')
|
||||
const nextSections = formSectionsFromPlanTemplateRows(tpl.sections)
|
||||
setSections(nextSections.length ? nextSections : [defaultSection()])
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || 'Laden fehlgeschlagen')
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
}
|
||||
load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [templateId])
|
||||
|
||||
const buildBody = useCallback(() => {
|
||||
let cid = null
|
||||
if (visibility === 'club') {
|
||||
const raw = (clubIdField || '').trim()
|
||||
if (raw !== '') {
|
||||
const p = parseInt(raw, 10)
|
||||
if (Number.isFinite(p) && p >= 1) cid = p
|
||||
} else if (visibilityClubChoices.length === 1) {
|
||||
cid = visibilityClubChoices[0].id
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: name.trim(),
|
||||
description: description.trim() || null,
|
||||
visibility,
|
||||
club_id:
|
||||
cid != null && Number.isFinite(cid) && cid >= 1
|
||||
? cid
|
||||
: visibility === 'club'
|
||||
? undefined
|
||||
: null,
|
||||
sections: templateSectionsPayloadFromFormSections(sections),
|
||||
}
|
||||
}, [name, description, visibility, clubIdField, visibilityClubChoices, sections])
|
||||
|
||||
const performSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
|
||||
if (!name.trim()) {
|
||||
toast.error('Name ist Pflicht.')
|
||||
return false
|
||||
}
|
||||
if (visibility === 'club') {
|
||||
const bodyPreview = buildBody()
|
||||
if (bodyPreview.club_id === undefined) {
|
||||
toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
|
||||
return false
|
||||
}
|
||||
}
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
await api.updateTrainingPlanTemplate(templateId, buildBody())
|
||||
baselineRef.current = templateFormSnapshot(latestFormRef.current)
|
||||
setBypassDirty(false)
|
||||
toast.success('Vorlage gespeichert.')
|
||||
if (closeAfter) goBack()
|
||||
return true
|
||||
} catch (err) {
|
||||
const msg = err.message || 'Speichern fehlgeschlagen'
|
||||
setError(msg)
|
||||
toast.error(msg)
|
||||
return false
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async (e) => {
|
||||
e?.preventDefault?.()
|
||||
await performSave({ closeAfter: false })
|
||||
}
|
||||
|
||||
const handleSaveAndClose = async () => {
|
||||
await performSave({ closeAfter: true })
|
||||
}
|
||||
|
||||
const handleUnsavedDialogSave = async () => {
|
||||
const ok = await performSave({ fromUnsavedDialog: true })
|
||||
if (ok) blocker.proceed()
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="app-page" style={{ padding: '2rem 0', textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
<p>Laden …</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<h1 className="page-title" style={{ marginBottom: '0.35rem' }}>
|
||||
Trainingsvorlage bearbeiten
|
||||
</h1>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', marginBottom: '1.25rem', maxWidth: '42rem', lineHeight: 1.5 }}>
|
||||
Nur die <strong>Abschnitts-Gliederung</strong> (inkl. Split-Sessions / parallele Gruppen) — ohne Übungen.
|
||||
Beim Anwenden auf eine Einheit wird der Ablauf als Struktur übernommen.
|
||||
</p>
|
||||
|
||||
{error ? <p style={{ color: 'var(--danger)', marginBottom: '1rem' }}>{error}</p> : null}
|
||||
|
||||
<form
|
||||
id="plan-template-form"
|
||||
className="card page-form-shell"
|
||||
style={{ padding: 'clamp(14px, 3vw, 1.75rem)', maxWidth: '920px' }}
|
||||
onSubmit={handleSave}
|
||||
>
|
||||
<div className="page-form-shell__scroll">
|
||||
<div className="form-row">
|
||||
<label className="form-label">Name *</label>
|
||||
<input className="form-input" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label">Kurzbeschreibung</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={2}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Wofür eignet sich diese Gliederung? (optional)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 200px), 1fr))',
|
||||
gap: '12px',
|
||||
marginBottom: '1rem',
|
||||
}}
|
||||
>
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label">Sichtbarkeit</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={visibility}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
setVisibility(v)
|
||||
if (v === 'club' && !(clubIdField || '').trim()) {
|
||||
const fb = getDefaultClubIdForGovernanceForms(user)
|
||||
if (fb != null) setClubIdField(String(fb))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="private">Privat (nur du)</option>
|
||||
<option value="club">Verein</option>
|
||||
{isPlatformAdmin ? <option value="official">Offiziell (global)</option> : null}
|
||||
</select>
|
||||
</div>
|
||||
{visibility === 'club' ? (
|
||||
<div className="form-row" style={{ marginBottom: 0 }}>
|
||||
<label className="form-label">Verein</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={clubIdField}
|
||||
onChange={(e) => setClubIdField(e.target.value)}
|
||||
>
|
||||
<option value="">— Verein wählen —</option>
|
||||
{visibilityClubChoices.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name || `Verein #${c.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<TrainingUnitSectionsEditor
|
||||
heading="Abschnitts-Gliederung"
|
||||
structureOnly
|
||||
enableParallelPhaseControls
|
||||
betweenInsertMenus={false}
|
||||
enableItemDragReorder={false}
|
||||
sections={sections}
|
||||
onSectionsChange={(updater) => setSections((prev) => updater(prev))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormActionBar
|
||||
placement="bottom"
|
||||
variant="page"
|
||||
formId="plan-template-form"
|
||||
saving={saving}
|
||||
onCancel={goBack}
|
||||
onSaveAndClose={handleSaveAndClose}
|
||||
/>
|
||||
</form>
|
||||
|
||||
<UnsavedChangesPrompt
|
||||
blocker={blocker}
|
||||
isBusy={saving}
|
||||
onSave={handleUnsavedDialogSave}
|
||||
onDiscardWithoutSave={() => setBypassDirty(true)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { useToast } from '../context/ToastContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import { canDeleteLibraryContent, canEditLibraryContent } from '../utils/libraryContentPermissions'
|
||||
import PlanTemplateStructurePreview from '../components/planning/PlanTemplateStructurePreview'
|
||||
import { buildPlanTemplatesListReturnContext } from '../utils/navReturnContext'
|
||||
|
||||
function visibilityLabel(v) {
|
||||
const x = String(v || 'club').toLowerCase()
|
||||
if (x === 'private') return 'Privat'
|
||||
if (x === 'official') return 'Offiziell'
|
||||
return 'Verein'
|
||||
}
|
||||
|
||||
export default function TrainingPlanTemplatesListPage() {
|
||||
const { user } = useAuth()
|
||||
const templatesListReturn = useMemo(() => buildPlanTemplatesListReturnContext(), [])
|
||||
const toast = useToast()
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
const [rows, setRows] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const list = await api.listTrainingPlanTemplates()
|
||||
setRows(Array.isArray(list) ? list : [])
|
||||
} catch (e) {
|
||||
setError(e.message || 'Laden fehlgeschlagen')
|
||||
setRows([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load, tenantClubDepKey])
|
||||
|
||||
async function handleDelete(tpl) {
|
||||
if (!tpl?.id) return
|
||||
const label = (tpl.name || '').trim() || `Vorlage #${tpl.id}`
|
||||
if (
|
||||
!window.confirm(
|
||||
`Trainingsvorlage „${label}“ wirklich löschen? Einheiten mit Verweis behalten ihren Ablauf; die Vorlage wird entkoppelt.`
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await api.deleteTrainingPlanTemplate(tpl.id)
|
||||
await load()
|
||||
toast.success('Vorlage gelöscht.')
|
||||
} catch (e) {
|
||||
toast.error(e.message || 'Löschen fehlgeschlagen')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'space-between',
|
||||
gap: '1rem',
|
||||
marginBottom: '1.25rem',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h1 className="page-title" style={{ marginBottom: '0.35rem' }}>
|
||||
Trainingsvorlagen
|
||||
</h1>
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '42rem', margin: 0, lineHeight: 1.5 }}>
|
||||
Mikrovorlagen für die <strong>Sektions-Gliederung</strong> einer Einheit (ohne Übungen), inklusive{' '}
|
||||
<strong>Split-Sessions</strong>. Neue Vorlagen legst du beim Bearbeiten einer Trainingseinheit über „Vorlage
|
||||
aus Aufbau speichern“ an; hier kannst du sie prüfen und anpassen.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? <p style={{ color: 'var(--danger)', marginBottom: '1rem' }}>{error}</p> : null}
|
||||
|
||||
{loading ? (
|
||||
<p style={{ color: 'var(--text2)' }}>Laden …</p>
|
||||
) : rows.length === 0 ? (
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<p style={{ margin: 0, color: 'var(--text2)', lineHeight: 1.5 }}>
|
||||
Noch keine Vorlagen gespeichert. Öffne unter <strong>Trainingsplanung</strong> eine Einheit, strukturiere
|
||||
die Abschnitte (auch parallele Gruppen) und nutze dort „Vorlage aus Aufbau speichern“.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: '0.75rem' }}>
|
||||
{rows.map((t) => {
|
||||
const canEdit = user && canEditLibraryContent(user, t)
|
||||
const canDel = user && canDeleteLibraryContent(user, t)
|
||||
const desc = (t.description || '').trim()
|
||||
return (
|
||||
<li key={t.id} className="card" style={{ padding: '14px 16px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'space-between',
|
||||
gap: '12px',
|
||||
}}
|
||||
>
|
||||
<div style={{ minWidth: 0, flex: '1 1 240px' }}>
|
||||
{canEdit ? (
|
||||
<NavStateLink
|
||||
to={`/planning/plan-templates/${t.id}`}
|
||||
returnContext={templatesListReturn}
|
||||
style={{
|
||||
fontWeight: 700,
|
||||
fontSize: '1rem',
|
||||
color: 'var(--accent-dark)',
|
||||
textDecoration: 'none',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
{(t.name || '').trim() || `Vorlage #${t.id}`}
|
||||
</NavStateLink>
|
||||
) : (
|
||||
<strong style={{ color: 'var(--text1)', fontSize: '1rem', wordBreak: 'break-word' }}>
|
||||
{(t.name || '').trim() || `Vorlage #${t.id}`}
|
||||
</strong>
|
||||
)}
|
||||
<div style={{ fontSize: '0.85rem', color: 'var(--text2)', marginTop: '4px' }}>
|
||||
{visibilityLabel(t.visibility)}
|
||||
{typeof t.sections_count === 'number' ? ` · ${t.sections_count} Abschn.` : ''}
|
||||
{t.updated_at ? (
|
||||
<span style={{ color: 'var(--text3)' }}>
|
||||
{' '}
|
||||
· aktualisiert {String(t.updated_at).slice(0, 10)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{desc ? (
|
||||
<p
|
||||
style={{
|
||||
margin: '0.45rem 0 0',
|
||||
fontSize: '0.88rem',
|
||||
color: 'var(--text2)',
|
||||
lineHeight: 1.45,
|
||||
maxWidth: '42rem',
|
||||
}}
|
||||
>
|
||||
{desc}
|
||||
</p>
|
||||
) : null}
|
||||
<PlanTemplateStructurePreview sections={t.sections} compact />
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', flexShrink: 0 }}>
|
||||
{canEdit ? (
|
||||
<NavStateLink
|
||||
className="btn btn-secondary"
|
||||
style={{ textDecoration: 'none' }}
|
||||
to={`/planning/plan-templates/${t.id}`}
|
||||
returnContext={templatesListReturn}
|
||||
>
|
||||
Bearbeiten
|
||||
</NavStateLink>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.82rem', color: 'var(--text3)', alignSelf: 'center' }}>
|
||||
nur Lesen
|
||||
</span>
|
||||
)}
|
||||
{canDel ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ color: 'var(--danger)', borderColor: 'var(--danger)' }}
|
||||
onClick={() => handleDelete(t)}
|
||||
>
|
||||
Löschen
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<p style={{ marginTop: '1.25rem', fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.45, maxWidth: '40rem' }}>
|
||||
Bearbeiten: eigene private Vorlagen, Vereinsinhalte für Trainer im Verein, offizielle nur als Plattform-Admin.
|
||||
Löschen nach Rolle: eigene private Vorlagen; Vereinsinhalte als Vereinsadmin; offizielle nur als Plattform-Admin.
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,809 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import { useToast } from '../context/ToastContext'
|
||||
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||
import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import TrainingUnitFormShell from '../components/planning/TrainingUnitFormShell'
|
||||
import TrainingPlanningModuleApplyModal from '../components/planning/TrainingPlanningModuleApplyModal'
|
||||
import TrainingPublishToFrameworkModal from '../components/planning/TrainingPublishToFrameworkModal'
|
||||
import SaveExercisesAsModuleModal from '../components/planning/SaveExercisesAsModuleModal'
|
||||
import {
|
||||
defaultSection,
|
||||
enrichSectionsWithVariants,
|
||||
formSectionsFromPlanTemplateRows,
|
||||
hydrateExercisePlanningRow,
|
||||
insertTrainingModuleIntoPlanningSections,
|
||||
normalizeUnitToForm,
|
||||
templateSectionsPayloadFromFormSections,
|
||||
} from '../utils/trainingUnitSectionsForm'
|
||||
import {
|
||||
filterDirectoryExcludingLead,
|
||||
} from '../utils/trainingPlanningPageHelpers'
|
||||
import {
|
||||
createEmptyTrainingUnitFormData,
|
||||
buildTrainingUnitSavePayload,
|
||||
trainingUnitToFormFields,
|
||||
trainingUnitFormSnapshot,
|
||||
validateTrainingUnitFormForSave,
|
||||
} from '../utils/trainingUnitEditorCore'
|
||||
import PageFormEditorChrome from '../components/PageFormEditorChrome'
|
||||
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
||||
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
||||
import { buildPlanUnitEditPath } from '../utils/planningUnitRoutes'
|
||||
import {
|
||||
PLANNING_HUB_PATH,
|
||||
buildCurrentLocationReturnContext,
|
||||
goNavReturn,
|
||||
} from '../utils/navReturnContext'
|
||||
|
||||
export default function TrainingUnitEditPage() {
|
||||
const { id: routeId } = useParams()
|
||||
const isNew = !routeId || routeId === 'new'
|
||||
const unitId = !isNew ? parseInt(routeId, 10) : NaN
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [searchParams] = useSearchParams()
|
||||
const { user } = useAuth()
|
||||
const toast = useToast()
|
||||
const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])
|
||||
|
||||
const [loading, setLoading] = useState(!isNew)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [groups, setGroups] = useState([])
|
||||
const [planTemplates, setPlanTemplates] = useState([])
|
||||
const [editingUnit, setEditingUnit] = useState(null)
|
||||
const [draftPlanTemplateId, setDraftPlanTemplateId] = useState('')
|
||||
const [sectionsEditMode, setSectionsEditMode] = useState('planning')
|
||||
const [clubDirectory, setClubDirectory] = useState([])
|
||||
const [formData, setFormData] = useState(() => createEmptyTrainingUnitFormData())
|
||||
const formRef = useRef(formData)
|
||||
formRef.current = formData
|
||||
|
||||
const baselineRef = useRef(null)
|
||||
const [baselineReady, setBaselineReady] = useState(false)
|
||||
const [bypassDirty, setBypassDirty] = useState(false)
|
||||
|
||||
const dirtySignature = trainingUnitFormSnapshot(formRef.current, {
|
||||
editingUnit,
|
||||
draftPlanTemplateId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
baselineRef.current = null
|
||||
setBaselineReady(false)
|
||||
setBypassDirty(false)
|
||||
}, [isNew, unitId])
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return undefined
|
||||
const handle = window.setTimeout(() => {
|
||||
baselineRef.current = trainingUnitFormSnapshot(formRef.current, {
|
||||
editingUnit,
|
||||
draftPlanTemplateId,
|
||||
})
|
||||
setBaselineReady(true)
|
||||
}, 120)
|
||||
return () => clearTimeout(handle)
|
||||
// Baseline nur nach initialem Laden — nicht bei Template-/Form-Änderungen im Editor
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- editingUnit/draftPlanTemplateId bewusst ausgeschlossen
|
||||
}, [loading, isNew, unitId])
|
||||
|
||||
const formDirtyEffective =
|
||||
baselineReady &&
|
||||
baselineRef.current != null &&
|
||||
!bypassDirty &&
|
||||
!loading &&
|
||||
dirtySignature !== baselineRef.current
|
||||
|
||||
const blocker = useUnsavedChangesBlocker(Boolean(formDirtyEffective && !saving))
|
||||
useBeforeUnloadWhen(Boolean(formDirtyEffective && !saving))
|
||||
|
||||
const [exercisePickerOpen, setExercisePickerOpen] = useState(false)
|
||||
const [exercisePickerTarget, setExercisePickerTarget] = useState(null)
|
||||
const [planningPeekCtx, setPlanningPeekCtx] = useState(null)
|
||||
const [moduleApplyOpen, setModuleApplyOpen] = useState(false)
|
||||
const [moduleApplyBusy, setModuleApplyBusy] = useState(false)
|
||||
const [moduleApplyList, setModuleApplyList] = useState([])
|
||||
const [moduleApplyModuleId, setModuleApplyModuleId] = useState('')
|
||||
const [moduleApplySectionIx, setModuleApplySectionIx] = useState(0)
|
||||
const [moduleApplyInsertSlot, setModuleApplyInsertSlot] = useState('before:0')
|
||||
const [moduleApplyErr, setModuleApplyErr] = useState('')
|
||||
const [moduleApplyPlacementLocked, setModuleApplyPlacementLocked] = useState(false)
|
||||
const [moduleApplySearchQuery, setModuleApplySearchQuery] = useState('')
|
||||
const [modulePickPreview, setModulePickPreview] = useState({
|
||||
loading: false,
|
||||
moduleId: '',
|
||||
exercises: [],
|
||||
notes: 0,
|
||||
err: '',
|
||||
})
|
||||
const [publishFrameworkOpen, setPublishFrameworkOpen] = useState(false)
|
||||
const [saveModuleOpen, setSaveModuleOpen] = useState(false)
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
goNavReturn(navigate, location, {
|
||||
path: PLANNING_HUB_PATH,
|
||||
label: 'Zurück zur Planung',
|
||||
})
|
||||
}, [location, navigate])
|
||||
|
||||
const moduleSaveReturnContext = useMemo(
|
||||
() => buildCurrentLocationReturnContext(location, 'Zurück zur Trainingseinheit'),
|
||||
[location]
|
||||
)
|
||||
|
||||
const planningClubId = useMemo(() => {
|
||||
const gid = Number(formData.group_id)
|
||||
if (!Number.isFinite(gid) || gid < 1) return null
|
||||
const g = groups.find((x) => Number(x.id) === gid)
|
||||
if (!g?.club_id) return null
|
||||
const c = Number(g.club_id)
|
||||
return Number.isFinite(c) ? c : null
|
||||
}, [groups, formData.group_id])
|
||||
|
||||
const moduleApplyFilteredList = useMemo(() => {
|
||||
const q = moduleApplySearchQuery.trim().toLowerCase().replace(/\s+/g, ' ')
|
||||
const words = q ? q.split(' ').filter(Boolean) : []
|
||||
const list = Array.isArray(moduleApplyList) ? moduleApplyList : []
|
||||
if (!words.length) return list
|
||||
return list.filter((m) => {
|
||||
const blob = [m.title, m.summary, m.goal, m.target_group_notes, m.deployment_context_notes]
|
||||
.map((x) => String(x ?? '').toLowerCase())
|
||||
.join('\n')
|
||||
return words.every((w) => blob.includes(w))
|
||||
})
|
||||
}, [moduleApplySearchQuery, moduleApplyList])
|
||||
|
||||
const modulePlacementSummary = useMemo(() => {
|
||||
const secs = Array.isArray(formData.sections) ? formData.sections : []
|
||||
let si =
|
||||
typeof moduleApplySectionIx === 'number'
|
||||
? moduleApplySectionIx
|
||||
: parseInt(String(moduleApplySectionIx), 10)
|
||||
if (!Number.isFinite(si)) si = 0
|
||||
si = Math.max(0, Math.min(si, secs.length ? secs.length - 1 : 0))
|
||||
const cap = secs[si]?.items?.length ?? 0
|
||||
let beforeIx = cap
|
||||
if (typeof moduleApplyInsertSlot === 'string' && moduleApplyInsertSlot.startsWith('before:')) {
|
||||
const zi = parseInt(moduleApplyInsertSlot.slice('before:'.length), 10)
|
||||
if (Number.isFinite(zi)) beforeIx = Math.min(Math.max(0, zi), cap)
|
||||
}
|
||||
const rawTitle = (secs[si]?.title || '').trim()
|
||||
const secTitle = rawTitle || `Abschnitt ${si + 1}`
|
||||
let positionDescription
|
||||
if (cap <= 0) positionDescription = 'als erste Einträge dieses Abschnitts'
|
||||
else if (beforeIx <= 0) positionDescription = 'vor dem ersten Eintrag dieses Abschnitts'
|
||||
else if (beforeIx >= cap) positionDescription = 'nach dem letzten Eintrag dieses Abschnitts'
|
||||
else positionDescription = `unmittelbar vor Eintrag ${beforeIx + 1} (${cap} Einträge im Abschnitt)`
|
||||
return { secTitle, positionDescription }
|
||||
}, [formData.sections, moduleApplySectionIx, moduleApplyInsertSlot])
|
||||
|
||||
const moduleApplyTargetItems = useMemo(() => {
|
||||
const secs = formData.sections || []
|
||||
if (!secs.length) return []
|
||||
let ix =
|
||||
typeof moduleApplySectionIx === 'number'
|
||||
? moduleApplySectionIx
|
||||
: parseInt(String(moduleApplySectionIx), 10)
|
||||
if (!Number.isFinite(ix)) ix = 0
|
||||
if (ix < 0 || ix >= secs.length) return []
|
||||
const sec = secs[ix]
|
||||
return Array.isArray(sec?.items) ? sec.items : []
|
||||
}, [formData.sections, moduleApplySectionIx])
|
||||
|
||||
useEffect(() => {
|
||||
if (!moduleApplyOpen || !moduleApplyFilteredList.length) return
|
||||
if (moduleApplyFilteredList.some((m) => String(m.id) === String(moduleApplyModuleId))) return
|
||||
setModuleApplyModuleId(String(moduleApplyFilteredList[0].id))
|
||||
}, [moduleApplyOpen, moduleApplyFilteredList, moduleApplyModuleId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!moduleApplyOpen) {
|
||||
setModulePickPreview({
|
||||
loading: false,
|
||||
moduleId: '',
|
||||
exercises: [],
|
||||
notes: 0,
|
||||
err: '',
|
||||
})
|
||||
return undefined
|
||||
}
|
||||
const mid = parseInt(String(moduleApplyModuleId), 10)
|
||||
if (!Number.isFinite(mid) || mid < 1) {
|
||||
setModulePickPreview({
|
||||
loading: false,
|
||||
moduleId: '',
|
||||
exercises: [],
|
||||
notes: 0,
|
||||
err: '',
|
||||
})
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
setModulePickPreview({
|
||||
loading: true,
|
||||
moduleId: String(mid),
|
||||
exercises: [],
|
||||
notes: 0,
|
||||
err: '',
|
||||
})
|
||||
;(async () => {
|
||||
try {
|
||||
const detail = await api.getTrainingModule(mid)
|
||||
if (cancelled) return
|
||||
const itemsSorted = [...(detail.items ?? [])].sort(
|
||||
(a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)
|
||||
)
|
||||
const uniqueEx = new Set()
|
||||
let notes = 0
|
||||
for (const row of itemsSorted) {
|
||||
if ((row.item_type || '') !== 'note') {
|
||||
const eid = row.exercise_id
|
||||
if (eid) uniqueEx.add(Number(eid))
|
||||
continue
|
||||
}
|
||||
const b = String(row.note_body ?? '').trim()
|
||||
if (b === '---') continue
|
||||
notes += 1
|
||||
}
|
||||
const titleById = new Map()
|
||||
await Promise.all(
|
||||
[...uniqueEx].map(async (eid) => {
|
||||
try {
|
||||
const ex = await api.getExercise(eid)
|
||||
titleById.set(eid, (ex?.title || '').trim() || `Übung #${eid}`)
|
||||
} catch {
|
||||
titleById.set(eid, `Übung #${eid}`)
|
||||
}
|
||||
})
|
||||
)
|
||||
if (cancelled) return
|
||||
const exTitlesInOrder = []
|
||||
for (const row of itemsSorted) {
|
||||
if ((row.item_type || '') !== 'exercise') continue
|
||||
const eid = Number(row.exercise_id)
|
||||
if (!Number.isFinite(eid)) continue
|
||||
exTitlesInOrder.push(titleById.get(eid) || `Übung #${eid}`)
|
||||
}
|
||||
setModulePickPreview({
|
||||
loading: false,
|
||||
moduleId: String(mid),
|
||||
exercises: exTitlesInOrder,
|
||||
notes,
|
||||
err: '',
|
||||
})
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setModulePickPreview({
|
||||
loading: false,
|
||||
moduleId: String(mid),
|
||||
exercises: [],
|
||||
notes: 0,
|
||||
err: e?.message || 'Vorschau fehlgeschlagen',
|
||||
})
|
||||
}
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [moduleApplyOpen, moduleApplyModuleId])
|
||||
|
||||
useEffect(() => {
|
||||
if (planningClubId == null) {
|
||||
setClubDirectory([])
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const d = await api.clubMembersDirectory(planningClubId)
|
||||
if (!cancelled) setClubDirectory(Array.isArray(d) ? d : [])
|
||||
} catch {
|
||||
if (!cancelled) setClubDirectory([])
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [planningClubId])
|
||||
|
||||
const clubDirectoryForCo = useMemo(() => {
|
||||
let exclude = null
|
||||
const leadTrim = String(formData.lead_trainer_profile_id || '').trim()
|
||||
if (leadTrim) {
|
||||
const n = parseInt(leadTrim, 10)
|
||||
if (Number.isFinite(n)) exclude = n
|
||||
} else if (editingUnit?.effective_lead_trainer_profile_id != null) {
|
||||
exclude = Number(editingUnit.effective_lead_trainer_profile_id)
|
||||
} else {
|
||||
const gid = parseInt(formData.group_id || '0', 10)
|
||||
const g = groups.find((gr) => gr.id === gid)
|
||||
if (g?.trainer_id != null) exclude = Number(g.trainer_id)
|
||||
}
|
||||
return filterDirectoryExcludingLead(clubDirectory, exclude)
|
||||
}, [clubDirectory, formData.lead_trainer_profile_id, formData.group_id, editingUnit, groups])
|
||||
|
||||
const loadCatalogs = useCallback(async () => {
|
||||
const [groupsData, tpl] = await Promise.all([
|
||||
api.listTrainingGroups({ status: 'active' }),
|
||||
api.listTrainingPlanTemplates(),
|
||||
])
|
||||
setGroups(Array.isArray(groupsData) ? groupsData : [])
|
||||
setPlanTemplates(Array.isArray(tpl) ? tpl : [])
|
||||
return Array.isArray(groupsData) ? groupsData : []
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
async function init() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const groupsData = await loadCatalogs()
|
||||
if (cancelled) return
|
||||
|
||||
if (isNew) {
|
||||
const qGroup = searchParams.get('group') || ''
|
||||
const qDate = searchParams.get('date') || new Date().toISOString().slice(0, 10)
|
||||
const qTemplate = searchParams.get('template') || ''
|
||||
const gid =
|
||||
qGroup ||
|
||||
(groupsData.length === 1 ? String(groupsData[0].id) : '') ||
|
||||
(groupsData.find((g) => g.trainer_id === user?.id)
|
||||
? String(groupsData.find((g) => g.trainer_id === user?.id).id)
|
||||
: '')
|
||||
const group = groupsData.find((g) => String(g.id) === String(gid))
|
||||
setEditingUnit(null)
|
||||
setDraftPlanTemplateId(qTemplate)
|
||||
setSectionsEditMode(searchParams.get('mode') === 'debrief' ? 'debrief' : 'planning')
|
||||
setFormData(
|
||||
createEmptyTrainingUnitFormData({
|
||||
groupId: gid,
|
||||
plannedDate: qDate,
|
||||
timeStart: group?.time_start?.slice(0, 5) || '',
|
||||
timeEnd: group?.time_end?.slice(0, 5) || '',
|
||||
})
|
||||
)
|
||||
if (qTemplate) {
|
||||
const tpl = await api.getTrainingPlanTemplate(parseInt(qTemplate, 10))
|
||||
if (!cancelled && tpl?.sections?.length) {
|
||||
setFormData((fd) => ({
|
||||
...fd,
|
||||
sections: formSectionsFromPlanTemplateRows(tpl.sections),
|
||||
}))
|
||||
}
|
||||
}
|
||||
} else if (Number.isFinite(unitId)) {
|
||||
const fullUnit = await api.getTrainingUnit(unitId)
|
||||
if (cancelled) return
|
||||
setEditingUnit(fullUnit)
|
||||
setDraftPlanTemplateId(fullUnit.plan_template_id ? String(fullUnit.plan_template_id) : '')
|
||||
let sections = normalizeUnitToForm(fullUnit)
|
||||
sections = await enrichSectionsWithVariants(sections)
|
||||
if (cancelled) return
|
||||
setFormData(trainingUnitToFormFields(fullUnit, sections))
|
||||
const modeParam = searchParams.get('mode')
|
||||
setSectionsEditMode(
|
||||
modeParam === 'debrief' || fullUnit.status === 'completed' ? 'debrief' : 'planning'
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) toast.error(e.message || 'Laden fehlgeschlagen')
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
}
|
||||
init()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isNew, unitId, searchParams, loadCatalogs, user?.id, tenantClubDepKey, toast])
|
||||
|
||||
const updateFormField = useCallback(
|
||||
(field, value) => {
|
||||
setFormData((prev) => {
|
||||
if (field !== 'lead_trainer_profile_id') {
|
||||
const patch = { ...prev, [field]: value }
|
||||
if (field === 'status' && value !== 'completed') patch.debrief_completed = false
|
||||
return patch
|
||||
}
|
||||
const ts = typeof value === 'string' ? value.trim() : String(value ?? '').trim()
|
||||
const strip = new Set()
|
||||
if (ts !== '') {
|
||||
const nid = parseInt(ts, 10)
|
||||
if (Number.isFinite(nid)) strip.add(nid)
|
||||
} else {
|
||||
const gidParsed = parseInt(prev.group_id || '0', 10)
|
||||
const gr =
|
||||
Number.isFinite(gidParsed) && gidParsed >= 1
|
||||
? groups.find((xg) => xg.id === gidParsed)
|
||||
: null
|
||||
if (gr?.trainer_id != null) {
|
||||
const ht = Number(gr.trainer_id)
|
||||
if (Number.isFinite(ht)) strip.add(ht)
|
||||
}
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
lead_trainer_profile_id: value,
|
||||
session_assistant_profile_ids: prev.session_assistant_profile_ids.filter((id) => !strip.has(id)),
|
||||
}
|
||||
})
|
||||
},
|
||||
[groups]
|
||||
)
|
||||
|
||||
const applyTemplateFromSelect = async (templateId) => {
|
||||
setDraftPlanTemplateId(templateId)
|
||||
if (!templateId) return
|
||||
try {
|
||||
const tpl = await api.getTrainingPlanTemplate(parseInt(templateId, 10))
|
||||
setFormData((fd) => ({
|
||||
...fd,
|
||||
sections: (tpl.sections || []).length
|
||||
? formSectionsFromPlanTemplateRows(tpl.sections)
|
||||
: [defaultSection()],
|
||||
}))
|
||||
} catch (err) {
|
||||
toast.error('Vorlage laden: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const reloadUnitAfterSave = useCallback(
|
||||
async (savedId) => {
|
||||
const fullUnit = await api.getTrainingUnit(savedId)
|
||||
const nextDraftTemplateId = fullUnit.plan_template_id ? String(fullUnit.plan_template_id) : ''
|
||||
setEditingUnit(fullUnit)
|
||||
setDraftPlanTemplateId(nextDraftTemplateId)
|
||||
let sections = normalizeUnitToForm(fullUnit)
|
||||
sections = await enrichSectionsWithVariants(sections)
|
||||
const nextForm = trainingUnitToFormFields(fullUnit, sections)
|
||||
setFormData(nextForm)
|
||||
baselineRef.current = trainingUnitFormSnapshot(nextForm, {
|
||||
editingUnit: fullUnit,
|
||||
draftPlanTemplateId: nextDraftTemplateId,
|
||||
})
|
||||
setBypassDirty(false)
|
||||
if (!isNew && savedId !== unitId) {
|
||||
navigate(buildPlanUnitEditPath(savedId), { replace: true, state: location.state })
|
||||
}
|
||||
},
|
||||
[isNew, unitId, navigate, location.state]
|
||||
)
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e, { closeAfter = true } = {}) => {
|
||||
e?.preventDefault?.()
|
||||
const v = validateTrainingUnitFormForSave(formData)
|
||||
if (!v.ok) {
|
||||
toast.error(v.message)
|
||||
return false
|
||||
}
|
||||
setSaving(true)
|
||||
try {
|
||||
const payload = buildTrainingUnitSavePayload(formData, {
|
||||
editingUnit,
|
||||
draftPlanTemplateId,
|
||||
})
|
||||
let savedUnit
|
||||
if (editingUnit) {
|
||||
savedUnit = await api.updateTrainingUnit(editingUnit.id, payload)
|
||||
} else {
|
||||
savedUnit = await api.createTrainingUnit(payload)
|
||||
}
|
||||
toast.success('Gespeichert.')
|
||||
if (closeAfter) {
|
||||
goBack()
|
||||
} else if (savedUnit?.id) {
|
||||
await reloadUnitAfterSave(savedUnit.id)
|
||||
}
|
||||
return true
|
||||
} catch (err) {
|
||||
toast.error('Fehler beim Speichern: ' + err.message)
|
||||
return false
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
},
|
||||
[formData, editingUnit, draftPlanTemplateId, toast, goBack, reloadUnitAfterSave]
|
||||
)
|
||||
|
||||
const handleUnsavedDialogSave = async () => {
|
||||
const ok = await handleSubmit(null, { closeAfter: false })
|
||||
if (ok) blocker.proceed()
|
||||
}
|
||||
|
||||
const actionConfig = useMemo(
|
||||
() => ({
|
||||
formId: 'planning-unit-form',
|
||||
saving,
|
||||
isNew: !editingUnit,
|
||||
onSave: (e) => handleSubmit(e, { closeAfter: false }),
|
||||
onSaveAndClose: (e) => handleSubmit(e, { closeAfter: true }),
|
||||
onCancel: goBack,
|
||||
showSave: true,
|
||||
showSaveAndClose: true,
|
||||
}),
|
||||
[saving, editingUnit, handleSubmit, goBack]
|
||||
)
|
||||
|
||||
const hubBackPath = PLANNING_HUB_PATH
|
||||
const pageTitle = editingUnit ? 'Trainingseinheit bearbeiten' : 'Neue Trainingseinheit'
|
||||
|
||||
const handleSaveAsTemplate = async (opts = {}) => {
|
||||
const name = window.prompt('Name für die neue Trainingsvorlage (nur Abschnitts-Gliederung):')
|
||||
if (!name?.trim()) return
|
||||
const descRaw = window.prompt('Kurzbeschreibung (optional, leer lassen zum Überspringen):')
|
||||
const visibility =
|
||||
typeof opts.visibility === 'string' && opts.visibility.trim()
|
||||
? String(opts.visibility).trim().toLowerCase()
|
||||
: 'private'
|
||||
let club_id = opts.club_id != null && opts.club_id !== '' ? Number(opts.club_id) : null
|
||||
if (visibility === 'club') {
|
||||
if (!Number.isFinite(club_id) || club_id < 1) club_id = planningClubId
|
||||
if (!Number.isFinite(club_id) || club_id < 1) {
|
||||
toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
|
||||
return
|
||||
}
|
||||
} else {
|
||||
club_id = null
|
||||
}
|
||||
try {
|
||||
await api.createTrainingPlanTemplate({
|
||||
name: name.trim(),
|
||||
description: descRaw?.trim() ? descRaw.trim() : null,
|
||||
visibility,
|
||||
club_id: visibility === 'club' ? club_id : null,
|
||||
sections: templateSectionsPayloadFromFormSections(formData.sections),
|
||||
})
|
||||
toast.success('Vorlage gespeichert.')
|
||||
} catch (err) {
|
||||
toast.error('Speichern: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const openModuleApplyModal = useCallback(async (placement) => {
|
||||
setModuleApplyErr('')
|
||||
setModuleApplySearchQuery('')
|
||||
const placementLocked =
|
||||
placement != null &&
|
||||
typeof placement.sectionIndex === 'number' &&
|
||||
typeof placement.insertBeforeIndex === 'number'
|
||||
setModuleApplyPlacementLocked(placementLocked)
|
||||
const secs = formRef.current?.sections ?? []
|
||||
let secIx = 0
|
||||
let before = 0
|
||||
if (secs.length) {
|
||||
if (placement && typeof placement.sectionIndex === 'number') {
|
||||
secIx = Math.min(Math.max(0, placement.sectionIndex), secs.length - 1)
|
||||
const items = Array.isArray(secs[secIx]?.items) ? secs[secIx].items : []
|
||||
before =
|
||||
typeof placement.insertBeforeIndex === 'number'
|
||||
? Math.min(Math.max(0, placement.insertBeforeIndex), items.length)
|
||||
: items.length
|
||||
} else {
|
||||
before = Array.isArray(secs[0]?.items) ? secs[0].items.length : 0
|
||||
}
|
||||
}
|
||||
setModuleApplySectionIx(secIx)
|
||||
setModuleApplyInsertSlot(`before:${before}`)
|
||||
setModuleApplyOpen(true)
|
||||
try {
|
||||
const list = await api.listTrainingModules()
|
||||
const arr = Array.isArray(list) ? list : []
|
||||
setModuleApplyList(arr)
|
||||
setModuleApplyModuleId(arr.length ? String(arr[0].id) : '')
|
||||
} catch (e) {
|
||||
setModuleApplyErr(e.message || 'Module konnten nicht geladen werden')
|
||||
setModuleApplyList([])
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onModuleApplySectionIndexChange = useCallback((newIx) => {
|
||||
setModuleApplySectionIx(newIx)
|
||||
const secsNow = formRef.current?.sections ?? []
|
||||
const len = Array.isArray(secsNow[newIx]?.items) ? secsNow[newIx].items.length : 0
|
||||
setModuleApplyInsertSlot(`before:${len}`)
|
||||
}, [])
|
||||
|
||||
const handleApplyTrainingModuleConfirm = useCallback(async () => {
|
||||
const mid = parseInt(moduleApplyModuleId, 10)
|
||||
if (!Number.isFinite(mid)) {
|
||||
toast.error('Bitte ein Trainingsmodul wählen.')
|
||||
return
|
||||
}
|
||||
let secIx = parseInt(String(moduleApplySectionIx), 10)
|
||||
const baseSections = formRef.current?.sections ?? []
|
||||
if (!baseSections.length) return
|
||||
if (!Number.isFinite(secIx) || secIx < 0 || secIx >= baseSections.length) secIx = 0
|
||||
const itemCap = Array.isArray(baseSections[secIx]?.items) ? baseSections[secIx].items.length : 0
|
||||
let insertBefore = itemCap
|
||||
if (typeof moduleApplyInsertSlot === 'string' && moduleApplyInsertSlot.startsWith('before:')) {
|
||||
const zi = parseInt(moduleApplyInsertSlot.slice('before:'.length), 10)
|
||||
if (Number.isFinite(zi)) insertBefore = Math.min(Math.max(0, zi), itemCap)
|
||||
}
|
||||
setModuleApplyBusy(true)
|
||||
try {
|
||||
const detail = await api.getTrainingModule(mid)
|
||||
let nextSections = await insertTrainingModuleIntoPlanningSections({
|
||||
sections: baseSections,
|
||||
moduleDetail: detail,
|
||||
sectionIndex: secIx,
|
||||
insertBeforeItemIndex: insertBefore,
|
||||
})
|
||||
nextSections = await enrichSectionsWithVariants(nextSections)
|
||||
setFormData((fd) => ({ ...fd, sections: nextSections }))
|
||||
setModuleApplyOpen(false)
|
||||
setModuleApplyPlacementLocked(false)
|
||||
} catch (e) {
|
||||
setModuleApplyErr(e.message || 'Einfügen fehlgeschlagen')
|
||||
} finally {
|
||||
setModuleApplyBusy(false)
|
||||
}
|
||||
}, [moduleApplyModuleId, moduleApplySectionIx, moduleApplyInsertSlot, toast])
|
||||
|
||||
const refreshPlanningSectionMeta = useCallback(async () => {
|
||||
const next = await enrichSectionsWithVariants(formRef.current.sections)
|
||||
setFormData((prev) => ({ ...prev, sections: next }))
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="app-page" style={{ padding: '2rem 0', textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
<p>Laden …</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PageFormEditorChrome
|
||||
testId="planning-unit-form"
|
||||
title={pageTitle}
|
||||
fallbackPath={hubBackPath}
|
||||
fallbackLabel="Zurück zur Planung"
|
||||
actionConfig={actionConfig}
|
||||
>
|
||||
<TrainingUnitFormShell
|
||||
editingUnit={editingUnit}
|
||||
formData={formData}
|
||||
updateFormField={updateFormField}
|
||||
setFormData={setFormData}
|
||||
onSaveOnly={(e) => handleSubmit(e, { closeAfter: false })}
|
||||
onSaveAndClose={(e) => handleSubmit(e, { closeAfter: true })}
|
||||
draftPlanTemplateId={draftPlanTemplateId}
|
||||
onDraftTemplateSelect={applyTemplateFromSelect}
|
||||
planTemplates={planTemplates}
|
||||
clubDirectory={clubDirectory}
|
||||
clubDirectoryForCo={clubDirectoryForCo}
|
||||
planningClubId={planningClubId}
|
||||
user={user}
|
||||
onMetaRefresh={refreshPlanningSectionMeta}
|
||||
sectionsEditMode={sectionsEditMode}
|
||||
setSectionsEditMode={setSectionsEditMode}
|
||||
onSaveAsTemplate={handleSaveAsTemplate}
|
||||
onRequestPublishToFramework={() => editingUnit?.id && setPublishFrameworkOpen(true)}
|
||||
onRequestSaveAsModule={() => editingUnit?.id && setSaveModuleOpen(true)}
|
||||
onRequestTrainingModulePick={(ctx) => void openModuleApplyModal(ctx)}
|
||||
onRequestExercisePick={({ sectionIndex, itemIndex, insertBeforeIndex }) => {
|
||||
setExercisePickerTarget({
|
||||
sIdx: sectionIndex,
|
||||
iIdx: typeof itemIndex === 'number' ? itemIndex : undefined,
|
||||
insertBeforeIndex:
|
||||
typeof insertBeforeIndex === 'number' && Number.isFinite(insertBeforeIndex)
|
||||
? insertBeforeIndex
|
||||
: undefined,
|
||||
})
|
||||
setExercisePickerOpen(true)
|
||||
}}
|
||||
onPeekExercise={(id, variantId, peekExtras) =>
|
||||
setPlanningPeekCtx({ exerciseId: id, variantId: variantId ?? null, peekExtras: peekExtras ?? null })
|
||||
}
|
||||
/>
|
||||
|
||||
<TrainingPlanningModuleApplyModal
|
||||
open={moduleApplyOpen}
|
||||
busy={moduleApplyBusy}
|
||||
err={moduleApplyErr}
|
||||
placementLocked={moduleApplyPlacementLocked}
|
||||
placementSummary={modulePlacementSummary}
|
||||
sections={formData.sections}
|
||||
sectionIx={moduleApplySectionIx}
|
||||
onSectionIndexChange={onModuleApplySectionIndexChange}
|
||||
insertSlot={moduleApplyInsertSlot}
|
||||
onInsertSlotChange={setModuleApplyInsertSlot}
|
||||
targetItems={moduleApplyTargetItems}
|
||||
searchQuery={moduleApplySearchQuery}
|
||||
onSearchQueryChange={setModuleApplySearchQuery}
|
||||
filteredList={moduleApplyFilteredList}
|
||||
fullList={moduleApplyList}
|
||||
selectedModuleId={moduleApplyModuleId}
|
||||
onSelectModuleId={setModuleApplyModuleId}
|
||||
modulePickPreview={modulePickPreview}
|
||||
onConfirm={handleApplyTrainingModuleConfirm}
|
||||
onCancel={() => {
|
||||
setModuleApplyOpen(false)
|
||||
setModuleApplyPlacementLocked(false)
|
||||
}}
|
||||
/>
|
||||
|
||||
<TrainingPublishToFrameworkModal
|
||||
open={publishFrameworkOpen}
|
||||
onClose={() => setPublishFrameworkOpen(false)}
|
||||
onSuccess={() => setPublishFrameworkOpen(false)}
|
||||
unitId={editingUnit?.id}
|
||||
planningModalClubId={planningClubId}
|
||||
returnContext={moduleSaveReturnContext}
|
||||
/>
|
||||
|
||||
<SaveExercisesAsModuleModal
|
||||
open={saveModuleOpen}
|
||||
onClose={() => setSaveModuleOpen(false)}
|
||||
onSuccess={() => setSaveModuleOpen(false)}
|
||||
unitId={editingUnit?.id}
|
||||
planningModalClubId={planningClubId}
|
||||
returnContext={moduleSaveReturnContext}
|
||||
/>
|
||||
|
||||
<ExercisePickerModal
|
||||
open={exercisePickerOpen}
|
||||
multiSelect
|
||||
enableQuickCreateDraft
|
||||
onClose={() => {
|
||||
setExercisePickerOpen(false)
|
||||
setExercisePickerTarget(null)
|
||||
}}
|
||||
onSelectExercises={async (picked) => {
|
||||
if (!exercisePickerTarget || !picked?.length) return
|
||||
const rows = []
|
||||
for (const ex of picked) {
|
||||
const row = await hydrateExercisePlanningRow(ex)
|
||||
if (row) rows.push(row)
|
||||
}
|
||||
if (!rows.length) return
|
||||
const { sIdx, iIdx, insertBeforeIndex } = exercisePickerTarget
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
sections: prev.sections.map((s, si) => {
|
||||
if (si !== sIdx) return s
|
||||
const items = [...(s.items || [])]
|
||||
if (typeof iIdx === 'number') {
|
||||
const [first, ...tail] = rows
|
||||
items[iIdx] = { ...items[iIdx], ...first, item_type: 'exercise' }
|
||||
if (tail.length) items.splice(iIdx + 1, 0, ...tail)
|
||||
return { ...s, items }
|
||||
}
|
||||
const at = Math.min(
|
||||
typeof insertBeforeIndex === 'number' ? insertBeforeIndex : items.length,
|
||||
items.length
|
||||
)
|
||||
items.splice(at, 0, ...rows)
|
||||
return { ...s, items }
|
||||
}),
|
||||
}))
|
||||
setExercisePickerOpen(false)
|
||||
setExercisePickerTarget(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
<ExercisePeekModal
|
||||
open={planningPeekCtx != null}
|
||||
exerciseId={planningPeekCtx?.exerciseId}
|
||||
variantId={planningPeekCtx?.variantId ?? undefined}
|
||||
peekExtras={planningPeekCtx?.peekExtras ?? undefined}
|
||||
onClose={() => setPlanningPeekCtx(null)}
|
||||
/>
|
||||
|
||||
<UnsavedChangesPrompt
|
||||
blocker={blocker}
|
||||
isBusy={saving}
|
||||
onSave={handleUnsavedDialogSave}
|
||||
onDiscardWithoutSave={() => setBypassDirty(true)}
|
||||
detail="Du hast ungespeicherte Änderungen vorgenommen. Möchtest du die Seite wirklich verlassen?"
|
||||
/>
|
||||
</PageFormEditorChrome>
|
||||
)
|
||||
}
|
||||
@@ -3,10 +3,16 @@
|
||||
* Phasen: Ganzgruppe vs. Split (planLoc); Druck mit optional getrennten Breakout-Seiten.
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import api from '../utils/api'
|
||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||
import PageReturnButton from '../components/PageReturnButton'
|
||||
import NavStateLink from '../components/NavStateLink'
|
||||
import CombinationPlanBracket from '../components/CombinationPlanBracket'
|
||||
import {
|
||||
buildPlanningHubFallbackReturnContext,
|
||||
buildTrainingRunReturnContext,
|
||||
} from '../utils/navReturnContext'
|
||||
import {
|
||||
buildPlanRunViewModelFromSections,
|
||||
itemStableKey,
|
||||
@@ -34,8 +40,9 @@ function statusLabel(s) {
|
||||
|
||||
export default function TrainingUnitRunPage() {
|
||||
const { unitId } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const idNum = unitId ? parseInt(unitId, 10) : NaN
|
||||
const planningReturn = useMemo(() => buildPlanningHubFallbackReturnContext(), [])
|
||||
const runReturn = useMemo(() => buildTrainingRunReturnContext(unitId), [unitId])
|
||||
|
||||
const [unit, setUnit] = useState(null)
|
||||
const [loadError, setLoadError] = useState(null)
|
||||
@@ -337,12 +344,13 @@ export default function TrainingUnitRunPage() {
|
||||
>
|
||||
Katalog (Popup)
|
||||
</button>
|
||||
<Link
|
||||
<NavStateLink
|
||||
to={`/exercises/${it.exercise_id}`}
|
||||
returnContext={runReturn}
|
||||
style={{ fontSize: '0.82rem', color: 'var(--accent)' }}
|
||||
>
|
||||
Vollständige Seite öffnen
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
@@ -368,9 +376,11 @@ export default function TrainingUnitRunPage() {
|
||||
return (
|
||||
<div className="card" style={{ margin: '1rem', padding: '1.5rem' }}>
|
||||
<p style={{ marginBottom: '1rem' }}>{loadError || 'Trainingseinheit nicht gefunden.'}</p>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||
Zur Planung
|
||||
</button>
|
||||
<PageReturnButton
|
||||
fallbackPath={planningReturn.path}
|
||||
fallbackLabel={planningReturn.label}
|
||||
className="page-return-btn btn btn-secondary btn-small"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -382,6 +392,7 @@ export default function TrainingUnitRunPage() {
|
||||
exerciseId={peekCtx?.exerciseId}
|
||||
variantId={peekCtx?.variantId ?? undefined}
|
||||
peekExtras={peekCtx?.peekExtras ?? undefined}
|
||||
returnContext={runReturn}
|
||||
onClose={() => setPeekCtx(null)}
|
||||
/>
|
||||
|
||||
@@ -395,11 +406,14 @@ export default function TrainingUnitRunPage() {
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||
Zur Planung
|
||||
</button>
|
||||
<Link
|
||||
<PageReturnButton
|
||||
fallbackPath={planningReturn.path}
|
||||
fallbackLabel={planningReturn.label}
|
||||
className="page-return-btn btn btn-secondary btn-small"
|
||||
/>
|
||||
<NavStateLink
|
||||
to={`/planning/run/${unitId}/coach`}
|
||||
returnContext={runReturn}
|
||||
className="btn btn-primary"
|
||||
style={{
|
||||
textDecoration: 'none',
|
||||
@@ -409,7 +423,7 @@ export default function TrainingUnitRunPage() {
|
||||
}}
|
||||
>
|
||||
Im Training (Coach)
|
||||
</Link>
|
||||
</NavStateLink>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => window.print()}>
|
||||
Drucken / PDF
|
||||
</button>
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
import { request, ACTIVE_CLUB_STORAGE_KEY } from '../api/client.js'
|
||||
import * as exercises from '../api/exercises.js'
|
||||
import * as planning from '../api/planning.js'
|
||||
import * as skillProfiles from '../api/skillProfiles.js'
|
||||
|
||||
export { ACTIVE_CLUB_STORAGE_KEY }
|
||||
export * from '../api/exercises.js'
|
||||
export * from '../api/planning.js'
|
||||
export * from '../api/skillProfiles.js'
|
||||
|
||||
// ============================================================================
|
||||
// Auth
|
||||
@@ -753,6 +755,9 @@ export const api = {
|
||||
// Training Planning → frontend/src/api/planning.js
|
||||
...planning,
|
||||
|
||||
// Fähigkeiten-Profile & Vorschläge (Phase 3) → frontend/src/api/skillProfiles.js
|
||||
...skillProfiles,
|
||||
|
||||
// Catalogs
|
||||
listFocusAreas,
|
||||
createFocusArea,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
|
||||
import { EXERCISE_VISIBILITY_FIELD_LABEL } from '../constants/exerciseGovernanceLabels'
|
||||
|
||||
const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)
|
||||
|
||||
@@ -164,7 +165,7 @@ export function buildExerciseListFilterChips({
|
||||
'visibility_rules',
|
||||
filters.visibility_rules,
|
||||
visibilityOptions,
|
||||
'Sichtbarkeit',
|
||||
EXERCISE_VISIBILITY_FIELD_LABEL,
|
||||
setFilters
|
||||
)
|
||||
pushCatalogRuleFilterChips(chips, 'status_rules', filters.status_rules, statusOptions, 'Status', setFilters)
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/** Minimaler Snapshot einer Übung für die modulübergreifende Auswahl (filterunabhängig). */
|
||||
export function snapshotExerciseForSelection(exercise) {
|
||||
if (!exercise || exercise.id == null) return null
|
||||
const id = Number(exercise.id)
|
||||
if (!Number.isFinite(id) || id < 1) return null
|
||||
return {
|
||||
id,
|
||||
title: exercise.title || '',
|
||||
summary: exercise.summary || '',
|
||||
visibility: exercise.visibility,
|
||||
status: exercise.status,
|
||||
exercise_kind: exercise.exercise_kind,
|
||||
created_by: exercise.created_by,
|
||||
focus_area: exercise.focus_area,
|
||||
focus_area_names: exercise.focus_area_names,
|
||||
style_direction_names: exercise.style_direction_names,
|
||||
training_type_names: exercise.training_type_names,
|
||||
media_count: exercise.media_count,
|
||||
variant_count: exercise.variant_count,
|
||||
media: Array.isArray(exercise.media) ? exercise.media : [],
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeSelectedEntries(raw) {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
for (const item of raw) {
|
||||
const snap = snapshotExerciseForSelection(item)
|
||||
if (!snap || seen.has(snap.id)) continue
|
||||
seen.add(snap.id)
|
||||
out.push(snap)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function mergeSelectedWithListEntries(selectedEntries, exercises) {
|
||||
const byId = new Map()
|
||||
for (const e of exercises || []) {
|
||||
const id = Number(e?.id)
|
||||
if (Number.isFinite(id) && id > 0) byId.set(id, e)
|
||||
}
|
||||
return (selectedEntries || []).map((entry) => byId.get(Number(entry.id)) || entry)
|
||||
}
|
||||
|
||||
export function moduleItemToPayload(row, orderIndex) {
|
||||
if ((row?.item_type || 'exercise') === 'note') {
|
||||
return {
|
||||
item_type: 'note',
|
||||
order_index: orderIndex,
|
||||
note_body: row.note_body ?? '',
|
||||
}
|
||||
}
|
||||
const eid = Number(row.exercise_id)
|
||||
if (!Number.isFinite(eid) || eid < 1) return null
|
||||
const vidRaw = row.exercise_variant_id
|
||||
const vid =
|
||||
vidRaw === '' || vidRaw == null || row.exercise_kind === 'combination'
|
||||
? null
|
||||
: Number(vidRaw)
|
||||
return {
|
||||
item_type: 'exercise',
|
||||
order_index: orderIndex,
|
||||
exercise_id: eid,
|
||||
exercise_variant_id: Number.isFinite(vid) && vid > 0 ? vid : null,
|
||||
planned_duration_min:
|
||||
row.planned_duration_min !== '' && row.planned_duration_min != null
|
||||
? Number(row.planned_duration_min)
|
||||
: null,
|
||||
notes: row.notes != null && String(row.notes).trim() ? String(row.notes).trim() : null,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRowsPayload(rows) {
|
||||
return rows
|
||||
.map((row, idx) =>
|
||||
moduleItemToPayload(
|
||||
{
|
||||
...row,
|
||||
exercise_id: row.exercise_id,
|
||||
exercise_variant_id: row.exercise_variant_id,
|
||||
planned_duration_min: row.planned_duration_min,
|
||||
notes: row.notes,
|
||||
exercise_kind: row.exercise_kind,
|
||||
},
|
||||
idx
|
||||
)
|
||||
)
|
||||
.filter(Boolean)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { INITIAL_EXERCISE_LIST_FILTERS, mergeExerciseListPrefsFromApi } from '../constants/exerciseListFilters'
|
||||
import { normalizeSelectedEntries } from './exerciseListSelection'
|
||||
|
||||
const STORAGE_KEY = 'shinkan.exerciseList.session.v1'
|
||||
|
||||
function safeParse(raw) {
|
||||
if (!raw) return null
|
||||
try {
|
||||
return JSON.parse(raw)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns {{ filters: object, searchInput: string, aiSearchInput: string, mineOnly: boolean, selectedEntries: object[] } | null} */
|
||||
export function readExerciseListSessionState() {
|
||||
if (typeof sessionStorage === 'undefined') return null
|
||||
const parsed = safeParse(sessionStorage.getItem(STORAGE_KEY))
|
||||
if (!parsed || typeof parsed !== 'object') return null
|
||||
|
||||
const filters =
|
||||
parsed.filters && typeof parsed.filters === 'object'
|
||||
? mergeExerciseListPrefsFromApi(parsed.filters)
|
||||
: { ...INITIAL_EXERCISE_LIST_FILTERS }
|
||||
|
||||
return {
|
||||
filters,
|
||||
searchInput: typeof parsed.searchInput === 'string' ? parsed.searchInput : '',
|
||||
aiSearchInput: typeof parsed.aiSearchInput === 'string' ? parsed.aiSearchInput : '',
|
||||
mineOnly: !!parsed.mineOnly,
|
||||
selectedEntries: normalizeSelectedEntries(parsed.selectedEntries),
|
||||
}
|
||||
}
|
||||
|
||||
export function writeExerciseListSessionState(state) {
|
||||
if (typeof sessionStorage === 'undefined' || !state || typeof state !== 'object') return
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
filters: state.filters ?? { ...INITIAL_EXERCISE_LIST_FILTERS },
|
||||
searchInput: typeof state.searchInput === 'string' ? state.searchInput : '',
|
||||
aiSearchInput: typeof state.aiSearchInput === 'string' ? state.aiSearchInput : '',
|
||||
mineOnly: !!state.mineOnly,
|
||||
selectedEntries: normalizeSelectedEntries(state.selectedEntries),
|
||||
})
|
||||
)
|
||||
} catch {
|
||||
/* quota / private mode */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { formatDurationDisplay, formatSessionDurationRange } from './trainingDurationUtils'
|
||||
import {
|
||||
frameworkSkillSummaryKey,
|
||||
maxSelectedSkillClubPercent,
|
||||
summaryHasSkill,
|
||||
} from './skillProfileListHelpers'
|
||||
|
||||
export function frameworkSessionDurationLabel(row) {
|
||||
return formatSessionDurationRange(row?.session_duration_min, row?.session_duration_max, {
|
||||
empty: 'Dauer nicht angegeben',
|
||||
})
|
||||
}
|
||||
|
||||
/** Komma-getrennte Aggregat-Strings aus der Listen-API in Einträge zerlegen. */
|
||||
export function splitFrameworkCommaAgg(value) {
|
||||
const s = (value ?? '').toString().trim()
|
||||
if (!s) return []
|
||||
return s
|
||||
.split(',')
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
/** Entwicklungsziele aus goal_titles_agg (Trenner „|“). */
|
||||
export function splitFrameworkGoalsAgg(value) {
|
||||
const s = (value ?? '').toString().trim()
|
||||
if (!s) return []
|
||||
return s
|
||||
.split('|')
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function frameworkProgramHasCatalogMeta(row) {
|
||||
return (
|
||||
splitFrameworkCommaAgg(row?.focus_area_names_agg).length > 0 ||
|
||||
splitFrameworkCommaAgg(row?.style_direction_names_agg).length > 0 ||
|
||||
splitFrameworkCommaAgg(row?.training_type_names_agg).length > 0 ||
|
||||
splitFrameworkCommaAgg(row?.target_group_names_agg).length > 0
|
||||
)
|
||||
}
|
||||
|
||||
function parseIdList(raw) {
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.map((x) => String(x)).filter(Boolean)
|
||||
}
|
||||
if (typeof raw === 'string' && raw.trim().startsWith('[')) {
|
||||
try {
|
||||
const arr = JSON.parse(raw)
|
||||
if (Array.isArray(arr)) return arr.map((x) => String(x))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/** Eindeutige Session-Dauern (Minuten) aus allen Rahmen in der Liste. */
|
||||
export function collectDistinctSessionDurationsMinutes(rows) {
|
||||
const set = new Set()
|
||||
for (const r of rows || []) {
|
||||
const lo = r.session_duration_min
|
||||
const hi = r.session_duration_max
|
||||
if (lo != null && lo !== '' && Number.isFinite(Number(lo))) set.add(Number(lo))
|
||||
if (hi != null && hi !== '' && Number.isFinite(Number(hi))) set.add(Number(hi))
|
||||
}
|
||||
return [...set].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
function programDurationBounds(row) {
|
||||
const lo = row.session_duration_min != null ? Number(row.session_duration_min) : null
|
||||
const hi = row.session_duration_max != null ? Number(row.session_duration_max) : null
|
||||
if (lo != null && Number.isFinite(lo) && lo > 0) {
|
||||
const hiEff = hi != null && Number.isFinite(hi) && hi > 0 ? hi : lo
|
||||
return { lo, hi: hiEff }
|
||||
}
|
||||
if (hi != null && Number.isFinite(hi) && hi > 0) {
|
||||
return { lo: hi, hi }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Überlappung Programm-Session-Spanne mit Filter-Spanne (Minuten). */
|
||||
function rowMatchesDurationRange(row, fromMin, toMin) {
|
||||
const hasFrom = fromMin != null && fromMin !== '' && !Number.isNaN(Number(fromMin))
|
||||
const hasTo = toMin != null && toMin !== '' && !Number.isNaN(Number(toMin))
|
||||
if (!hasFrom && !hasTo) return true
|
||||
|
||||
const bounds = programDurationBounds(row)
|
||||
if (!bounds) return false
|
||||
|
||||
const fLo = hasFrom ? Number(fromMin) : bounds.lo
|
||||
const fHi = hasTo ? Number(toMin) : hasFrom ? Number(fromMin) : bounds.hi
|
||||
const filterLo = Math.min(fLo, fHi)
|
||||
const filterHi = Math.max(fLo, fHi)
|
||||
|
||||
return bounds.lo <= filterHi && bounds.hi >= filterLo
|
||||
}
|
||||
|
||||
function rowMatchesDurationPreset(row, presetMin, toleranceMin = 10) {
|
||||
if (presetMin == null || presetMin === '' || Number.isNaN(Number(presetMin))) return true
|
||||
const t = Number(presetMin)
|
||||
const bounds = programDurationBounds(row)
|
||||
if (!bounds) return false
|
||||
return t >= bounds.lo - toleranceMin && t <= bounds.hi + toleranceMin
|
||||
}
|
||||
|
||||
export const EMPTY_FRAMEWORK_IMPORT_FILTERS = {
|
||||
query: '',
|
||||
focusAreaIds: [],
|
||||
trainingTypeIds: [],
|
||||
targetGroupIds: [],
|
||||
durationMode: 'any',
|
||||
durationRangeFrom: '',
|
||||
durationRangeTo: '',
|
||||
durationPresetMin: null,
|
||||
skillIds: [],
|
||||
skillSort: 'title',
|
||||
skillMinClubPercent: 0,
|
||||
skillDisplayLimit: 24,
|
||||
}
|
||||
|
||||
export function hasActiveFrameworkImportFilters(filters = {}) {
|
||||
const f = { ...EMPTY_FRAMEWORK_IMPORT_FILTERS, ...filters }
|
||||
if ((f.query || '').trim()) return true
|
||||
if ((f.focusAreaIds || []).length) return true
|
||||
if ((f.trainingTypeIds || []).length) return true
|
||||
if ((f.targetGroupIds || []).length) return true
|
||||
if (f.durationMode === 'range') {
|
||||
if (String(f.durationRangeFrom || '').trim() !== '') return true
|
||||
if (String(f.durationRangeTo || '').trim() !== '') return true
|
||||
}
|
||||
if (f.durationMode === 'preset' && f.durationPresetMin != null) return true
|
||||
if ((f.skillIds || []).length) return true
|
||||
if (Number(f.skillMinClubPercent) > 0) return true
|
||||
if (f.skillSort === 'skill_strength' && (f.skillIds || []).length) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Kurzbeschreibung aktiver Filter (für Zusammenfassung außerhalb des Panels).
|
||||
*/
|
||||
export function summarizeFrameworkImportFilters(filters = {}, catalogs = {}) {
|
||||
const f = { ...EMPTY_FRAMEWORK_IMPORT_FILTERS, ...filters }
|
||||
const parts = []
|
||||
const q = (f.query || '').trim()
|
||||
if (q) parts.push(`Suche: „${q}"`)
|
||||
|
||||
const nameById = (list, id) => list?.find((x) => String(x.id) === String(id))?.name || id
|
||||
|
||||
if ((f.skillIds || []).length) {
|
||||
const names = f.skillIds.map((id) => nameById(catalogs.skills, id))
|
||||
parts.push(`Fähigkeiten: ${names.join(', ')}`)
|
||||
}
|
||||
if (Number(f.skillMinClubPercent) > 0) {
|
||||
parts.push(`mind. ${f.skillMinClubPercent}% vom Rahmenprogramm-Maximum`)
|
||||
}
|
||||
if (f.skillSort === 'skill_strength' && (f.skillIds || []).length) {
|
||||
parts.push('Sortierung: Fähigkeiten-Stärke')
|
||||
}
|
||||
|
||||
if ((f.focusAreaIds || []).length) {
|
||||
const names = f.focusAreaIds.map((id) => nameById(catalogs.focusAreas, id))
|
||||
parts.push(`Fokus: ${names.join(', ')}`)
|
||||
}
|
||||
if ((f.trainingTypeIds || []).length) {
|
||||
const names = f.trainingTypeIds.map((id) => nameById(catalogs.trainingTypes, id))
|
||||
parts.push(`Trainingsart: ${names.join(', ')}`)
|
||||
}
|
||||
if ((f.targetGroupIds || []).length) {
|
||||
const names = f.targetGroupIds.map((id) => nameById(catalogs.targetGroups, id))
|
||||
parts.push(`Zielgruppe: ${names.join(', ')}`)
|
||||
}
|
||||
|
||||
if (f.durationMode === 'range') {
|
||||
const a = String(f.durationRangeFrom || '').trim()
|
||||
const b = String(f.durationRangeTo || '').trim()
|
||||
if (a || b) {
|
||||
const fromLbl = a ? formatDurationDisplay(Number(a), { empty: a }) : '—'
|
||||
const toLbl = b ? formatDurationDisplay(Number(b), { empty: b }) : '—'
|
||||
parts.push(`Dauer: ${fromLbl} – ${toLbl}`)
|
||||
}
|
||||
} else if (f.durationMode === 'preset' && f.durationPresetMin != null) {
|
||||
parts.push(`Dauer: ${formatDurationDisplay(f.durationPresetMin)}`)
|
||||
}
|
||||
|
||||
return parts
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-Filter für Rahmenprogramm-Auswahl (Liste / Import-Dialog).
|
||||
*/
|
||||
export function filterFrameworkPrograms(rows, filters = {}, skillSummaries = null) {
|
||||
const f = { ...EMPTY_FRAMEWORK_IMPORT_FILTERS, ...filters }
|
||||
const q = (f.query || '').trim().toLowerCase()
|
||||
const focusIds = new Set((f.focusAreaIds || []).map(String))
|
||||
const typeIds = new Set((f.trainingTypeIds || []).map(String))
|
||||
const tgIds = new Set((f.targetGroupIds || []).map(String))
|
||||
const skillIds = f.skillIds || []
|
||||
const minClubPct = Number(f.skillMinClubPercent) || 0
|
||||
|
||||
let list = (rows || []).filter((r) => {
|
||||
if (q) {
|
||||
const blob = [
|
||||
r.title,
|
||||
r.description,
|
||||
r.goal_titles_agg,
|
||||
r.focus_area_names_agg,
|
||||
r.style_direction_names_agg,
|
||||
r.training_type_names_agg,
|
||||
r.target_group_names_agg,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
if (!blob.includes(q)) return false
|
||||
}
|
||||
|
||||
if (focusIds.size) {
|
||||
const fa = parseIdList(r.focus_area_ids)
|
||||
if (!fa.some((id) => focusIds.has(id))) return false
|
||||
}
|
||||
if (typeIds.size) {
|
||||
const tt = parseIdList(r.training_type_ids)
|
||||
if (!tt.some((id) => typeIds.has(id))) return false
|
||||
}
|
||||
if (tgIds.size) {
|
||||
const tg = parseIdList(r.target_group_ids)
|
||||
if (!tg.some((id) => tgIds.has(id))) return false
|
||||
}
|
||||
|
||||
if (f.durationMode === 'range') {
|
||||
if (!rowMatchesDurationRange(r, f.durationRangeFrom, f.durationRangeTo)) return false
|
||||
} else if (f.durationMode === 'preset') {
|
||||
if (!rowMatchesDurationPreset(r, f.durationPresetMin)) return false
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
if (skillIds.length && skillSummaries) {
|
||||
list = list.filter((r) => {
|
||||
const summary = skillSummaries[frameworkSkillSummaryKey(r.id)]
|
||||
if (!summary) return false
|
||||
return skillIds.some((sid) => summaryHasSkill(summary, sid, minClubPct))
|
||||
})
|
||||
}
|
||||
|
||||
if (f.skillSort === 'skill_strength' && skillIds.length && skillSummaries) {
|
||||
list = [...list].sort((a, b) => {
|
||||
const sa = skillSummaries[frameworkSkillSummaryKey(a.id)]
|
||||
const sb = skillSummaries[frameworkSkillSummaryKey(b.id)]
|
||||
const pa = maxSelectedSkillClubPercent(sa, skillIds) ?? -1
|
||||
const pb = maxSelectedSkillClubPercent(sb, skillIds) ?? -1
|
||||
return pb - pa
|
||||
})
|
||||
}
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
export function frameworkProgramOptionLabel(row) {
|
||||
const title = (row?.title || '').trim() || `Rahmen #${row?.id}`
|
||||
const dur = frameworkSessionDurationLabel(row)
|
||||
const slots = row?.slots_count != null ? `${row.slots_count} Slot(s)` : ''
|
||||
const bits = [dur !== 'Dauer nicht angegeben' ? dur : null, slots].filter(Boolean)
|
||||
return bits.length ? `${title} · ${bits.join(' · ')}` : title
|
||||
}
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user