Compare commits
80
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99a5fccaa5 | ||
|
|
cb868373f4 | ||
|
|
472cf1afdb | ||
|
|
0cb0e81d27 | ||
|
|
6a9351874f | ||
|
|
734d943d73 | ||
|
|
16eaf839e7 | ||
|
|
295c7e7efc | ||
|
|
c9175bd2fd | ||
|
|
f15aa7c415 | ||
|
|
1684892bcb | ||
|
|
4fee5a2b47 | ||
|
|
82705f0c3e | ||
|
|
a51f794945 | ||
|
|
7693139242 | ||
|
|
55d87d8d17 | ||
|
|
623af621b4 | ||
|
|
949a77fe38 | ||
|
|
0275f76432 | ||
|
|
bc1790bd82 | ||
|
|
b35a5ae216 | ||
|
|
8c07cf36ee | ||
|
|
7d2661a8e8 | ||
|
|
0fdee610ed | ||
|
|
f1c470a8a3 | ||
|
|
736656bde8 | ||
|
|
e441f59bff | ||
|
|
c3eb5a62c4 | ||
|
|
79e748b470 | ||
|
|
88c4201f80 | ||
|
|
6e1cc62065 | ||
|
|
76cc81a385 | ||
|
|
bd9cfaa6e4 | ||
|
|
a4f11a8225 | ||
|
|
5e5350d5ac | ||
|
|
73ac2218c7 | ||
|
|
352237bbb9 | ||
|
|
4cf7133bce | ||
|
|
c182ced7cd | ||
|
|
5338871f36 | ||
|
|
3005f1cb3e | ||
|
|
72e8f31cff | ||
|
|
73975d3402 | ||
|
|
4902771772 | ||
|
|
c2efbee4ee | ||
|
|
514b64682c | ||
|
|
a0a0be8bef | ||
|
|
613fedfaff | ||
|
|
2e761161ef | ||
|
|
0a203aaf75 | ||
|
|
f50e9db523 | ||
|
|
749c185e3d | ||
|
|
214f90d39b | ||
|
|
639392e133 | ||
|
|
d153a22545 | ||
|
|
81d1e9bdfd | ||
|
|
3214055531 | ||
|
|
4c974620d8 | ||
|
|
3134160003 | ||
|
|
b19940c997 | ||
|
|
dbc9057601 | ||
|
|
6136813f60 | ||
|
|
d82b805ffa | ||
|
|
c8c40474d1 | ||
|
|
f035b5bb0b | ||
|
|
696cb09bf4 | ||
|
|
33fedd5ec6 | ||
|
|
c8a08f8a94 | ||
|
|
d04ebee1f6 | ||
|
|
0c1fbab0ef | ||
|
|
a7d68c0646 | ||
|
|
a34dc19f5d | ||
|
|
9227b98431 | ||
|
|
390b0ecb73 | ||
|
|
7e7adfab54 | ||
|
|
bce235b9f6 | ||
|
|
5334836207 | ||
|
|
38d78abc3b | ||
|
|
a143532486 | ||
|
|
2f54fef88e |
No files matched your search
@@ -1,8 +1,8 @@
|
|||||||
# Shinkan Jinkendo - Projekt-Status
|
# Shinkan Jinkendo - Projekt-Status
|
||||||
|
|
||||||
**Stand:** 2026-05-12
|
**Stand:** 2026-05-14
|
||||||
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
|
**Version (Code):** 0.8.140 (`backend/version.py`, APP_VERSION)
|
||||||
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
|
**DB-Schema-Version:** `20260515063` (`backend/version.py`, DB_SCHEMA_VERSION)
|
||||||
**Branch:** develop
|
**Branch:** develop
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
||||||
|
|
||||||
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
||||||
|
|
||||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
||||||
|
|
||||||
@@ -36,7 +36,8 @@
|
|||||||
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
|
||||||
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
|
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
|
||||||
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
|
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
|
||||||
4. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
|
4. **Breakout / Coaching (Arbeitspaket):** Backend-Konsistenz `phases`↔`sections`, Run-UI vs. Spec (Stream-Tabs), Vorlagen phasenfähig, E2E-Smoke — siehe **`docs/HANDOVER.md`** (Tabelle „Coaching & Breakout“).
|
||||||
|
5. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -92,6 +93,8 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
|||||||
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
|
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
|
||||||
- [x] **Trainingsrahmenprogramm Bibliothek** (Ziele, Slots, Kontext) + **Slot‑Blueprints** in `training_units` (036–037)
|
- [x] **Trainingsrahmenprogramm Bibliothek** (Ziele, Slots, Kontext) + **Slot‑Blueprints** in `training_units` (036–037)
|
||||||
- [x] **Materialisierung** aus Rahmen‑Slot (`POST …/training-units/from-framework-slot`; UI‑Anbindung optional)
|
- [x] **Materialisierung** aus Rahmen‑Slot (`POST …/training-units/from-framework-slot`; UI‑Anbindung optional)
|
||||||
|
- [x] **Phasenmodell & parallele Streams** pro Einheit (Migration **063**): `training_unit_phases`, `training_unit_parallel_streams`; GET mit **`phases`** + flachen **`sections`**; PUT mit **`phases`** (App **0.8.137–0.8.140**)
|
||||||
|
- [x] **Coaching-Modus** für Breakout: Timeline mit Split-Wahl, Rejoin vor Ganzgruppe/nächstem Split, Nachbereitung speichern → Plan & Ablauf (`TrainingCoachPage`, `trainingPlanUtils.js`)
|
||||||
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
|
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
|
||||||
|
|
||||||
**MediaWiki Import:**
|
**MediaWiki Import:**
|
||||||
@@ -155,18 +158,19 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
| Dokument | Pfad | Stand | Status |
|
| Dokument | Pfad | Stand | Status |
|
||||||
|----------|------|-------|--------|
|
|----------|------|-------|--------|
|
||||||
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-12 | neu, Ist-Überblick |
|
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-14 | Phasen/Coach/Rejoin |
|
||||||
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-12 | Verweis Version siehe `version.py` |
|
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-14 | §11a Breakout |
|
||||||
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
|
||||||
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
|
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
|
||||||
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
|
||||||
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
|
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-14 | Parallele Streams Ist 063 |
|
||||||
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
|
||||||
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
|
||||||
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
|
||||||
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
|
||||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
|
||||||
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
|
| Parallele Streams (Fach/Technik) | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | 2026-05-14 | Ist-Stand P1 teils |
|
||||||
|
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-14 | Keyset, KPIs, Breakout/Coach Kurzverweis |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -177,4 +181,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Letzte Aktualisierung:** 2026-05-12 (Version 0.8.96, Executive Summary P-13/P-01, `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
|
**Letzte Aktualisierung:** 2026-05-14 (Version 0.8.140, DB 063, Handover Coaching/Breakout)
|
||||||
@@ -474,25 +474,23 @@ 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**).
|
**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**).
|
||||||
|
|
||||||
### Parallele Trainingsstreams (Breakout, Entwurf)
|
### 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.
|
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
|
||||||
|
|
||||||
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
|
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
|
||||||
|
|
||||||
|
**Umsetzung (2026-05, Migration 063, App 0.8.137 ff.):** Tabellen **`training_unit_phases`** und **`training_unit_parallel_streams`**; **`training_unit_sections`** mit **`phase_id`** und **`parallel_stream_id`** (exakt eine Zuordnung pro Sektion). **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und flache **`sections`**. **Coaching** und **Durchführung** nutzen dieselbe Phasenlogik im Frontend (`trainingPlanUtils.js`).
|
||||||
|
|
||||||
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||||
|
|
||||||
**Schema-Hinweis (2026-05):** Tabelle `training_unit_sections` hat **`UNIQUE (training_unit_id, order_index)`** (Migration 031). Damit sind **zwei gleichzeitige „Spuren“ mit jeweils eigener Sektion auf derselben `order_index`** nicht abbildbar — Voraussetzung für Parallele Streams ist eine **geplante Migrations-/Constraint-Anpassung** (partielle Uniques pro Phase/Stream); siehe Arbeitsdokument `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`. **Keine invasive Migration ohne explizite Freigabe.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
|
||||||
|
|
||||||
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
|
||||||
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
|
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
|
||||||
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
|
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
|
||||||
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
|
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
|
||||||
- **Geplant:** **Inline-Verweise** in Fließtextfeldern auf dieselbe Verknüpfung (`exercise_media.id`) — **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
|
- **Inline-Verweise** in Fließtextfeldern: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Parallele Trainingsstreams (Breakout) — Fachkonzept
|
# Parallele Trainingsstreams (Breakout) — Fachkonzept
|
||||||
|
|
||||||
**Status:** Entwurf zur Abstimmung · **Stand:** 2026-05-14
|
**Status:** MVP-Umsetzung **teilweise** (Code) · **Stand:** 2026-05-14
|
||||||
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
|
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
|
||||||
|
|
||||||
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
|
||||||
@@ -95,7 +95,14 @@ Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächste
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Verwandte Dokumente
|
## 9. Umsetzungsstand (kurz, 2026-05-14)
|
||||||
|
|
||||||
|
- **Erreicht:** Datenmodell Phasen/Streams (**063**), API **GET/PUT** mit **`phases`**, Planungs-Breakout-UI, Durchführung und Coach nutzen dieselbe Phasen-/Stream-Logik im Frontend (`trainingPlanUtils.js`). **Synchronisationspunkt** fachlich umgesetzt: vor nächster Ganzgruppenphase oder nächstem Split erscheint im Coach die **Rejoin-Karte** (mehrere Streams), sofern nicht am absoluten Planende.
|
||||||
|
- **Noch offen:** vollständige **Persistenz-Konsistenz** bei nachträglich geänderten Sektionen, **Vorlagen** mit Phasen, **Trainer pro Stream** in der UI, ggf. **Stream-Tabs** in der Durchführungsansicht wie in §5.2 skizziert — siehe **`docs/HANDOVER.md`** (Arbeitspaket-Tabelle).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Verwandte Dokumente
|
||||||
|
|
||||||
| Dokument | Bezug |
|
| Dokument | Bezug |
|
||||||
|----------|--------|
|
|----------|--------|
|
||||||
@@ -103,4 +110,5 @@ Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächste
|
|||||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
|
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
|
||||||
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
|
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
|
||||||
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
|
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
|
||||||
|
| `docs/HANDOVER.md` | Ist-Stand Coach, offene Breakout-Punkte |
|
||||||
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
|
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
|
||||||
@@ -123,7 +123,16 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
## 12. Trainingsplan: Phasen & parallele Streams (DB **063**, App **0.8.137–0.8.140**)
|
||||||
|
|
||||||
|
- **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` / `parallel_stream_id`; Default-Ganzgruppenphase für Bestand.
|
||||||
|
- **API:** `GET /api/training-units/:id` mit **`phases`** + **`sections`**; `PUT`/`POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); Rahmen-Slot-Materialisierung kopiert Phasen (**0.8.138**).
|
||||||
|
- **Frontend:** Planung Breakout-Panel (**0.8.139–0.8.140**); **`trainingPlanUtils.js`** — `sectionsWithPlanLocForDisplay`, `flattenPlanTimeline`, `buildCoachSavePlanPayload`, Split-Rejoin (`coachShouldPromptSplitRejoinTransition`); **`TrainingCoachPage`**, **`TrainingUnitRunPage`**.
|
||||||
|
- **Doku:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`, `docs/HANDOVER.md` §3, Arbeitspaket „offen“.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
|
||||||
|
|
||||||
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
|
||||||
|
|
||||||
@@ -150,7 +159,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
|
## 14. Nächste sinnvolle Schritte (nicht Lieferstand)
|
||||||
|
|
||||||
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
|
||||||
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
|
||||||
@@ -160,7 +169,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 14. Verweise
|
## 15. Verweise
|
||||||
|
|
||||||
| Thema | Dokument |
|
| Thema | Dokument |
|
||||||
|--------|----------|
|
|--------|----------|
|
||||||
@@ -170,5 +179,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
|
|||||||
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
|
||||||
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
|
||||||
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
|
||||||
|
| Parallele Phasen/Streams | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` |
|
||||||
|
| Coaching/Breakout-Handover | `docs/HANDOVER.md` |
|
||||||
| Fachlicher Nutzerüberblick | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` (Repo-Root) |
|
| Fachlicher Nutzerüberblick | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` (Repo-Root) |
|
||||||
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
# KI-gestützte Trainingsplanung – Zentrales Konzept
|
||||||
|
|
||||||
|
**Version:** 0.1
|
||||||
|
**Datum:** 2026-05-16
|
||||||
|
**Status:** Arbeitsdokument (Verfeinerung durch fachliche Konzept-Agentur vorgesehen)
|
||||||
|
**Ziel:** Einheitlicher Rahmen für **stufenweise** KI-Unterstützung bei der Planung (Abschnitte, Einheiten, später mehrtägig/Rahmen) – ohne vollständigen Katalog im Prompt zu spiegeln.
|
||||||
|
|
||||||
|
**Verwandte Dokumente:**
|
||||||
|
`functional/DOMAIN_MODEL.md` · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (u. a. CURR-003 zu Progressions-/KI-Automatik) · `technical/TRAINING_FRAMEWORK_SPEC.md` · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `docs/FACHLICHE_NUTZERFUNKTIONEN.md` · `docs/HANDOVER.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Produktliche Leitlinien
|
||||||
|
|
||||||
|
- **Nutzer:** Trainer/Vereinskontext, **Gruppenplanung** – keine Pflicht zur individuellen Sportler-Verfolgung; Kontext soll primär aus **Gruppe**, **bereits geplanten/durchgeführten Einheiten**, **Rahmen-/Zielen** und **berechtigtem Übungskorpus** bestehen.
|
||||||
|
- **Human-in-the-loop:** KI liefert **Vorschläge** (Liste, Reihenfolge, Begründung); schreibende Übernahme in Pläne nur nach **Trainer-Bestätigung** oder expliziter Aktion (analog „Manual First“ in `KI_FEATURES_SPEC.md`).
|
||||||
|
- **Governance-first:** Nur Übungen, die die API bereits für den Mandanten/Kontext **sichtbar** freigibt, dürfen in Kandidatenlisten landen – **vor** Retrieval und **vor** jedem Prompt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Kernproblem: Skalierung des Kontextes
|
||||||
|
|
||||||
|
Aus einer **großen Übungssammlung** („>1000 Übungen“) können weder alle **Felder** (Ziele, Ablauf, Skills, Varianten …) noch alle **Zeilen** sinnvoll in einen LLM-Prompt.
|
||||||
|
|
||||||
|
**Festlegung:** Der LLM-Prompt erhält immer nur ein **begrenztes Kontext-Paket** mit:
|
||||||
|
|
||||||
|
| Paketteil | Zweck |
|
||||||
|
|-----------|--------|
|
||||||
|
| **Auftrag** | z. B. Sektionstyp, Dauerbudget, Schwierigkeit, erlaubte Phasen/Streams |
|
||||||
|
| **Hard Constraints** | Gruppe, Termin/Zeitraum, Governance-Filter bereits angewendet |
|
||||||
|
| **Komprimierte Historie** | Letzte *N* Einheiten als **Liste von Übungs-IDs + Kurzlabels** (+ optional Haupt-Skills), keine vollen Fließtexte |
|
||||||
|
| **Ziele / Rahmen** | Kurztexte aus Rahmen-Slot/Zielblöcken oder Trainer-Prompt |
|
||||||
|
| **Kandidaten-Top‑K** | z. B. 30–120 Übungen, **je Zeile gekürzt** (Titel, `summary`, 2–5 Skill-Namen/Stufen); **nie** der gesamte Katalog |
|
||||||
|
| **Strukturierte Kanten optional** | Kleine Mengen Kanten aus Progressionsgraph: „Nachbarn von zuletzt genutzten Übungen“ |
|
||||||
|
|
||||||
|
**Zahlen‑Richtwerte (überarbeitungsfähig):**
|
||||||
|
Kandidaten **vor** dem LLM typischerweise **50–150** Einträge; im Prompt durch Token-Limit weiter **truncate** oder **zweistufig** (grober Ranking-Schritt ohne LLM, dann finer mit LLM auf Top‑40).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Pipeline: „Selektion vor dem Prompt“
|
||||||
|
|
||||||
|
Die **„optimale“** Auswahl entsteht **nicht**, indem das Modell den Katalog „im Kopf“ hält, sondern über eine **mehrstufige Pipeline**:
|
||||||
|
|
||||||
|
### Stufe 1 – Harte Filter (deterministisch, DB)
|
||||||
|
|
||||||
|
Synchron zur bestehenden Suche/List-API-Logik, z. B.:
|
||||||
|
|
||||||
|
- Sichtbarkeit / Verein / `official`‑Regeln
|
||||||
|
- Aktivitäts-/Archiv-Status der Übung
|
||||||
|
- Fokusbereich, Stil, Zielgruppe (wenn Trainings-/Gruppenkontext das vorgibt)
|
||||||
|
- Ausschluss bereits in **dieser Einheit** fester Übernutzung (optional)
|
||||||
|
|
||||||
|
Ergebnis: Menge \(M\) – kann noch sehr groß sein.
|
||||||
|
|
||||||
|
### Stufe 2 – Kontext-Verankerung (deterministisch + Graph)
|
||||||
|
|
||||||
|
- **Historie:** aus letzten *N* Gruppeneinheiten extrahierte `exercise_id`s (optional Variant).
|
||||||
|
- **Progressionsgraph:** ausgehend davon Nachbarn (eingehend/ausgehend begrenzte Tiefe) – bereits im Produkt als **unterstützend** modelliert (**CURR‑013**).
|
||||||
|
- **Rahmen/Slot-Ziele:** Überlapp mit Skill-Tags oder Stichwortliste (falls formalisiert).
|
||||||
|
- **Variantenketten:** `prerequisite_variant_id` / `progression_level` nur innerhalb bereits gewählter Übung prüfen oder als Hint an den LLM-Block durchreichen.
|
||||||
|
|
||||||
|
Ergebnis: **„Anker‑Menge“** + **„Graph‑Nachbarschaft“** → priorisierte Kandidaten.
|
||||||
|
|
||||||
|
### Stufe 3 – Weiches Ranking / Retrieval (halb-strukturiert)
|
||||||
|
|
||||||
|
Mindestens **eine** der folgenden Optionen – kombinierbar:
|
||||||
|
|
||||||
|
1. **Skill-/Facet-Overlap:** Punktezahl, wenn Übungs-Skills mit Ziel-/Matrix-Schwerpunkten übereinstimmen (bereits Daten in `exercise_skills`).
|
||||||
|
2. **Diversitäts-/Wiederholungsstrafe:** häufig in letzten Wochen geübte Übungen abwerten.
|
||||||
|
3. **Textsuche:** PostgreSQL **`tsvector`/Volltext** auf `title`, `summary`, ggf. gekürzte `goal` – für Trainer-Stichwort „Koordination Sprung“.
|
||||||
|
4. **Semantische Suche:** Embeddings + **Ähnlichkeitsuche** auf Kurztexte (siehe §5).
|
||||||
|
|
||||||
|
Ergebnis: sortierte Liste, **Top‑K** für den Prompt.
|
||||||
|
|
||||||
|
### Stufe 4 – LLM (optional zweistufig)
|
||||||
|
|
||||||
|
- **Optional 1:** LLM nur **sortiert/rankted** bereits vorgegebene IDs (Ranking mit kurzer Begründung).
|
||||||
|
- **Optional 2:** Zwei Calls: erst „welche drei Schwerpunkte“ / „Welche Constraints habe ich übersehen?“, zweiter Call nur mit gekürztem Top‑K – nur wenn UX den Mehraufwand rechtfertigt.
|
||||||
|
|
||||||
|
**Ausgabe-Contract:** Zurückkommen dürfen **nur gültige `exercise_id`s** aus der übergebenen Kandidatenliste (Server validiert gegen Set); **Halluzinationsrisiko damit entschärft**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Antwort auf die konkrete Frage: „Alle Übungen in den Prompt?“
|
||||||
|
|
||||||
|
**Nein.** Workflow:
|
||||||
|
|
||||||
|
1. **DB + Regeln + Graph + Historie** reduzieren auf **einige Hundert bis wenige tausend** Rohzeilen höchstens **intern** – aber
|
||||||
|
2. in den **LLM-Prompt** gehen nur **Top‑K kompakte Artefakte** (siehe §2).
|
||||||
|
|
||||||
|
Das LLM löst dann **Ranking, Reihenfolge, Timing-Hinweise, Trainer-sprachliche Kurzkommentare** – nicht die Frage „gibt es diese Übung überhaupt im System?“.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Vector DB (z. B. Qdrant) – wann nötig, wann nicht?
|
||||||
|
|
||||||
|
### 5.1 Ziel embeddings
|
||||||
|
|
||||||
|
Semantic Retrieval: „wie springt Coordinative Belastung ohne das Wort ‚Koordination‘ im Titel zu stehen.“ Das ist **über** reine Filtersuche und oft **über** stumpfe Volltextsuche erreichbar.
|
||||||
|
|
||||||
|
### 5.2 Option A – ohne separate Vector DB
|
||||||
|
|
||||||
|
- **PostgreSQL + `pgvector`** (Extension): Embeddings-Spalte an `exercises` (oder an „Search Document“-Zeilen), Indices, Abfrage zusammen mit SQL-Filtern in **einer Transaktions-DB**.
|
||||||
|
- **Größenordnung** einige 10 k–100 k Zeilen für Übungen: für Shinkan **oft ausreichend**.
|
||||||
|
- Vorteile: ein Betriebspfad, Mandanten-/Governance weiter in SQL lösen; Backup wie heute.
|
||||||
|
|
||||||
|
### 5.3 Option B – Qdrant (oder anderer Dediz-Vektorstore)
|
||||||
|
|
||||||
|
Sinnvoller zeitlicher Punkt oder technische Auslöser:
|
||||||
|
|
||||||
|
- sehr hohe Latenz-Anforderung mit **Hybrid-Filter** über viele kombinierte Metadaten in nahezu Echtzeit,
|
||||||
|
- Entkopplung: Embedding-Pipeline läuft asynchron und soll die **Operational DB** nicht beschweren,
|
||||||
|
- später **mehrsprachig** oder **mehrere Embedding-Versionen**/Re-Index ohne großen Migrationstress,
|
||||||
|
- Team bevorzugt **Dedicated** Vector-Ops gegenüber Postgres-Ops.
|
||||||
|
|
||||||
|
### 5.4 Empfehlung für diese Codebasis (überarbeitungsfähig)
|
||||||
|
|
||||||
|
1. **Phase 1:** Harte Filter + Graph + Historie + **PostgreSQL-Volltext** + Top‑K; LLM erst auf komprimierten Kandidaten → hoher Nutzen ohne neuen Infrastructure-Typen.
|
||||||
|
2. **Phase 2:** Bei nachweisbaren „Recall-Lücken“ (Trainer findet nichts Passendes trotz großem Korpus) **`pgvector` in Postgres** evaluieren – **vor** zusätzlicher Infrastruktur wie Qdrant.
|
||||||
|
3. **Phase 3:** Qdrant (o. ä.) wenn Größenordnung, Betrieb oder Produkt-Anforderungen **pgvector** sprengen oder klar eine **embedding-first** Produktstraße geplant wird.
|
||||||
|
|
||||||
|
**Fazit:** Eine dedizierte **Vector DB ist nicht zwingende Voraussetzung** für vernünftige Selektion; sie ist eine **Ausbaustufe**, wenn **semantische Lücke** und Skalierung es rechtfertigen. **Selektion** ist immer **„Filter + Ranking + kleines Top‑K“**, unabhängig vom Speicherort der Vektoren.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Datenpflege für gutes Retrieval (fachlicher Hebel)
|
||||||
|
|
||||||
|
Retrieval‑Qualität hängt stärker an **Metadaten** als an der Embedding-Technologie allein:
|
||||||
|
|
||||||
|
- verlässliche **Skills** (`exercise_skills`, ggf. KI-geholfen bereits laut Spez beim Übungs-Anlegen);
|
||||||
|
- sinnvolle **`summary`**-Felder für Karten/Liste/KI-Pack;
|
||||||
|
- **Progressionsgraph** dort, wo pädagogische Ketten gefestigt sind;
|
||||||
|
- konsistente **Fokusbereich/Stil**-Zuordnung.
|
||||||
|
|
||||||
|
Das fachliche Konzept sollte entscheiden: **wie viel automatische Pflege vs. Trainer-Pflichtfelder**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Produkt-/Release-Stufen (Anknüpfung)
|
||||||
|
|
||||||
|
| Stufe | Nutzen | Technik-Schwerpunkt |
|
||||||
|
|-------|--------|---------------------|
|
||||||
|
| A | Backend-KI-Service + Prompt-Slugs unter `technical/AI_PROMPT_SYSTEM_SPEC.md` | OpenRouter, Timeouts, 503 ohne Key |
|
||||||
|
| B | „Übungen für Abschnitt vorschlagen“ | Pipeline §3 Stufen 1–3 + Prompt mit Top‑K |
|
||||||
|
| C | Reihenfolge / Zeitslots innerhalb bestehender Sektion | Graph + LLM Ranking |
|
||||||
|
| D | Ganze Einheit (inkl. Phasen/Streams vereinfacht) | strukturiertere JSON-Ausgabe, strikte Schema-Validation |
|
||||||
|
| E | Mehreinheiten / Rahmen‑Alignment | Ziele aus Rahmenprogramm, Serie von Slots |
|
||||||
|
|
||||||
|
Die **Selektions‑Pipeline §3 bleibt** über alle Stufen konsistent und wird nur parametrierbar erweitert.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Compliance & Datenschutz (Kurzhinweis)
|
||||||
|
|
||||||
|
- Datenminimierung: **keine Teilnehmerliste** ohne expliziten Scope; Kontext über **Einheiten-Metadaten** und Übungen.
|
||||||
|
- **OpenRouter**/Modellwahl: Organisation intern klären (AV/Verarbeitungsvertrag, Datenflüsse außerhalb EU – siehe Repo-Compliance-Dokumente).
|
||||||
|
- **Logging:** Prompts keine unnötigen personenbezogenen Daten; wenn Debug: Retention definieren.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Offene Punkte für die fachliche Verfeinerung
|
||||||
|
|
||||||
|
- Gewichtung „**Wiederholung** vs. **Progression** vs. **Motivation**“ (domänenspezifisch).
|
||||||
|
- Umgang mit **Kombinationsübungen** und **Coach-Stufen B/C** in der Datenübergabe.
|
||||||
|
- Soll das System **„Lücken“** aus der **Matrix-Auflösung** aktiv quantifizieren oder nur Narrative verwenden?
|
||||||
|
- Akzeptierte **Übersetzungen**: nur Deutsch oder mehrsprachige Embeddings erforderlich?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Glossar
|
||||||
|
|
||||||
|
| Begriff | Bedeutung |
|
||||||
|
|---------|-----------|
|
||||||
|
| **Top‑K** | Feste kleine Obergrenze Übungen pro LLM-Anfrage |
|
||||||
|
| **Hard filter** | Deterministische SQL-/Policy-Einschränkung vor KI |
|
||||||
|
| **Kontext-Paket** | Zusammengesetztes, tokenlimitiertes Eingabeobjekt für den Prompt |
|
||||||
|
| **Retrieval** | algorithmischer Schritt ohne Generierung („wer kommt überhaupt in Frage“) |
|
||||||
@@ -1,23 +1,26 @@
|
|||||||
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
|
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
|
||||||
|
|
||||||
**Status:** Entwurf · **Stand:** 2026-05-14
|
**Status:** Umsetzung **Phase 1 (teils)** · **Stand:** 2026-05-14
|
||||||
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
|
||||||
|
|
||||||
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand Analyse 2026-05-14): eine `training_unit` mit **`training_unit_sections`** und **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung **`TrainingUnitRunPage`** (sequentiell über Sektionen).
|
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand 2026-05-14): **`training_unit_phases` / `training_unit_parallel_streams`** (Migration **063**) und **`training_unit_sections`** mit Phasen-/Stream-Bezug; **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung und Coaching über **`TrainingUnitRunPage`**, **`TrainingCoachPage`** und **`trainingPlanUtils.js`**.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Ist-Stand (relevant)
|
## 1. Ist-Stand (Code, 2026-05-14)
|
||||||
|
|
||||||
| Bereich | Aktuell |
|
| Bereich | Aktuell |
|
||||||
|---------|---------|
|
|---------|---------|
|
||||||
| Planstruktur | **Eine** lineare Liste `training_unit_sections` je `training_unit_id`; Items in `training_unit_section_items`. |
|
| **Schema** | Migration **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` **oder** `parallel_stream_id`. |
|
||||||
| Rahmenprogramm | `training_framework_slots` verweisen auf **Blueprint**-`training_units` — Slots = **Serien-Spalten**, nicht simultane Breakouts in **einer** Halle. |
|
| **API** | `GET /api/training-units/:id` — **`phases`** (verschachtelt) + flache **`sections`**. `PUT/POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); höchstens eines von `phases`, `sections`, `exercises` pro Request (Planning-Router). Legacy-PUT mit nur `sections` erzeugt/ergänzt Ganzgruppen-Phase. |
|
||||||
| Kombinationsübung | Ein **Item** kann Kombi sein; `planning_method_profile` = Snapshot; Coaching-UI teilweise (`CombinationPlanBracket` in Run/Peek). |
|
| **Planung (UI)** | Breakout-Panel: Ganzgruppen-/parallele Phasen, Streams; Speichern phasenbasiert (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`). |
|
||||||
| Trainer-Zuweisung | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am **`training_units`**-Kopf; **keine** Zuordnung zu „welcher parallelen Spur“. |
|
| **Durchführung** | `TrainingUnitRunPage.jsx` + `trainingPlanUtils.js` (`sectionsWithPlanLocForDisplay`, `buildPlanRunViewModelFromSections`) — Phasenfolge in „Plan & Ablauf“. |
|
||||||
| Run-Modus | `TrainingUnitRunPage`: sortierte Sektionen/Items, Checkliste, Fortschritt in `sessionStorage` pro Einheit. |
|
| **Coaching** | `TrainingCoachPage.jsx` + `flattenPlanTimeline`, Stream-Picks, Rejoin vor Ganzgruppe/nächstem Split (`coachShouldPromptSplitRejoinTransition`), Nachbereitung mit `buildCoachSavePlanPayload`, danach Navigation zu `/planning/run/:id`. |
|
||||||
|
| **Kombinationsübung** | Unverändert je Item; `planning_method_profile`, Coach-Kombi-Stufe A. |
|
||||||
|
| **Trainer-Zuweisung** | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am Einheitskopf; **Stream-**`assigned_trainer_profile_ids` im Schema — UI/Policy noch nicht vollständig (siehe **§8 offen**). |
|
||||||
|
| **Rahmenprogramm** | Blueprint-`training_units` können dieselbe Phasenstruktur tragen; Kopie aus Slot (`from-framework-slot`, **0.8.138**). |
|
||||||
|
|
||||||
**Konsequenz:** Parallele Streams erfordern ein **erweitertes konzeptionelles „Gefäß“** unterhalb der Einheit (Phasen und/oder Streams) und eine **Verknüpfung** bestehender Sektionen mit diesem Gefäß — oder eine **Migration** zu einem neuen Pflicht-Container (siehe §3).
|
**Hinweis:** Die frühere Planungsvariante „nur lineare `training_unit_sections` ohne Phasen“ gilt weiter für Alt-Daten; Migration **063** ordnet Bestand einer Default-Ganzgruppenphase zu.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -37,9 +40,11 @@ training_unit (Kalender-Einheit)
|
|||||||
|
|
||||||
## 3. Datenmodell — Optionen
|
## 3. Datenmodell — Optionen
|
||||||
|
|
||||||
|
**Ist (063):** Die unten skizzierte **empfohlene** Normalform ist unter den genannten Tabellennamen produktiv; die Abschnitte 3.1/3.2 bleiben zur Einordnung erhalten.
|
||||||
|
|
||||||
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
|
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
|
||||||
|
|
||||||
Neue Tabellen (Namen bei Implementierung final festlegen):
|
Die Tabellen sind **umgesetzt** (Namen final):
|
||||||
|
|
||||||
| Tabelle | Zweck |
|
| Tabelle | Zweck |
|
||||||
|---------|--------|
|
|---------|--------|
|
||||||
@@ -109,15 +114,15 @@ Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; P
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Implementierungsphasen (Vorschlag)
|
## 8. Implementierungsphasen (Abgleich)
|
||||||
|
|
||||||
| Phase | Inhalt |
|
| Phase | Inhalt | Stand 2026-05-14 |
|
||||||
|-------|--------|
|
|-------|--------|------------------|
|
||||||
| **P1** | Schema Phasen + Streams; Migration; GET/PATCH Einheit verschachtelt; Planungs-UI; Run-UI mit Stream-Tabs |
|
| **P1** | Schema Phasen + Streams; Migration **063**; GET/PUT verschachtelt; Planungs-UI; Run + Coach phasenbasiert | **Teilweise erledigt** — Run-UI nutzt Phasen-Timeline in der Anzeige; **Stream-Tabs** optional noch zu vereinheitlichen (§5.2) |
|
||||||
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert |
|
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert | **Offen** |
|
||||||
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) |
|
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) | **Offen** |
|
||||||
|
|
||||||
---
|
**Offene Punkte (kurz):** siehe **`docs/HANDOVER.md`** Tabelle „Coaching & Breakout“.
|
||||||
|
|
||||||
## 9. Verwandte Dokumente
|
## 9. Verwandte Dokumente
|
||||||
|
|
||||||
@@ -127,4 +132,5 @@ Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; P
|
|||||||
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
|
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
|
||||||
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
|
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
|
||||||
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
|
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
|
||||||
| `frontend/src/pages/TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Ist-UI |
|
| `TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Planung, Durchführung, Rahmen |
|
||||||
|
| `frontend/src/utils/trainingPlanUtils.js`, `TrainingCoachPage.jsx` | Phasen-Timeline, Rejoin, Coach-Speichern |
|
||||||
@@ -86,7 +86,7 @@ frontend/src/
|
|||||||
|
|
||||||
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
|
||||||
|
|
||||||
Kurz (Stand 2026-05-12): App **0.8.96**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
|
Kurz (Stand 2026-05-14): App- und DB-Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit **Phasen & parallelen Streams (Breakout, 063)**, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `PARALLEL_TRAINING_STREAMS_SPEC.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
|
||||||
|
|
||||||
### Log (Auszug)
|
### Log (Auszug)
|
||||||
|
|
||||||
|
|||||||
+160
-1
@@ -3,7 +3,7 @@ Vereins-Mandanten: Mitgliedschaften, aktiver Vereinskontext, einfache Berechtigu
|
|||||||
|
|
||||||
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
|
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
|
||||||
"""
|
"""
|
||||||
from typing import Any, Dict, List, Optional, Set
|
from typing import Any, Dict, List, Mapping, Optional, Set, Union
|
||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
@@ -155,6 +155,165 @@ def club_ids_for_profile_with_roles(cur, profile_id: int, *role_codes: str) -> S
|
|||||||
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
|
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
|
||||||
|
|
||||||
|
|
||||||
|
def _library_governance_triplet(
|
||||||
|
row: Mapping[str, Any],
|
||||||
|
) -> tuple[str, Optional[int], Optional[int]]:
|
||||||
|
"""visibility, club_id, created_by als normalisierte Werte für Bibliotheks-/Planungsartefakte."""
|
||||||
|
vis = str(row.get("visibility") or "private").strip().lower()
|
||||||
|
if vis not in _GOVERNANCE_VISIBILITY:
|
||||||
|
vis = "private"
|
||||||
|
cid_raw = row.get("club_id")
|
||||||
|
try:
|
||||||
|
ex_cid = int(cid_raw) if cid_raw is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
ex_cid = None
|
||||||
|
cr_raw = row.get("created_by")
|
||||||
|
try:
|
||||||
|
creator = int(cr_raw) if cr_raw is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
creator = None
|
||||||
|
return vis, ex_cid, creator
|
||||||
|
|
||||||
|
|
||||||
|
def assert_library_content_editable(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
role: Optional[str],
|
||||||
|
row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
"""Inhalt bearbeiten: wie Übungen — Ersteller, Plattform-Admin oder Planungsberechtigter im Verein."""
|
||||||
|
pid = int(profile_id)
|
||||||
|
ex_vis, ex_cid, creator = _library_governance_triplet(row)
|
||||||
|
if creator is not None and creator == pid:
|
||||||
|
return
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, pid, ex_cid, role):
|
||||||
|
return
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Bearbeiten dieses Inhalts")
|
||||||
|
|
||||||
|
|
||||||
|
def assert_library_content_deletable(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
role: Optional[str],
|
||||||
|
row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
"""Löschen: wie Übungen — privat Eigentümer/Vereins-Admin-Kontext, Verein nur Vereinsadmin, offiziell nur Plattform."""
|
||||||
|
pid = int(profile_id)
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
vis, cid, creator = _library_governance_triplet(row)
|
||||||
|
try:
|
||||||
|
creator_int = int(creator) if creator is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
creator_int = None
|
||||||
|
|
||||||
|
if vis == "official":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Offizielle Inhalte dürfen nur von Plattform-Admins gelöscht werden.",
|
||||||
|
)
|
||||||
|
if vis == "club":
|
||||||
|
try:
|
||||||
|
ex_club = int(cid) if cid is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
ex_club = None
|
||||||
|
if ex_club is None:
|
||||||
|
raise HTTPException(status_code=400, detail="Vereinsinhalt ohne gültige Vereinszuordnung")
|
||||||
|
if not has_club_role(cur, pid, ex_club, "club_admin"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Vereins-Admins dürfen Vereins-Inhalte löschen.",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if creator_int is not None and creator_int == pid:
|
||||||
|
return
|
||||||
|
if creator_int is not None and club_admin_shares_club_with_creator(cur, pid, creator_int):
|
||||||
|
return
|
||||||
|
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Löschen dieses Inhalts")
|
||||||
|
|
||||||
|
|
||||||
|
def assert_library_content_governance_transition(
|
||||||
|
cur,
|
||||||
|
profile_id: int,
|
||||||
|
role: Optional[str],
|
||||||
|
prev_row: Union[Dict[str, Any], Mapping[str, Any]],
|
||||||
|
next_visibility: str,
|
||||||
|
next_club_id: Optional[int],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Zusätzliche Regeln beim Ändern von visibility/club_id (Zielzustand vor assert_valid_governance_visibility prüfen).
|
||||||
|
|
||||||
|
- Abwahl „official“: nur Plattform-Admin.
|
||||||
|
- private → club: nur Ersteller (oder Plattform-Admin).
|
||||||
|
- club → private: Ersteller, Vereinsadmin im bisherigen Verein oder Plattform-Admin.
|
||||||
|
- club → club mit Wechsel club_id: Vereinsadmin im alten oder neuen Verein oder Plattform-Admin.
|
||||||
|
"""
|
||||||
|
nv = str(next_visibility or "").strip().lower()
|
||||||
|
if nv not in _GOVERNANCE_VISIBILITY:
|
||||||
|
raise HTTPException(status_code=400, detail="Ungültige visibility")
|
||||||
|
|
||||||
|
old_vis, old_cid, creator = _library_governance_triplet(prev_row)
|
||||||
|
new_cid: Optional[int]
|
||||||
|
try:
|
||||||
|
new_cid = int(next_club_id) if next_club_id is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
new_cid = None
|
||||||
|
|
||||||
|
pid = int(profile_id)
|
||||||
|
try:
|
||||||
|
creator_int = int(creator) if creator is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
creator_int = None
|
||||||
|
|
||||||
|
if old_vis == nv and (nv != "club" or old_cid == new_cid):
|
||||||
|
return
|
||||||
|
|
||||||
|
if old_vis == "official" and nv != "official":
|
||||||
|
if not is_platform_admin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Plattform-Admins dürfen offizielle Inhalte auf Verein oder privat setzen.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if nv == "official":
|
||||||
|
return
|
||||||
|
|
||||||
|
if old_vis == "private" and nv == "club":
|
||||||
|
if creator_int is not None and creator_int != pid and not is_platform_admin(role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur der Ersteller darf private Inhalte für den Verein freigeben.",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if old_vis == "club" and nv == "private":
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
if creator_int is not None and creator_int == pid:
|
||||||
|
return
|
||||||
|
if old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin"):
|
||||||
|
return
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Ersteller, Vereins-Admins oder Plattform-Admins dürfen Vereins-Inhalte auf privat setzen.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if old_vis == "club" and nv == "club" and old_cid != new_cid:
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return
|
||||||
|
ok_old = old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin")
|
||||||
|
ok_new = new_cid is not None and has_club_role(cur, pid, new_cid, "club_admin")
|
||||||
|
if ok_old or ok_new:
|
||||||
|
return
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Nur Vereins-Admins oder Plattform-Admins dürfen die Vereinszuordnung ändern.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def assert_valid_governance_visibility(
|
def assert_valid_governance_visibility(
|
||||||
cur,
|
cur,
|
||||||
profile_id: int,
|
profile_id: int,
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Vorlagen: Phasen/Parallel-Streams wie im Einheiten-Editor (planLoc-Abbild)
|
||||||
|
ALTER TABLE training_plan_template_sections
|
||||||
|
ADD COLUMN IF NOT EXISTS phase_kind VARCHAR(20) NOT NULL DEFAULT 'whole_group',
|
||||||
|
ADD COLUMN IF NOT EXISTS phase_order_index INT NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN IF NOT EXISTS parallel_stream_order_index INT NULL;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN training_plan_template_sections.parallel_stream_order_index IS
|
||||||
|
'NULL = Ganzgruppen-Abschnitt; 0..n = Stream innerhalb paralleler Phase';
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- Migration 065: Wiki-spezifische Felder fuer Fähigkeiten (KarateRelevanz, RelevanzLevel)
|
||||||
|
-- SMW karatetrainer.net; Import mappt in strukturierte Spalten statt nur Freitext in description
|
||||||
|
|
||||||
|
ALTER TABLE skills
|
||||||
|
ADD COLUMN IF NOT EXISTS karate_relevance TEXT;
|
||||||
|
|
||||||
|
ALTER TABLE skills
|
||||||
|
ADD COLUMN IF NOT EXISTS relevance_level SMALLINT CHECK (relevance_level IS NULL OR relevance_level BETWEEN 1 AND 3);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN skills.karate_relevance IS 'Wiki Karate-Relevanz (Plaintext aus SMW Property KarateRelevanz)';
|
||||||
|
COMMENT ON COLUMN skills.relevance_level IS 'Wiki-RelevanzLevel 1–3 (Semantic MediaWiki)';
|
||||||
@@ -117,6 +117,8 @@ class SkillCreate(BaseModel):
|
|||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
importance: Optional[int] = Field(None, ge=1, le=5)
|
importance: Optional[int] = Field(None, ge=1, le=5)
|
||||||
keywords: Optional[List[str]] = []
|
keywords: Optional[List[str]] = []
|
||||||
|
karate_relevance: Optional[str] = None
|
||||||
|
relevance_level: Optional[int] = Field(None, ge=1, le=3)
|
||||||
|
|
||||||
class SkillResponse(BaseModel):
|
class SkillResponse(BaseModel):
|
||||||
id: int
|
id: int
|
||||||
@@ -125,6 +127,8 @@ class SkillResponse(BaseModel):
|
|||||||
description: Optional[str]
|
description: Optional[str]
|
||||||
importance: Optional[int]
|
importance: Optional[int]
|
||||||
keywords: Optional[List[str]]
|
keywords: Optional[List[str]]
|
||||||
|
karate_relevance: Optional[str] = None
|
||||||
|
relevance_level: Optional[int] = None
|
||||||
status: str
|
status: str
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
|
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
|
||||||
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
||||||
AuthZ analog training_plan_templates (_template_access / _has_planning_role).
|
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
|
||||||
"""
|
"""
|
||||||
from typing import Any, List, Optional
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
@@ -12,8 +12,10 @@ from psycopg2 import IntegrityError
|
|||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||||
from club_tenancy import (
|
from club_tenancy import (
|
||||||
|
assert_library_content_deletable,
|
||||||
|
assert_library_content_editable,
|
||||||
|
assert_library_content_governance_transition,
|
||||||
assert_valid_governance_visibility,
|
assert_valid_governance_visibility,
|
||||||
is_platform_admin,
|
|
||||||
library_content_visible_to_profile,
|
library_content_visible_to_profile,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -111,13 +113,7 @@ def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
||||||
if is_platform_admin(role):
|
assert_library_content_editable(cur, profile_id, role, row)
|
||||||
return
|
|
||||||
created_by = row.get("created_by")
|
|
||||||
if created_by is not None:
|
|
||||||
created_by = int(created_by)
|
|
||||||
if created_by != profile_id:
|
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
|
|
||||||
|
|
||||||
|
|
||||||
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||||
@@ -333,6 +329,7 @@ def update_progression_graph(
|
|||||||
)
|
)
|
||||||
|
|
||||||
gov_club = next_club if next_vis == "club" else None
|
gov_club = next_club if next_vis == "club" else None
|
||||||
|
assert_library_content_governance_transition(cur, profile_id, role, row, next_vis, gov_club)
|
||||||
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
|
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
|
||||||
|
|
||||||
fields: List[str] = []
|
fields: List[str] = []
|
||||||
@@ -376,7 +373,9 @@ def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_
|
|||||||
role = tenant.global_role
|
role = tenant.global_role
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_require_graph_write(cur, graph_id, profile_id, role)
|
row = _graph_row(cur, graph_id)
|
||||||
|
_assert_graph_readable(cur, row, profile_id, role)
|
||||||
|
assert_library_content_deletable(cur, profile_id, role, row)
|
||||||
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|||||||
@@ -30,6 +30,17 @@ CATEGORY_METHODS = os.getenv("MEDIAWIKI_CATEGORY_METHODS", "Methodenbeschrei
|
|||||||
CATEGORY_MODELS = os.getenv("MEDIAWIKI_CATEGORY_MODELS", "Reifegradmodelle")
|
CATEGORY_MODELS = os.getenv("MEDIAWIKI_CATEGORY_MODELS", "Reifegradmodelle")
|
||||||
|
|
||||||
|
|
||||||
|
def _wiki_category_or_default(category: Optional[str], import_type: str) -> str:
|
||||||
|
"""Leeres category ⇒ Standard je import_type."""
|
||||||
|
if (category or "").strip():
|
||||||
|
return category.strip()
|
||||||
|
if import_type == "skill":
|
||||||
|
return CATEGORY_SKILLS
|
||||||
|
if import_type == "method":
|
||||||
|
return CATEGORY_METHODS
|
||||||
|
return CATEGORY_EXERCISES
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# Pydantic Models #
|
# Pydantic Models #
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
@@ -59,7 +70,7 @@ def require_admin(session: dict = Depends(require_auth)) -> dict:
|
|||||||
|
|
||||||
@router.get("/import/mediawiki/preview")
|
@router.get("/import/mediawiki/preview")
|
||||||
async def preview_import(
|
async def preview_import(
|
||||||
category: str = Query(default=CATEGORY_EXERCISES),
|
category: Optional[str] = Query(default=None),
|
||||||
import_type: str = Query(default="exercise"),
|
import_type: str = Query(default="exercise"),
|
||||||
limit: int = Query(default=10, ge=1, le=500),
|
limit: int = Query(default=10, ge=1, le=500),
|
||||||
session: dict = Depends(require_admin),
|
session: dict = Depends(require_admin),
|
||||||
@@ -68,9 +79,10 @@ async def preview_import(
|
|||||||
Zeigt Vorschau: Welche Seiten würden importiert werden?
|
Zeigt Vorschau: Welche Seiten würden importiert werden?
|
||||||
Überprüft Duplikate und mapped Felder ohne zu speichern.
|
Überprüft Duplikate und mapped Felder ohne zu speichern.
|
||||||
"""
|
"""
|
||||||
|
resolved_category = _wiki_category_or_default(category, import_type)
|
||||||
client = SmwClient()
|
client = SmwClient()
|
||||||
try:
|
try:
|
||||||
members = await client.get_category_members(category, limit=limit)
|
members = await client.get_category_members(resolved_category, limit=limit)
|
||||||
except SmwClientError as e:
|
except SmwClientError as e:
|
||||||
raise HTTPException(status_code=502, detail=f"Wiki-API nicht erreichbar: {e}")
|
raise HTTPException(status_code=502, detail=f"Wiki-API nicht erreichbar: {e}")
|
||||||
|
|
||||||
@@ -129,7 +141,7 @@ async def preview_import(
|
|||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"category": category,
|
"category": resolved_category,
|
||||||
"import_type": import_type,
|
"import_type": import_type,
|
||||||
"total_found": len(members),
|
"total_found": len(members),
|
||||||
"preview": preview,
|
"preview": preview,
|
||||||
@@ -151,6 +163,7 @@ async def execute_import(
|
|||||||
Gibt sofort log_id zurück – Status via GET /import/mediawiki/status/{log_id}.
|
Gibt sofort log_id zurück – Status via GET /import/mediawiki/status/{log_id}.
|
||||||
"""
|
"""
|
||||||
profile_id = session["profile_id"]
|
profile_id = session["profile_id"]
|
||||||
|
resolved_category = _wiki_category_or_default(body.category, body.import_type)
|
||||||
|
|
||||||
# Log-Eintrag anlegen
|
# Log-Eintrag anlegen
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
@@ -160,7 +173,7 @@ async def execute_import(
|
|||||||
(import_type, import_status, category, dry_run, reimport, imported_by)
|
(import_type, import_status, category, dry_run, reimport, imported_by)
|
||||||
VALUES (%s, 'running', %s, %s, %s, %s)
|
VALUES (%s, 'running', %s, %s, %s, %s)
|
||||||
RETURNING id""",
|
RETURNING id""",
|
||||||
(body.import_type, body.category, body.dry_run, body.reimport_existing, profile_id)
|
(body.import_type, resolved_category, body.dry_run, body.reimport_existing, profile_id)
|
||||||
)
|
)
|
||||||
log_id = cur.fetchone()['id']
|
log_id = cur.fetchone()['id']
|
||||||
conn.commit()
|
conn.commit()
|
||||||
@@ -169,7 +182,7 @@ async def execute_import(
|
|||||||
background_tasks.add_task(
|
background_tasks.add_task(
|
||||||
_run_import,
|
_run_import,
|
||||||
log_id=log_id,
|
log_id=log_id,
|
||||||
category=body.category,
|
category=resolved_category,
|
||||||
import_type=body.import_type,
|
import_type=body.import_type,
|
||||||
reimport=body.reimport_existing,
|
reimport=body.reimport_existing,
|
||||||
dry_run=body.dry_run,
|
dry_run=body.dry_run,
|
||||||
@@ -615,8 +628,8 @@ def _assign_exercise_skills(cur, conn, exercise_id: int, skill_assignments: list
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
|
def _upsert_skill(mapped: dict, _reimport: bool) -> Optional[int]:
|
||||||
"""Legt Skill an oder überspringt bei Duplikat."""
|
"""Legt Skill an oder aktualisiert bestehenden Datensatz bei Namenskonflikt (Wiki-Reimport)."""
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
@@ -626,17 +639,27 @@ def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
|
|||||||
cur.execute("SELECT id FROM skill_categories WHERE name ILIKE %s", (mapped["category_name"],))
|
cur.execute("SELECT id FROM skill_categories WHERE name ILIKE %s", (mapped["category_name"],))
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if row:
|
if row:
|
||||||
category_id = row['id']
|
category_id = row["id"]
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""INSERT INTO skills (name, description, category_id)
|
"""INSERT INTO skills (name, description, category_id, karate_relevance, relevance_level)
|
||||||
VALUES (%s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
ON CONFLICT (name) DO UPDATE SET
|
ON CONFLICT (name) DO UPDATE SET
|
||||||
description = EXCLUDED.description
|
description = COALESCE(EXCLUDED.description, skills.description),
|
||||||
|
category_id = COALESCE(EXCLUDED.category_id, skills.category_id),
|
||||||
|
karate_relevance = COALESCE(EXCLUDED.karate_relevance, skills.karate_relevance),
|
||||||
|
relevance_level = COALESCE(EXCLUDED.relevance_level, skills.relevance_level),
|
||||||
|
updated_at = NOW()
|
||||||
RETURNING id""",
|
RETURNING id""",
|
||||||
(mapped["name"], mapped.get("description"), category_id)
|
(
|
||||||
|
mapped["name"],
|
||||||
|
mapped.get("description"),
|
||||||
|
category_id,
|
||||||
|
mapped.get("karate_relevance"),
|
||||||
|
mapped.get("relevance_level"),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
skill_id = cur.fetchone()['id']
|
skill_id = cur.fetchone()["id"]
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return skill_id
|
return skill_id
|
||||||
|
|
||||||
|
|||||||
@@ -181,9 +181,10 @@ def create_skill(data: dict, session=Depends(require_auth)):
|
|||||||
"""
|
"""
|
||||||
INSERT INTO skills (
|
INSERT INTO skills (
|
||||||
name, category, description, importance, keywords, status,
|
name, category, description, importance, keywords, status,
|
||||||
category_id, main_category_id, focus_areas, sort_order
|
category_id, main_category_id, focus_areas, sort_order,
|
||||||
|
karate_relevance, relevance_level
|
||||||
)
|
)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
@@ -197,6 +198,8 @@ def create_skill(data: dict, session=Depends(require_auth)):
|
|||||||
main_id,
|
main_id,
|
||||||
focus if focus is not None else "[]",
|
focus if focus is not None else "[]",
|
||||||
data.get("sort_order"),
|
data.get("sort_order"),
|
||||||
|
data.get("karate_relevance"),
|
||||||
|
data.get("relevance_level"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -232,6 +235,8 @@ def update_skill(skill_id: int, data: dict, session=Depends(require_auth)):
|
|||||||
"category_id",
|
"category_id",
|
||||||
"main_category_id",
|
"main_category_id",
|
||||||
"sort_order",
|
"sort_order",
|
||||||
|
"karate_relevance",
|
||||||
|
"relevance_level",
|
||||||
):
|
):
|
||||||
if key in data:
|
if key in data:
|
||||||
sets.append(f"{key} = %s")
|
sets.append(f"{key} = %s")
|
||||||
|
|||||||
@@ -3,13 +3,16 @@ Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere
|
|||||||
|
|
||||||
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
|
||||||
nicht über group_id oder training_unit_id am Rahmen.
|
nicht über group_id oder training_unit_id am Rahmen.
|
||||||
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
|
Lesen wie Übungen (official / private / club); Bearbeiten wie Übungen; Löschen nach Rolle (s. club_tenancy).
|
||||||
"""
|
"""
|
||||||
from typing import Any, Dict, List, Optional, Sequence
|
from typing import Any, Dict, List, Optional, Sequence
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
from club_tenancy import (
|
from club_tenancy import (
|
||||||
|
assert_library_content_deletable,
|
||||||
|
assert_library_content_editable,
|
||||||
|
assert_library_content_governance_transition,
|
||||||
assert_valid_governance_visibility,
|
assert_valid_governance_visibility,
|
||||||
is_platform_admin,
|
is_platform_admin,
|
||||||
library_content_visible_to_profile,
|
library_content_visible_to_profile,
|
||||||
@@ -21,6 +24,7 @@ from routers.training_planning import (
|
|||||||
_hydrate_training_unit_payload,
|
_hydrate_training_unit_payload,
|
||||||
_optional_positive_int,
|
_optional_positive_int,
|
||||||
_insert_sections_from_legacy_exercises,
|
_insert_sections_from_legacy_exercises,
|
||||||
|
_replace_unit_phases,
|
||||||
_replace_unit_sections,
|
_replace_unit_sections,
|
||||||
_validate_variant_for_exercise,
|
_validate_variant_for_exercise,
|
||||||
)
|
)
|
||||||
@@ -55,13 +59,6 @@ def _framework_assert_readable(
|
|||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
||||||
|
|
||||||
|
|
||||||
def _framework_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
|
||||||
if is_platform_admin(role):
|
|
||||||
return
|
|
||||||
if row.get("created_by") != profile_id:
|
|
||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
|
|
||||||
|
|
||||||
|
|
||||||
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||||
row = _fetch_framework_row(cur, framework_id)
|
row = _fetch_framework_row(cur, framework_id)
|
||||||
_framework_assert_readable(cur, row, profile_id, role)
|
_framework_assert_readable(cur, row, profile_id, role)
|
||||||
@@ -132,6 +129,7 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
row_b = cur.fetchone()
|
row_b = cur.fetchone()
|
||||||
if not row_b:
|
if not row_b:
|
||||||
s["blueprint_training_unit_id"] = None
|
s["blueprint_training_unit_id"] = None
|
||||||
|
s["phases"] = []
|
||||||
s["sections"] = []
|
s["sections"] = []
|
||||||
s["exercises"] = []
|
s["exercises"] = []
|
||||||
continue
|
continue
|
||||||
@@ -139,6 +137,7 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
|
|||||||
s["blueprint_training_unit_id"] = uid
|
s["blueprint_training_unit_id"] = uid
|
||||||
unit_min: Dict[str, Any] = {"id": uid}
|
unit_min: Dict[str, Any] = {"id": uid}
|
||||||
_hydrate_training_unit_payload(cur, unit_min)
|
_hydrate_training_unit_payload(cur, unit_min)
|
||||||
|
s["phases"] = unit_min.get("phases", [])
|
||||||
s["sections"] = unit_min.get("sections", [])
|
s["sections"] = unit_min.get("sections", [])
|
||||||
s["exercises"] = unit_min.get("exercises", [])
|
s["exercises"] = unit_min.get("exercises", [])
|
||||||
row["slots"] = slots
|
row["slots"] = slots
|
||||||
@@ -250,6 +249,7 @@ def _insert_slots_and_blueprints(
|
|||||||
framework_id: int,
|
framework_id: int,
|
||||||
slots_in: Optional[List[Any]],
|
slots_in: Optional[List[Any]],
|
||||||
profile_id: int,
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
) -> None:
|
) -> None:
|
||||||
if slots_in is None:
|
if slots_in is None:
|
||||||
return
|
return
|
||||||
@@ -296,10 +296,13 @@ def _insert_slots_and_blueprints(
|
|||||||
)
|
)
|
||||||
bid = cur.fetchone()["id"]
|
bid = cur.fetchone()["id"]
|
||||||
|
|
||||||
|
phases_in = slot.get("phases")
|
||||||
sections_in = slot.get("sections")
|
sections_in = slot.get("sections")
|
||||||
exercises_in = slot.get("exercises")
|
exercises_in = slot.get("exercises")
|
||||||
|
|
||||||
if sections_in is not None:
|
if phases_in is not None and isinstance(phases_in, list) and len(phases_in) > 0:
|
||||||
|
_replace_unit_phases(cur, bid, phases_in, profile_id, role, profile_id)
|
||||||
|
elif sections_in is not None:
|
||||||
if len(sections_in) == 0:
|
if len(sections_in) == 0:
|
||||||
_insert_default_blueprint_section(cur, bid)
|
_insert_default_blueprint_section(cur, bid)
|
||||||
else:
|
else:
|
||||||
@@ -432,7 +435,7 @@ def create_training_framework_program(
|
|||||||
)
|
)
|
||||||
fid = cur.fetchone()["id"]
|
fid = cur.fetchone()["id"]
|
||||||
_insert_goal_rows(cur, fid, goals_in)
|
_insert_goal_rows(cur, fid, goals_in)
|
||||||
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id)
|
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id, role)
|
||||||
_replace_training_types(cur, fid, tt_ids)
|
_replace_training_types(cur, fid, tt_ids)
|
||||||
_replace_target_groups(cur, fid, tg_ids)
|
_replace_target_groups(cur, fid, tg_ids)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
@@ -452,7 +455,7 @@ def update_training_framework_program(
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
row_prev = _fetch_framework_row(cur, framework_id)
|
row_prev = _fetch_framework_row(cur, framework_id)
|
||||||
_framework_assert_writable(cur, row_prev, profile_id, role)
|
assert_library_content_editable(cur, profile_id, role, row_prev)
|
||||||
|
|
||||||
merged_vis = row_prev.get("visibility") or "private"
|
merged_vis = row_prev.get("visibility") or "private"
|
||||||
merged_club = row_prev.get("club_id")
|
merged_club = row_prev.get("club_id")
|
||||||
@@ -465,7 +468,12 @@ def update_training_framework_program(
|
|||||||
merged_club = data.get("club_id")
|
merged_club = data.get("club_id")
|
||||||
if merged_club in ("", []):
|
if merged_club in ("", []):
|
||||||
merged_club = None
|
merged_club = None
|
||||||
|
if merged_vis == "club" and merged_club is None:
|
||||||
|
merged_club = tenant.effective_club_id
|
||||||
if "visibility" in data or "club_id" in data:
|
if "visibility" in data or "club_id" in data:
|
||||||
|
assert_library_content_governance_transition(
|
||||||
|
cur, profile_id, role, row_prev, merged_vis, merged_club
|
||||||
|
)
|
||||||
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
||||||
|
|
||||||
header_fields = []
|
header_fields = []
|
||||||
@@ -543,7 +551,9 @@ def update_training_framework_program(
|
|||||||
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
|
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
|
||||||
(framework_id,),
|
(framework_id,),
|
||||||
)
|
)
|
||||||
_insert_slots_and_blueprints(cur, framework_id, data.get("slots") or [], profile_id)
|
_insert_slots_and_blueprints(
|
||||||
|
cur, framework_id, data.get("slots") or [], profile_id, role
|
||||||
|
)
|
||||||
|
|
||||||
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
|
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
@@ -565,7 +575,7 @@ def delete_training_framework_program(
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
row_fw = _fetch_framework_row(cur, framework_id)
|
row_fw = _fetch_framework_row(cur, framework_id)
|
||||||
_framework_assert_writable(cur, row_fw, profile_id, role)
|
assert_library_content_deletable(cur, profile_id, role, row_fw)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"DELETE FROM training_framework_programs WHERE id = %s",
|
"DELETE FROM training_framework_programs WHERE id = %s",
|
||||||
(framework_id,),
|
(framework_id,),
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
|
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
|
||||||
|
|
||||||
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
|
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
|
||||||
Liste/Detail über `library_content_visibility_sql`; Schreiben: Ersteller oder Plattform‑Admin.
|
Liste/Detail über `library_content_visibility_sql`; Bearbeiten/Löschen wie Übungen (s. club_tenancy).
|
||||||
|
|
||||||
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
|
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
|
||||||
"""
|
"""
|
||||||
@@ -13,6 +13,9 @@ from fastapi import APIRouter, Depends, HTTPException
|
|||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||||
from club_tenancy import (
|
from club_tenancy import (
|
||||||
|
assert_library_content_deletable,
|
||||||
|
assert_library_content_editable,
|
||||||
|
assert_library_content_governance_transition,
|
||||||
assert_valid_governance_visibility,
|
assert_valid_governance_visibility,
|
||||||
is_platform_admin,
|
is_platform_admin,
|
||||||
library_content_visible_to_profile,
|
library_content_visible_to_profile,
|
||||||
@@ -47,13 +50,6 @@ def _module_assert_readable(cur, row: Dict[str, Any], profile_id: int, role: Opt
|
|||||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
|
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
|
||||||
|
|
||||||
|
|
||||||
def _module_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
|
|
||||||
if is_platform_admin(role):
|
|
||||||
return
|
|
||||||
if row.get("created_by") != profile_id:
|
|
||||||
raise HTTPException(status_code=403, detail="Nur der Ersteller darf dieses Modul ändern")
|
|
||||||
|
|
||||||
|
|
||||||
def _module_access(cur, mid: int, profile_id: int, role: str) -> Dict[str, Any]:
|
def _module_access(cur, mid: int, profile_id: int, role: str) -> Dict[str, Any]:
|
||||||
row = _fetch_training_module_row(cur, mid)
|
row = _fetch_training_module_row(cur, mid)
|
||||||
_module_assert_readable(cur, row, profile_id, role)
|
_module_assert_readable(cur, row, profile_id, role)
|
||||||
@@ -288,7 +284,7 @@ def update_training_module(
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
row_prev = _fetch_training_module_row(cur, module_id)
|
row_prev = _fetch_training_module_row(cur, module_id)
|
||||||
_module_assert_writable(cur, row_prev, profile_id, role)
|
assert_library_content_editable(cur, profile_id, role, row_prev)
|
||||||
|
|
||||||
merged_vis = row_prev.get("visibility") or "club"
|
merged_vis = row_prev.get("visibility") or "club"
|
||||||
merged_club = row_prev.get("club_id")
|
merged_club = row_prev.get("club_id")
|
||||||
@@ -303,8 +299,12 @@ def update_training_module(
|
|||||||
merged_club = data.get("club_id")
|
merged_club = data.get("club_id")
|
||||||
if merged_club in ("", []):
|
if merged_club in ("", []):
|
||||||
merged_club = None
|
merged_club = None
|
||||||
|
if merged_vis == "club" and merged_club is None:
|
||||||
|
merged_club = tenant.effective_club_id
|
||||||
if "visibility" in data or "club_id" in data:
|
if "visibility" in data or "club_id" in data:
|
||||||
|
assert_library_content_governance_transition(
|
||||||
|
cur, profile_id, role, row_prev, merged_vis, merged_club
|
||||||
|
)
|
||||||
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
|
||||||
|
|
||||||
fields: List[str] = []
|
fields: List[str] = []
|
||||||
@@ -375,7 +375,7 @@ def delete_training_module(module_id: int, tenant: TenantContext = Depends(get_t
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
row_del = _fetch_training_module_row(cur, module_id)
|
row_del = _fetch_training_module_row(cur, module_id)
|
||||||
_module_assert_writable(cur, row_del, profile_id, role)
|
assert_library_content_deletable(cur, profile_id, role, row_del)
|
||||||
cur.execute("DELETE FROM training_modules WHERE id = %s", (module_id,))
|
cur.execute("DELETE FROM training_modules WHERE id = %s", (module_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
File diff suppressed because it is too large.
Load diff
+26
-4
@@ -20,6 +20,26 @@ class SmwClientError(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_mw_category(category: str) -> str:
|
||||||
|
"""
|
||||||
|
Bereinigt Kategorienamen für API cmtitle=Kategorie:…
|
||||||
|
Erlaubt z. B. 'Fähigkeitsbeschreibung', ' Kategorie:X ', 'kategorie:X' ohne Doppel-Prefix.
|
||||||
|
"""
|
||||||
|
c = (category or "").strip()
|
||||||
|
if not c:
|
||||||
|
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
|
||||||
|
|
||||||
|
pref = "kategorie:"
|
||||||
|
while c.lower().startswith(pref):
|
||||||
|
c = c[len(pref) :].lstrip()
|
||||||
|
|
||||||
|
remaining = (c or "").strip()
|
||||||
|
if not remaining:
|
||||||
|
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
|
||||||
|
|
||||||
|
return remaining
|
||||||
|
|
||||||
|
|
||||||
class SmwClient:
|
class SmwClient:
|
||||||
"""Stateless MediaWiki/SMW API Client mit Session-Login."""
|
"""Stateless MediaWiki/SMW API Client mit Session-Login."""
|
||||||
|
|
||||||
@@ -110,12 +130,13 @@ class SmwClient:
|
|||||||
"""
|
"""
|
||||||
members = []
|
members = []
|
||||||
cmcontinue = None
|
cmcontinue = None
|
||||||
|
cat = _normalize_mw_category(category)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
params = {
|
params = {
|
||||||
"action": "query",
|
"action": "query",
|
||||||
"list": "categorymembers",
|
"list": "categorymembers",
|
||||||
"cmtitle": f"Kategorie:{category}",
|
"cmtitle": f"Kategorie:{cat}",
|
||||||
"cmlimit": min(limit, 500),
|
"cmlimit": min(limit, 500),
|
||||||
"cmtype": "page", # Nur Seiten, keine Unterkategorien
|
"cmtype": "page", # Nur Seiten, keine Unterkategorien
|
||||||
"cmprop": "ids|title",
|
"cmprop": "ids|title",
|
||||||
@@ -134,8 +155,8 @@ class SmwClient:
|
|||||||
|
|
||||||
# Rekursiv durch Unterkategorien gehen
|
# Rekursiv durch Unterkategorien gehen
|
||||||
if recursive:
|
if recursive:
|
||||||
subcats = await self._get_subcategories(category)
|
subcats = await self._get_subcategories(cat)
|
||||||
logger.info(f"Kategorie '{category}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
|
logger.info(f"Kategorie '{cat}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
|
||||||
|
|
||||||
for subcat in subcats:
|
for subcat in subcats:
|
||||||
if len(members) >= limit:
|
if len(members) >= limit:
|
||||||
@@ -150,12 +171,13 @@ class SmwClient:
|
|||||||
"""Gibt alle Unterkategorien einer Kategorie zurück."""
|
"""Gibt alle Unterkategorien einer Kategorie zurück."""
|
||||||
subcats = []
|
subcats = []
|
||||||
cmcontinue = None
|
cmcontinue = None
|
||||||
|
cat = _normalize_mw_category(category)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
params = {
|
params = {
|
||||||
"action": "query",
|
"action": "query",
|
||||||
"list": "categorymembers",
|
"list": "categorymembers",
|
||||||
"cmtitle": f"Kategorie:{category}",
|
"cmtitle": f"Kategorie:{cat}",
|
||||||
"cmlimit": 500,
|
"cmlimit": 500,
|
||||||
"cmtype": "subcat", # Nur Unterkategorien
|
"cmtype": "subcat", # Nur Unterkategorien
|
||||||
"cmprop": "ids|title",
|
"cmprop": "ids|title",
|
||||||
|
|||||||
+52
-9
@@ -63,8 +63,8 @@ EXERCISE_PROPERTY_MAP = {
|
|||||||
# Fähigkeiten (skills) – Kategorie: Fähigkeitsbeschreibung
|
# Fähigkeiten (skills) – Kategorie: Fähigkeitsbeschreibung
|
||||||
SKILL_PROPERTY_MAP = {
|
SKILL_PROPERTY_MAP = {
|
||||||
"Summary": "description",
|
"Summary": "description",
|
||||||
"KarateRelevanz": "karate_relevance", # Wird in description ergänzt
|
"KarateRelevanz": "karate_relevance", # Spalte skills.karate_relevance (+ Wiki-Import)
|
||||||
"RelevanzLevel": "relevance_level", # 1-3, nicht direkt in skills DB
|
"RelevanzLevel": "relevance_level", # Spalte skills.relevance_level 1–3
|
||||||
}
|
}
|
||||||
|
|
||||||
# Trainingsmethoden – Kategorie: Methodenbeschreibung
|
# Trainingsmethoden – Kategorie: Methodenbeschreibung
|
||||||
@@ -172,6 +172,27 @@ def map_capability_level(level_str: str) -> str:
|
|||||||
return CAPABILITY_LEVEL_MAP.get(level_str.strip(), "basis")
|
return CAPABILITY_LEVEL_MAP.get(level_str.strip(), "basis")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_wiki_relevance_level(raw: str | None) -> Optional[int]:
|
||||||
|
"""
|
||||||
|
RelevanzLevel aus Wiki (typisch 1–3). Erlaubt Zahl oder Text mit Ziffer z.B. "Level_2".
|
||||||
|
"""
|
||||||
|
if raw is None:
|
||||||
|
return None
|
||||||
|
s = str(raw).strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
digits = re.findall(r"\d+", s)
|
||||||
|
if not digits:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
n = int(digits[0])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if n < 1 or n > 3:
|
||||||
|
return None
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ #
|
# ------------------------------------------------------------------ #
|
||||||
# SMW-Property-Label → Mapper-Zielfeld (Werte wie in EXERCISE_PROPERTY_MAP) #
|
# SMW-Property-Label → Mapper-Zielfeld (Werte wie in EXERCISE_PROPERTY_MAP) #
|
||||||
# browse_subject liefert Anzeigenamen, nicht zwingend interne Property-IDs. #
|
# browse_subject liefert Anzeigenamen, nicht zwingend interne Property-IDs. #
|
||||||
@@ -184,6 +205,23 @@ def _norm_prop_synonym(name: str) -> str:
|
|||||||
return "".join(c for c in s if c.isalnum())
|
return "".join(c for c in s if c.isalnum())
|
||||||
|
|
||||||
|
|
||||||
|
# Alternative SMW-Anzeigelabel → Zielfeld (gleiche Targets wie SKILL_PROPERTY_MAP)
|
||||||
|
SKILL_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
|
||||||
|
"karaterelevanz": "karate_relevance",
|
||||||
|
"karatebezug": "karate_relevance",
|
||||||
|
"relevanzlevel": "relevance_level",
|
||||||
|
"wikirelevanz": "karate_relevance",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _skill_property_target(prop_name: str) -> str | None:
|
||||||
|
"""Ermittelt Zielfeld für eine Skill-SMW-Property."""
|
||||||
|
if prop_name in SKILL_PROPERTY_MAP:
|
||||||
|
return SKILL_PROPERTY_MAP[prop_name]
|
||||||
|
n = _norm_prop_synonym(prop_name)
|
||||||
|
return SKILL_PROPERTY_SYNONYM_TO_TARGET.get(n)
|
||||||
|
|
||||||
|
|
||||||
# alternative Labels → Zielfeld-Name (gleiche Strings wie Werte in EXERCISE_PROPERTY_MAP)
|
# alternative Labels → Zielfeld-Name (gleiche Strings wie Werte in EXERCISE_PROPERTY_MAP)
|
||||||
EXERCISE_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
|
EXERCISE_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
|
||||||
"primarycapability": "skill_names",
|
"primarycapability": "skill_names",
|
||||||
@@ -359,24 +397,29 @@ def map_wiki_to_skill(
|
|||||||
"warnings": [],
|
"warnings": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
description_parts = []
|
description_text: Optional[str] = None
|
||||||
|
|
||||||
for prop_name, values in smw_props.items():
|
for prop_name, values in smw_props.items():
|
||||||
if not values:
|
if not values:
|
||||||
continue
|
continue
|
||||||
target = SKILL_PROPERTY_MAP.get(prop_name)
|
target = _skill_property_target(prop_name)
|
||||||
if not target:
|
if not target:
|
||||||
continue
|
continue
|
||||||
first_value = values[0] if isinstance(values, list) else values
|
first_value = values[0] if isinstance(values, list) else values
|
||||||
|
|
||||||
if target == "description":
|
if target == "description":
|
||||||
description_parts.insert(0, wikitext_to_plaintext(first_value))
|
description_text = wikitext_to_plaintext(str(first_value))
|
||||||
elif target == "karate_relevance":
|
elif target == "karate_relevance":
|
||||||
rel = wikitext_to_plaintext(first_value)
|
mapped["karate_relevance"] = wikitext_to_plaintext(str(first_value))
|
||||||
description_parts.append(f"\nKarate-Relevanz: {rel}")
|
elif target == "relevance_level":
|
||||||
|
parsed = parse_wiki_relevance_level(first_value if isinstance(first_value, str) else str(first_value))
|
||||||
|
if parsed is None:
|
||||||
|
mapped["warnings"].append(f"Unbekanntes RelevanzLevel: {first_value!r}")
|
||||||
|
else:
|
||||||
|
mapped["relevance_level"] = parsed
|
||||||
|
|
||||||
if description_parts:
|
if description_text:
|
||||||
mapped["description"] = "\n".join(description_parts).strip()
|
mapped["description"] = description_text
|
||||||
|
|
||||||
return mapped
|
return mapped
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Resolver für leere/fehlende Kategorie je import_type."""
|
||||||
|
|
||||||
|
from routers.import_wiki import (
|
||||||
|
CATEGORY_EXERCISES,
|
||||||
|
CATEGORY_METHODS,
|
||||||
|
CATEGORY_SKILLS,
|
||||||
|
_wiki_category_or_default,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_wiki_category_or_default_explicit():
|
||||||
|
assert _wiki_category_or_default(" MeineKat ", "skill") == "MeineKat"
|
||||||
|
|
||||||
|
|
||||||
|
def test_wiki_category_or_default_falls_through():
|
||||||
|
assert _wiki_category_or_default(None, "exercise") == CATEGORY_EXERCISES
|
||||||
|
assert _wiki_category_or_default("", "skill") == CATEGORY_SKILLS
|
||||||
|
assert _wiki_category_or_default(" ", "method") == CATEGORY_METHODS
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from smw_client import _normalize_mw_category, SmwClientError
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_strips_optional_kategorie_prefix():
|
||||||
|
assert _normalize_mw_category("Fähigkeitsbeschreibung") == "Fähigkeitsbeschreibung"
|
||||||
|
assert _normalize_mw_category(" Kategorie:Fähigkeitsbeschreibung ") == "Fähigkeitsbeschreibung"
|
||||||
|
assert _normalize_mw_category("kategorie:test") == "test"
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_strips_duplicate_prefix_chain():
|
||||||
|
assert _normalize_mw_category("Kategorie:Kategorie:Foo") == "Foo"
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_rejects_empty():
|
||||||
|
with pytest.raises(SmwClientError, match="leer"):
|
||||||
|
_normalize_mw_category("")
|
||||||
|
with pytest.raises(SmwClientError, match="leer"):
|
||||||
|
_normalize_mw_category(" Kategorie: ")
|
||||||
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Tests: Wiki → Skill Mapping (KarateRelevanz, RelevanzLevel)."""
|
||||||
|
|
||||||
|
from smw_mapper import (
|
||||||
|
map_wiki_to_skill,
|
||||||
|
parse_wiki_relevance_level,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_wiki_relevance_level_accepted_range():
|
||||||
|
assert parse_wiki_relevance_level("1") == 1
|
||||||
|
assert parse_wiki_relevance_level("3") == 3
|
||||||
|
assert parse_wiki_relevance_level("Level_2_-_foo") == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_wiki_relevance_level_rejects():
|
||||||
|
assert parse_wiki_relevance_level("") is None
|
||||||
|
assert parse_wiki_relevance_level("4") is None
|
||||||
|
assert parse_wiki_relevance_level("0") is None
|
||||||
|
assert parse_wiki_relevance_level("text") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_map_wiki_to_skill_karate_and_level():
|
||||||
|
out = map_wiki_to_skill(
|
||||||
|
"Test_Skill",
|
||||||
|
99,
|
||||||
|
{
|
||||||
|
"Summary": ["Kurztext"],
|
||||||
|
"KarateRelevanz": ["''Wichtig'' für [[Kumite]]"],
|
||||||
|
"RelevanzLevel": ["2"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert out["name"] == "Test_Skill"
|
||||||
|
assert out["description"] == "Kurztext"
|
||||||
|
assert "Kumite" in out["karate_relevance"]
|
||||||
|
assert out["relevance_level"] == 2
|
||||||
|
assert out["warnings"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_map_wiki_to_skill_synonym_props():
|
||||||
|
out = map_wiki_to_skill("S", None, {"relevanzlevel": ["3"], "karaterelevanz": ["Nur Karate"]})
|
||||||
|
assert out["relevance_level"] == 3
|
||||||
|
assert out["karate_relevance"] == "Nur Karate"
|
||||||
|
|
||||||
|
|
||||||
|
def test_map_wiki_to_skill_invalid_level_warning():
|
||||||
|
out = map_wiki_to_skill("S", None, {"RelevanzLevel": ["9"]})
|
||||||
|
assert "relevance_level" not in out
|
||||||
|
assert len(out["warnings"]) == 1
|
||||||
|
assert "9" in out["warnings"][0]
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
"""
|
||||||
|
PostgreSQL-Integration: Rahmenprogramm-Slot mit verschachtelten `phases` (Blueprint-Unit).
|
||||||
|
|
||||||
|
Aktivierung:
|
||||||
|
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
||||||
|
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf.
|
||||||
|
|
||||||
|
Prüft `_insert_slots_and_blueprints` → `_replace_unit_phases` wie beim API-PUT mit Slot-Payload.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
from routers.training_framework_programs import _insert_slots_and_blueprints
|
||||||
|
from routers.training_planning import _fetch_phases_nested
|
||||||
|
|
||||||
|
|
||||||
|
def _integration_enabled() -> bool:
|
||||||
|
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
pytestmark = [
|
||||||
|
pytest.mark.integration,
|
||||||
|
pytest.mark.skipif(
|
||||||
|
not _integration_enabled(),
|
||||||
|
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _db_ping() -> bool:
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT 1 AS ok")
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row is not None and row.get("ok") == 1
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def db_ready():
|
||||||
|
if not _db_ping():
|
||||||
|
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_framework_blueprint_slot_phases_roundtrip(db_ready):
|
||||||
|
"""Ein Slot mit `phases` erzeugt eine Blueprint-Unit mit identischer Phasenstruktur."""
|
||||||
|
suffix = uuid.uuid4().hex[:12]
|
||||||
|
club_name = f"fw_ph_club_{suffix}"
|
||||||
|
email = f"fw_ph_{suffix}@test.local"
|
||||||
|
|
||||||
|
from auth import hash_pin
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||||
|
(club_name, "F", "active"),
|
||||||
|
)
|
||||||
|
club_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(email, hash_pin("x"), f"FWPH {suffix}", "trainer", club_id),
|
||||||
|
)
|
||||||
|
profile_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(f"Übung FWPH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||||
|
)
|
||||||
|
ex_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO training_framework_programs (
|
||||||
|
title, description,
|
||||||
|
planned_period_start, planned_period_end,
|
||||||
|
visibility, club_id, created_by,
|
||||||
|
focus_area_id, style_direction_id
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
f"Rahmen FWPH {suffix}",
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"private",
|
||||||
|
club_id,
|
||||||
|
profile_id,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
fw_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
phases_in = [
|
||||||
|
{
|
||||||
|
"phase_kind": "whole_group",
|
||||||
|
"order_index": 0,
|
||||||
|
"title": "Aufwärmen",
|
||||||
|
"sections": [
|
||||||
|
{
|
||||||
|
"title": "Gemeinsam",
|
||||||
|
"order_index": 0,
|
||||||
|
"items": [
|
||||||
|
{"item_type": "note", "order_index": 0, "note_body": "Los"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase_kind": "parallel",
|
||||||
|
"order_index": 1,
|
||||||
|
"title": "Breakout",
|
||||||
|
"streams": [
|
||||||
|
{
|
||||||
|
"order_index": 0,
|
||||||
|
"title": "Matte A",
|
||||||
|
"sections": [
|
||||||
|
{
|
||||||
|
"title": "Technik A",
|
||||||
|
"order_index": 0,
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"item_type": "exercise",
|
||||||
|
"order_index": 0,
|
||||||
|
"exercise_id": ex_id,
|
||||||
|
"planned_duration_min": 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
slots_in = [
|
||||||
|
{
|
||||||
|
"sort_order": 0,
|
||||||
|
"title": "Session 1",
|
||||||
|
"notes": None,
|
||||||
|
"phases": phases_in,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
_insert_slots_and_blueprints(cur, fw_id, slots_in, profile_id, "trainer")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM training_framework_slots
|
||||||
|
WHERE framework_program_id = %s
|
||||||
|
ORDER BY sort_order
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(fw_id,),
|
||||||
|
)
|
||||||
|
slot_row = cur.fetchone()
|
||||||
|
assert slot_row is not None
|
||||||
|
slot_id = int(slot_row["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM training_units WHERE framework_slot_id = %s",
|
||||||
|
(slot_id,),
|
||||||
|
)
|
||||||
|
bu_row = cur.fetchone()
|
||||||
|
assert bu_row is not None
|
||||||
|
blueprint_unit_id = int(bu_row["id"])
|
||||||
|
|
||||||
|
nested = _fetch_phases_nested(cur, blueprint_unit_id)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert len(nested) == 2
|
||||||
|
assert nested[0]["phase_kind"] == "whole_group"
|
||||||
|
assert len(nested[0].get("sections") or []) == 1
|
||||||
|
assert nested[1]["phase_kind"] == "parallel"
|
||||||
|
streams = nested[1].get("streams") or []
|
||||||
|
assert len(streams) == 1
|
||||||
|
assert len(streams[0].get("sections") or []) == 1
|
||||||
|
assert streams[0]["sections"][0]["title"] == "Technik A"
|
||||||
|
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
|
||||||
|
finally:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM training_framework_programs WHERE id = %s", (fw_id,))
|
||||||
|
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||||
|
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||||
|
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
conn.commit()
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
PostgreSQL-Integration: Roundtrip _replace_unit_sections ↔ _fetch_sections.
|
PostgreSQL-Integration: Roundtrip _replace_unit_sections / _replace_unit_phases ↔ Fetch-Helfer.
|
||||||
|
|
||||||
Aktivierung:
|
Aktivierung:
|
||||||
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
- Lokal: TRAINING_PLANNING_INTEGRATION=1
|
||||||
@@ -15,7 +15,12 @@ import uuid
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from db import get_db, get_cursor
|
from db import get_db, get_cursor
|
||||||
from routers.training_planning import _fetch_sections, _replace_unit_sections
|
from routers.training_planning import (
|
||||||
|
_fetch_phases_nested,
|
||||||
|
_fetch_sections,
|
||||||
|
_replace_unit_phases,
|
||||||
|
_replace_unit_sections,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _integration_enabled() -> bool:
|
def _integration_enabled() -> bool:
|
||||||
@@ -157,3 +162,129 @@ def test_replace_sections_roundtrip(db_ready):
|
|||||||
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||||
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def test_replace_phases_roundtrip_parallel_stream(db_ready):
|
||||||
|
"""Phasen inkl. parallel-Stream-Sektionen ersetzen und wieder laden."""
|
||||||
|
suffix = uuid.uuid4().hex[:12]
|
||||||
|
club_name = f"ph_it_club_{suffix}"
|
||||||
|
email = f"ph_it_{suffix}@test.local"
|
||||||
|
|
||||||
|
from auth import hash_pin
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
|
||||||
|
(club_name, "P", "active"),
|
||||||
|
)
|
||||||
|
club_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(email, hash_pin("x"), f"PH {suffix}", "trainer", club_id),
|
||||||
|
)
|
||||||
|
profile_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO training_groups (club_id, name, trainer_id, status)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(club_id, f"Gruppe PH {suffix}", profile_id, "active"),
|
||||||
|
)
|
||||||
|
group_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(f"Übung PH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
|
||||||
|
)
|
||||||
|
ex_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO training_units (
|
||||||
|
group_id, planned_date, status, created_by
|
||||||
|
) VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(group_id, "2026-06-02", "planned", profile_id),
|
||||||
|
)
|
||||||
|
unit_id = int(cur.fetchone()["id"])
|
||||||
|
|
||||||
|
phases_in = [
|
||||||
|
{
|
||||||
|
"phase_kind": "whole_group",
|
||||||
|
"order_index": 0,
|
||||||
|
"title": "Aufwärmen",
|
||||||
|
"sections": [
|
||||||
|
{
|
||||||
|
"title": "Gemeinsam",
|
||||||
|
"order_index": 0,
|
||||||
|
"items": [
|
||||||
|
{"item_type": "note", "order_index": 0, "note_body": "Los"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"phase_kind": "parallel",
|
||||||
|
"order_index": 1,
|
||||||
|
"title": "Breakout",
|
||||||
|
"streams": [
|
||||||
|
{
|
||||||
|
"order_index": 0,
|
||||||
|
"title": "Matte A",
|
||||||
|
"sections": [
|
||||||
|
{
|
||||||
|
"title": "Technik A",
|
||||||
|
"order_index": 0,
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"item_type": "exercise",
|
||||||
|
"order_index": 0,
|
||||||
|
"exercise_id": ex_id,
|
||||||
|
"planned_duration_min": 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
_replace_unit_phases(cur, unit_id, phases_in, profile_id, "trainer", profile_id)
|
||||||
|
nested = _fetch_phases_nested(cur, unit_id)
|
||||||
|
flat_sec = _fetch_sections(cur, unit_id)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert len(nested) == 2
|
||||||
|
assert nested[0]["phase_kind"] == "whole_group"
|
||||||
|
assert len(nested[0].get("sections") or []) == 1
|
||||||
|
assert nested[1]["phase_kind"] == "parallel"
|
||||||
|
streams = nested[1].get("streams") or []
|
||||||
|
assert len(streams) == 1
|
||||||
|
assert len(streams[0].get("sections") or []) == 1
|
||||||
|
assert streams[0]["sections"][0]["title"] == "Technik A"
|
||||||
|
assert len(streams[0]["sections"][0].get("items") or []) == 1
|
||||||
|
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
|
||||||
|
assert len(flat_sec) == 2
|
||||||
|
finally:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
|
||||||
|
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
|
||||||
|
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||||
|
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
|
||||||
|
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
|
||||||
|
conn.commit()
|
||||||
+97
-8
@@ -1,8 +1,8 @@
|
|||||||
# Shinkan Jinkendo Version Information
|
# Shinkan Jinkendo Version Information
|
||||||
|
|
||||||
APP_VERSION = "0.8.137"
|
APP_VERSION = "0.8.149"
|
||||||
BUILD_DATE = "2026-05-12"
|
BUILD_DATE = "2026-05-19"
|
||||||
DB_SCHEMA_VERSION = "20260515063"
|
DB_SCHEMA_VERSION = "20260516065"
|
||||||
|
|
||||||
MODULE_VERSIONS = {
|
MODULE_VERSIONS = {
|
||||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||||
@@ -19,15 +19,15 @@ MODULE_VERSIONS = {
|
|||||||
"media_legal_hold": "1.0.0", # P-11: Sofortsperre-Services (set_legal_hold, release_legal_hold)
|
"media_legal_hold": "1.0.0", # P-11: Sofortsperre-Services (set_legal_hold, release_legal_hold)
|
||||||
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
"media_lifecycle": "1.1.0", # P-11: Retention-Job ueberspringt Legal-Hold-Assets
|
||||||
"groups": "0.1.0",
|
"groups": "0.1.0",
|
||||||
"skills": "0.1.0",
|
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||||
"methods": "0.1.0",
|
"methods": "0.1.0",
|
||||||
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
"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",
|
"training_programs": "0.1.0",
|
||||||
"planning": "0.10.0", # Migration 063: training_unit_phases + parallel_streams; Sektionen phase_id|parallel_stream_id; GET phases + sections
|
"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)
|
"dashboard": "1.1.0", # GET /api/dashboard/kpis inkl. training_home (ein Client-Roundtrip für KPIs + nächste Termine)
|
||||||
"training_modules": "1.0.0",
|
"training_modules": "1.1.0", # PUT/DELETE: assert_library_content_* (Vereinsadmin löscht Vereins-Inhalt, Trainer bearbeitet club wie Übungen)
|
||||||
"import_wiki": "1.0.0",
|
"import_wiki": "1.0.3", # Default-Kategorie Fähigkeiten: Fähigkeitsbeschreibung; cmtitle-Normalisierung; UI Preview/Execute Defaults je Typ
|
||||||
"admin": "1.0.0",
|
"admin": "1.0.0",
|
||||||
"membership": "1.0.0",
|
"membership": "1.0.0",
|
||||||
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
|
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
|
||||||
@@ -36,6 +36,95 @@ MODULE_VERSIONS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
CHANGELOG = [
|
CHANGELOG = [
|
||||||
|
{
|
||||||
|
"version": "0.8.149",
|
||||||
|
"date": "2026-05-19",
|
||||||
|
"changes": [
|
||||||
|
"Trainingsplanung: Einheiten-Editor als Vollseite (/planning/units/new|/:id/edit); Hub ohne Modal; Legacy ?unit= Redirect",
|
||||||
|
"Drift-Schutz: planningUnitRoutes.js, trainingUnitEditorCore.js, Vitest; Playwright 14–15",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.148",
|
||||||
|
"date": "2026-05-19",
|
||||||
|
"changes": [
|
||||||
|
"Planung Vorlagen: Strukturvorschau (Split-Sessions), Kurzbeschreibung, Bearbeitungsseite; Liste liefert sections[] mit",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.147",
|
||||||
|
"date": "2026-05-19",
|
||||||
|
"changes": [
|
||||||
|
"Planung: Liste – Rahmen-Session & Übungen→Modul; Dialog Modul aus Einheit; klarere Rahmen-Unit-ID aus Liste",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.146",
|
||||||
|
"date": "2026-05-19",
|
||||||
|
"changes": [
|
||||||
|
"Planung: Trainingseinheit → Rahmenprogramm (Session-Slot) speichern; API POST /api/training-units/{id}/publish-to-framework",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.145",
|
||||||
|
"date": "2026-05-16",
|
||||||
|
"changes": [
|
||||||
|
"Wiki-Import: Standard-Kategorie Fähigkeiten korrigiert auf „Fähigkeitsbeschreibung“ (korrekter Wiki-Name).",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.144",
|
||||||
|
"date": "2026-05-16",
|
||||||
|
"changes": [
|
||||||
|
"Wiki-Import: Default-Kategorie Fähigkeiten; SMW-Client entfernt versehentliches „Kategorie:“-Prefix; Vorschau/Ausführung nutzen Default-Kategorie je import_type wenn leer.",
|
||||||
|
"Admin UI Wiki-Import: Wechsel Import-Typ setzt passende Standard-Kategorie.",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.143",
|
||||||
|
"date": "2026-05-16",
|
||||||
|
"changes": [
|
||||||
|
"DB 065: skills.karate_relevance + skills.relevance_level (Wiki KarateRelevanz / RelevanzLevel 1–3); smw_mapper + Wiki-Import upsert.",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.142",
|
||||||
|
"date": "2026-05-16",
|
||||||
|
"changes": [
|
||||||
|
"Bibliothek Planung: Bearbeiten/Löschen von Vorlagen, Rahmenprogrammen, Trainingsmodulen, Progressionsgraphen nach RBAC wie Übungen (club_tenancy.assert_library_content_* + Governance-Übergänge)",
|
||||||
|
"Planungs-UI: Sichtbarkeit/Verein beim Speichern neuer Trainingsvorlage",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.141",
|
||||||
|
"date": "2026-05-14",
|
||||||
|
"changes": [
|
||||||
|
"DB 064: Vorlagen-Sektionen mit phase_kind / phase_order_index / parallel_stream_order_index; Speichern und Anwenden behält Split-Sessions; Server: Vorlage → Einheit über Phasen-Replace.",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.140",
|
||||||
|
"date": "2026-05-14",
|
||||||
|
"changes": [
|
||||||
|
"Frontend Trainingsplanung: Breakout-Panel (neue Ganzgruppen-/parallele Phase, Stream in letzter parallelen Phase); pro Abschnitt Zuordnung zu Phase/Stream oder klassischer Ein-Ganzgruppen-Ablauf.",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.139",
|
||||||
|
"date": "2026-05-14",
|
||||||
|
"changes": [
|
||||||
|
"Frontend Trainingsplanung: GET phases → Editor mit planLoc pro Abschnitt; Speichern sendet PUT phases bei Breakout-Einheiten (sonst weiter sections); Modul-Dialog zeigt Phase/Stream in der Abschnittsauswahl.",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.8.138",
|
||||||
|
"date": "2026-05-14",
|
||||||
|
"changes": [
|
||||||
|
"Planung Paket 2: POST/PUT training_units mit phases (voller Phasen-/Stream-Plan); höchstens eines von phases, sections, exercises pro Request; Rahmen-Blueprint→Termin kopiert verschachtelten Plan; apply-training-module optional phase_order_index + parallel_stream_order_index.",
|
||||||
|
"Fix: POST from-framework-slot übergibt role an _copy_blueprint_into_scheduled_unit (Stream-Trainer-Validierung).",
|
||||||
|
"Integrationstest test_replace_phases_roundtrip_parallel_stream.",
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "0.8.137",
|
"version": "0.8.137",
|
||||||
"date": "2026-05-14",
|
"date": "2026-05-14",
|
||||||
|
|||||||
@@ -75,10 +75,12 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
|||||||
### 4.4 Trainingsplanung
|
### 4.4 Trainingsplanung
|
||||||
|
|
||||||
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
|
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
|
||||||
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden.
|
- **Phasen & parallele Streams (Breakout):** Eine Einheit kann aus abwechselnden **Ganzgruppenphasen** und **Parallelphasen** bestehen; in einer Parallelphase führen **mehrere Streams** (Teilstrecken) je eigene Abschnitte/Übungen. Planung über Breakout-UI; API liefert **`phases`** und flache **`sections`** (Migration **063**, siehe **`docs/HANDOVER.md`**). Technische Details: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||||
|
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden (Phasen in Vorlagen: Ausbau siehe Handover „offen“).
|
||||||
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
|
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
|
||||||
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
|
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
|
||||||
- **Durchführung:** Ansicht zum Abarbeiten einer Einheit; **Coaching-Modus** als separater Erlebnispfad (generischer Zeit-Block pro Platzierung); bei **Kombinationsübungen** zusätzliche **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** siehe Kombination-Fachspez **Anhang A** (implementierter Umfang vs. nächste Stufen).
|
- **Durchführung („Plan & Ablauf“):** Ablauf anhand Phasen/Streams darstellen und abarbeiten (inkl. Split-Logik in der Anzeige).
|
||||||
|
- **Coaching-Modus:** eigener Ablauf mit Schritt-für-Schritt-Timeline, Stream-Wahl pro Parallelphase, Hinweis **„Parallelphase · Abschluss“** (Gruppen zusammenführen) vor der nächsten Ganzgruppenphase oder vor dem nächsten Split; **Nachbereitung** mit Ist-Minuten und Speichern wie in der Planung (inkl. **`phases`**). Nach erfolgreichem Speichern Wechsel zur **Plan- und Ablaufsicht** derselben Einheit. Bei **Kombinationsübungen** zusätzlich **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** (Fachspez **Anhang A**; Ausbauschritte B/C).
|
||||||
|
|
||||||
### 4.5 Medienbibliothek und Archiv
|
### 4.5 Medienbibliothek und Archiv
|
||||||
|
|
||||||
@@ -118,7 +120,8 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
|
|||||||
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
|
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
|
||||||
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
|
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
|
||||||
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
|
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
|
||||||
- **Coach / Kombination:** nächste Stufen **Zeitleisten-Splitting** und **Archetyp-Timer** (Fachspez § 10.4 Stufe B/C; Umsetzungsplan Phase 4b–d); **geführtes Erfassen** von `method_profile` im Übungseditor.
|
- **Coach / Kombination:** Kombi-spezifische **Archetyp-Stufen B/C** (Zeitleisten-Splitting, archetypnahe Timer — Fachspez § 10.4); **geführtes Erfassen** von `method_profile` im Übungseditor.
|
||||||
|
- **Breakout:** vollständige **Server-Spiegelung** neuer Abschnitte in **`phases`**; **Vorlagen** phasengleich mit Kalendereinheit; optional **Stream-Tabs** in der Durchführungsansicht laut technischer Spec — siehe **`docs/HANDOVER.md`** (Arbeitspaket „Coaching & Breakout“).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -126,5 +129,6 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
|
|||||||
|
|
||||||
| Datum | Änderung |
|
| Datum | Änderung |
|
||||||
|-------|----------|
|
|-------|----------|
|
||||||
|
| 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 | 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`. |
|
| 2026-05-12 | Kombinationsübungen + Coaching Stufe A; Verweise auf Fachspezifikation (`…Kombinationsuebungen…` V3 Anhang A) und `TRAINING_MODULES_IMPLEMENTATION_PLAN.md`. |
|
||||||
+49
-15
@@ -1,7 +1,7 @@
|
|||||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||||
|
|
||||||
**Stand:** 2026-05-13
|
**Stand:** 2026-05-19
|
||||||
**App-Version / DB-Schema:** App **0.8.120**, DB-Schema **`20260514062`** (`backend/version.py`: `APP_VERSION`, `DB_SCHEMA_VERSION`)
|
**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**.
|
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**.
|
||||||
|
|
||||||
@@ -76,7 +76,39 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
|||||||
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
|
- **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`.
|
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
|
||||||
|
|
||||||
### Trainingsmodule, Kombinationsübungen und Coach (Stand **0.8.120**)
|
### Trainingsplanung: Einheiten-Editor als Vollseite (Stand **0.8.149**)
|
||||||
|
|
||||||
|
- **Routen:** `/planning` (Hub), `/planning/units/new`, `/planning/units/:id/edit`; Legacy `/planning?unit={id}` → Redirect auf Edit-Route.
|
||||||
|
- **Code:** `TrainingUnitEditPage.jsx`, `TrainingUnitFormShell.jsx`, `planningUnitRoutes.js`, `trainingUnitEditorCore.js` (Payload-Drift-Schutz + Vitest).
|
||||||
|
- **Hub:** `TrainingPlanningPageRoot.jsx` ohne Einheiten-Modal; Modals nur noch Import, Trainer zuweisen, Rahmen-Session/Modul aus Liste.
|
||||||
|
- **Spec / DoD:** `docs/architecture/TRAINING_UNIT_EDIT_PAGE_MIGRATION.md`; Playwright **14–15** (Edit-Route, Legacy-Redirect).
|
||||||
|
|
||||||
|
### Trainingsplan: Phasen, parallele Streams und Coaching (Stand **0.8.137–0.8.140**)
|
||||||
|
|
||||||
|
- **Schema / API:** Migration **063** — `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` bzw. `parallel_stream_id`. **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und weiterhin flache **`sections`**. **`PUT/POST`** mit **`phases`** für Breakout-Einheiten (vgl. `CHANGELOG` **0.8.138**); Legacy: flache `sections` → implizite Ganzgruppen-Phase.
|
||||||
|
- **Planung (Frontend):** Breakout-Panel — neue Ganzgruppen-/parallele Phase, Streams in der Parallelphase; Speichern sendet `phases` bei phasierten Einheiten (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`).
|
||||||
|
- **Durchführung „Plan & Ablauf“:** `TrainingUnitRunPage.jsx` nutzt **`sectionsWithPlanLocForDisplay`** / **`buildPlanRunViewModelFromSections`** aus **`frontend/src/utils/trainingPlanUtils.js`**, damit Anzeige mit Phasen/Streams konsistent ist (inkl. Normalisierung fehlender `planLoc` auf flachen Sektionen).
|
||||||
|
- **Coaching-Modus (`TrainingCoachPage.jsx`):**
|
||||||
|
- Flache Timeline aus Phasen (`flattenPlanTimeline`): **Split-Punkte** (`branch_gate`) bis Stream-Wahl, eine gewählte Spur pro Parallelphase, **Outline**, Timer, Ist-Minuten pro Item.
|
||||||
|
- **Rejoin nach Parallelphase:** Beim Übergang **Parallel → Ganzgruppe** (oder **Parallel → nächster Split** / `branch_gate`) erscheint die Karte „Parallelphase · Abschluss“ mit **„Gruppen zusammengeführt — weiter mit dem Plan“**, solange noch Einträge folgen; am Planende weiter **„Zur Nachbereitung“** (`coachShouldPromptSplitRejoinTransition` in `trainingPlanUtils.js`).
|
||||||
|
- **Nachbereitung / Speichern:** Payload über **`buildCoachSavePlanPayload`** (wie Planungseditor: **`phases`**, keine Zerstörung phasierter Struktur). Nach erfolgreichem Speichern: Coach-Session-Storage bereinigt, **`navigate('/planning/run/:unitId', { replace: true })`** (Plan & Ablauf).
|
||||||
|
- **Robustheit:** Abschnitte ohne Eintrag im `phases`-Baum, die nach Erben fälschlich **`parallel`** wären, werden für die **Anzeige** als **Ganzgruppenblock** nach der letzten bekannten Phasen-Ordnung ausgewiesen (`sectionsWithPlanLocForDisplay`).
|
||||||
|
- **Konzept / technische Spec:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
|
||||||
|
|
||||||
|
#### Arbeitspaket „Coaching & Breakout“ — noch offen
|
||||||
|
|
||||||
|
| # | Thema | Kurzbeschreibung |
|
||||||
|
|---|--------|------------------|
|
||||||
|
| 1 | **Backend / Datenkonsistenz** | Neue oder verschobene Sektionen konsistent in **`phases`** persistieren (nicht nur Client-Normalisierung). |
|
||||||
|
| 2 | **UX nach Speichern** | Optional: **im Coach bleiben** vs. **Planansicht** (aktuell: immer Plan & Ablauf). |
|
||||||
|
| 3 | **Kantenfälle Coach** | „Fertig“ bei abweichendem **Timer-Owner** vs. **Rejoin**/letzter Schritt prüfen. |
|
||||||
|
| 4 | **Tests** | Smoke: zwei Splitphasen, Ganzgruppe dazwischen/am Ende, Nachbereitung speichern, Rejoin. |
|
||||||
|
| 5 | **Run-UI vs. Spec** | Technische Spec §5.2 (Tabs pro Stream): Abgleich mit **`TrainingUnitRunPage`**. |
|
||||||
|
| 6 | **Trainer pro Stream** | UI und Policy zu **`assigned_trainer_profile_ids`** / Kopf-Co-Trainer offen. |
|
||||||
|
| 7 | **Vorlagen** | `training_plan_templates` phasen-/stream-kompatibel (Spec §5.3). |
|
||||||
|
| 8 | **Kombi-Coach B/C** | Fachspez **§ 10.4 / § 10.6**, `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` Phase **4**. |
|
||||||
|
|
||||||
|
### Trainingsmodule, Kombinationsübungen und Coach Stufe A
|
||||||
|
|
||||||
- **Fachspez & Drift-Schutz:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (**§ 10.2.1** IDs, **§ 10.4** Coaching-Stufen, **§ 10.6** Produkt-Backlog, **Anhang A** Abgleich).
|
- **Fachspez & Drift-Schutz:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (**§ 10.2.1** IDs, **§ 10.4** Coaching-Stufen, **§ 10.6** Produkt-Backlog, **Anhang A** Abgleich).
|
||||||
- **Umsetzungsplan:** `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase **2** / **4** teilweise; Pakete **4a–g** — u. a. **4e** Archetyp-Admin, **4f** Massen-Vorbelegung, **4g** Backend-Validierung).
|
- **Umsetzungsplan:** `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase **2** / **4** teilweise; Pakete **4a–g** — u. a. **4e** Archetyp-Admin, **4f** Massen-Vorbelegung, **4g** Backend-Validierung).
|
||||||
@@ -155,17 +187,18 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
|||||||
|
|
||||||
## 7. Nächste Session — sinnvolle Arbeitspakete
|
## 7. Nächste Session — sinnvolle Arbeitspakete
|
||||||
|
|
||||||
1. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
|
||||||
2. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
||||||
3. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||||
4. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||||
5. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||||
6. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||||
7. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||||
8. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||||
9. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||||
10. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||||
11. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||||
|
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -174,7 +207,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
|||||||
| Bereich | Einstieg |
|
| Bereich | Einstieg |
|
||||||
|---------|----------|
|
|---------|----------|
|
||||||
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
|
||||||
| Coach-Kombination / Merge-Profil (Frontend) | `TrainingCoachPage.jsx`, `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
|
| Coach, Plan-Timeline, PUT-Payload phasiert | `TrainingCoachPage.jsx`, **`frontend/src/utils/trainingPlanUtils.js`** (`flattenPlanTimeline`, `buildCoachSavePlanPayload`, `sectionsWithPlanLocForDisplay`, Split-Rejoin-Helfer), `TrainingUnitRunPage.jsx` |
|
||||||
|
| Coach-Kombination / Merge-Profil (Frontend) | `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
|
||||||
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
|
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
|
||||||
| Frontend API | `frontend/src/utils/api.js` |
|
| Frontend API | `frontend/src/utils/api.js` |
|
||||||
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
|
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
- **Offen Phase 1:** Inbox optional **TTL** / nur bei sichtbarem Widget.
|
- **Offen Phase 1:** Inbox optional **TTL** / nur bei sichtbarem Widget.
|
||||||
- **Phase 3 (abgeschlossen 2026-05-14):** Übungsliste modularisiert; Trainingsplanung/Übungsformular: **Page-Dateien unter Soft-Limit** — Implementierung in `TrainingPlanningPageRoot.jsx`, `ExerciseFormPageRoot.jsx`, `ExercisesListPageRoot.jsx`; `pages/*.jsx` nur Re-Export. Playwright **Tests 9–10**.
|
- **Phase 3 (abgeschlossen 2026-05-14):** Übungsliste modularisiert; Trainingsplanung/Übungsformular: **Page-Dateien unter Soft-Limit** — Implementierung in `TrainingPlanningPageRoot.jsx`, `ExerciseFormPageRoot.jsx`, `ExercisesListPageRoot.jsx`; `pages/*.jsx` nur Re-Export. Playwright **Tests 9–10**.
|
||||||
- **Phase 4 (fortlaufend 2026-05-14):** API **Welle 1** `client.js`; **Welle 2** `planning.js`; **Welle 3** `exercises.js`; `utils/api.js` bleibt Facade (`export *`, `api`-Objekt `...exercises`, `...planning`).
|
- **Phase 4 (fortlaufend 2026-05-14):** API **Welle 1** `client.js`; **Welle 2** `planning.js`; **Welle 3** `exercises.js`; `utils/api.js` bleibt Facade (`export *`, `api`-Objekt `...exercises`, `...planning`).
|
||||||
|
- **Trainingsplan Breakout / Coach (2026-05-14):** Phasen + parallele Streams (**063**, Frontend **0.8.137–0.8.140**), Coach-Rejoin und Nachbereitung — siehe **`docs/HANDOVER.md`**, **`technical/PARALLEL_TRAINING_STREAMS_SPEC.md`**.
|
||||||
|
|
||||||
**Ziel:** Nach MVP eine **nachhaltige** Architektur für Wachstum, **Performance** (Server + schwache Clients) und **sichere Feature-Erweiterung**.
|
**Ziel:** Nach MVP eine **nachhaltige** Architektur für Wachstum, **Performance** (Server + schwache Clients) und **sichere Feature-Erweiterung**.
|
||||||
**Leitdokumente:** [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md), [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md), [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md).
|
**Leitdokumente:** [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md), [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md), [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md).
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite --port 3098",
|
"dev": "vite --port 3098",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-virtual": "^3.13.24",
|
"@tanstack/react-virtual": "^3.13.24",
|
||||||
@@ -20,6 +22,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@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,
|
Outlet,
|
||||||
} from 'react-router-dom'
|
} from 'react-router-dom'
|
||||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||||
|
import { FormEditorActionsProvider, FormEditorBottomSlot } from './context/FormEditorActionsContext'
|
||||||
import { ToastProvider } from './context/ToastContext'
|
import { ToastProvider } from './context/ToastContext'
|
||||||
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
|
||||||
import DesktopSidebar from './components/DesktopSidebar'
|
import DesktopSidebar from './components/DesktopSidebar'
|
||||||
@@ -30,6 +31,9 @@ const ClubsPage = lazy(() => import('./pages/ClubsPage'))
|
|||||||
const InboxPage = lazy(() => import('./pages/InboxPage'))
|
const InboxPage = lazy(() => import('./pages/InboxPage'))
|
||||||
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
|
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
|
||||||
const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
|
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(() =>
|
const TrainingFrameworkProgramsListPage = lazy(() =>
|
||||||
import('./pages/TrainingFrameworkProgramsListPage'),
|
import('./pages/TrainingFrameworkProgramsListPage'),
|
||||||
)
|
)
|
||||||
@@ -39,6 +43,7 @@ const TrainingFrameworkProgramEditPage = lazy(() =>
|
|||||||
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
|
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
|
||||||
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
|
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
|
||||||
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
|
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
|
||||||
|
const TrainingUnitEditPage = lazy(() => import('./pages/TrainingUnitEditPage'))
|
||||||
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
|
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
|
||||||
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
|
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
|
||||||
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
|
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
|
||||||
@@ -141,22 +146,26 @@ function ProtectedLayout() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<OrgInboxProvider user={user}>
|
<OrgInboxProvider user={user}>
|
||||||
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
<FormEditorActionsProvider>
|
||||||
<div className="app-shell">
|
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
|
||||||
<div className="app-shell__column">
|
<div className="app-shell">
|
||||||
<div className="app-header app-header--mobile app-header--mobile-stack">
|
<div className="app-shell__column">
|
||||||
<div className="app-header-mobile__top">
|
<div className="app-header app-header--mobile app-header--mobile-stack">
|
||||||
<div className="app-logo">🥋 Shinkan</div>
|
<div className="app-header-mobile__top">
|
||||||
|
<div className="app-logo">🥋 Shinkan</div>
|
||||||
|
</div>
|
||||||
|
<ActiveClubSwitcher variant="mobile" />
|
||||||
</div>
|
</div>
|
||||||
<ActiveClubSwitcher variant="mobile" />
|
<div className="app-main">
|
||||||
|
<InactiveMembershipBanner />
|
||||||
|
<Outlet />
|
||||||
|
</div>
|
||||||
|
<FormEditorBottomSlot>
|
||||||
|
<Nav showAdminNav={showAdminNav} />
|
||||||
|
</FormEditorBottomSlot>
|
||||||
</div>
|
</div>
|
||||||
<div className="app-main">
|
|
||||||
<InactiveMembershipBanner />
|
|
||||||
<Outlet />
|
|
||||||
</div>
|
|
||||||
<Nav showAdminNav={showAdminNav} />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</FormEditorActionsProvider>
|
||||||
</OrgInboxProvider>
|
</OrgInboxProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -223,15 +232,25 @@ const appRouter = createBrowserRouter([
|
|||||||
{ path: 'clubs', element: <ClubsPage /> },
|
{ path: 'clubs', element: <ClubsPage /> },
|
||||||
{ path: 'inbox', element: <InboxPage /> },
|
{ path: 'inbox', element: <InboxPage /> },
|
||||||
{ path: 'skills', element: <SkillsPage /> },
|
{ 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/new', element: <TrainingFrameworkProgramEditPage /> },
|
||||||
{ path: 'planning/framework-programs/:id', 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/new', element: <TrainingModuleEditPage /> },
|
||||||
{ path: 'planning/training-modules/:id', 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/coach', element: <TrainingCoachPage /> },
|
||||||
{ path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
|
{ path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
|
||||||
{ path: 'planning', element: <TrainingPlanningPage /> },
|
|
||||||
{ path: 'admin', element: <AdminHomeRedirect /> },
|
{ path: 'admin', element: <AdminHomeRedirect /> },
|
||||||
{
|
{
|
||||||
path: 'admin/users',
|
path: 'admin/users',
|
||||||
|
|||||||
@@ -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() {
|
export async function listTrainingFrameworkPrograms() {
|
||||||
return request('/api/training-framework-programs')
|
return request('/api/training-framework-programs')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1155,6 +1155,359 @@ a.analysis-split__nav-item {
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Planung: gemeinsame Chip-Navigation + Inhalt */
|
||||||
|
.planning-layout__main {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.planning-route-nav {
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Formular-Aktionsleiste (sticky, schmal, touch-freundlich) */
|
||||||
|
.form-action-bar {
|
||||||
|
flex-shrink: 0;
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
z-index: 12;
|
||||||
|
background: var(--surface);
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding: 8px clamp(10px, 2.5vw, 14px);
|
||||||
|
padding-bottom: max(8px, env(safe-area-inset-bottom, 0px));
|
||||||
|
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.06);
|
||||||
|
}
|
||||||
|
.form-action-bar--top {
|
||||||
|
border-top: none;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||||
|
}
|
||||||
|
.form-action-bar--modal {
|
||||||
|
margin-top: auto;
|
||||||
|
}
|
||||||
|
.form-action-bar__inner {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: stretch;
|
||||||
|
justify-content: flex-start;
|
||||||
|
gap: 8px;
|
||||||
|
max-width: min(1100px, 100%);
|
||||||
|
margin: 0 auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.form-action-bar__primary-group {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: stretch;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
margin-left: auto;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
.form-action-bar__btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 8px 14px;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.form-action-bar__btn--cancel {
|
||||||
|
min-width: 5.5rem;
|
||||||
|
}
|
||||||
|
.form-action-bar__icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.form-action-bar__text--short {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.form-action-bar__saving {
|
||||||
|
font-size: 0.82rem;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form-Modale: Overlay + Panel (Desktop zentriert, Mobile Vollbild) */
|
||||||
|
html.modal-scroll-locked {
|
||||||
|
overflow: hidden;
|
||||||
|
overscroll-behavior: none;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
html.modal-scroll-locked body {
|
||||||
|
overflow: hidden !important;
|
||||||
|
overscroll-behavior: none;
|
||||||
|
}
|
||||||
|
html.modal-scroll-locked .app-shell,
|
||||||
|
html.modal-scroll-locked .app-shell__column {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
html.modal-scroll-locked .app-main {
|
||||||
|
overflow: hidden !important;
|
||||||
|
overscroll-behavior: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-overlay--form {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1000;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 1rem;
|
||||||
|
overflow: hidden;
|
||||||
|
overscroll-behavior: none;
|
||||||
|
touch-action: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100vw;
|
||||||
|
}
|
||||||
|
.modal-overlay--form.modal-overlay--raised {
|
||||||
|
z-index: 1100;
|
||||||
|
}
|
||||||
|
.modal-overlay__focus-catcher {
|
||||||
|
position: absolute;
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.modal-panel--form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--surface);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: clamp(12px, 3vw, 2rem);
|
||||||
|
width: 100%;
|
||||||
|
max-width: min(1100px, 100%);
|
||||||
|
max-height: min(92vh, 100dvh);
|
||||||
|
overflow: hidden;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
touch-action: manipulation;
|
||||||
|
flex: 0 1 auto;
|
||||||
|
margin: auto;
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
.modal-panel--form.modal-panel--narrow {
|
||||||
|
max-width: min(560px, 100%);
|
||||||
|
}
|
||||||
|
.modal-panel--form.card {
|
||||||
|
/* card-Klasse nur für Desktop-Rahmen; Mobile überschreibt unten */
|
||||||
|
}
|
||||||
|
.modal-panel__title {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: clamp(1.05rem, 4vw, 1.25rem);
|
||||||
|
line-height: 1.25;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.modal-panel__intro {
|
||||||
|
font-size: 0.88rem;
|
||||||
|
color: var(--text2);
|
||||||
|
line-height: 1.45;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.modal-form-shell {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.modal-form-shell__body {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-x: hidden;
|
||||||
|
overflow-y: auto;
|
||||||
|
overscroll-behavior: contain;
|
||||||
|
overscroll-behavior-x: none;
|
||||||
|
touch-action: pan-y;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
.modal-panel--form > *,
|
||||||
|
.modal-form-shell__body > * {
|
||||||
|
max-width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 639px) {
|
||||||
|
.modal-overlay--form {
|
||||||
|
padding: 0;
|
||||||
|
align-items: stretch;
|
||||||
|
justify-content: stretch;
|
||||||
|
width: 100vw;
|
||||||
|
max-width: 100vw;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
.modal-panel--form {
|
||||||
|
max-width: 100%;
|
||||||
|
width: 100%;
|
||||||
|
max-height: 100dvh;
|
||||||
|
height: 100dvh;
|
||||||
|
border-radius: 0;
|
||||||
|
margin: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
align-self: stretch;
|
||||||
|
padding: 12px;
|
||||||
|
padding-left: max(12px, env(safe-area-inset-left, 0px));
|
||||||
|
padding-right: max(12px, env(safe-area-inset-right, 0px));
|
||||||
|
padding-top: max(12px, env(safe-area-inset-top, 0px));
|
||||||
|
padding-bottom: max(0px, env(safe-area-inset-bottom, 0px));
|
||||||
|
}
|
||||||
|
.modal-panel--form.card {
|
||||||
|
border: none;
|
||||||
|
border-radius: 0;
|
||||||
|
padding: 12px;
|
||||||
|
padding-top: max(12px, env(safe-area-inset-top, 0px));
|
||||||
|
padding-bottom: max(0px, env(safe-area-inset-bottom, 0px));
|
||||||
|
}
|
||||||
|
.modal-panel__title {
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
.modal-panel__intro {
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-action-bar {
|
||||||
|
padding: 5px 6px;
|
||||||
|
padding-bottom: max(5px, env(safe-area-inset-bottom, 0px));
|
||||||
|
}
|
||||||
|
.form-action-bar__inner {
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
gap: 6px;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
.form-action-bar__primary-group {
|
||||||
|
flex: 1 1 0;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
gap: 6px;
|
||||||
|
margin-left: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.form-action-bar__btn {
|
||||||
|
min-height: 38px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
gap: 4px;
|
||||||
|
flex: 1 1 0;
|
||||||
|
}
|
||||||
|
.form-action-bar__btn--cancel {
|
||||||
|
flex: 0 0 38px;
|
||||||
|
width: 38px;
|
||||||
|
min-width: 38px;
|
||||||
|
max-width: 38px;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.form-action-bar__btn--cancel .form-action-bar__text--long,
|
||||||
|
.form-action-bar__btn--cancel .form-action-bar__text--short {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
.form-action-bar__icon {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
.form-action-bar__text--long {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.form-action-bar__text--short {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
.form-action-bar--single-primary .form-action-bar__primary-group .form-action-bar__btn {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-form-shell {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
.page-form-shell__scroll {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
.page-form-shell .form-action-bar {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
margin-top: 1rem;
|
||||||
|
margin-left: calc(-1 * var(--page-pad, 16px));
|
||||||
|
margin-right: calc(-1 * var(--page-pad, 16px));
|
||||||
|
padding-left: var(--page-pad, 16px);
|
||||||
|
padding-right: var(--page-pad, 16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Vollseiten-Editor: Kopfzeile (Zurück/Titel) + fixiertes Action-Dock unten (alle Viewports) */
|
||||||
|
.page-form-editor__header {
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
padding-bottom: 0.75rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.page-form-editor__intro {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.page-form-editor__back {
|
||||||
|
display: inline-block;
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
color: var(--accent-dark);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.page-form-editor__title {
|
||||||
|
margin: 0;
|
||||||
|
font-size: clamp(1.15rem, 4vw, 1.45rem);
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Ersetzt Bottom-Nav (Mobile) bzw. schwebt unten fix (Desktop) — nur Breite per Breakpoint */
|
||||||
|
.form-editor-mobile-dock {
|
||||||
|
position: fixed;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
z-index: 20;
|
||||||
|
width: auto;
|
||||||
|
max-width: none;
|
||||||
|
background: var(--surface);
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.06);
|
||||||
|
padding: var(--nav-pad-top, 8px) max(10px, env(safe-area-inset-right, 0px))
|
||||||
|
max(8px, env(safe-area-inset-bottom, 0px)) max(10px, env(safe-area-inset-left, 0px));
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.form-editor-mobile-dock .form-action-bar {
|
||||||
|
position: static;
|
||||||
|
border: none;
|
||||||
|
box-shadow: none;
|
||||||
|
margin: 0;
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-shell__column:has(.form-editor-mobile-dock) .app-main {
|
||||||
|
padding-bottom: calc(56px + var(--nav-pad-top, 8px) + env(safe-area-inset-bottom, 0px) + 16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.form-editor-mobile-dock {
|
||||||
|
left: var(--desktop-sidebar-width, 220px);
|
||||||
|
width: calc(100% - var(--desktop-sidebar-width, 220px));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Einstellungen: gleiche Split-Struktur wie Analyse/Admin */
|
/* Einstellungen: gleiche Split-Struktur wie Analyse/Admin */
|
||||||
.settings-shell {
|
.settings-shell {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -3342,6 +3695,12 @@ a.analysis-split__nav-item {
|
|||||||
.admin-matrix-skill-list__name {
|
.admin-matrix-skill-list__name {
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
}
|
}
|
||||||
|
.admin-matrix-skill-list__buttons {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
.admin-matrix-skill-list__path {
|
.admin-matrix-skill-list__path {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
@@ -3388,6 +3747,16 @@ a.analysis-split__nav-item {
|
|||||||
margin-top: 6px;
|
margin-top: 6px;
|
||||||
line-height: 1.35;
|
line-height: 1.35;
|
||||||
}
|
}
|
||||||
|
.admin-matrix-matrix__skill-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.admin-matrix-matrix__skill-head .btn-tiny {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
.admin-matrix-matrix__cell {
|
.admin-matrix-matrix__cell {
|
||||||
vertical-align: top;
|
vertical-align: top;
|
||||||
padding: 6px;
|
padding: 6px;
|
||||||
@@ -5935,6 +6304,78 @@ a.analysis-split__nav-item {
|
|||||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 42%, transparent);
|
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 42%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Planungseditor: Einfügebänder — Split vs. Ganzgruppe (inaktiv sichtbar, aktiv weiterhin Akzent-Ring) */
|
||||||
|
.tu-section-dropband--region-split {
|
||||||
|
height: 12px;
|
||||||
|
background: hsl(200 38% 92%);
|
||||||
|
border: 1px dashed hsl(200 42% 58%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--region-whole {
|
||||||
|
height: 12px;
|
||||||
|
background: color-mix(in srgb, var(--accent) 10%, var(--surface2));
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--accent) 32%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--region-split-to-whole {
|
||||||
|
height: 12px;
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
hsl(200 38% 92%) 0%,
|
||||||
|
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 100%
|
||||||
|
);
|
||||||
|
border: 1px dashed hsl(200 36% 50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--region-whole-to-split {
|
||||||
|
height: 12px;
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 0%,
|
||||||
|
hsl(200 38% 92%) 100%
|
||||||
|
);
|
||||||
|
border: 1px dashed hsl(200 36% 50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--region-neutral {
|
||||||
|
height: 11px;
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--border) 70%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--surface2) 55%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Stream-Tag / Planende: klar getrennte Drop-Ziele bei parallelen Phasen */
|
||||||
|
.tu-stream-chip-pill--drop-active {
|
||||||
|
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--whole-plan-end {
|
||||||
|
background: color-mix(in srgb, var(--accent) 14%, var(--surface2));
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--accent) 35%, transparent);
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-stream-append__drop {
|
||||||
|
margin: 0;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Parallele Phase: feste Einfügebänder oberhalb/unterhalb des Split-Headers */
|
||||||
|
.tu-phase-drop--above-split,
|
||||||
|
.tu-phase-drop--below-split {
|
||||||
|
margin: 6px 2px 8px;
|
||||||
|
min-height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tu-section-dropband--phase-parallel-slot {
|
||||||
|
height: 14px;
|
||||||
|
background: linear-gradient(
|
||||||
|
180deg,
|
||||||
|
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 0%,
|
||||||
|
hsl(200 30% 94%) 100%
|
||||||
|
);
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--accent) 38%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
.tu-sec-drag-grip {
|
.tu-sec-drag-grip {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -6586,6 +7027,21 @@ button.combo-coach-cand-link:hover {
|
|||||||
max-width: none !important;
|
max-width: none !important;
|
||||||
padding: 0 !important;
|
padding: 0 !important;
|
||||||
}
|
}
|
||||||
|
/* Split: jede weitere Breakout-Spalte auf neuer Seite (Gesamtplan-Druck) */
|
||||||
|
.training-run-breakout-stream--page-break {
|
||||||
|
break-before: page;
|
||||||
|
page-break-before: always;
|
||||||
|
}
|
||||||
|
.training-run-parallel-columns {
|
||||||
|
display: block !important;
|
||||||
|
}
|
||||||
|
.training-run-breakout-stream {
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.training-run-phase-schedule {
|
||||||
|
break-inside: avoid;
|
||||||
|
page-break-inside: avoid;
|
||||||
|
}
|
||||||
.training-run-section,
|
.training-run-section,
|
||||||
.training-run-header {
|
.training-run-header {
|
||||||
break-inside: avoid;
|
break-inside: avoid;
|
||||||
|
|||||||
@@ -268,7 +268,7 @@ export default function DashboardTrainingVisibilityWidget({ user }) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Link
|
<Link
|
||||||
to={`/planning?unit=${first.id}`}
|
to={`/planning/units/${first.id}/edit`}
|
||||||
className="btn-ghost"
|
className="btn-ghost"
|
||||||
style={{
|
style={{
|
||||||
padding: '2px 4px',
|
padding: '2px 4px',
|
||||||
|
|||||||
@@ -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,31 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { useFormEditorActions } from '../context/FormEditorActionsContext'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vollseiten-Editor: Zurück/Titel oben; FormActionBar fix unten (alle Viewports via FormEditorBottomSlot).
|
||||||
|
*/
|
||||||
|
export default function PageFormEditorChrome({
|
||||||
|
title,
|
||||||
|
backTo,
|
||||||
|
backLabel = 'Zurück',
|
||||||
|
actionConfig,
|
||||||
|
children,
|
||||||
|
testId,
|
||||||
|
}) {
|
||||||
|
useFormEditorActions(actionConfig)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-form-editor" data-testid={testId}>
|
||||||
|
<header className="page-form-editor__header">
|
||||||
|
{backTo ? (
|
||||||
|
<Link to={backTo} className="page-form-editor__back">
|
||||||
|
← {backLabel}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
<h1 className="page-form-editor__title">{title}</h1>
|
||||||
|
</header>
|
||||||
|
<div className="page-form-editor__body">{children}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -25,6 +25,13 @@ export default function MaturityModelsAdminPanel() {
|
|||||||
const [levelsForm, setLevelsForm] = useState([])
|
const [levelsForm, setLevelsForm] = useState([])
|
||||||
const [cellDraft, setCellDraft] = useState({})
|
const [cellDraft, setCellDraft] = useState({})
|
||||||
const [skillToAdd, setSkillToAdd] = useState('')
|
const [skillToAdd, setSkillToAdd] = useState('')
|
||||||
|
/** Modal: Stammdaten Fähigkeit (Wiki-Felder) aus Matrix-Kontext */
|
||||||
|
const [skillWikiModal, setSkillWikiModal] = useState(null)
|
||||||
|
const [skillWikiForm, setSkillWikiForm] = useState({
|
||||||
|
karate_relevance: '',
|
||||||
|
relevance_level: ''
|
||||||
|
})
|
||||||
|
const [skillWikiLoading, setSkillWikiLoading] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
@@ -219,6 +226,57 @@ export default function MaturityModelsAdminPanel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openSkillWikiModal(skillId, skillName) {
|
||||||
|
setSkillWikiModal({ skill_id: skillId, skill_name: skillName })
|
||||||
|
setSkillWikiLoading(true)
|
||||||
|
setSkillWikiForm({ karate_relevance: '', relevance_level: '' })
|
||||||
|
try {
|
||||||
|
const s = await api.getSkill(skillId)
|
||||||
|
setSkillWikiForm({
|
||||||
|
karate_relevance: s.karate_relevance || '',
|
||||||
|
relevance_level:
|
||||||
|
s.relevance_level != null && s.relevance_level !== ''
|
||||||
|
? String(s.relevance_level)
|
||||||
|
: ''
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message || String(e))
|
||||||
|
setSkillWikiModal(null)
|
||||||
|
} finally {
|
||||||
|
setSkillWikiLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSkillWikiModal() {
|
||||||
|
setSkillWikiModal(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveSkillWikiFields(e) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!skillWikiModal) return
|
||||||
|
setError('')
|
||||||
|
setSkillWikiLoading(true)
|
||||||
|
try {
|
||||||
|
await api.updateSkill(skillWikiModal.skill_id, {
|
||||||
|
karate_relevance:
|
||||||
|
skillWikiForm.karate_relevance && skillWikiForm.karate_relevance.trim()
|
||||||
|
? skillWikiForm.karate_relevance.trim()
|
||||||
|
: null,
|
||||||
|
relevance_level:
|
||||||
|
skillWikiForm.relevance_level === '' || skillWikiForm.relevance_level == null
|
||||||
|
? null
|
||||||
|
: Number(skillWikiForm.relevance_level)
|
||||||
|
})
|
||||||
|
const sk = await api.listSkills({ status: 'active' })
|
||||||
|
setAllSkills(sk)
|
||||||
|
closeSkillWikiModal()
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message || String(e))
|
||||||
|
} finally {
|
||||||
|
setSkillWikiLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleDeleteModel() {
|
async function handleDeleteModel() {
|
||||||
if (!selectedId || !isSuperadmin) return
|
if (!selectedId || !isSuperadmin) return
|
||||||
if (!confirm('Reifegradmodell dauerhaft löschen?')) return
|
if (!confirm('Reifegradmodell dauerhaft löschen?')) return
|
||||||
@@ -552,13 +610,24 @@ export default function MaturityModelsAdminPanel() {
|
|||||||
<li key={ms.skill_id} className="admin-matrix-skill-list__item">
|
<li key={ms.skill_id} className="admin-matrix-skill-list__item">
|
||||||
<div className="admin-matrix-skill-list__row">
|
<div className="admin-matrix-skill-list__row">
|
||||||
<strong className="admin-matrix-skill-list__name">{ms.skill_name}</strong>
|
<strong className="admin-matrix-skill-list__name">{ms.skill_name}</strong>
|
||||||
<button
|
<span className="admin-matrix-skill-list__buttons">
|
||||||
type="button"
|
<button
|
||||||
className="btn btn-secondary btn-small"
|
type="button"
|
||||||
onClick={() => handleRemoveSkill(ms.skill_id)}
|
className="btn btn-secondary btn-small"
|
||||||
>
|
disabled={saving || skillWikiLoading}
|
||||||
Entfernen
|
title="Karate-Relevanz und Relevanzgrad bearbeiten"
|
||||||
</button>
|
onClick={() => openSkillWikiModal(ms.skill_id, ms.skill_name)}
|
||||||
|
>
|
||||||
|
Wiki-Felder
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary btn-small"
|
||||||
|
onClick={() => handleRemoveSkill(ms.skill_id)}
|
||||||
|
>
|
||||||
|
Entfernen
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
||||||
<div className="admin-matrix-skill-list__path muted">
|
<div className="admin-matrix-skill-list__path muted">
|
||||||
@@ -595,13 +664,26 @@ export default function MaturityModelsAdminPanel() {
|
|||||||
{(detail.model_skills || []).map((ms) => (
|
{(detail.model_skills || []).map((ms) => (
|
||||||
<tr key={ms.skill_id}>
|
<tr key={ms.skill_id}>
|
||||||
<td className="admin-matrix-matrix__skill-cell">
|
<td className="admin-matrix-matrix__skill-cell">
|
||||||
<div>{ms.skill_name}</div>
|
<div className="admin-matrix-matrix__skill-head">
|
||||||
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
<div>
|
||||||
<div className="admin-matrix-matrix__skill-path muted">
|
<div>{ms.skill_name}</div>
|
||||||
{ms.skill_main_category_name || '—'}
|
{(ms.skill_main_category_name || ms.skill_subcategory_name) ? (
|
||||||
{ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
|
<div className="admin-matrix-matrix__skill-path muted">
|
||||||
|
{ms.skill_main_category_name || '—'}
|
||||||
|
{ms.skill_subcategory_name ? ` › ${ms.skill_subcategory_name}` : ''}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-ghost btn-tiny"
|
||||||
|
title="Karate-Relevanz und Relevanzgrad bearbeiten"
|
||||||
|
disabled={saving || skillWikiLoading}
|
||||||
|
onClick={() => openSkillWikiModal(ms.skill_id, ms.skill_name)}
|
||||||
|
>
|
||||||
|
✎
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
{(detail.levels || []).map((l) => {
|
{(detail.levels || []).map((l) => {
|
||||||
const key = `${ms.skill_id}-${l.level_number}`
|
const key = `${ms.skill_id}-${l.level_number}`
|
||||||
@@ -643,6 +725,90 @@ export default function MaturityModelsAdminPanel() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{skillWikiModal ? (
|
||||||
|
<div
|
||||||
|
className="admin-modal-backdrop"
|
||||||
|
role="presentation"
|
||||||
|
onClick={closeSkillWikiModal}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="admin-modal-sheet"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="matrix-skill-wiki-title"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="admin-modal-sheet__header">
|
||||||
|
<h3 id="matrix-skill-wiki-title" className="admin-modal-sheet__title">
|
||||||
|
Fähigkeit: {skillWikiModal.skill_name}
|
||||||
|
</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary admin-modal-sheet__close"
|
||||||
|
disabled={skillWikiLoading}
|
||||||
|
onClick={closeSkillWikiModal}
|
||||||
|
aria-label="Schließen"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="admin-modal-sheet__body">
|
||||||
|
{skillWikiLoading ? (
|
||||||
|
<p className="muted">Lade Daten…</p>
|
||||||
|
) : (
|
||||||
|
<form className="skills-catalog-form" onSubmit={handleSaveSkillWikiFields}>
|
||||||
|
<label className="form-label">Karate-Relevanz (Wiki)</label>
|
||||||
|
<textarea
|
||||||
|
className="form-input"
|
||||||
|
rows={4}
|
||||||
|
value={skillWikiForm.karate_relevance}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSkillWikiForm((f) => ({ ...f, karate_relevance: e.target.value }))
|
||||||
|
}
|
||||||
|
disabled={skillWikiLoading}
|
||||||
|
placeholder="Freitext (Wiki-Eigenschaft KarateRelevanz)"
|
||||||
|
/>
|
||||||
|
<label className="form-label">Relevanzgrad (Wiki, 1–3)</label>
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
value={
|
||||||
|
skillWikiForm.relevance_level === ''
|
||||||
|
? ''
|
||||||
|
: String(skillWikiForm.relevance_level)
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSkillWikiForm((f) => ({ ...f, relevance_level: e.target.value }))
|
||||||
|
}
|
||||||
|
disabled={skillWikiLoading}
|
||||||
|
>
|
||||||
|
<option value="">– nicht gesetzt –</option>
|
||||||
|
<option value="1">1</option>
|
||||||
|
<option value="2">2</option>
|
||||||
|
<option value="3">3</option>
|
||||||
|
</select>
|
||||||
|
<p className="muted admin-matrix-hint">
|
||||||
|
Änderungen gelten für die Fähigkeit im gesamten Katalog (gemeinsame Stammdaten).
|
||||||
|
</p>
|
||||||
|
<div className="skills-catalog-form__actions">
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={skillWikiLoading}>
|
||||||
|
Speichern
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
disabled={skillWikiLoading}
|
||||||
|
onClick={closeSkillWikiModal}
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,7 +71,9 @@ export default function SkillsCatalogAdmin() {
|
|||||||
keywords: '',
|
keywords: '',
|
||||||
status: 'active',
|
status: 'active',
|
||||||
sort_order: '',
|
sort_order: '',
|
||||||
category_id: ''
|
category_id: '',
|
||||||
|
karate_relevance: '',
|
||||||
|
relevance_level: ''
|
||||||
})
|
})
|
||||||
|
|
||||||
const [newMainName, setNewMainName] = useState('')
|
const [newMainName, setNewMainName] = useState('')
|
||||||
@@ -176,7 +178,12 @@ export default function SkillsCatalogAdmin() {
|
|||||||
keywords: s.keywords || '',
|
keywords: s.keywords || '',
|
||||||
status: s.status || 'active',
|
status: s.status || 'active',
|
||||||
sort_order: s.sort_order ?? '',
|
sort_order: s.sort_order ?? '',
|
||||||
category_id: s.category_id ?? ''
|
category_id: s.category_id ?? '',
|
||||||
|
karate_relevance: s.karate_relevance || '',
|
||||||
|
relevance_level:
|
||||||
|
s.relevance_level != null && s.relevance_level !== ''
|
||||||
|
? String(s.relevance_level)
|
||||||
|
: ''
|
||||||
})
|
})
|
||||||
setEditDialog({ type: 'skill', id: s.id })
|
setEditDialog({ type: 'skill', id: s.id })
|
||||||
}
|
}
|
||||||
@@ -304,7 +311,15 @@ export default function SkillsCatalogAdmin() {
|
|||||||
skillForm.sort_order === '' || skillForm.sort_order == null
|
skillForm.sort_order === '' || skillForm.sort_order == null
|
||||||
? null
|
? null
|
||||||
: Number(skillForm.sort_order),
|
: Number(skillForm.sort_order),
|
||||||
category_id: cid
|
category_id: cid,
|
||||||
|
karate_relevance:
|
||||||
|
typeof skillForm.karate_relevance === 'string' && skillForm.karate_relevance.trim()
|
||||||
|
? skillForm.karate_relevance.trim()
|
||||||
|
: null,
|
||||||
|
relevance_level:
|
||||||
|
skillForm.relevance_level === '' || skillForm.relevance_level == null
|
||||||
|
? null
|
||||||
|
: Number(skillForm.relevance_level)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
if (ok) {
|
if (ok) {
|
||||||
@@ -922,6 +937,31 @@ export default function SkillsCatalogAdmin() {
|
|||||||
onChange={(e) => setSkillForm((f) => ({ ...f, description: e.target.value }))}
|
onChange={(e) => setSkillForm((f) => ({ ...f, description: e.target.value }))}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
/>
|
/>
|
||||||
|
<label className="form-label">Karate-Relevanz (Wiki)</label>
|
||||||
|
<textarea
|
||||||
|
className="form-input"
|
||||||
|
rows={3}
|
||||||
|
value={skillForm.karate_relevance}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSkillForm((f) => ({ ...f, karate_relevance: e.target.value }))
|
||||||
|
}
|
||||||
|
disabled={busy}
|
||||||
|
placeholder="Freitext aus Wiki / eigene Erläuterung"
|
||||||
|
/>
|
||||||
|
<label className="form-label">Relevanzgrad (Wiki, 1–3)</label>
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
value={skillForm.relevance_level === '' ? '' : String(skillForm.relevance_level)}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSkillForm((f) => ({ ...f, relevance_level: e.target.value }))
|
||||||
|
}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
<option value="">– nicht gesetzt –</option>
|
||||||
|
<option value="1">1</option>
|
||||||
|
<option value="2">2</option>
|
||||||
|
<option value="3">3</option>
|
||||||
|
</select>
|
||||||
<label className="form-label">Sortierung (optional)</label>
|
<label className="form-label">Sortierung (optional)</label>
|
||||||
<input
|
<input
|
||||||
className="form-input"
|
className="form-input"
|
||||||
|
|||||||
@@ -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,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,312 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erstellt ein Trainingsmodul aus den Übungen einer gespeicherten Trainingseinheit (Mehrfachauswahl).
|
||||||
|
*/
|
||||||
|
export default function SaveExercisesAsModuleModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
unitId,
|
||||||
|
planningModalClubId,
|
||||||
|
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) {
|
||||||
|
navigate(`/planning/training-modules/${created.id}`)
|
||||||
|
}
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -5,6 +5,18 @@ import { trainingVisibilityShortDE } from '../../utils/trainingPlanningPageHelpe
|
|||||||
/**
|
/**
|
||||||
* Dialog: Trainingsmodul in die Abschnitte einer Einheit einfügen (Bibliothekskopie).
|
* Dialog: Trainingsmodul in die Abschnitte einer Einheit einfügen (Bibliothekskopie).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
function formatModuleApplySectionOptionLabel(section, flatIndex) {
|
||||||
|
const title = (section?.title || '').trim() || `Abschnitt ${flatIndex + 1}`
|
||||||
|
const pl = section?.planLoc
|
||||||
|
if (pl?.phaseKind === 'parallel') {
|
||||||
|
const st = (pl.streamTitle || '').trim()
|
||||||
|
const streamHint = st ? ` — ${st}` : ''
|
||||||
|
return `${title}${streamHint} (Phase ${pl.phaseOrderIndex ?? 0}, Stream ${pl.parallelStreamOrderIndex ?? 0})`
|
||||||
|
}
|
||||||
|
return title
|
||||||
|
}
|
||||||
|
|
||||||
export default function TrainingPlanningModuleApplyModal({
|
export default function TrainingPlanningModuleApplyModal({
|
||||||
open,
|
open,
|
||||||
busy,
|
busy,
|
||||||
@@ -101,7 +113,7 @@ export default function TrainingPlanningModuleApplyModal({
|
|||||||
>
|
>
|
||||||
{(sections || []).map((s, i) => (
|
{(sections || []).map((s, i) => (
|
||||||
<option key={`sec-opt-u-${i}`} value={String(i)}>
|
<option key={`sec-opt-u-${i}`} value={String(i)}>
|
||||||
{(s.title || `Abschnitt ${i + 1}`).trim()}
|
{formatModuleApplySectionOptionLabel(s, i)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
@@ -148,7 +160,7 @@ export default function TrainingPlanningModuleApplyModal({
|
|||||||
>
|
>
|
||||||
{(sections || []).map((s, i) => (
|
{(sections || []).map((s, i) => (
|
||||||
<option key={`sec-opt-${i}`} value={String(i)}>
|
<option key={`sec-opt-${i}`} value={String(i)}>
|
||||||
{(s.title || `Abschnitt ${i + 1}`).trim()}
|
{formatModuleApplySectionOptionLabel(s, i)}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,10 @@
|
|||||||
import React from 'react'
|
import React, { useEffect, useMemo, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
|
import FormActionBar from '../FormActionBar'
|
||||||
|
import FormModalOverlay from '../FormModalOverlay'
|
||||||
import TrainingPlanExerciseVisibilityPanel from '../TrainingPlanExerciseVisibilityPanel'
|
import TrainingPlanExerciseVisibilityPanel from '../TrainingPlanExerciseVisibilityPanel'
|
||||||
import TrainingUnitSectionsEditor from '../TrainingUnitSectionsEditor'
|
import TrainingUnitSectionsEditor from '../TrainingUnitSectionsEditor'
|
||||||
|
import { activeClubMemberships } from '../../utils/activeClub'
|
||||||
import { frameworkLineageText } from '../../utils/trainingPlanningPageHelpers'
|
import { frameworkLineageText } from '../../utils/trainingPlanningPageHelpers'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -14,6 +17,8 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
updateFormField,
|
updateFormField,
|
||||||
setFormData,
|
setFormData,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
|
onSaveOnly,
|
||||||
|
onSaveAndClose,
|
||||||
onCancel,
|
onCancel,
|
||||||
draftPlanTemplateId,
|
draftPlanTemplateId,
|
||||||
onDraftTemplateSelect,
|
onDraftTemplateSelect,
|
||||||
@@ -26,48 +31,45 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
sectionsEditMode,
|
sectionsEditMode,
|
||||||
setSectionsEditMode,
|
setSectionsEditMode,
|
||||||
onSaveAsTemplate,
|
onSaveAsTemplate,
|
||||||
|
onRequestPublishToFramework,
|
||||||
|
onRequestSaveAsModule,
|
||||||
onRequestTrainingModulePick,
|
onRequestTrainingModulePick,
|
||||||
onRequestExercisePick,
|
onRequestExercisePick,
|
||||||
onPeekExercise,
|
onPeekExercise,
|
||||||
}) {
|
}) {
|
||||||
|
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'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
if (planningModalClubId != null && planningModalClubId !== '') {
|
||||||
|
setNewTplClubId(String(planningModalClubId))
|
||||||
|
} else if (memberClubs.length === 1) {
|
||||||
|
setNewTplClubId(String(memberClubs[0].id))
|
||||||
|
}
|
||||||
|
}, [open, planningModalClubId, memberClubs])
|
||||||
|
|
||||||
if (!open) return null
|
if (!open) return null
|
||||||
|
|
||||||
|
const formId = 'planning-unit-form'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<FormModalOverlay open={open} data-testid="planning-unit-form-modal" onBackdropClick={onCancel}>
|
||||||
data-testid="planning-unit-form-modal"
|
<div className="modal-panel--form">
|
||||||
style={{
|
<h2 className="modal-panel__title">
|
||||||
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' }}>
|
|
||||||
{editingUnit ? 'Trainingseinheit bearbeiten' : 'Neue Trainingseinheit'}
|
{editingUnit ? 'Trainingseinheit bearbeiten' : 'Neue Trainingseinheit'}
|
||||||
</h2>
|
</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
|
{editingUnit?.origin_framework_slot_id
|
||||||
? (() => {
|
? (() => {
|
||||||
const L = frameworkLineageText(editingUnit)
|
const L = frameworkLineageText(editingUnit)
|
||||||
@@ -115,21 +117,25 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
onChange={(e) => onDraftTemplateSelect(e.target.value)}
|
onChange={(e) => onDraftTemplateSelect(e.target.value)}
|
||||||
>
|
>
|
||||||
<option value="">Ohne Vorlage — leere Gliederung (ein Abschnitt)</option>
|
<option value="">Ohne Vorlage — leere Gliederung (ein Abschnitt)</option>
|
||||||
{planTemplates.map((t) => (
|
{planTemplates.map((t) => {
|
||||||
<option key={t.id} value={String(t.id)}>
|
const v = String(t.visibility || 'club').toLowerCase()
|
||||||
{t.name}
|
const vLabel = v === 'private' ? 'Privat' : v === 'official' ? 'Offiziell' : 'Verein'
|
||||||
{typeof t.sections_count === 'number' ? ` · ${t.sections_count} Abschn.` : ''}
|
return (
|
||||||
</option>
|
<option key={t.id} value={String(t.id)}>
|
||||||
))}
|
{t.name}
|
||||||
|
{typeof t.sections_count === 'number' ? ` · ${t.sections_count} Abschn.` : ''}{' '}
|
||||||
|
· {vLabel}
|
||||||
|
</option>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</select>
|
</select>
|
||||||
<p className="training-planning-template-panel__help">
|
<p className="training-planning-template-panel__help">
|
||||||
Übernimmt nur die <strong>Sektionsstruktur</strong> aus der Bibliothek; Übungen trägst du unten bei den
|
Ü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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<form onSubmit={onSubmit}>
|
|
||||||
<h3 style={{ marginBottom: '1rem' }}>Planung</h3>
|
<h3 style={{ marginBottom: '1rem' }}>Planung</h3>
|
||||||
|
|
||||||
<div className="responsive-grid-3" style={{ marginBottom: '1rem' }}>
|
<div className="responsive-grid-3" style={{ marginBottom: '1rem' }}>
|
||||||
@@ -336,9 +342,93 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
heading="Abschnitte & Übungen"
|
heading="Abschnitte & Übungen"
|
||||||
headingAccessory={
|
headingAccessory={
|
||||||
<>
|
<>
|
||||||
<button type="button" className="btn btn-secondary" onClick={onSaveAsTemplate}>
|
<div
|
||||||
Vorlage aus Aufbau speichern
|
style={{
|
||||||
</button>
|
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 && planningModalClubId != null) {
|
||||||
|
setNewTplClubId(String(planningModalClubId))
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<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"
|
||||||
|
style={{ marginBottom: '2px' }}
|
||||||
|
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"
|
||||||
|
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>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
sections={formData.sections}
|
sections={formData.sections}
|
||||||
@@ -353,6 +443,7 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
onRequestExercisePick={onRequestExercisePick}
|
onRequestExercisePick={onRequestExercisePick}
|
||||||
onPeekExercise={onPeekExercise}
|
onPeekExercise={onPeekExercise}
|
||||||
showExecutionExtras={Boolean(editingUnit) && sectionsEditMode === 'debrief'}
|
showExecutionExtras={Boolean(editingUnit) && sectionsEditMode === 'debrief'}
|
||||||
|
enableParallelPhaseControls
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -470,16 +561,21 @@ export default function TrainingPlanningUnitFormModal({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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>
|
</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>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</FormModalOverlay>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,406 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Übernimmt den gespeicherten Ablauf einer geplanten Trainingseinheit in ein Rahmenprogramm (neu oder bestehend, Slot wählbar).
|
||||||
|
*/
|
||||||
|
export default function TrainingPublishToFrameworkModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
unitId,
|
||||||
|
planningModalClubId,
|
||||||
|
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) {
|
||||||
|
navigate(`/planning/framework-programs/${created.id}`)
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
navigate(`/planning/framework-programs/${updated.id}`)
|
||||||
|
}
|
||||||
|
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,485 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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'
|
||||||
|
|
||||||
|
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">
|
||||||
|
<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,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])
|
||||||
|
}
|
||||||
@@ -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,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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -266,7 +266,7 @@ function Dashboard() {
|
|||||||
<ul className="dashboard-preview-card__list">
|
<ul className="dashboard-preview-card__list">
|
||||||
{trainingHome.reviewPending.map((u) => (
|
{trainingHome.reviewPending.map((u) => (
|
||||||
<li key={`r-${u.id}`}>
|
<li key={`r-${u.id}`}>
|
||||||
<Link to={`/planning?unit=${u.id}`} className="dashboard-preview-card__link">
|
<Link to={`/planning/units/${u.id}/edit`} className="dashboard-preview-card__link">
|
||||||
{(u.actual_date || u.planned_date || '').toString().slice(0, 10) || 'Datum'}
|
{(u.actual_date || u.planned_date || '').toString().slice(0, 10) || 'Datum'}
|
||||||
</Link>
|
</Link>
|
||||||
{u.group_name ? (
|
{u.group_name ? (
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ function MediaUsageBlock({ usage, compact }) {
|
|||||||
[t.planned_date, (t.group_name || '').trim()].filter(Boolean).join(' · ') || `Einheit #${t.id}`
|
[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
|
const short = label.length > (compact ? 20 : 36) ? `${label.slice(0, compact ? 20 : 36)}…` : label
|
||||||
return (
|
return (
|
||||||
<Link key={t.id} to={`/planning?unit=${t.id}`} title={label}>
|
<Link key={t.id} to={`/planning/units/${t.id}/edit`} title={label}>
|
||||||
{short}
|
{short}
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,6 +10,13 @@ const WIKI_IMPORT_TABS = [
|
|||||||
{ id: 'history', label: 'Historie', icon: History },
|
{ id: 'history', label: 'Historie', icon: History },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/** MediaWiki-Kategorienamen ohne Präfix „Kategorie:“ — karatetrainer.net aktueller Stand */
|
||||||
|
function defaultWikiCategory(importType) {
|
||||||
|
if (importType === 'skill') return 'Fähigkeitsbeschreibung'
|
||||||
|
if (importType === 'method') return 'Methodenbeschreibung'
|
||||||
|
return 'Übungen'
|
||||||
|
}
|
||||||
|
|
||||||
export default function MediaWikiImportPage() {
|
export default function MediaWikiImportPage() {
|
||||||
const [activeTab, setActiveTab] = useState('preview')
|
const [activeTab, setActiveTab] = useState('preview')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
@@ -169,7 +176,11 @@ export default function MediaWikiImportPage() {
|
|||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
value={previewType}
|
value={previewType}
|
||||||
onChange={(e) => setPreviewType(e.target.value)}
|
onChange={(e) => {
|
||||||
|
const t = e.target.value
|
||||||
|
setPreviewType(t)
|
||||||
|
setPreviewCategory(defaultWikiCategory(t))
|
||||||
|
}}
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
padding: '12px',
|
padding: '12px',
|
||||||
@@ -315,7 +326,11 @@ export default function MediaWikiImportPage() {
|
|||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
value={executeType}
|
value={executeType}
|
||||||
onChange={(e) => setExecuteType(e.target.value)}
|
onChange={(e) => {
|
||||||
|
const t = e.target.value
|
||||||
|
setExecuteType(t)
|
||||||
|
setExecuteCategory(defaultWikiCategory(t))
|
||||||
|
}}
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
padding: '12px',
|
padding: '12px',
|
||||||
|
|||||||
@@ -52,7 +52,9 @@ function SkillsPage() {
|
|||||||
description: '',
|
description: '',
|
||||||
importance: 3,
|
importance: 3,
|
||||||
keywords: [],
|
keywords: [],
|
||||||
status: 'active'
|
status: 'active',
|
||||||
|
karate_relevance: '',
|
||||||
|
relevance_level: ''
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
setFormData({
|
setFormData({
|
||||||
@@ -102,10 +104,20 @@ function SkillsPage() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (modalType === 'skill') {
|
if (modalType === 'skill') {
|
||||||
|
const raw = { ...formData }
|
||||||
|
raw.karate_relevance =
|
||||||
|
typeof raw.karate_relevance === 'string' && raw.karate_relevance.trim()
|
||||||
|
? raw.karate_relevance.trim()
|
||||||
|
: null
|
||||||
|
raw.relevance_level =
|
||||||
|
raw.relevance_level === '' || raw.relevance_level == null || raw.relevance_level === undefined
|
||||||
|
? null
|
||||||
|
: Number(raw.relevance_level)
|
||||||
|
|
||||||
if (editing) {
|
if (editing) {
|
||||||
await api.updateSkill(editing.id, formData)
|
await api.updateSkill(editing.id, raw)
|
||||||
} else {
|
} else {
|
||||||
await api.createSkill(formData)
|
await api.createSkill(raw)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (editing) {
|
if (editing) {
|
||||||
@@ -394,6 +406,41 @@ function SkillsPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{modalType === 'skill' && (
|
||||||
|
<>
|
||||||
|
<div className="form-row">
|
||||||
|
<label className="form-label">Karate-Relevanz (Wiki)</label>
|
||||||
|
<textarea
|
||||||
|
className="form-input"
|
||||||
|
rows={3}
|
||||||
|
value={formData.karate_relevance || ''}
|
||||||
|
onChange={(e) => updateFormField('karate_relevance', e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-row">
|
||||||
|
<label className="form-label">Relevanzgrad (Wiki, 1–3)</label>
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
value={
|
||||||
|
formData.relevance_level === null ||
|
||||||
|
formData.relevance_level === undefined ||
|
||||||
|
formData.relevance_level === ''
|
||||||
|
? ''
|
||||||
|
: String(formData.relevance_level)
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateFormField('relevance_level', e.target.value === '' ? '' : e.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">– nicht gesetzt –</option>
|
||||||
|
<option value="1">1</option>
|
||||||
|
<option value="2">2</option>
|
||||||
|
<option value="3">3</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{modalType === 'skill' && (
|
{modalType === 'skill' && (
|
||||||
<div className="form-row">
|
<div className="form-row">
|
||||||
<label className="form-label">Wichtigkeit (1-5)</label>
|
<label className="form-label">Wichtigkeit (1-5)</label>
|
||||||
|
|||||||
@@ -1,21 +1,43 @@
|
|||||||
/**
|
/**
|
||||||
* Coach-Modus: eine Position nach der anderen mit Assistentenhinweisen, Zeitnahme und optionaler Nachbereitung.
|
* Coach-Modus: Schrittfolge mit Split-Punkten (branch_gate), Stream-Wahl pro paralleler Phase, Assistenz und Zeitnahme.
|
||||||
* Parallele Streams: Schritte aus flattenPlanTimeline (linear); Stream-/Phasenwahl später einzubinden.
|
|
||||||
*/
|
*/
|
||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import ExerciseFullContent from '../components/ExerciseFullContent'
|
import ExerciseFullContent from '../components/ExerciseFullContent'
|
||||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||||
import {
|
import {
|
||||||
|
COACH_ENTRY_BRANCH_GATE,
|
||||||
|
buildCoachSavePlanPayload,
|
||||||
|
coachBranchPicksStepStorageSuffix,
|
||||||
|
coachBranchPicksStorageKey,
|
||||||
|
coachOutlineGroupsFromTimeline,
|
||||||
|
coachShouldPromptSplitRejoin,
|
||||||
|
coachShouldPromptSplitRejoinTransition,
|
||||||
|
durationOverridesMapFromDeltas,
|
||||||
|
findCoachTimelineJumpIndexForPhase,
|
||||||
flattenPlanTimeline,
|
flattenPlanTimeline,
|
||||||
itemStableKey,
|
itemStableKey,
|
||||||
sectionsToPutPayload,
|
listCoachStreamFocusOptions,
|
||||||
|
mergeCoachBranchPicksWithUrlFocus,
|
||||||
|
normalizeCoachBranchPicks,
|
||||||
summarizeTimelineEntry,
|
summarizeTimelineEntry,
|
||||||
} from '../utils/trainingPlanUtils'
|
} from '../utils/trainingPlanUtils'
|
||||||
|
|
||||||
function storageStepKey(unitId) {
|
function storageStepKey(unitId, mergedPicks) {
|
||||||
return `sj_coach_step_${unitId}`
|
return `sj_coach_step_${unitId}_${coachBranchPicksStepStorageSuffix(mergedPicks)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearCoachStepStorageForUnit(unitId) {
|
||||||
|
const pref = `sj_coach_step_${unitId}_`
|
||||||
|
try {
|
||||||
|
for (let i = sessionStorage.length - 1; i >= 0; i -= 1) {
|
||||||
|
const k = sessionStorage.key(i)
|
||||||
|
if (k && k.startsWith(pref)) sessionStorage.removeItem(k)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function storageDeltasKey(unitId) {
|
function storageDeltasKey(unitId) {
|
||||||
@@ -55,14 +77,16 @@ function CoachControlsBand({
|
|||||||
showJumpToTimerOwnerRow = true,
|
showJumpToTimerOwnerRow = true,
|
||||||
onJumpToTimerOwner,
|
onJumpToTimerOwner,
|
||||||
timerOwnerLabelIndex,
|
timerOwnerLabelIndex,
|
||||||
|
branchGateMode = false,
|
||||||
}) {
|
}) {
|
||||||
const disPrev = step <= 0
|
const disPrev = step <= 0
|
||||||
const disNext = step >= timelineLength - 1
|
const disNext = branchGateMode || step >= timelineLength - 1
|
||||||
const alive = runStartAt != null || pausedAccumMs > 0
|
const alive = runStartAt != null || pausedAccumMs > 0
|
||||||
const canApplyForOwner = roundedMinForApply != null && roundedMinForApply >= 1
|
const canApplyForOwner = !branchGateMode && roundedMinForApply != null && roundedMinForApply >= 1
|
||||||
const istLabelMin = roundedMinForApply == null ? '—' : String(roundedMinForApply)
|
const istLabelMin = roundedMinForApply == null ? '—' : String(roundedMinForApply)
|
||||||
const doneLabel =
|
const doneLabel = branchGateMode
|
||||||
timelineLength <= 1
|
? 'Zuerst Gruppe wählen'
|
||||||
|
: timelineLength <= 1
|
||||||
? 'Nachbereitung öffnen'
|
? 'Nachbereitung öffnen'
|
||||||
: isLastCoachStep
|
: isLastCoachStep
|
||||||
? 'Nachbereitung & Ist-Zeit'
|
? 'Nachbereitung & Ist-Zeit'
|
||||||
@@ -106,6 +130,7 @@ function CoachControlsBand({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
style={{ minHeight: '44px', flex: '1 1 auto', fontWeight: 700 }}
|
style={{ minHeight: '44px', flex: '1 1 auto', fontWeight: 700 }}
|
||||||
|
disabled={branchGateMode}
|
||||||
onClick={onTimerStart}
|
onClick={onTimerStart}
|
||||||
>
|
>
|
||||||
▶ Start{alive ? ` · ${clockStr}` : ''}
|
▶ Start{alive ? ` · ${clockStr}` : ''}
|
||||||
@@ -118,7 +143,7 @@ function CoachControlsBand({
|
|||||||
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px', flex: '0 1 auto', fontWeight: 600 }} disabled={!canApplyForOwner} onClick={onApplyActual}>
|
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px', flex: '0 1 auto', fontWeight: 600 }} disabled={!canApplyForOwner} onClick={onApplyActual}>
|
||||||
Ist ({istLabelMin} Min)
|
Ist ({istLabelMin} Min)
|
||||||
</button>
|
</button>
|
||||||
{alive && (
|
{alive && !branchGateMode && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
@@ -134,6 +159,7 @@ function CoachControlsBand({
|
|||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
style={{ width: '100%', minHeight: '44px', fontWeight: 700, lineHeight: 1.2, padding: '6px 10px', whiteSpace: 'normal', textAlign: 'center' }}
|
style={{ width: '100%', minHeight: '44px', fontWeight: 700, lineHeight: 1.2, padding: '6px 10px', whiteSpace: 'normal', textAlign: 'center' }}
|
||||||
|
disabled={branchGateMode}
|
||||||
onClick={onDone}
|
onClick={onDone}
|
||||||
>
|
>
|
||||||
{doneLabel}
|
{doneLabel}
|
||||||
@@ -156,8 +182,11 @@ function CoachControlsBand({
|
|||||||
export default function TrainingCoachPage() {
|
export default function TrainingCoachPage() {
|
||||||
const { unitId } = useParams()
|
const { unitId } = useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams()
|
||||||
const idNum = unitId ? parseInt(unitId, 10) : NaN
|
const idNum = unitId ? parseInt(unitId, 10) : NaN
|
||||||
|
|
||||||
|
const coachFocusResetRef = useRef(null)
|
||||||
|
|
||||||
const [unit, setUnit] = useState(null)
|
const [unit, setUnit] = useState(null)
|
||||||
const [loadError, setLoadError] = useState(null)
|
const [loadError, setLoadError] = useState(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
@@ -170,6 +199,8 @@ export default function TrainingCoachPage() {
|
|||||||
const [coachDebriefPhase, setCoachDebriefPhase] = useState(false)
|
const [coachDebriefPhase, setCoachDebriefPhase] = useState(false)
|
||||||
|
|
||||||
const [step, setStep] = useState(0)
|
const [step, setStep] = useState(0)
|
||||||
|
const [branchPicks, setBranchPicks] = useState({})
|
||||||
|
const [streamChoiceHint, setStreamChoiceHint] = useState(null)
|
||||||
const [deltas, setDeltas] = useState({})
|
const [deltas, setDeltas] = useState({})
|
||||||
|
|
||||||
const [runStartAt, setRunStartAt] = useState(null)
|
const [runStartAt, setRunStartAt] = useState(null)
|
||||||
@@ -177,6 +208,8 @@ export default function TrainingCoachPage() {
|
|||||||
const [timerOwningStep, setTimerOwningStep] = useState(null)
|
const [timerOwningStep, setTimerOwningStep] = useState(null)
|
||||||
const [, setPulse] = useState(0)
|
const [, setPulse] = useState(0)
|
||||||
|
|
||||||
|
const [splitRejoinPrompt, setSplitRejoinPrompt] = useState(null)
|
||||||
|
|
||||||
const [trainerAppend, setTrainerAppend] = useState('')
|
const [trainerAppend, setTrainerAppend] = useState('')
|
||||||
const [saveMarkDone, setSaveMarkDone] = useState(true)
|
const [saveMarkDone, setSaveMarkDone] = useState(true)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
@@ -188,12 +221,52 @@ export default function TrainingCoachPage() {
|
|||||||
setUnit(u)
|
setUnit(u)
|
||||||
}, [idNum])
|
}, [idNum])
|
||||||
|
|
||||||
|
const coachFocus = useMemo(() => {
|
||||||
|
const poRaw = searchParams.get('po')
|
||||||
|
const soRaw = searchParams.get('so')
|
||||||
|
if (poRaw == null || poRaw === '' || soRaw == null || soRaw === '') return null
|
||||||
|
const po = parseInt(poRaw, 10)
|
||||||
|
const so = parseInt(soRaw, 10)
|
||||||
|
if (!Number.isFinite(po) || !Number.isFinite(so)) return null
|
||||||
|
if (!unit) return null
|
||||||
|
const opts = listCoachStreamFocusOptions(unit)
|
||||||
|
if (!opts.some((o) => o.phaseOrder === po && o.streamOrder === so)) return null
|
||||||
|
return { phaseOrder: po, streamOrder: so }
|
||||||
|
}, [searchParams, unit])
|
||||||
|
|
||||||
|
const mergedPicks = useMemo(
|
||||||
|
() => mergeCoachBranchPicksWithUrlFocus(branchPicks, coachFocus),
|
||||||
|
[branchPicks, coachFocus]
|
||||||
|
)
|
||||||
|
|
||||||
|
const streamFocusOptions = useMemo(() => (unit ? listCoachStreamFocusOptions(unit) : []), [unit])
|
||||||
|
|
||||||
|
const navigationKey = coachBranchPicksStepStorageSuffix(mergedPicks)
|
||||||
|
|
||||||
|
const streamQuickSelectValue = useMemo(() => {
|
||||||
|
for (let i = 0; i < streamFocusOptions.length; i++) {
|
||||||
|
const o = streamFocusOptions[i]
|
||||||
|
if (mergedPicks[o.phaseOrder] === o.streamOrder) return o.valueKey
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
}, [streamFocusOptions, mergedPicks])
|
||||||
|
|
||||||
|
const hasStreamSelectParams =
|
||||||
|
(searchParams.get('po') != null && searchParams.get('po') !== '') ||
|
||||||
|
(searchParams.get('so') != null && searchParams.get('so') !== '')
|
||||||
|
const streamParamsInvalid = Boolean(unit && hasStreamSelectParams && !coachFocus)
|
||||||
|
|
||||||
|
const timeline = useMemo(() => flattenPlanTimeline(unit, mergedPicks), [unit, mergedPicks])
|
||||||
|
|
||||||
|
const outlineGroups = useMemo(() => coachOutlineGroupsFromTimeline(timeline), [timeline])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!unitId || Number.isNaN(idNum)) {
|
if (!unitId || Number.isNaN(idNum)) {
|
||||||
setLoadError('Ungültige Trainingseinheit')
|
setLoadError('Ungültige Trainingseinheit')
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
coachFocusResetRef.current = null
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
;(async () => {
|
;(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
@@ -201,9 +274,13 @@ export default function TrainingCoachPage() {
|
|||||||
try {
|
try {
|
||||||
await reloadUnit()
|
await reloadUnit()
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
|
let nextBranchPicks = {}
|
||||||
try {
|
try {
|
||||||
const s = parseInt(sessionStorage.getItem(storageStepKey(idNum)), 10)
|
const br = sessionStorage.getItem(coachBranchPicksStorageKey(idNum))
|
||||||
if (!Number.isNaN(s) && s >= 0) setStep(s)
|
if (br) {
|
||||||
|
const o = JSON.parse(br)
|
||||||
|
if (o && typeof o === 'object') nextBranchPicks = normalizeCoachBranchPicks(o)
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
@@ -221,6 +298,10 @@ export default function TrainingCoachPage() {
|
|||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
|
if (!cancelled) {
|
||||||
|
setBranchPicks(nextBranchPicks)
|
||||||
|
setStreamChoiceHint(null)
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!cancelled) setLoadError(e.message || 'Laden fehlgeschlagen')
|
if (!cancelled) setLoadError(e.message || 'Laden fehlgeschlagen')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -233,8 +314,68 @@ export default function TrainingCoachPage() {
|
|||||||
}, [unitId, idNum, reloadUnit])
|
}, [unitId, idNum, reloadUnit])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
sessionStorage.setItem(storageStepKey(idNum), String(step))
|
if (!unit) return
|
||||||
}, [idNum, step])
|
const po = searchParams.get('po')
|
||||||
|
const so = searchParams.get('so')
|
||||||
|
if ((po == null || po === '') && (so == null || so === '')) return
|
||||||
|
const p = parseInt(po, 10)
|
||||||
|
const s = parseInt(so, 10)
|
||||||
|
if (!Number.isFinite(p) || !Number.isFinite(s)) {
|
||||||
|
setSearchParams({}, { replace: true })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const opts = listCoachStreamFocusOptions(unit)
|
||||||
|
if (opts.length === 0 || !opts.some((o) => o.phaseOrder === p && o.streamOrder === s)) {
|
||||||
|
setSearchParams({}, { replace: true })
|
||||||
|
}
|
||||||
|
}, [unit, searchParams, setSearchParams])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!unit) return
|
||||||
|
const ab = searchParams.get('atBranch')
|
||||||
|
if (ab == null || ab === '') return
|
||||||
|
const po = parseInt(ab, 10)
|
||||||
|
const phaseOrders = [...new Set(streamFocusOptions.map((o) => o.phaseOrder))]
|
||||||
|
if (!Number.isFinite(po) || !phaseOrders.includes(po)) {
|
||||||
|
const next = new URLSearchParams(searchParams)
|
||||||
|
next.delete('atBranch')
|
||||||
|
next.delete('preferSo')
|
||||||
|
setSearchParams(next, { replace: true })
|
||||||
|
}
|
||||||
|
}, [unit, searchParams, setSearchParams, streamFocusOptions])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!unit || timeline.length === 0) return
|
||||||
|
const ab = searchParams.get('atBranch')
|
||||||
|
if (ab == null || ab === '') return
|
||||||
|
const po = parseInt(ab, 10)
|
||||||
|
if (!Number.isFinite(po)) return
|
||||||
|
const prefRaw = searchParams.get('preferSo')
|
||||||
|
const pref = prefRaw != null && prefRaw !== '' ? parseInt(prefRaw, 10) : NaN
|
||||||
|
const ix = findCoachTimelineJumpIndexForPhase(timeline, po, Number.isFinite(pref) ? pref : null)
|
||||||
|
if (ix >= 0) {
|
||||||
|
setStep(ix)
|
||||||
|
if (Number.isFinite(pref)) setStreamChoiceHint({ phaseOrder: po, streamOrder: pref })
|
||||||
|
}
|
||||||
|
const next = new URLSearchParams(searchParams)
|
||||||
|
next.delete('atBranch')
|
||||||
|
next.delete('preferSo')
|
||||||
|
setSearchParams(next, { replace: true })
|
||||||
|
}, [unit, timeline, searchParams, setSearchParams])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (Number.isNaN(idNum)) return
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(coachBranchPicksStorageKey(idNum), JSON.stringify(branchPicks))
|
||||||
|
} catch {
|
||||||
|
/* quota */
|
||||||
|
}
|
||||||
|
}, [idNum, branchPicks])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (Number.isNaN(idNum)) return
|
||||||
|
sessionStorage.setItem(storageStepKey(idNum, mergedPicks), String(step))
|
||||||
|
}, [idNum, mergedPicks, step])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
try {
|
||||||
@@ -258,46 +399,91 @@ export default function TrainingCoachPage() {
|
|||||||
return () => clearInterval(iv)
|
return () => clearInterval(iv)
|
||||||
}, [runStartAt])
|
}, [runStartAt])
|
||||||
|
|
||||||
const timeline = useMemo(() => flattenPlanTimeline(unit), [unit])
|
|
||||||
|
|
||||||
const clampStep = (s, len = timeline.length) =>
|
const clampStep = (s, len = timeline.length) =>
|
||||||
Math.max(0, Math.min(s, Math.max(len - 1, 0)))
|
Math.max(0, Math.min(s, Math.max(len - 1, 0)))
|
||||||
|
|
||||||
|
const timerReset = useCallback(() => {
|
||||||
|
setRunStartAt(null)
|
||||||
|
setPausedAccumMs(0)
|
||||||
|
setTimerOwningStep(null)
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!unit) return
|
if (!unit) return
|
||||||
if (timeline.length === 0) {
|
if (timeline.length === 0) {
|
||||||
setStep(0)
|
setStep(0)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (coachDebriefPhase) return
|
if (coachDebriefPhase) {
|
||||||
setStep((prev) => clampStep(prev, timeline.length))
|
setStep(timeline.length - 1)
|
||||||
|
} else {
|
||||||
|
setStep((prev) => clampStep(prev, timeline.length))
|
||||||
|
}
|
||||||
}, [unit, timeline.length, coachDebriefPhase])
|
}, [unit, timeline.length, coachDebriefPhase])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!coachDebriefPhase || !unit || timeline.length === 0) return
|
if (!unit || Number.isNaN(idNum)) return
|
||||||
setStep(timeline.length - 1)
|
if (timeline.length === 0) {
|
||||||
}, [coachDebriefPhase, unit, timeline.length])
|
setStep(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const prev = coachFocusResetRef.current
|
||||||
|
if (prev === null) {
|
||||||
|
coachFocusResetRef.current = navigationKey
|
||||||
|
} else if (prev !== navigationKey) {
|
||||||
|
coachFocusResetRef.current = navigationKey
|
||||||
|
setCoachDebriefPhase(false)
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
timerReset()
|
||||||
|
} else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(storageStepKey(idNum, mergedPicks))
|
||||||
|
const s = parseInt(raw, 10)
|
||||||
|
const maxIdx = Math.max(0, timeline.length - 1)
|
||||||
|
if (!Number.isNaN(s) && s >= 0) setStep(Math.min(s, maxIdx))
|
||||||
|
else setStep(0)
|
||||||
|
} catch {
|
||||||
|
setStep(0)
|
||||||
|
}
|
||||||
|
}, [unit, idNum, navigationKey, mergedPicks, timeline.length, timerReset])
|
||||||
|
|
||||||
const elapsedMs =
|
const elapsedMs =
|
||||||
pausedAccumMs + (runStartAt != null ? Date.now() - runStartAt : 0)
|
pausedAccumMs + (runStartAt != null ? Date.now() - runStartAt : 0)
|
||||||
|
|
||||||
const tickDisplaySec = Math.max(0, Math.floor(elapsedMs / 1000))
|
const tickDisplaySec = Math.max(0, Math.floor(elapsedMs / 1000))
|
||||||
|
|
||||||
const currentEntry = timeline[step]
|
const safeStep = useMemo(() => {
|
||||||
const nextEntry = timeline[step + 1] || null
|
if (!timeline.length) return 0
|
||||||
const next2Entry = timeline[step + 2] || null
|
return Math.min(Math.max(0, step), timeline.length - 1)
|
||||||
|
}, [step, timeline.length])
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!timeline.length) return
|
||||||
|
const max = timeline.length - 1
|
||||||
|
const s = Math.min(Math.max(0, step), max)
|
||||||
|
if (s !== step) setStep(s)
|
||||||
|
}, [step, timeline.length])
|
||||||
|
|
||||||
|
const currentEntry = timeline[safeStep] ?? null
|
||||||
|
const nextEntry = timeline[safeStep + 1] || null
|
||||||
|
const next2Entry = timeline[safeStep + 2] || null
|
||||||
|
|
||||||
const clockStr = formatClock(tickDisplaySec)
|
const clockStr = formatClock(tickDisplaySec)
|
||||||
const roundedMinApply = elapsedMs <= 650 ? null : Math.max(1, Math.round(elapsedMs / 60000))
|
const roundedMinApply = elapsedMs <= 650 ? null : Math.max(1, Math.round(elapsedMs / 60000))
|
||||||
const showJumpToTimerOwner =
|
const showJumpToTimerOwner =
|
||||||
timerOwningStep != null &&
|
timerOwningStep != null &&
|
||||||
step !== timerOwningStep &&
|
safeStep !== timerOwningStep &&
|
||||||
(runStartAt != null || pausedAccumMs > 0)
|
(runStartAt != null || pausedAccumMs > 0)
|
||||||
const isLastCoachStep = timeline.length > 0 && step >= timeline.length - 1
|
const isLastCoachStep =
|
||||||
|
timeline.length > 0 &&
|
||||||
|
safeStep >= timeline.length - 1 &&
|
||||||
|
currentEntry?.entryKind !== COACH_ENTRY_BRANCH_GATE
|
||||||
|
|
||||||
const timerStart = () => {
|
const timerStart = () => {
|
||||||
setRunStartAt(Date.now())
|
setRunStartAt(Date.now())
|
||||||
setTimerOwningStep(step)
|
setTimerOwningStep(safeStep)
|
||||||
}
|
}
|
||||||
|
|
||||||
const timerPause = () => {
|
const timerPause = () => {
|
||||||
@@ -307,14 +493,8 @@ export default function TrainingCoachPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const timerReset = () => {
|
|
||||||
setRunStartAt(null)
|
|
||||||
setPausedAccumMs(0)
|
|
||||||
setTimerOwningStep(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
const applySuggestedDuration = () => {
|
const applySuggestedDuration = () => {
|
||||||
const idx = timerOwningStep != null ? timerOwningStep : step
|
const idx = timerOwningStep != null ? timerOwningStep : safeStep
|
||||||
const ent = timeline[idx]
|
const ent = timeline[idx]
|
||||||
const item = ent?.item
|
const item = ent?.item
|
||||||
if (!item || item.item_type !== 'exercise') return
|
if (!item || item.item_type !== 'exercise') return
|
||||||
@@ -325,12 +505,28 @@ export default function TrainingCoachPage() {
|
|||||||
timerPause()
|
timerPause()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pickStreamForPhase = useCallback(
|
||||||
|
(phaseOrder, streamOrder) => {
|
||||||
|
if (!Number.isFinite(phaseOrder) || !Number.isFinite(streamOrder)) return
|
||||||
|
setStreamChoiceHint(null)
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setBranchPicks((prev) => ({ ...normalizeCoachBranchPicks(prev), [phaseOrder]: streamOrder }))
|
||||||
|
timerReset()
|
||||||
|
setCoachDebriefPhase(false)
|
||||||
|
setSearchParams({ po: String(phaseOrder), so: String(streamOrder) }, { replace: true })
|
||||||
|
},
|
||||||
|
[timerReset, setSearchParams]
|
||||||
|
)
|
||||||
|
|
||||||
|
const atBranchGate = currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE
|
||||||
|
|
||||||
const goPrev = () => setStep((s) => clampStep(s - 1))
|
const goPrev = () => setStep((s) => clampStep(s - 1))
|
||||||
const goNext = () => setStep((s) => clampStep(s + 1))
|
const goNext = () => setStep((s) => clampStep(s + 1))
|
||||||
|
|
||||||
const markCurrentDoneAdvance = () => {
|
const markCurrentDoneAdvance = () => {
|
||||||
const ownerIdx = timerOwningStep != null ? timerOwningStep : step
|
const ownerIdx = timerOwningStep != null ? timerOwningStep : safeStep
|
||||||
const ent = timeline[ownerIdx]
|
const ent = timeline[ownerIdx]
|
||||||
|
if (ent?.entryKind === COACH_ENTRY_BRANCH_GATE) return
|
||||||
const item = ent?.item
|
const item = ent?.item
|
||||||
if (item?.item_type === 'exercise' && elapsedMs > 650) {
|
if (item?.item_type === 'exercise' && elapsedMs > 650) {
|
||||||
const key = itemStableKey(item, ent.secOrder, ent.ii)
|
const key = itemStableKey(item, ent.secOrder, ent.ii)
|
||||||
@@ -340,7 +536,12 @@ export default function TrainingCoachPage() {
|
|||||||
timerReset()
|
timerReset()
|
||||||
|
|
||||||
const lastIdx = timeline.length - 1
|
const lastIdx = timeline.length - 1
|
||||||
if (step >= lastIdx && lastIdx >= 0) {
|
if (safeStep >= lastIdx && lastIdx >= 0) {
|
||||||
|
const rejoin = coachShouldPromptSplitRejoin(unit, timeline[safeStep])
|
||||||
|
if (rejoin) {
|
||||||
|
setSplitRejoinPrompt(rejoin)
|
||||||
|
return
|
||||||
|
}
|
||||||
setCoachDebriefPhase(true)
|
setCoachDebriefPhase(true)
|
||||||
try {
|
try {
|
||||||
sessionStorage.setItem(storageDebriefKey(idNum), '1')
|
sessionStorage.setItem(storageDebriefKey(idNum), '1')
|
||||||
@@ -349,25 +550,31 @@ export default function TrainingCoachPage() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const nextIdx = safeStep + 1
|
||||||
|
if (nextIdx < timeline.length) {
|
||||||
|
const rejoinMid = coachShouldPromptSplitRejoinTransition(unit, timeline[safeStep], timeline[nextIdx])
|
||||||
|
if (rejoinMid) {
|
||||||
|
setSplitRejoinPrompt(rejoinMid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
setStep((s) => clampStep(s + 1, timeline.length))
|
setStep((s) => clampStep(s + 1, timeline.length))
|
||||||
}
|
}
|
||||||
|
|
||||||
const durationOverridesForApi = useMemo(() => {
|
useEffect(() => {
|
||||||
const out = {}
|
if (!atBranchGate) return
|
||||||
for (let i = 0; i < timeline.length; i++) {
|
if (runStartAt != null || pausedAccumMs > 0) timerReset()
|
||||||
const ent = timeline[i]
|
}, [step, atBranchGate, runStartAt, pausedAccumMs, timerReset])
|
||||||
const { item } = ent
|
|
||||||
if (item.item_type !== 'exercise' || item.id == null) continue
|
const durationOverridesForApi = useMemo(() => durationOverridesMapFromDeltas(unit, deltas), [unit, deltas])
|
||||||
const k = itemStableKey(item, ent.secOrder, ent.ii)
|
|
||||||
const dv = deltas[k]?.actual_duration_min
|
|
||||||
if (dv !== undefined && dv !== '' && dv !== null && !Number.isNaN(Number(dv))) {
|
|
||||||
out[String(item.id)] = { actual_duration_min: Number(dv) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}, [timeline, deltas])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE) {
|
||||||
|
setCatalogExercise(null)
|
||||||
|
setCatalogError(null)
|
||||||
|
setCatalogLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
const item = currentEntry?.item
|
const item = currentEntry?.item
|
||||||
if (!item || item.item_type === 'note') {
|
if (!item || item.item_type === 'note') {
|
||||||
setCatalogExercise(null)
|
setCatalogExercise(null)
|
||||||
@@ -403,16 +610,16 @@ export default function TrainingCoachPage() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true
|
cancelled = true
|
||||||
}
|
}
|
||||||
}, [step, currentEntry?.item?.exercise_id, currentEntry?.item?.exercise_variant_id, currentEntry?.item?.item_type])
|
}, [step, currentEntry?.entryKind, currentEntry?.item?.exercise_id, currentEntry?.item?.exercise_variant_id, currentEntry?.item?.item_type])
|
||||||
|
|
||||||
const handleSaveDebrief = async () => {
|
const handleSaveDebrief = async () => {
|
||||||
setSaveOk(null)
|
setSaveOk(null)
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
try {
|
try {
|
||||||
const sectionsPayload = sectionsToPutPayload(unit, durationOverridesForApi)
|
const sectionsPayloadPart = buildCoachSavePlanPayload(unit, durationOverridesForApi)
|
||||||
const tn = trainerAppend.trim()
|
const tn = trainerAppend.trim()
|
||||||
const payload = {
|
const payload = {
|
||||||
sections: sectionsPayload,
|
...sectionsPayloadPart,
|
||||||
...(saveMarkDone ? { status: 'completed' } : {}),
|
...(saveMarkDone ? { status: 'completed' } : {}),
|
||||||
}
|
}
|
||||||
if (tn) {
|
if (tn) {
|
||||||
@@ -422,18 +629,24 @@ export default function TrainingCoachPage() {
|
|||||||
.trim()
|
.trim()
|
||||||
}
|
}
|
||||||
await api.updateTrainingUnit(idNum, payload)
|
await api.updateTrainingUnit(idNum, payload)
|
||||||
await reloadUnit()
|
|
||||||
setTrainerAppend('')
|
setTrainerAppend('')
|
||||||
try {
|
try {
|
||||||
sessionStorage.removeItem(storageDeltasKey(idNum))
|
sessionStorage.removeItem(storageDeltasKey(idNum))
|
||||||
sessionStorage.removeItem(storageDebriefKey(idNum))
|
sessionStorage.removeItem(storageDebriefKey(idNum))
|
||||||
|
sessionStorage.removeItem(coachBranchPicksStorageKey(idNum))
|
||||||
|
clearCoachStepStorageForUnit(idNum)
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
setDeltas({})
|
setDeltas({})
|
||||||
|
setBranchPicks({})
|
||||||
|
setStreamChoiceHint(null)
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
setCoachDebriefPhase(false)
|
setCoachDebriefPhase(false)
|
||||||
setSaveOk('Gespeichert.')
|
|
||||||
setDebriefOpen(false)
|
setDebriefOpen(false)
|
||||||
|
setSaveOk('Gespeichert.')
|
||||||
|
setSearchParams({}, { replace: true })
|
||||||
|
navigate(`/planning/run/${unitId}`, { replace: true })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setSaveOk(`Fehler: ${e.message || e}`)
|
setSaveOk(`Fehler: ${e.message || e}`)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -487,6 +700,41 @@ export default function TrainingCoachPage() {
|
|||||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||||
Planung
|
Planung
|
||||||
</button>
|
</button>
|
||||||
|
{streamFocusOptions.length > 0 ? (
|
||||||
|
<label
|
||||||
|
className="no-print"
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '0.82rem', color: 'var(--text2)' }}
|
||||||
|
>
|
||||||
|
<span style={{ color: 'var(--text3)', whiteSpace: 'nowrap' }}>Ansicht</span>
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
style={{ minWidth: 'min(220px, 72vw)', margin: 0, padding: '6px 8px', fontSize: '0.82rem' }}
|
||||||
|
value={streamQuickSelectValue}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setCoachDebriefPhase(false)
|
||||||
|
timerReset()
|
||||||
|
const v = e.target.value
|
||||||
|
if (!v) {
|
||||||
|
setBranchPicks({})
|
||||||
|
setStreamChoiceHint(null)
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setSearchParams({}, { replace: true })
|
||||||
|
} else {
|
||||||
|
const [ppo, sso] = v.split('-').map((x) => parseInt(x, 10))
|
||||||
|
pickStreamForPhase(ppo, sso)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Ablauf mit Split-Punkten (Standard)</option>
|
||||||
|
{streamFocusOptions.map((o) => (
|
||||||
|
<option key={o.valueKey} value={o.valueKey}>
|
||||||
|
{o.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
) : null}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
@@ -497,6 +745,111 @@ export default function TrainingCoachPage() {
|
|||||||
</button>
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
{streamParamsInvalid ? (
|
||||||
|
<p
|
||||||
|
className="no-print card"
|
||||||
|
style={{
|
||||||
|
padding: '10px 12px',
|
||||||
|
fontSize: '0.82rem',
|
||||||
|
color: 'var(--danger)',
|
||||||
|
marginBottom: '8px',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Ungültige Stream-Parameter in der Adresszeile — es wird der Gesamtplan angezeigt.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{splitRejoinPrompt && !coachDebriefPhase ? (
|
||||||
|
<div
|
||||||
|
className="card no-print"
|
||||||
|
style={{
|
||||||
|
flexShrink: 0,
|
||||||
|
marginBottom: '10px',
|
||||||
|
padding: '16px 14px',
|
||||||
|
borderRadius: '12px',
|
||||||
|
border: '2px solid var(--accent)',
|
||||||
|
background: 'linear-gradient(135deg, var(--accent-light), var(--surface))',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
|
||||||
|
Parallelphase · Abschluss
|
||||||
|
</div>
|
||||||
|
<p style={{ fontSize: '0.95rem', fontWeight: 700, margin: '0 0 8px', color: 'var(--text1)' }}>
|
||||||
|
{splitRejoinPrompt.phaseTitle != null && String(splitRejoinPrompt.phaseTitle).trim()
|
||||||
|
? String(splitRejoinPrompt.phaseTitle).trim()
|
||||||
|
: `Phase ${splitRejoinPrompt.phaseOrderIndex}`}
|
||||||
|
{' — '}
|
||||||
|
alle Gruppen zusammen?
|
||||||
|
</p>
|
||||||
|
<p style={{ fontSize: '0.84rem', color: 'var(--text2)', margin: '0 0 12px', lineHeight: 1.45 }}>
|
||||||
|
Diese Phase hat mehrere Streams. Kurz mit dem anderen Trainer klären, dann gemeinsam weitermachen. Ist-Zeiten
|
||||||
|
und Speichern erfolgen in der Nachbereitung am Ende der Einheit.
|
||||||
|
</p>
|
||||||
|
<ul style={{ margin: '0 0 14px', paddingLeft: '1.2rem', fontSize: '0.82rem', color: 'var(--text2)' }}>
|
||||||
|
{splitRejoinPrompt.streams.map((st) => (
|
||||||
|
<li key={st.printStreamId || `s-${st.streamOrder}`}>
|
||||||
|
{st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}{' '}
|
||||||
|
<span style={{ color: 'var(--text3)' }}>(ca. {st.minutes} Min. Üb.)</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||||
|
{safeStep < timeline.length - 1 ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
style={{ minHeight: '48px', fontWeight: 700 }}
|
||||||
|
onClick={() => {
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setStep((s) => clampStep(s + 1, timeline.length))
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Gruppen zusammengeführt — weiter mit dem Plan
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
style={{ minHeight: '48px', fontWeight: 700 }}
|
||||||
|
onClick={() => {
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setCoachDebriefPhase(true)
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(storageDebriefKey(idNum), '1')
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Alle Gruppen fertig — zur Nachbereitung
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px' }} onClick={() => setSplitRejoinPrompt(null)}>
|
||||||
|
Zurück — andere Gruppe läuft noch
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
style={{ minHeight: '44px', fontSize: '0.82rem' }}
|
||||||
|
onClick={() => {
|
||||||
|
setSplitRejoinPrompt(null)
|
||||||
|
setCoachDebriefPhase(true)
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(storageDebriefKey(idNum), '1')
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{safeStep < timeline.length - 1
|
||||||
|
? 'Ausnahme: jetzt schon zur Nachbereitung'
|
||||||
|
: 'Ausnahme: trotzdem zur Nachbereitung'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<header
|
<header
|
||||||
className="card training-coach-hero training-coach-hero--compact"
|
className="card training-coach-hero training-coach-hero--compact"
|
||||||
style={{
|
style={{
|
||||||
@@ -510,44 +863,93 @@ export default function TrainingCoachPage() {
|
|||||||
>
|
>
|
||||||
<div style={{ fontSize: '0.7rem', color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
|
<div style={{ fontSize: '0.7rem', color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
|
||||||
Coach ·{' '}
|
Coach ·{' '}
|
||||||
{coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(step || 0) + 1} / ${Math.max(timeline.length, 1)}`}
|
{coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(safeStep || 0) + 1} / ${Math.max(timeline.length, 1)}`}
|
||||||
</div>
|
</div>
|
||||||
<h1 style={{ fontSize: '1.1rem', margin: '4px 0 0', lineHeight: 1.28 }}>
|
<h1 style={{ fontSize: '1.1rem', margin: '4px 0 0', lineHeight: 1.28 }}>
|
||||||
{unit.planned_date}
|
{unit.planned_date}
|
||||||
{unit.planned_time_start && ` · ${String(unit.planned_time_start).slice(0, 5)}`}
|
{unit.planned_time_start && ` · ${String(unit.planned_time_start).slice(0, 5)}`}
|
||||||
{unit.planned_focus ? ` · ${unit.planned_focus}` : ''}
|
{unit.planned_focus ? ` · ${unit.planned_focus}` : ''}
|
||||||
</h1>
|
</h1>
|
||||||
|
{streamFocusOptions.length > 0 ? (
|
||||||
|
<p style={{ fontSize: '0.8rem', color: 'var(--text2)', margin: '8px 0 0', lineHeight: 1.4 }}>
|
||||||
|
Parallele Phasen erscheinen als Schritt <strong>Gruppe wählen</strong> — kein Durcheinander mehr aus
|
||||||
|
verschränkten Streams. Pro paralleler Phase entscheiden Sie (oder der Co-Trainer auf dem eigenen Gerät), welcher
|
||||||
|
Stream coacht wird. Kurzwahl oben springt die betreffende Phase sofort auf einen Stream (z. B. zwischen Gruppen
|
||||||
|
wechseln).
|
||||||
|
{Object.keys(mergedPicks).length > 0 ? (
|
||||||
|
<span style={{ display: 'block', marginTop: '6px', color: 'var(--text3)', fontSize: '0.78rem' }}>
|
||||||
|
Aktuell festgelegt:{' '}
|
||||||
|
{Object.keys(mergedPicks)
|
||||||
|
.map((pk) => {
|
||||||
|
const po = parseInt(pk, 10)
|
||||||
|
const so = mergedPicks[pk]
|
||||||
|
const o = streamFocusOptions.find((x) => x.phaseOrder === po && x.streamOrder === so)
|
||||||
|
return o?.label ?? `Phase ${po} · Stream ${so}`
|
||||||
|
})
|
||||||
|
.join(' · ')}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{outlineOpen && (
|
{outlineOpen && (
|
||||||
<div className="card training-coach-outline" style={{ flexShrink: 0, marginBottom: '8px', padding: '10px 12px', maxHeight: 'min(28vh, 260px)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
<div className="card training-coach-outline" style={{ flexShrink: 0, marginBottom: '8px', padding: '10px 12px', maxHeight: 'min(28vh, 260px)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
||||||
<div style={{ fontSize: '0.75rem', color: 'var(--text3)', marginBottom: '6px', flexShrink: 0 }}>Ablauf · Antippen zum Springen</div>
|
<div style={{ fontSize: '0.75rem', color: 'var(--text3)', marginBottom: '6px', flexShrink: 0 }}>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px', overflowY: 'auto', minHeight: 0 }}>
|
Trainingsrahmen · nach Blöcken und Streams
|
||||||
{timeline.map((ent, ix) => {
|
</div>
|
||||||
const lbl = summarizeTimelineEntry(ent)
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', overflowY: 'auto', minHeight: 0 }}>
|
||||||
const secTitle = ent.sec.title || `Abschnitt ${ent.si + 1}`
|
{outlineGroups.map((grp) => (
|
||||||
const active = coachDebriefPhase ? ix === timeline.length - 1 : ix === step
|
<div key={grp.mergeKey} style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
|
||||||
return (
|
<div
|
||||||
<button
|
|
||||||
key={`${itemStableKey(ent.item, ent.secOrder, ent.ii)}-${ix}`}
|
|
||||||
type="button"
|
|
||||||
className={`btn ${active ? 'btn-primary' : 'btn-secondary'}`}
|
|
||||||
style={{
|
style={{
|
||||||
textAlign: 'left',
|
fontSize: '0.72rem',
|
||||||
justifyContent: 'flex-start',
|
fontWeight: 700,
|
||||||
opacity: active ? 1 : 0.92,
|
color: 'var(--accent-dark)',
|
||||||
fontWeight: active ? 700 : 500
|
textTransform: 'uppercase',
|
||||||
}}
|
letterSpacing: '0.04em',
|
||||||
onClick={() => {
|
|
||||||
setCoachDebriefPhase(false)
|
|
||||||
setStep(ix)
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span style={{ opacity: 0.75 }}>{secTitle.substring(0, 14)} › </span>
|
{grp.heading}
|
||||||
<span>{lbl}</span>
|
{grp.sub ? <span style={{ fontWeight: 600, color: 'var(--text3)', textTransform: 'none' }}> · {grp.sub}</span> : null}
|
||||||
</button>
|
</div>
|
||||||
)
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
|
||||||
})}
|
{grp.entries.map(({ ix, ent }) => {
|
||||||
|
const lbl = summarizeTimelineEntry(ent)
|
||||||
|
const ctx = ent.coachContext || ''
|
||||||
|
const active = coachDebriefPhase ? ix === timeline.length - 1 : ix === safeStep
|
||||||
|
const rowKey =
|
||||||
|
ent.entryKind === COACH_ENTRY_BRANCH_GATE
|
||||||
|
? `gate-${ix}`
|
||||||
|
: `${itemStableKey(ent.item, ent.secOrder, ent.ii)}-${ix}`
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={rowKey}
|
||||||
|
type="button"
|
||||||
|
className={`btn ${active ? 'btn-primary' : 'btn-secondary'}`}
|
||||||
|
style={{
|
||||||
|
textAlign: 'left',
|
||||||
|
justifyContent: 'flex-start',
|
||||||
|
opacity: active ? 1 : 0.92,
|
||||||
|
fontWeight: active ? 700 : 500,
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
setCoachDebriefPhase(false)
|
||||||
|
setStep(ix)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{ctx ? (
|
||||||
|
<span style={{ opacity: 0.8, display: 'block', fontSize: '0.72rem', marginBottom: '2px' }}>
|
||||||
|
{ctx.length > 42 ? `${ctx.slice(0, 40)}…` : ctx}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<span>{lbl}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -567,13 +969,16 @@ export default function TrainingCoachPage() {
|
|||||||
</p>
|
</p>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
|
||||||
{timeline
|
{timeline
|
||||||
.filter((e) => e.item.item_type === 'exercise')
|
.filter((e) => e.item?.item_type === 'exercise')
|
||||||
.map((ent) => {
|
.map((ent) => {
|
||||||
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
|
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
|
||||||
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
|
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
|
||||||
return (
|
return (
|
||||||
<label key={`db-${k}`} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
|
<label key={`db-${k}`} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
|
||||||
<span style={{ wordBreak: 'break-word' }}>{summarizeTimelineEntry(ent)}</span>
|
<span style={{ wordBreak: 'break-word' }}>
|
||||||
|
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
|
||||||
|
{summarizeTimelineEntry(ent)}
|
||||||
|
</span>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min="0"
|
min="0"
|
||||||
@@ -636,6 +1041,8 @@ export default function TrainingCoachPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
{!splitRejoinPrompt ? (
|
||||||
|
<>
|
||||||
<div
|
<div
|
||||||
className="training-coach-assist training-coach-assist--compact"
|
className="training-coach-assist training-coach-assist--compact"
|
||||||
style={{
|
style={{
|
||||||
@@ -649,7 +1056,12 @@ export default function TrainingCoachPage() {
|
|||||||
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
|
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
|
||||||
Als Nächstes
|
Als Nächstes
|
||||||
</div>
|
</div>
|
||||||
{nextEntry ? (
|
{atBranchGate ? (
|
||||||
|
<p style={{ margin: 0, fontSize: '0.88rem', color: 'var(--text2)', lineHeight: 1.45 }}>
|
||||||
|
Wählen Sie unten eine Gruppe. Danach zeigt der Coach fortlaufend nur die Übungen dieses Streams in dieser
|
||||||
|
parallelen Phase.
|
||||||
|
</p>
|
||||||
|
) : nextEntry ? (
|
||||||
<>
|
<>
|
||||||
<p style={{ margin: '0', fontSize: '0.9rem', color: 'var(--text1)', lineHeight: 1.4 }}>
|
<p style={{ margin: '0', fontSize: '0.9rem', color: 'var(--text1)', lineHeight: 1.4 }}>
|
||||||
<strong>Nächste:</strong> {summarizeTimelineEntry(nextEntry)}
|
<strong>Nächste:</strong> {summarizeTimelineEntry(nextEntry)}
|
||||||
@@ -668,7 +1080,7 @@ export default function TrainingCoachPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CoachControlsBand
|
<CoachControlsBand
|
||||||
step={step}
|
step={safeStep}
|
||||||
timelineLength={timeline.length}
|
timelineLength={timeline.length}
|
||||||
onPrev={goPrev}
|
onPrev={goPrev}
|
||||||
onNext={goNext}
|
onNext={goNext}
|
||||||
@@ -684,15 +1096,99 @@ export default function TrainingCoachPage() {
|
|||||||
isLastCoachStep={isLastCoachStep}
|
isLastCoachStep={isLastCoachStep}
|
||||||
showJumpToTimerOwner={showJumpToTimerOwner}
|
showJumpToTimerOwner={showJumpToTimerOwner}
|
||||||
showJumpToTimerOwnerRow
|
showJumpToTimerOwnerRow
|
||||||
onJumpToTimerOwner={() => setStep(timerOwningStep ?? step)}
|
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
|
||||||
timerOwnerLabelIndex={timerOwningStep ?? 0}
|
timerOwnerLabelIndex={timerOwningStep ?? 0}
|
||||||
|
branchGateMode={atBranchGate}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="training-coach-scroll">
|
<div className="training-coach-scroll">
|
||||||
{currentEntry?.item?.item_type === 'note' ? (
|
{atBranchGate && currentEntry?.branchMeta ? (
|
||||||
|
<div
|
||||||
|
className="card"
|
||||||
|
style={{
|
||||||
|
padding: '18px 16px',
|
||||||
|
marginBottom: '12px',
|
||||||
|
borderRadius: '14px',
|
||||||
|
border: '2px solid var(--accent)',
|
||||||
|
background: 'linear-gradient(180deg, var(--accent-light) 0%, var(--surface) 38%)',
|
||||||
|
boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontSize: '0.74rem', fontWeight: 800, color: 'var(--accent-dark)', marginBottom: '6px', letterSpacing: '0.04em' }}>
|
||||||
|
⑂ SPLIT — GRUPPE WÄHLEN
|
||||||
|
</div>
|
||||||
|
<p style={{ fontSize: '1.05rem', fontWeight: 800, margin: '0 0 8px', color: 'var(--text1)' }}>
|
||||||
|
{currentEntry.branchMeta.phaseTitle != null && String(currentEntry.branchMeta.phaseTitle).trim()
|
||||||
|
? String(currentEntry.branchMeta.phaseTitle).trim()
|
||||||
|
: `Phase ${currentEntry.branchMeta.phaseOrderIndex}`}
|
||||||
|
</p>
|
||||||
|
<p style={{ fontSize: '0.88rem', color: 'var(--text2)', margin: '0 0 16px', lineHeight: 1.45 }}>
|
||||||
|
Tippen Sie auf eine Kachel, um <strong>diese Gruppe</strong> zu coachen. Andere Trainer:innen wählen auf
|
||||||
|
ihrem Gerät parallel eine andere Kachel.
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '12px' }}>
|
||||||
|
{(currentEntry.branchMeta.streams || []).map((st) => {
|
||||||
|
const hinted =
|
||||||
|
streamChoiceHint?.phaseOrder === currentEntry.branchMeta.phaseOrderIndex &&
|
||||||
|
streamChoiceHint?.streamOrder === st.streamOrder
|
||||||
|
const label = st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`
|
||||||
|
const baseBg = hinted ? 'var(--accent)' : 'var(--surface2)'
|
||||||
|
const baseColor = hinted ? '#fff' : 'var(--text1)'
|
||||||
|
const borderCol = hinted ? 'var(--accent-dark)' : 'var(--border)'
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={st.printStreamId || `s-${st.streamOrder}`}
|
||||||
|
type="button"
|
||||||
|
className="btn"
|
||||||
|
style={{
|
||||||
|
textAlign: 'left',
|
||||||
|
justifyContent: 'flex-start',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'stretch',
|
||||||
|
padding: '14px 16px',
|
||||||
|
minHeight: '96px',
|
||||||
|
fontWeight: 700,
|
||||||
|
background: baseBg,
|
||||||
|
color: baseColor,
|
||||||
|
border: `2px solid ${borderCol}`,
|
||||||
|
borderRadius: '12px',
|
||||||
|
boxShadow: hinted ? '0 4px 0 var(--accent-dark)' : '0 3px 0 hsl(200 20% 78%)',
|
||||||
|
transition: 'transform 0.08s ease, box-shadow 0.08s ease',
|
||||||
|
}}
|
||||||
|
onClick={() => pickStreamForPhase(currentEntry.branchMeta.phaseOrderIndex, st.streamOrder)}
|
||||||
|
>
|
||||||
|
<span style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '1rem' }}>
|
||||||
|
<span style={{ fontSize: '1.35rem', lineHeight: 1 }} aria-hidden="true">
|
||||||
|
{hinted ? '◉' : '○'}
|
||||||
|
</span>
|
||||||
|
<span>{label}</span>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
display: 'block',
|
||||||
|
fontSize: '0.82rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
opacity: hinted ? 0.95 : 0.88,
|
||||||
|
marginTop: '8px',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
≈ {st.minutes} Min. Üb. · Jetzt aktivieren
|
||||||
|
</span>
|
||||||
|
{hinted ? (
|
||||||
|
<span style={{ display: 'block', fontSize: '0.74rem', fontWeight: 600, marginTop: '8px', opacity: 0.92 }}>
|
||||||
|
Vorschlag aus Planansicht — trotzdem andere Kachel möglich
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : currentEntry?.item?.item_type === 'note' ? (
|
||||||
<div className="card" style={{ padding: '16px 14px' }}>
|
<div className="card" style={{ padding: '16px 14px' }}>
|
||||||
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '8px' }}>
|
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '8px' }}>
|
||||||
{currentEntry.sec.title || 'Abschnitt'} · Coach-Notiz · Teil {step + 1}
|
{currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Coach-Notiz · Teil{' '}
|
||||||
|
{safeStep + 1}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginBottom: '6px' }}>Coach-Notiz</div>
|
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginBottom: '6px' }}>Coach-Notiz</div>
|
||||||
<p style={{ fontSize: '1.05rem', lineHeight: 1.52, whiteSpace: 'pre-wrap', margin: 0 }}>{currentEntry.item.note_body || ''}</p>
|
<p style={{ fontSize: '1.05rem', lineHeight: 1.52, whiteSpace: 'pre-wrap', margin: 0 }}>{currentEntry.item.note_body || ''}</p>
|
||||||
@@ -701,7 +1197,8 @@ export default function TrainingCoachPage() {
|
|||||||
<>
|
<>
|
||||||
<div className="card training-coach-plan-strip" style={{ padding: '12px 14px', marginBottom: '12px', borderRadius: '12px', borderLeft: `3px solid var(--accent)` }}>
|
<div className="card training-coach-plan-strip" style={{ padding: '12px 14px', marginBottom: '12px', borderRadius: '12px', borderLeft: `3px solid var(--accent)` }}>
|
||||||
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '6px' }}>
|
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '6px' }}>
|
||||||
In diesem Training · {currentEntry?.sec.title || 'Abschnitt'} · Teil {step + 1}
|
In diesem Training · {currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Teil{' '}
|
||||||
|
{safeStep + 1}
|
||||||
</div>
|
</div>
|
||||||
{currentEntry?.item && (
|
{currentEntry?.item && (
|
||||||
<>
|
<>
|
||||||
@@ -789,13 +1286,16 @@ export default function TrainingCoachPage() {
|
|||||||
</p>
|
</p>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
|
||||||
{timeline
|
{timeline
|
||||||
.filter((e) => e.item.item_type === 'exercise')
|
.filter((e) => e.item?.item_type === 'exercise')
|
||||||
.map((ent) => {
|
.map((ent) => {
|
||||||
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
|
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
|
||||||
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
|
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
|
||||||
return (
|
return (
|
||||||
<label key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
|
<label key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
|
||||||
<span style={{ wordBreak: 'break-word' }}>{summarizeTimelineEntry(ent)}</span>
|
<span style={{ wordBreak: 'break-word' }}>
|
||||||
|
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
|
||||||
|
{summarizeTimelineEntry(ent)}
|
||||||
|
</span>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min="0"
|
min="0"
|
||||||
@@ -841,7 +1341,7 @@ export default function TrainingCoachPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CoachControlsBand
|
<CoachControlsBand
|
||||||
step={step}
|
step={safeStep}
|
||||||
timelineLength={timeline.length}
|
timelineLength={timeline.length}
|
||||||
onPrev={goPrev}
|
onPrev={goPrev}
|
||||||
onNext={goNext}
|
onNext={goNext}
|
||||||
@@ -857,9 +1357,12 @@ export default function TrainingCoachPage() {
|
|||||||
isLastCoachStep={isLastCoachStep}
|
isLastCoachStep={isLastCoachStep}
|
||||||
showJumpToTimerOwner={showJumpToTimerOwner}
|
showJumpToTimerOwner={showJumpToTimerOwner}
|
||||||
showJumpToTimerOwnerRow={false}
|
showJumpToTimerOwnerRow={false}
|
||||||
onJumpToTimerOwner={() => setStep(timerOwningStep ?? step)}
|
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
|
||||||
timerOwnerLabelIndex={timerOwningStep ?? 0}
|
timerOwnerLabelIndex={timerOwningStep ?? 0}
|
||||||
|
branchGateMode={atBranchGate}
|
||||||
/>
|
/>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import ExercisePickerModal from '../components/ExercisePickerModal'
|
|||||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||||
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
|
||||||
import PageSectionNav from '../components/PageSectionNav'
|
import PageSectionNav from '../components/PageSectionNav'
|
||||||
|
import FormActionBar from '../components/FormActionBar'
|
||||||
import { useToast } from '../context/ToastContext'
|
import { useToast } from '../context/ToastContext'
|
||||||
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
|
||||||
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
|
||||||
@@ -12,8 +13,12 @@ import {
|
|||||||
defaultSection,
|
defaultSection,
|
||||||
normalizeUnitToForm,
|
normalizeUnitToForm,
|
||||||
enrichSectionsWithVariants,
|
enrichSectionsWithVariants,
|
||||||
buildSectionsPayload,
|
buildPlanPayloadForSave,
|
||||||
hydrateExercisePlanningRow,
|
hydrateExercisePlanningRow,
|
||||||
|
reorderBlockIntoParallelStreamEnd,
|
||||||
|
indicesOfParallelPhase,
|
||||||
|
reorderSectionBeforeParallelRunAsWholeGroup,
|
||||||
|
reorderSectionAsFirstInParallelStream,
|
||||||
} from '../utils/trainingUnitSectionsForm'
|
} from '../utils/trainingUnitSectionsForm'
|
||||||
|
|
||||||
const DND_FW_SLOT = 'application/x-shinkan-framework-slot'
|
const DND_FW_SLOT = 'application/x-shinkan-framework-slot'
|
||||||
@@ -47,10 +52,10 @@ function emptySlot() {
|
|||||||
async function enrichFrameworkSlotSections(slots) {
|
async function enrichFrameworkSlotSections(slots) {
|
||||||
const out = []
|
const out = []
|
||||||
for (const s of slots || []) {
|
for (const s of slots || []) {
|
||||||
const sec = normalizeUnitToForm({ sections: s.sections, exercises: s.exercises })
|
const baseSecs = s.sections && s.sections.length ? s.sections : [defaultSection('Ablauf')]
|
||||||
out.push({
|
out.push({
|
||||||
...s,
|
...s,
|
||||||
sections: await enrichSectionsWithVariants(sec),
|
sections: await enrichSectionsWithVariants(baseSecs),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
@@ -131,7 +136,11 @@ function serverFrameworkToForm(fw) {
|
|||||||
slots: (fw.slots || []).map((s) => ({
|
slots: (fw.slots || []).map((s) => ({
|
||||||
title: s.title || '',
|
title: s.title || '',
|
||||||
notes: s.notes || '',
|
notes: s.notes || '',
|
||||||
sections: normalizeUnitToForm({ sections: s.sections, exercises: s.exercises }),
|
sections: normalizeUnitToForm({
|
||||||
|
sections: s.sections,
|
||||||
|
exercises: s.exercises,
|
||||||
|
phases: s.phases,
|
||||||
|
}),
|
||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -150,13 +159,16 @@ function buildApiPayload(form) {
|
|||||||
|
|
||||||
const slots = (form.slots || []).map((s, si) => {
|
const slots = (form.slots || []).map((s, si) => {
|
||||||
const secList = s.sections && s.sections.length ? s.sections : [defaultSection('Ablauf')]
|
const secList = s.sections && s.sections.length ? s.sections : [defaultSection('Ablauf')]
|
||||||
const sectionsPayload = buildSectionsPayload(secList)
|
const plan = buildPlanPayloadForSave(secList)
|
||||||
return {
|
const base = {
|
||||||
sort_order: si,
|
sort_order: si,
|
||||||
title: (s.title || '').trim() || null,
|
title: (s.title || '').trim() || null,
|
||||||
notes: (s.notes || '').trim() || null,
|
notes: (s.notes || '').trim() || null,
|
||||||
sections: sectionsPayload,
|
|
||||||
}
|
}
|
||||||
|
if (plan.phases) {
|
||||||
|
return { ...base, phases: plan.phases }
|
||||||
|
}
|
||||||
|
return { ...base, sections: plan.sections }
|
||||||
})
|
})
|
||||||
|
|
||||||
const focusAreaId =
|
const focusAreaId =
|
||||||
@@ -416,7 +428,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
const performFrameworkSave = async ({ fromUnsavedDialog = false } = {}) => {
|
const performFrameworkSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
|
||||||
if (!(form.title || '').trim()) {
|
if (!(form.title || '').trim()) {
|
||||||
toast.error('Titel ist Pflichtfeld.')
|
toast.error('Titel ist Pflichtfeld.')
|
||||||
return false
|
return false
|
||||||
@@ -437,7 +449,9 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
if (isNew) {
|
if (isNew) {
|
||||||
const created = await api.createTrainingFrameworkProgram(payload)
|
const created = await api.createTrainingFrameworkProgram(payload)
|
||||||
toast.success('Rahmenprogramm angelegt.')
|
toast.success('Rahmenprogramm angelegt.')
|
||||||
if (!fromUnsavedDialog) {
|
if (closeAfter) {
|
||||||
|
navigate('/planning/framework-programs')
|
||||||
|
} else if (!fromUnsavedDialog) {
|
||||||
navigate(`/planning/framework-programs/${created.id}`, { replace: true })
|
navigate(`/planning/framework-programs/${created.id}`, { replace: true })
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -452,6 +466,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
setBypassDirty(false)
|
setBypassDirty(false)
|
||||||
setBaselineReady(true)
|
setBaselineReady(true)
|
||||||
toast.success('Gespeichert.')
|
toast.success('Gespeichert.')
|
||||||
|
if (closeAfter) navigate('/planning/framework-programs')
|
||||||
return true
|
return true
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error(e.message || 'Speichern fehlgeschlagen')
|
toast.error(e.message || 'Speichern fehlgeschlagen')
|
||||||
@@ -462,7 +477,11 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
await performFrameworkSave({ fromUnsavedDialog: false })
|
await performFrameworkSave({ fromUnsavedDialog: false, closeAfter: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSaveAndClose = async () => {
|
||||||
|
await performFrameworkSave({ fromUnsavedDialog: false, closeAfter: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleUnsavedDialogSave = async () => {
|
const handleUnsavedDialogSave = async () => {
|
||||||
@@ -553,7 +572,17 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const moveSectionsAcrossFrameworkSlots = useCallback(
|
const moveSectionsAcrossFrameworkSlots = useCallback(
|
||||||
({ fromSlot, fromSectionIdx, toSlot, toSectionIdx }) => {
|
(payload) => {
|
||||||
|
const {
|
||||||
|
fromSlot,
|
||||||
|
fromSectionIdx,
|
||||||
|
toSlot,
|
||||||
|
toSectionIdx,
|
||||||
|
toParallelStream,
|
||||||
|
parallelPhaseRunOrderIndex,
|
||||||
|
insertBeforeParallelInTarget,
|
||||||
|
firstInParallelStreamInTarget,
|
||||||
|
} = payload
|
||||||
setForm((prev) => {
|
setForm((prev) => {
|
||||||
const slots = prev.slots.map((sl) => ({
|
const slots = prev.slots.map((sl) => ({
|
||||||
...sl,
|
...sl,
|
||||||
@@ -571,6 +600,44 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fromSecs = slots[fromSlot].sections
|
const fromSecs = slots[fromSlot].sections
|
||||||
|
const toSecs = slots[toSlot].sections
|
||||||
|
|
||||||
|
const applyParallelStreamEnd =
|
||||||
|
toParallelStream != null && toParallelStream.po != null && toParallelStream.so != null
|
||||||
|
? (secs, insertedAt) => {
|
||||||
|
const po = Number(toParallelStream.po) || 0
|
||||||
|
const so = Number(toParallelStream.so) || 0
|
||||||
|
return reorderBlockIntoParallelStreamEnd(secs, insertedAt, po, so)
|
||||||
|
}
|
||||||
|
: null
|
||||||
|
|
||||||
|
/** Gesamten Parallel-Lauf aus fromSlot an toSectionIdx in toSlot legen */
|
||||||
|
if (parallelPhaseRunOrderIndex != null && parallelPhaseRunOrderIndex !== '') {
|
||||||
|
const po = Number(parallelPhaseRunOrderIndex) || 0
|
||||||
|
const idxs = indicesOfParallelPhase(fromSecs, po)
|
||||||
|
if (!idxs.length) {
|
||||||
|
return prev
|
||||||
|
}
|
||||||
|
const blocks = idxs.map((i) => fromSecs[i])
|
||||||
|
for (const i of [...idxs].sort((a, b) => b - a)) {
|
||||||
|
fromSecs.splice(i, 1)
|
||||||
|
}
|
||||||
|
if (fromSlot === toSlot) {
|
||||||
|
let insertAt = Number(toSectionIdx) || 0
|
||||||
|
for (const i of idxs) {
|
||||||
|
if (i < insertAt) insertAt -= 1
|
||||||
|
}
|
||||||
|
insertAt = Math.max(0, Math.min(insertAt, fromSecs.length))
|
||||||
|
fromSecs.splice(insertAt, 0, ...blocks)
|
||||||
|
slots[fromSlot].sections = fromSecs
|
||||||
|
return { ...prev, slots }
|
||||||
|
}
|
||||||
|
const insertAt = Math.max(0, Math.min(Number(toSectionIdx) || 0, toSecs.length))
|
||||||
|
toSecs.splice(insertAt, 0, ...blocks)
|
||||||
|
slots[toSlot].sections = toSecs
|
||||||
|
return { ...prev, slots }
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
typeof fromSectionIdx !== 'number' ||
|
typeof fromSectionIdx !== 'number' ||
|
||||||
fromSectionIdx < 0 ||
|
fromSectionIdx < 0 ||
|
||||||
@@ -586,12 +653,48 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
if (fromSectionIdx < toSectionIdx) insertAt = toSectionIdx - 1
|
if (fromSectionIdx < toSectionIdx) insertAt = toSectionIdx - 1
|
||||||
insertAt = Math.max(0, Math.min(insertAt, fromSecs.length))
|
insertAt = Math.max(0, Math.min(insertAt, fromSecs.length))
|
||||||
fromSecs.splice(insertAt, 0, block)
|
fromSecs.splice(insertAt, 0, block)
|
||||||
|
if (applyParallelStreamEnd) {
|
||||||
|
slots[fromSlot].sections = applyParallelStreamEnd(fromSecs, insertAt)
|
||||||
|
} else {
|
||||||
|
slots[fromSlot].sections = fromSecs
|
||||||
|
}
|
||||||
|
return { ...prev, slots }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (insertBeforeParallelInTarget != null && insertBeforeParallelInTarget !== '') {
|
||||||
|
const tpo = Number(insertBeforeParallelInTarget) || 0
|
||||||
|
const pIdxs = indicesOfParallelPhase(toSecs, tpo)
|
||||||
|
const ins = pIdxs.length ? pIdxs[0] : toSecs.length
|
||||||
|
toSecs.splice(ins, 0, block)
|
||||||
|
slots[toSlot].sections = reorderSectionBeforeParallelRunAsWholeGroup(toSecs, ins, tpo)
|
||||||
|
return { ...prev, slots }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
firstInParallelStreamInTarget != null &&
|
||||||
|
firstInParallelStreamInTarget.po != null &&
|
||||||
|
firstInParallelStreamInTarget.so != null
|
||||||
|
) {
|
||||||
|
const fpo = Number(firstInParallelStreamInTarget.po) || 0
|
||||||
|
const fso = Number(firstInParallelStreamInTarget.so) || 0
|
||||||
|
const nextSecs = [...toSecs, block]
|
||||||
|
const movedFromI = nextSecs.length - 1
|
||||||
|
slots[toSlot].sections = reorderSectionAsFirstInParallelStream(
|
||||||
|
nextSecs,
|
||||||
|
movedFromI,
|
||||||
|
fpo,
|
||||||
|
fso
|
||||||
|
)
|
||||||
return { ...prev, slots }
|
return { ...prev, slots }
|
||||||
}
|
}
|
||||||
|
|
||||||
const toSecs = slots[toSlot].sections
|
|
||||||
const ia = Math.max(0, Math.min(toSectionIdx, toSecs.length))
|
const ia = Math.max(0, Math.min(toSectionIdx, toSecs.length))
|
||||||
toSecs.splice(ia, 0, block)
|
toSecs.splice(ia, 0, block)
|
||||||
|
if (applyParallelStreamEnd) {
|
||||||
|
slots[toSlot].sections = applyParallelStreamEnd(toSecs, ia)
|
||||||
|
} else {
|
||||||
|
slots[toSlot].sections = toSecs
|
||||||
|
}
|
||||||
return { ...prev, slots }
|
return { ...prev, slots }
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -694,6 +797,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
showExecutionExtras={false}
|
showExecutionExtras={false}
|
||||||
wideExerciseGrid
|
wideExerciseGrid
|
||||||
slotIndex={si}
|
slotIndex={si}
|
||||||
|
enableParallelPhaseControls
|
||||||
onMoveSectionsAcrossSlots={moveSectionsAcrossFrameworkSlots}
|
onMoveSectionsAcrossSlots={moveSectionsAcrossFrameworkSlots}
|
||||||
onSectionsChange={(updater) => {
|
onSectionsChange={(updater) => {
|
||||||
setForm((prev) => ({
|
setForm((prev) => ({
|
||||||
@@ -758,7 +862,7 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
<strong style={{ color: 'var(--text1)' }}>Rahmenprogramm (Bibliothek):</strong> Wiederverwendbare Vorlage mit
|
<strong style={{ color: 'var(--text1)' }}>Rahmenprogramm (Bibliothek):</strong> Wiederverwendbare Vorlage mit
|
||||||
Zielen und Session‑Slots. Die <strong>Zuordnung zu Gruppe oder Kalendertermin</strong> erfolgt aus der{' '}
|
Zielen und Session‑Slots. Die <strong>Zuordnung zu Gruppe oder Kalendertermin</strong> erfolgt aus der{' '}
|
||||||
<strong>Gruppen‑Planung</strong> („Übernahme“). Pro Slot planst du den Ablauf wie bei einer Trainingsseinheit:{' '}
|
<strong>Gruppen‑Planung</strong> („Übernahme“). Pro Slot planst du den Ablauf wie bei einer Trainingsseinheit:{' '}
|
||||||
<strong>Abschnitte</strong>, Übungen mit Varianten und Dauer, <strong>Zwischen‑Anmerkungen</strong>.
|
<strong>Abschnitte</strong>, optional <strong>Ganzgruppen- und parallele Phasen (Breakout)</strong>, Übungen mit Varianten und Dauer, <strong>Zwischen‑Anmerkungen</strong>. Abschnitte kannst du per Ziehen auch in eine andere Session legen.
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@@ -1154,19 +1258,19 @@ export default function TrainingFrameworkProgramEditPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', alignItems: 'center' }}>
|
<FormActionBar
|
||||||
<button type="button" className="btn btn-primary" disabled={saving} onClick={handleSave}>
|
isNew={isNew}
|
||||||
{saving ? 'Speichern…' : isNew ? 'Anlegen' : 'Speichern'}
|
saving={saving}
|
||||||
|
onSave={handleSave}
|
||||||
|
onSaveAndClose={handleSaveAndClose}
|
||||||
|
onCancel={() => navigate('/planning/framework-programs')}
|
||||||
|
cancelLabel="Abbrechen"
|
||||||
|
/>
|
||||||
|
{!isNew ? (
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={handleDelete} style={{ marginTop: '10px' }}>
|
||||||
|
Löschen
|
||||||
</button>
|
</button>
|
||||||
<Link to="/planning/framework-programs" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
|
) : null}
|
||||||
Abbrechen
|
|
||||||
</Link>
|
|
||||||
{!isNew ? (
|
|
||||||
<button type="button" className="btn btn-secondary" onClick={handleDelete}>
|
|
||||||
Löschen
|
|
||||||
</button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ExercisePickerModal
|
<ExercisePickerModal
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ export default function TrainingFrameworkProgramsListPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-page">
|
<>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -108,11 +108,8 @@ export default function TrainingFrameworkProgramsListPage() {
|
|||||||
Trainingsrahmenprogramme
|
Trainingsrahmenprogramme
|
||||||
</h1>
|
</h1>
|
||||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '36rem', margin: 0 }}>
|
<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{' '}
|
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 (Registerkarte oben).
|
||||||
Trainingsplanung
|
|
||||||
</Link>
|
|
||||||
.
|
|
||||||
</p>
|
</p>
|
||||||
<details className="planning-filter-help" style={{ marginTop: '10px', maxWidth: '36rem' }}>
|
<details className="planning-filter-help" style={{ marginTop: '10px', maxWidth: '36rem' }}>
|
||||||
<summary className="planning-filter-help__summary">Mehr zur Übernahme in die Planung</summary>
|
<summary className="planning-filter-help__summary">Mehr zur Übernahme in die Planung</summary>
|
||||||
@@ -131,12 +128,6 @@ export default function TrainingFrameworkProgramsListPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p style={{ marginBottom: '1rem' }}>
|
|
||||||
<Link to="/planning" style={{ color: 'var(--accent-dark)' }}>
|
|
||||||
← Zurück zur Trainingsplanung
|
|
||||||
</Link>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="card" style={{ borderLeft: '4px solid var(--danger)', marginBottom: '1rem' }}>
|
<div className="card" style={{ borderLeft: '4px solid var(--danger)', marginBottom: '1rem' }}>
|
||||||
{error}
|
{error}
|
||||||
@@ -207,6 +198,6 @@ export default function TrainingFrameworkProgramsListPage() {
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|||||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import ExercisePickerModal from '../components/ExercisePickerModal'
|
import ExercisePickerModal from '../components/ExercisePickerModal'
|
||||||
|
import FormActionBar from '../components/FormActionBar'
|
||||||
import { hydrateExercisePlanningRow } from '../utils/trainingUnitSectionsForm'
|
import { hydrateExercisePlanningRow } from '../utils/trainingUnitSectionsForm'
|
||||||
import { useAuth } from '../context/AuthContext'
|
import { useAuth } from '../context/AuthContext'
|
||||||
import { useToast } from '../context/ToastContext'
|
import { useToast } from '../context/ToastContext'
|
||||||
@@ -301,7 +302,7 @@ export default function TrainingModuleEditPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const performModuleSave = async ({ fromUnsavedDialog = false } = {}) => {
|
const performModuleSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
|
||||||
if (!title.trim()) {
|
if (!title.trim()) {
|
||||||
toast.error('Titel ist Pflicht.')
|
toast.error('Titel ist Pflicht.')
|
||||||
return false
|
return false
|
||||||
@@ -313,7 +314,9 @@ export default function TrainingModuleEditPage() {
|
|||||||
if (isNew) {
|
if (isNew) {
|
||||||
const created = await api.createTrainingModule(body)
|
const created = await api.createTrainingModule(body)
|
||||||
toast.success('Trainingsmodul angelegt.')
|
toast.success('Trainingsmodul angelegt.')
|
||||||
if (!fromUnsavedDialog) {
|
if (closeAfter) {
|
||||||
|
navigate('/planning/training-modules')
|
||||||
|
} else if (!fromUnsavedDialog) {
|
||||||
navigate(`/planning/training-modules/${created.id}`, { replace: true })
|
navigate(`/planning/training-modules/${created.id}`, { replace: true })
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -322,6 +325,7 @@ export default function TrainingModuleEditPage() {
|
|||||||
baselineRef.current = moduleFormSnapshot(latestFormRef.current)
|
baselineRef.current = moduleFormSnapshot(latestFormRef.current)
|
||||||
setBypassDirty(false)
|
setBypassDirty(false)
|
||||||
toast.success('Gespeichert.')
|
toast.success('Gespeichert.')
|
||||||
|
if (closeAfter) navigate('/planning/training-modules')
|
||||||
return true
|
return true
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const msg = err.message || 'Speichern fehlgeschlagen'
|
const msg = err.message || 'Speichern fehlgeschlagen'
|
||||||
@@ -334,8 +338,12 @@ export default function TrainingModuleEditPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleSave = async (e) => {
|
const handleSave = async (e) => {
|
||||||
e.preventDefault()
|
e?.preventDefault?.()
|
||||||
await performModuleSave({ fromUnsavedDialog: false })
|
await performModuleSave({ fromUnsavedDialog: false, closeAfter: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSaveAndClose = async () => {
|
||||||
|
await performModuleSave({ fromUnsavedDialog: false, closeAfter: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleUnsavedDialogSave = async () => {
|
const handleUnsavedDialogSave = async () => {
|
||||||
@@ -367,7 +375,13 @@ export default function TrainingModuleEditPage() {
|
|||||||
{loading ? (
|
{loading ? (
|
||||||
<p style={{ color: 'var(--text2)' }}>Laden …</p>
|
<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">
|
||||||
<div className="form-row">
|
<div className="form-row">
|
||||||
<label className="form-label">Titel *</label>
|
<label className="form-label">Titel *</label>
|
||||||
<input className="form-input" value={title} onChange={(e) => setTitle(e.target.value)} />
|
<input className="form-input" value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||||
@@ -648,14 +662,17 @@ export default function TrainingModuleEditPage() {
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</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>
|
</div>
|
||||||
|
|
||||||
|
<FormActionBar
|
||||||
|
formId="training-module-form"
|
||||||
|
isNew={isNew}
|
||||||
|
saving={saving}
|
||||||
|
onSave={() => handleSave()}
|
||||||
|
onSaveAndClose={handleSaveAndClose}
|
||||||
|
onCancel={() => navigate('/planning/training-modules')}
|
||||||
|
cancelLabel="Abbrechen"
|
||||||
|
/>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export default function TrainingModulesListPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-page">
|
<>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -56,11 +56,8 @@ export default function TrainingModulesListPage() {
|
|||||||
Trainingsmodule
|
Trainingsmodule
|
||||||
</h1>
|
</h1>
|
||||||
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '38rem', margin: 0 }}>
|
<p style={{ color: 'var(--text2)', fontSize: '0.95rem', maxWidth: '38rem', margin: 0 }}>
|
||||||
Wiederverwendbare Übungsfolgen für die{' '}
|
Wiederverwendbare Übungsfolgen für die Trainingsplanung. Übernahme in eine Einheit erfolgt dort als
|
||||||
<Link to="/planning" style={{ fontWeight: 600, color: 'var(--accent-dark)' }}>
|
lokale Kopie (mit Herkunftsmarkierung).
|
||||||
Trainingsplanung
|
|
||||||
</Link>
|
|
||||||
. Übernahme in eine Einheit erfolgt dort als lokale Kopie (mit Herkunftsmarkierung).
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link to="/planning/training-modules/new" className="btn btn-primary" style={{ textDecoration: 'none' }}>
|
<Link to="/planning/training-modules/new" className="btn btn-primary" style={{ textDecoration: 'none' }}>
|
||||||
@@ -130,6 +127,6 @@ export default function TrainingModulesListPage() {
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { Link, 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 {
|
||||||
|
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 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) navigate('/planning/plan-templates')
|
||||||
|
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">
|
||||||
|
<p style={{ marginBottom: '0.75rem' }}>
|
||||||
|
<Link to="/planning/plan-templates" style={{ color: 'var(--accent-dark)', fontWeight: 600 }}>
|
||||||
|
← Zurück zu Vorlagen
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<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={() => navigate('/planning/plan-templates')}
|
||||||
|
onSaveAndClose={handleSaveAndClose}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<UnsavedChangesPrompt
|
||||||
|
blocker={blocker}
|
||||||
|
isBusy={saving}
|
||||||
|
onSave={handleUnsavedDialogSave}
|
||||||
|
onDiscardWithoutSave={() => setBypassDirty(true)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import api from '../utils/api'
|
||||||
|
import { useAuth } from '../context/AuthContext'
|
||||||
|
import { useToast } from '../context/ToastContext'
|
||||||
|
import { getTenantClubDependencyKey } from '../utils/activeClub'
|
||||||
|
import { canDeleteLibraryContent, canEditLibraryContent } from '../utils/libraryContentPermissions'
|
||||||
|
import PlanTemplateStructurePreview from '../components/planning/PlanTemplateStructurePreview'
|
||||||
|
|
||||||
|
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 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 ? (
|
||||||
|
<Link
|
||||||
|
to={`/planning/plan-templates/${t.id}`}
|
||||||
|
style={{
|
||||||
|
fontWeight: 700,
|
||||||
|
fontSize: '1rem',
|
||||||
|
color: 'var(--accent-dark)',
|
||||||
|
textDecoration: 'none',
|
||||||
|
wordBreak: 'break-word',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{(t.name || '').trim() || `Vorlage #${t.id}`}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<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 ? (
|
||||||
|
<Link
|
||||||
|
className="btn btn-secondary"
|
||||||
|
style={{ textDecoration: 'none' }}
|
||||||
|
to={`/planning/plan-templates/${t.id}`}
|
||||||
|
>
|
||||||
|
Bearbeiten
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<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,794 @@
|
|||||||
|
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, planningHubPathFromReturnState } from '../utils/planningUnitRoutes'
|
||||||
|
|
||||||
|
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(() => {
|
||||||
|
navigate(planningHubPathFromReturnState(location.state?.planningReturn))
|
||||||
|
}, [location.state, navigate])
|
||||||
|
|
||||||
|
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 = planningHubPathFromReturnState(location.state?.planningReturn)
|
||||||
|
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}
|
||||||
|
backTo={hubBackPath}
|
||||||
|
backLabel="Trainingsplanung"
|
||||||
|
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}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SaveExercisesAsModuleModal
|
||||||
|
open={saveModuleOpen}
|
||||||
|
onClose={() => setSaveModuleOpen(false)}
|
||||||
|
onSuccess={() => setSaveModuleOpen(false)}
|
||||||
|
unitId={editingUnit?.id}
|
||||||
|
planningModalClubId={planningClubId}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
/**
|
/**
|
||||||
* Trainingsablauf anzeigen, drucken und lokal auf der Matte abhaken (Fortschritt im Browser gespeichert).
|
* Trainingsablauf anzeigen, drucken und lokal auf der Matte abhaken (Fortschritt im Browser gespeichert).
|
||||||
* Parallele Streams: rendering nutzt sortedSections/sortedItems (trainingPlanUtils); Fortschritt pro unitId — später ggf. pro Stream.
|
* Phasen: Ganzgruppe vs. Split (planLoc); Druck mit optional getrennten Breakout-Seiten.
|
||||||
*/
|
*/
|
||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||||
import api from '../utils/api'
|
import api from '../utils/api'
|
||||||
import ExercisePeekModal from '../components/ExercisePeekModal'
|
import ExercisePeekModal from '../components/ExercisePeekModal'
|
||||||
import CombinationPlanBracket from '../components/CombinationPlanBracket'
|
import CombinationPlanBracket from '../components/CombinationPlanBracket'
|
||||||
import { itemStableKey, sortedSections, sortedItems } from '../utils/trainingPlanUtils'
|
import {
|
||||||
|
buildPlanRunViewModelFromSections,
|
||||||
|
itemStableKey,
|
||||||
|
sectionsWithPlanLocForDisplay,
|
||||||
|
sortedItems,
|
||||||
|
} from '../utils/trainingPlanUtils'
|
||||||
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
|
||||||
|
|
||||||
function storageKey(unitId) {
|
function storageKey(unitId) {
|
||||||
@@ -37,6 +42,8 @@ export default function TrainingUnitRunPage() {
|
|||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [checked, setChecked] = useState(() => new Set())
|
const [checked, setChecked] = useState(() => new Set())
|
||||||
const [peekCtx, setPeekCtx] = useState(null)
|
const [peekCtx, setPeekCtx] = useState(null)
|
||||||
|
/** null | printStreamId z. B. p0-s1 — nur dieser Split-Stream in @media print */
|
||||||
|
const [printOnlyStreamId, setPrintOnlyStreamId] = useState(null)
|
||||||
|
|
||||||
const loadChecked = useCallback((uid) => {
|
const loadChecked = useCallback((uid) => {
|
||||||
try {
|
try {
|
||||||
@@ -108,20 +115,245 @@ export default function TrainingUnitRunPage() {
|
|||||||
}
|
}
|
||||||
}, [idNum, persistChecked])
|
}, [idNum, persistChecked])
|
||||||
|
|
||||||
const sections = useMemo(() => sortedSections(unit), [unit])
|
const sections = useMemo(() => sectionsWithPlanLocForDisplay(unit), [unit])
|
||||||
|
const planModel = useMemo(() => buildPlanRunViewModelFromSections(sections), [sections])
|
||||||
|
|
||||||
const totalPlannedMin = useMemo(() => {
|
const printStreamOptions = useMemo(() => {
|
||||||
let t = 0
|
const opts = []
|
||||||
for (const sec of sections) {
|
for (const run of planModel.runs) {
|
||||||
for (const it of sortedItems(sec)) {
|
if (run.kind !== 'parallel' || !run.streams) continue
|
||||||
if (it.item_type === 'exercise' && it.planned_duration_min != null) {
|
for (const st of run.streams) {
|
||||||
const n = Number(it.planned_duration_min)
|
opts.push({
|
||||||
if (Number.isFinite(n)) t += n
|
id: st.printStreamId,
|
||||||
}
|
label: `${run.phaseTitle ? String(run.phaseTitle).trim().slice(0, 28) : `Phase ${run.phaseOrderIndex}`} · ${st.streamTitle ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}`,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return t
|
return opts
|
||||||
}, [sections])
|
}, [planModel.runs])
|
||||||
|
|
||||||
|
const totalPlannedMin = planModel.totalMin
|
||||||
|
const showWholeGroupInView = !printOnlyStreamId
|
||||||
|
const showStreamColumn = (streamPrintId) => !printOnlyStreamId || streamPrintId === printOnlyStreamId
|
||||||
|
|
||||||
|
const renderSectionCard = (sec, siInUnit) => {
|
||||||
|
const secOrder = sec.order_index ?? siInUnit
|
||||||
|
const items = sortedItems(sec)
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
key={sec.id ?? `sec-${secOrder}-${siInUnit}`}
|
||||||
|
className="card training-run-section"
|
||||||
|
style={{ padding: '1.15rem 1.25rem' }}
|
||||||
|
>
|
||||||
|
<h2 style={{ fontSize: '1.05rem', marginBottom: '0.65rem', color: 'var(--accent-dark)' }}>
|
||||||
|
{sec.title || `Abschnitt ${siInUnit + 1}`}
|
||||||
|
</h2>
|
||||||
|
{sec.guidance_notes && (
|
||||||
|
<p
|
||||||
|
style={{
|
||||||
|
fontSize: '0.88rem',
|
||||||
|
color: 'var(--text2)',
|
||||||
|
marginBottom: '0.85rem',
|
||||||
|
whiteSpace: 'pre-wrap',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{sec.guidance_notes}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<ul
|
||||||
|
style={{
|
||||||
|
listStyle: 'none',
|
||||||
|
padding: 0,
|
||||||
|
margin: 0,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: '0.65rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{items.map((it, ii) => {
|
||||||
|
const ck = itemStableKey(it, secOrder, ii)
|
||||||
|
const done = checked.has(ck)
|
||||||
|
|
||||||
|
if (it.item_type === 'note') {
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={ck}
|
||||||
|
className={`training-run-item training-run-item--note${done ? ' training-run-item--done' : ''}`}
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.75rem',
|
||||||
|
alignItems: 'flex-start',
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '0.92rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="training-run-checkbox training-run-checkbox--printable"
|
||||||
|
checked={done}
|
||||||
|
onChange={() => toggle(ck)}
|
||||||
|
style={{ marginTop: '4px', width: '20px', height: '20px' }}
|
||||||
|
/>
|
||||||
|
<span style={{ whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>
|
||||||
|
<em style={{ fontStyle: 'normal', color: 'var(--text3)', fontSize: '0.8rem' }}>
|
||||||
|
Notiz
|
||||||
|
</em>
|
||||||
|
<br />
|
||||||
|
{it.note_body || ''}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const title =
|
||||||
|
it.exercise_title || (it.exercise_id ? `Übung #${it.exercise_id}` : 'Übung')
|
||||||
|
const variant = it.exercise_variant_name ? ` (${it.exercise_variant_name})` : ''
|
||||||
|
const plan = formatMin(it.planned_duration_min)
|
||||||
|
const extras = []
|
||||||
|
if (it.exercise_focus_area) extras.push(it.exercise_focus_area)
|
||||||
|
const exKind = String(it.exercise_kind || 'simple').toLowerCase().trim()
|
||||||
|
const isComboRow = exKind === 'combination'
|
||||||
|
const metaParts = [...extras, isComboRow ? 'Kombination' : null, plan].filter(Boolean)
|
||||||
|
const comboEffectiveProfile = isComboRow
|
||||||
|
? effectiveComboMethodProfile(
|
||||||
|
it.catalog_method_profile || {},
|
||||||
|
it.planning_method_profile ?? null
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={ck}
|
||||||
|
className={`training-run-item training-run-item--exercise${done ? ' training-run-item--done' : ''}`}
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.75rem',
|
||||||
|
alignItems: 'flex-start',
|
||||||
|
cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="training-run-checkbox training-run-checkbox--printable"
|
||||||
|
checked={done}
|
||||||
|
onChange={() => toggle(ck)}
|
||||||
|
style={{
|
||||||
|
marginTop: '6px',
|
||||||
|
width: '22px',
|
||||||
|
height: '22px',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<span style={{ fontSize: '1.02rem', fontWeight: 600 }}>
|
||||||
|
{title}
|
||||||
|
{variant}
|
||||||
|
</span>
|
||||||
|
{metaParts.length > 0 && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: '0.85rem',
|
||||||
|
color: 'var(--text3)',
|
||||||
|
marginTop: '3px',
|
||||||
|
lineHeight: 1.35,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{metaParts.join(' · ')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(it.notes || it.modifications) && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: '0.35rem',
|
||||||
|
fontSize: '0.88rem',
|
||||||
|
color: 'var(--text2)',
|
||||||
|
whiteSpace: 'pre-wrap',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{it.notes && (
|
||||||
|
<>
|
||||||
|
<strong style={{ fontWeight: 600 }}>Coach:</strong> {it.notes}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{it.modifications && (
|
||||||
|
<>
|
||||||
|
{it.notes ? <br /> : null}
|
||||||
|
<strong style={{ fontWeight: 600 }}>Anpassung:</strong> {it.modifications}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{isComboRow && it.exercise_id ? (
|
||||||
|
<div className="training-run-combo-embed">
|
||||||
|
<CombinationPlanBracket
|
||||||
|
methodArchetype={String(it.catalog_method_archetype || '').trim()}
|
||||||
|
methodProfile={comboEffectiveProfile || {}}
|
||||||
|
combinationSlots={
|
||||||
|
Array.isArray(it.combination_slots) ? it.combination_slots : []
|
||||||
|
}
|
||||||
|
planningAdjusted={
|
||||||
|
it.planning_method_profile != null &&
|
||||||
|
typeof it.planning_method_profile === 'object' &&
|
||||||
|
!Array.isArray(it.planning_method_profile)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{it.exercise_id && (
|
||||||
|
<div
|
||||||
|
className="no-print"
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
gap: '10px',
|
||||||
|
marginTop: '0.55rem',
|
||||||
|
alignItems: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
style={{ fontSize: '0.82rem', margin: 0 }}
|
||||||
|
onClick={() =>
|
||||||
|
setPeekCtx({
|
||||||
|
exerciseId: it.exercise_id,
|
||||||
|
variantId:
|
||||||
|
it.exercise_variant_id != null
|
||||||
|
? Number(it.exercise_variant_id)
|
||||||
|
: null,
|
||||||
|
peekExtras: isComboRow
|
||||||
|
? {
|
||||||
|
catalog_method_profile: it.catalog_method_profile,
|
||||||
|
planning_method_profile: it.planning_method_profile,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Katalog (Popup)
|
||||||
|
</button>
|
||||||
|
<Link
|
||||||
|
to={`/exercises/${it.exercise_id}`}
|
||||||
|
style={{ fontSize: '0.82rem', color: 'var(--accent)' }}
|
||||||
|
>
|
||||||
|
Vollständige Seite öffnen
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
@@ -153,21 +385,66 @@ export default function TrainingUnitRunPage() {
|
|||||||
onClose={() => setPeekCtx(null)}
|
onClose={() => setPeekCtx(null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<nav className="training-run-toolbar no-print" style={{ marginBottom: '1rem', display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
|
<nav
|
||||||
|
className="training-run-toolbar no-print"
|
||||||
|
style={{
|
||||||
|
marginBottom: '1rem',
|
||||||
|
display: 'flex',
|
||||||
|
gap: '0.5rem',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
alignItems: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
|
||||||
Zur Planung
|
Zur Planung
|
||||||
</button>
|
</button>
|
||||||
<Link
|
<Link
|
||||||
to={`/planning/run/${unitId}/coach`}
|
to={`/planning/run/${unitId}/coach`}
|
||||||
className="btn btn-primary"
|
className="btn btn-primary"
|
||||||
style={{ textDecoration: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
|
style={{
|
||||||
|
textDecoration: 'none',
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Im Training (Coach)
|
Im Training (Coach)
|
||||||
</Link>
|
</Link>
|
||||||
<button type="button" className="btn btn-secondary" onClick={() => window.print()}>
|
<button type="button" className="btn btn-secondary" onClick={() => window.print()}>
|
||||||
Drucken / PDF
|
Drucken / PDF
|
||||||
</button>
|
</button>
|
||||||
<button type="button" className="btn btn-secondary" title="Alle Häkchen auf dieser Matte zurücksetzen" onClick={() => confirm('Fortschritt wirklich zurücksetzen?') && clearProgress()}>
|
{printStreamOptions.length > 0 ? (
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: '8px',
|
||||||
|
fontSize: '0.86rem',
|
||||||
|
color: 'var(--text2)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Druck / Vorschau
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
style={{ marginBottom: 0, minWidth: '200px', fontSize: '0.86rem' }}
|
||||||
|
value={printOnlyStreamId || ''}
|
||||||
|
onChange={(e) => setPrintOnlyStreamId(e.target.value || null)}
|
||||||
|
>
|
||||||
|
<option value="">Gesamter Plan (empfohlen)</option>
|
||||||
|
{printStreamOptions.map((o) => (
|
||||||
|
<option key={o.id} value={o.id}>
|
||||||
|
Nur: {o.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
title="Alle Häkchen auf dieser Matte zurücksetzen"
|
||||||
|
onClick={() => confirm('Fortschritt wirklich zurücksetzen?') && clearProgress()}
|
||||||
|
>
|
||||||
Fortschritt leeren
|
Fortschritt leeren
|
||||||
</button>
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
@@ -201,10 +478,81 @@ export default function TrainingUnitRunPage() {
|
|||||||
</span>
|
</span>
|
||||||
{totalPlannedMin > 0 && (
|
{totalPlannedMin > 0 && (
|
||||||
<span>
|
<span>
|
||||||
<strong>Geplante Zeit (Übungen):</strong> ca. {totalPlannedMin} Min.
|
<strong>Geplante Zeit (Übungen, gesamt):</strong> ca. {totalPlannedMin} Min.
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{printOnlyStreamId ? (
|
||||||
|
<div
|
||||||
|
className="no-print"
|
||||||
|
style={{
|
||||||
|
marginTop: '0.75rem',
|
||||||
|
padding: '0.5rem 0.75rem',
|
||||||
|
background: 'hsl(200 40% 94%)',
|
||||||
|
borderRadius: '8px',
|
||||||
|
fontSize: '0.82rem',
|
||||||
|
color: 'hsl(200 25% 28%)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Vorschau wie fürs Drucken: nur die gewählte Split-Gruppe. Ganzgruppen-Blöcke sind ausgeblendet.
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{planModel.mode === 'phased' && planModel.runs.length > 0 && showWholeGroupInView && (
|
||||||
|
<div
|
||||||
|
className="training-run-phase-schedule training-run-notes-print"
|
||||||
|
style={{
|
||||||
|
marginTop: '1rem',
|
||||||
|
padding: '0.75rem 0.9rem',
|
||||||
|
background: 'var(--surface2)',
|
||||||
|
borderRadius: '8px',
|
||||||
|
fontSize: '0.86rem',
|
||||||
|
overflowX: 'auto',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<strong style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text1)' }}>
|
||||||
|
Zeitplanung (Summe Übungsminuten)
|
||||||
|
</strong>
|
||||||
|
<table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '280px' }}>
|
||||||
|
<thead>
|
||||||
|
<tr style={{ textAlign: 'left', color: 'var(--text3)', fontSize: '0.78rem' }}>
|
||||||
|
<th style={{ padding: '4px 8px 4px 0', fontWeight: 600 }}>Block</th>
|
||||||
|
<th style={{ padding: '4px 8px', fontWeight: 600 }}>Art</th>
|
||||||
|
<th style={{ padding: '4px 8px', fontWeight: 600 }}> Min</th>
|
||||||
|
<th style={{ padding: '4px 0 4px 8px', fontWeight: 600 }}>∑ bis hier</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{planModel.runs.map((run, ri) => {
|
||||||
|
const cum = planModel.runCumulativeEnds[ri]
|
||||||
|
const label =
|
||||||
|
run.phaseTitle != null && String(run.phaseTitle).trim()
|
||||||
|
? String(run.phaseTitle).trim()
|
||||||
|
: run.kind === 'legacy'
|
||||||
|
? 'Ablauf'
|
||||||
|
: run.kind === 'whole_group'
|
||||||
|
? `Ganzgruppe (Phase ${run.phaseOrderIndex})`
|
||||||
|
: `Parallel (Phase ${run.phaseOrderIndex})`
|
||||||
|
return (
|
||||||
|
<tr key={`sched-${ri}-${run.kind}`} style={{ borderTop: '1px solid var(--border)' }}>
|
||||||
|
<td style={{ padding: '6px 8px 6px 0', verticalAlign: 'top' }}>{label}</td>
|
||||||
|
<td style={{ padding: '6px 8px', color: 'var(--text2)', whiteSpace: 'nowrap' }}>
|
||||||
|
{run.kind === 'parallel' ? 'Split' : run.kind === 'legacy' ? '—' : 'Ganzgruppe'}
|
||||||
|
</td>
|
||||||
|
<td style={{ padding: '6px 8px' }}>{run.minutes || '—'}</td>
|
||||||
|
<td style={{ padding: '6px 0 6px 8px', fontWeight: 600 }}>{cum}</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{unit.planned_time_start && (
|
||||||
|
<p style={{ margin: '0.55rem 0 0', fontSize: '0.78rem', color: 'var(--text3)', lineHeight: 1.4 }}>
|
||||||
|
Hinweis: Startzeit oben im Kopf; Minuten sind aus den Übungseinplanungen — ohne Pausen und ohne
|
||||||
|
automatische Uhrzeitliste.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{unit.notes && (
|
{unit.notes && (
|
||||||
<div
|
<div
|
||||||
className="training-run-notes-print"
|
className="training-run-notes-print"
|
||||||
@@ -213,7 +561,7 @@ export default function TrainingUnitRunPage() {
|
|||||||
padding: '0.65rem 0.85rem',
|
padding: '0.65rem 0.85rem',
|
||||||
background: 'var(--accent-light)',
|
background: 'var(--accent-light)',
|
||||||
borderRadius: '8px',
|
borderRadius: '8px',
|
||||||
fontSize: '0.92rem'
|
fontSize: '0.92rem',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<strong>Hinweis Teilnehmer:</strong> {unit.notes}
|
<strong>Hinweis Teilnehmer:</strong> {unit.notes}
|
||||||
@@ -226,171 +574,175 @@ export default function TrainingUnitRunPage() {
|
|||||||
Noch keine Abschnitte in diesem Plan. Unter <Link to="/planning">Planung</Link> bearbeiten.
|
Noch keine Abschnitte in diesem Plan. Unter <Link to="/planning">Planung</Link> bearbeiten.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
|
<div className="training-run-body" style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
|
||||||
{sections.map((sec, si) => {
|
{planModel.runs.map((run, runIdx) => {
|
||||||
const secOrder = sec.order_index ?? si
|
if (run.kind === 'parallel') {
|
||||||
const items = sortedItems(sec)
|
const visibleStreams = run.streams.filter((st) => showStreamColumn(st.printStreamId))
|
||||||
return (
|
if (!visibleStreams.length) return null
|
||||||
<section key={sec.id ?? `sec-${si}`} className="card training-run-section" style={{ padding: '1.15rem 1.25rem' }}>
|
return (
|
||||||
<h2 style={{ fontSize: '1.05rem', marginBottom: '0.65rem', color: 'var(--accent-dark)' }}>
|
<div
|
||||||
{sec.title || `Abschnitt ${si + 1}`}
|
key={`run-p-${run.phaseOrderIndex}-${runIdx}`}
|
||||||
</h2>
|
className="training-run-phase training-run-phase--parallel"
|
||||||
{sec.guidance_notes && (
|
>
|
||||||
<p style={{ fontSize: '0.88rem', color: 'var(--text2)', marginBottom: '0.85rem', whiteSpace: 'pre-wrap' }}>
|
<div
|
||||||
{sec.guidance_notes}
|
className="card training-run-phase-banner"
|
||||||
</p>
|
style={{
|
||||||
)}
|
padding: '0.85rem 1rem',
|
||||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '0.65rem' }}>
|
background: 'linear-gradient(135deg, hsl(200 35% 94%), var(--surface2))',
|
||||||
{items.map((it, ii) => {
|
border: '1px solid hsl(200 40% 80%)',
|
||||||
const ck = itemStableKey(it, secOrder, ii)
|
borderRadius: '10px',
|
||||||
const done = checked.has(ck)
|
}}
|
||||||
|
>
|
||||||
if (it.item_type === 'note') {
|
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--text3)', letterSpacing: '0.04em' }}>
|
||||||
|
PARALLELE PHASE
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: '1.02rem', fontWeight: 700, color: 'var(--accent-dark)', marginTop: '4px' }}>
|
||||||
|
{run.phaseTitle ? String(run.phaseTitle).trim() : `Phase ${run.phaseOrderIndex}`}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: '0.82rem', color: 'var(--text2)', marginTop: '4px' }}>
|
||||||
|
{printOnlyStreamId
|
||||||
|
? `Auszug eine Gruppe · ca. ${visibleStreams[0]?.minutes ?? run.minutes} Min. (Üb.)`
|
||||||
|
: `Geplante Übungszeit (gesamt): ca. ${run.minutes} Min. · Jede Spalte kann separat gedruckt werden (Dropdown oder Seitenumbruch).`}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="training-run-parallel-columns"
|
||||||
|
style={{
|
||||||
|
display: 'grid',
|
||||||
|
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
|
||||||
|
gap: '1rem',
|
||||||
|
alignItems: 'start',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{visibleStreams.map((st, streamIdx) => {
|
||||||
|
const siUnit = (sec) => Math.max(0, sections.indexOf(sec))
|
||||||
return (
|
return (
|
||||||
<li key={ck} className={`training-run-item training-run-item--note${done ? ' training-run-item--done' : ''}`}>
|
<div
|
||||||
<label
|
key={st.printStreamId}
|
||||||
|
className={
|
||||||
|
'training-run-breakout-stream' +
|
||||||
|
(!printOnlyStreamId && streamIdx > 0
|
||||||
|
? ' training-run-breakout-stream--page-break'
|
||||||
|
: '')
|
||||||
|
}
|
||||||
|
data-print-id={st.printStreamId}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="training-run-stream-ribbon"
|
||||||
style={{
|
style={{
|
||||||
|
marginBottom: '10px',
|
||||||
|
padding: '8px 12px',
|
||||||
|
borderRadius: '8px',
|
||||||
|
background: 'hsl(200 38% 92%)',
|
||||||
|
border: '1px dashed hsl(200 42% 58%)',
|
||||||
|
fontSize: '0.88rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
color: 'hsl(200 30% 28%)',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
gap: '0.75rem',
|
flexWrap: 'wrap',
|
||||||
alignItems: 'flex-start',
|
alignItems: 'center',
|
||||||
cursor: 'pointer',
|
justifyContent: 'space-between',
|
||||||
fontSize: '0.92rem'
|
gap: '8px',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<input type="checkbox" className="training-run-checkbox" checked={done} onChange={() => toggle(ck)} style={{ marginTop: '4px', width: '20px', height: '20px' }} />
|
<span>
|
||||||
<span style={{ whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>
|
{st.streamTitle ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}
|
||||||
<em style={{ fontStyle: 'normal', color: 'var(--text3)', fontSize: '0.8rem' }}>Notiz</em>
|
<span style={{ fontWeight: 500, marginLeft: '8px', opacity: 0.85 }}>
|
||||||
<br />
|
· ca. {st.minutes} Min. (Üb.)
|
||||||
{it.note_body || ''}
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
<Link
|
||||||
</li>
|
className="no-print"
|
||||||
|
to={`/planning/run/${unitId}/coach?atBranch=${run.phaseOrderIndex}&preferSo=${st.streamOrder}`}
|
||||||
|
style={{
|
||||||
|
fontSize: '0.78rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
color: 'var(--accent-dark)',
|
||||||
|
textDecoration: 'underline',
|
||||||
|
textUnderlineOffset: '2px',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Coach · Split-Punkt (Vorschlag)
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||||
|
{st.sections.map((sec) => renderSectionCard(sec, siUnit(sec)))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const title =
|
if (!showWholeGroupInView) return null
|
||||||
it.exercise_title ||
|
|
||||||
(it.exercise_id ? `Übung #${it.exercise_id}` : 'Übung')
|
|
||||||
const variant = it.exercise_variant_name ? ` (${it.exercise_variant_name})` : ''
|
|
||||||
const plan = formatMin(it.planned_duration_min)
|
|
||||||
const extras = []
|
|
||||||
if (it.exercise_focus_area) extras.push(it.exercise_focus_area)
|
|
||||||
const exKind = String(it.exercise_kind || 'simple').toLowerCase().trim()
|
|
||||||
const isComboRow = exKind === 'combination'
|
|
||||||
const metaParts = [...extras, isComboRow ? 'Kombination' : null, plan].filter(Boolean)
|
|
||||||
const comboEffectiveProfile = isComboRow
|
|
||||||
? effectiveComboMethodProfile(
|
|
||||||
it.catalog_method_profile || {},
|
|
||||||
it.planning_method_profile ?? null,
|
|
||||||
)
|
|
||||||
: null
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li key={ck} className={`training-run-item training-run-item--exercise${done ? ' training-run-item--done' : ''}`}>
|
<div
|
||||||
<label
|
key={`run-wg-${run.phaseOrderIndex}-${runIdx}`}
|
||||||
style={{
|
className="training-run-phase training-run-phase--whole training-run-wg-block"
|
||||||
display: 'flex',
|
>
|
||||||
gap: '0.75rem',
|
{run.kind !== 'legacy' ? (
|
||||||
alignItems: 'flex-start',
|
<div
|
||||||
cursor: 'pointer'
|
className="card training-run-phase-banner"
|
||||||
}}
|
style={{
|
||||||
>
|
padding: '0.85rem 1rem',
|
||||||
<input type="checkbox" className="training-run-checkbox" checked={done} onChange={() => toggle(ck)} style={{ marginTop: '6px', width: '22px', height: '22px', flexShrink: 0 }} />
|
marginBottom: '0.25rem',
|
||||||
<span style={{ flex: 1, minWidth: 0 }}>
|
background: 'color-mix(in srgb, var(--accent) 12%, var(--surface2))',
|
||||||
<span style={{ fontSize: '1.02rem', fontWeight: 600 }}>
|
border: '1px solid color-mix(in srgb, var(--accent) 28%, var(--border))',
|
||||||
{title}
|
borderRadius: '10px',
|
||||||
{variant}
|
}}
|
||||||
</span>
|
>
|
||||||
{metaParts.length > 0 && (
|
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--text3)', letterSpacing: '0.04em' }}>
|
||||||
<div style={{ fontSize: '0.85rem', color: 'var(--text3)', marginTop: '3px', lineHeight: 1.35 }}>
|
GANZGRUPPE
|
||||||
{metaParts.join(' · ')}
|
</div>
|
||||||
</div>
|
<div style={{ fontSize: '1.02rem', fontWeight: 700, color: 'var(--accent-dark)', marginTop: '4px' }}>
|
||||||
)}
|
{run.phaseTitle ? String(run.phaseTitle).trim() : `Phase ${run.phaseOrderIndex}`}
|
||||||
{(it.notes || it.modifications) && (
|
</div>
|
||||||
<div style={{ marginTop: '0.35rem', fontSize: '0.88rem', color: 'var(--text2)', whiteSpace: 'pre-wrap' }}>
|
<div style={{ fontSize: '0.82rem', color: 'var(--text2)', marginTop: '4px' }}>
|
||||||
{it.notes && (
|
Geplante Übungszeit: ca. {run.minutes} Min.
|
||||||
<>
|
</div>
|
||||||
<strong style={{ fontWeight: 600 }}>Coach:</strong> {it.notes}
|
</div>
|
||||||
</>
|
) : null}
|
||||||
)}
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
|
||||||
{it.modifications && (
|
{run.sections.map((sec) => renderSectionCard(sec, Math.max(0, sections.indexOf(sec))))}
|
||||||
<>
|
</div>
|
||||||
{it.notes ? <br /> : null}
|
</div>
|
||||||
<strong style={{ fontWeight: 600 }}>Anpassung:</strong> {it.modifications}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{isComboRow && it.exercise_id ? (
|
|
||||||
<div className="training-run-combo-embed">
|
|
||||||
<CombinationPlanBracket
|
|
||||||
methodArchetype={String(it.catalog_method_archetype || '').trim()}
|
|
||||||
methodProfile={comboEffectiveProfile || {}}
|
|
||||||
combinationSlots={
|
|
||||||
Array.isArray(it.combination_slots) ? it.combination_slots : []
|
|
||||||
}
|
|
||||||
planningAdjusted={
|
|
||||||
it.planning_method_profile != null &&
|
|
||||||
typeof it.planning_method_profile === 'object' &&
|
|
||||||
!Array.isArray(it.planning_method_profile)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
{it.exercise_id && (
|
|
||||||
<div className="no-print" style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', marginTop: '0.55rem', alignItems: 'center' }}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="btn btn-secondary"
|
|
||||||
style={{ fontSize: '0.82rem', margin: 0 }}
|
|
||||||
onClick={() =>
|
|
||||||
setPeekCtx({
|
|
||||||
exerciseId: it.exercise_id,
|
|
||||||
variantId:
|
|
||||||
it.exercise_variant_id != null
|
|
||||||
? Number(it.exercise_variant_id)
|
|
||||||
: null,
|
|
||||||
peekExtras: isComboRow
|
|
||||||
? {
|
|
||||||
catalog_method_profile: it.catalog_method_profile,
|
|
||||||
planning_method_profile: it.planning_method_profile,
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
Katalog (Popup)
|
|
||||||
</button>
|
|
||||||
<Link
|
|
||||||
to={`/exercises/${it.exercise_id}`}
|
|
||||||
style={{ fontSize: '0.82rem', color: 'var(--accent)' }}
|
|
||||||
>
|
|
||||||
Vollständige Seite öffnen
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
</li>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{unit.trainer_notes && (
|
{unit.trainer_notes && (
|
||||||
<div className="card training-run-trainer-note no-print" style={{ marginTop: '1.25rem', padding: '1rem', borderLeft: `4px solid var(--accent)` }}>
|
<div
|
||||||
<div style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text3)', marginBottom: '0.35rem', textTransform: 'uppercase' }}>
|
className="card training-run-trainer-note no-print"
|
||||||
|
style={{
|
||||||
|
marginTop: '1.25rem',
|
||||||
|
padding: '1rem',
|
||||||
|
borderLeft: `4px solid var(--accent)`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
color: 'var(--text3)',
|
||||||
|
marginBottom: '0.35rem',
|
||||||
|
textTransform: 'uppercase',
|
||||||
|
}}
|
||||||
|
>
|
||||||
Nur Trainer
|
Nur Trainer
|
||||||
</div>
|
</div>
|
||||||
<p style={{ fontSize: '0.92rem', whiteSpace: 'pre-wrap' }}>{unit.trainer_notes}</p>
|
<p style={{ fontSize: '0.92rem', whiteSpace: 'pre-wrap' }}>{unit.trainer_notes}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<footer className="no-print training-run-footer" style={{ marginTop: '1.75rem', textAlign: 'center', fontSize: '0.82rem', color: 'var(--text3)' }}>
|
<footer
|
||||||
|
className="no-print training-run-footer"
|
||||||
|
style={{ marginTop: '1.75rem', textAlign: 'center', fontSize: '0.82rem', color: 'var(--text3)' }}
|
||||||
|
>
|
||||||
Haken werden nur auf diesem Gerät gespeichert (Session — Tab schließen kann sie löschen).
|
Haken werden nur auf diesem Gerät gespeichert (Session — Tab schließen kann sie löschen).
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { activeClubMemberships } from './activeClub'
|
||||||
|
|
||||||
|
export function clubAdminInClub(user, clubId) {
|
||||||
|
const cid = Number(clubId)
|
||||||
|
if (!Number.isFinite(cid)) return false
|
||||||
|
const row = activeClubMemberships(user?.clubs).find((c) => Number(c.id) === cid)
|
||||||
|
return Boolean(row?.roles?.includes('club_admin'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Löschen von Bibliotheks-/Planungsinhalten (Vorlage, Modul, Rahmen, Graph) — grob wie Backend club_tenancy.
|
||||||
|
* Vereins-Admins können fremde private Einträge im API löschen (gemeinsamer Verein); das blenden wir hier nicht ein.
|
||||||
|
*/
|
||||||
|
/** Bearbeiten — grob wie Backend assert_library_content_editable (Ersteller, Plattform, Planung im Verein). */
|
||||||
|
export function canEditLibraryContent(user, row) {
|
||||||
|
const grole = String(user?.role || '').toLowerCase()
|
||||||
|
if (grole === 'admin' || grole === 'superadmin') return true
|
||||||
|
const uid = Number(user?.id)
|
||||||
|
if (!Number.isFinite(uid)) return false
|
||||||
|
|
||||||
|
const vis = String(row?.visibility ?? 'club').toLowerCase()
|
||||||
|
const createdBy = row?.created_by != null ? Number(row.created_by) : null
|
||||||
|
const clubId = row?.club_id != null ? Number(row.club_id) : null
|
||||||
|
|
||||||
|
if (vis === 'official') return false
|
||||||
|
if (Number.isFinite(createdBy) && createdBy === uid) return true
|
||||||
|
if (vis === 'club' && Number.isFinite(clubId)) {
|
||||||
|
return activeClubMemberships(user?.clubs).some((c) => Number(c.id) === clubId)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canDeleteLibraryContent(user, row) {
|
||||||
|
const grole = String(user?.role || '').toLowerCase()
|
||||||
|
if (grole === 'admin' || grole === 'superadmin') return true
|
||||||
|
const uid = Number(user?.id)
|
||||||
|
if (!Number.isFinite(uid)) return false
|
||||||
|
|
||||||
|
const vis = String(row?.visibility ?? 'club').toLowerCase()
|
||||||
|
const createdBy = row?.created_by != null ? Number(row.created_by) : null
|
||||||
|
const clubId = row?.club_id != null ? Number(row.club_id) : null
|
||||||
|
|
||||||
|
if (vis === 'official') return false
|
||||||
|
if (vis === 'club') return clubAdminInClub(user, clubId)
|
||||||
|
if (vis === 'private') return Number.isFinite(createdBy) && createdBy === uid
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/**
|
||||||
|
* Zentrale Routen & Rückkehr-Kontext Trainingsplanung ↔ Einheiten-Editor.
|
||||||
|
* Alle Navigations-URLs für Kalender-Einheiten hier pflegen (Drift-Schutz).
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const PLANNING_HUB_PATH = '/planning'
|
||||||
|
|
||||||
|
export function buildPlanUnitEditPath(unitId) {
|
||||||
|
const id = Number(unitId)
|
||||||
|
if (!Number.isFinite(id) || id < 1) return PLANNING_HUB_PATH
|
||||||
|
return `/planning/units/${id}/edit`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{ groupId?: string|number, plannedDate?: string, templateId?: string|number, mode?: string }} opts
|
||||||
|
*/
|
||||||
|
export function buildPlanUnitNewPath(opts = {}) {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (opts.groupId != null && opts.groupId !== '') params.set('group', String(opts.groupId))
|
||||||
|
if (opts.plannedDate) params.set('date', String(opts.plannedDate).slice(0, 10))
|
||||||
|
if (opts.templateId != null && opts.templateId !== '') params.set('template', String(opts.templateId))
|
||||||
|
if (opts.mode === 'debrief') params.set('mode', 'debrief')
|
||||||
|
const q = params.toString()
|
||||||
|
return q ? `/planning/units/new?${q}` : '/planning/units/new'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {import('react-router-dom').URLSearchParams|string|null|undefined} raw */
|
||||||
|
export function legacyPlanningUnitDeepLinkTarget(raw) {
|
||||||
|
const params =
|
||||||
|
raw instanceof URLSearchParams ? raw : new URLSearchParams(typeof raw === 'string' ? raw : '')
|
||||||
|
const uid = params.get('unit')
|
||||||
|
if (!uid) return null
|
||||||
|
const idNum = parseInt(uid, 10)
|
||||||
|
if (!Number.isFinite(idNum) || idNum < 1) return null
|
||||||
|
const debrief = params.get('debrief')
|
||||||
|
const base = buildPlanUnitEditPath(idNum)
|
||||||
|
if (debrief === '1' || debrief === 'true') {
|
||||||
|
return `${base}?mode=debrief`
|
||||||
|
}
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{
|
||||||
|
* selectedGroupId?: string,
|
||||||
|
* planView?: string,
|
||||||
|
* calendarMonthStr?: string,
|
||||||
|
* startDate?: string,
|
||||||
|
* endDate?: string,
|
||||||
|
* planScope?: string,
|
||||||
|
* assignedToMeOnly?: boolean,
|
||||||
|
* }} hubState
|
||||||
|
*/
|
||||||
|
export function buildPlanningHubReturnState(hubState = {}) {
|
||||||
|
return {
|
||||||
|
v: 1,
|
||||||
|
selectedGroupId: hubState.selectedGroupId != null ? String(hubState.selectedGroupId) : '',
|
||||||
|
planView: hubState.planView || 'list',
|
||||||
|
calendarMonthStr: hubState.calendarMonthStr || '',
|
||||||
|
startDate: hubState.startDate || '',
|
||||||
|
endDate: hubState.endDate || '',
|
||||||
|
planScope: hubState.planScope || 'group',
|
||||||
|
assignedToMeOnly: Boolean(hubState.assignedToMeOnly),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} pathname */
|
||||||
|
export function isPlanningUnitEditorPath(pathname) {
|
||||||
|
if (!pathname) return false
|
||||||
|
if (pathname === '/planning/units/new') return true
|
||||||
|
return /^\/planning\/units\/\d+\/edit$/.test(pathname)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {ReturnType<typeof buildPlanningHubReturnState>|null|undefined} state */
|
||||||
|
export function planningHubPathFromReturnState(state) {
|
||||||
|
if (!state || state.v !== 1) return PLANNING_HUB_PATH
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (state.selectedGroupId) params.set('group', state.selectedGroupId)
|
||||||
|
if (state.planView && state.planView !== 'list') params.set('view', state.planView)
|
||||||
|
if (state.planView === 'calendar' && state.calendarMonthStr) {
|
||||||
|
params.set('month', state.calendarMonthStr)
|
||||||
|
}
|
||||||
|
if (state.startDate) params.set('start', state.startDate)
|
||||||
|
if (state.endDate) params.set('end', state.endDate)
|
||||||
|
if (state.planScope && state.planScope !== 'group') params.set('scope', state.planScope)
|
||||||
|
if (state.assignedToMeOnly) params.set('mine', '1')
|
||||||
|
const q = params.toString()
|
||||||
|
return q ? `${PLANNING_HUB_PATH}?${q}` : PLANNING_HUB_PATH
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hub-Query beim Mount auf State-Felder mappen. */
|
||||||
|
export function parsePlanningHubQuery(searchParams) {
|
||||||
|
const p = searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams || '')
|
||||||
|
return {
|
||||||
|
selectedGroupId: p.get('group') || '',
|
||||||
|
planView: p.get('view') === 'calendar' ? 'calendar' : 'list',
|
||||||
|
calendarMonthStr: p.get('month') || '',
|
||||||
|
startDate: p.get('start') || '',
|
||||||
|
endDate: p.get('end') || '',
|
||||||
|
planScope: p.get('scope') === 'club' ? 'club' : 'group',
|
||||||
|
assignedToMeOnly: p.get('mine') === '1',
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
buildPlanUnitEditPath,
|
||||||
|
buildPlanUnitNewPath,
|
||||||
|
buildPlanningHubReturnState,
|
||||||
|
isPlanningUnitEditorPath,
|
||||||
|
legacyPlanningUnitDeepLinkTarget,
|
||||||
|
parsePlanningHubQuery,
|
||||||
|
planningHubPathFromReturnState,
|
||||||
|
} from './planningUnitRoutes.js'
|
||||||
|
|
||||||
|
describe('planningUnitRoutes', () => {
|
||||||
|
it('buildPlanUnitEditPath', () => {
|
||||||
|
expect(buildPlanUnitEditPath(42)).toBe('/planning/units/42/edit')
|
||||||
|
expect(buildPlanUnitEditPath('7')).toBe('/planning/units/7/edit')
|
||||||
|
expect(buildPlanUnitEditPath(0)).toBe('/planning')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('buildPlanUnitNewPath with query', () => {
|
||||||
|
expect(buildPlanUnitNewPath({ groupId: 3, plannedDate: '2026-05-20' })).toBe(
|
||||||
|
'/planning/units/new?group=3&date=2026-05-20'
|
||||||
|
)
|
||||||
|
expect(buildPlanUnitNewPath()).toBe('/planning/units/new')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('isPlanningUnitEditorPath', () => {
|
||||||
|
expect(isPlanningUnitEditorPath('/planning/units/new')).toBe(true)
|
||||||
|
expect(isPlanningUnitEditorPath('/planning/units/42/edit')).toBe(true)
|
||||||
|
expect(isPlanningUnitEditorPath('/planning')).toBe(false)
|
||||||
|
expect(isPlanningUnitEditorPath('/planning/training-modules')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('legacyPlanningUnitDeepLinkTarget', () => {
|
||||||
|
expect(legacyPlanningUnitDeepLinkTarget('unit=5')).toBe('/planning/units/5/edit')
|
||||||
|
expect(legacyPlanningUnitDeepLinkTarget('unit=5&debrief=1')).toBe(
|
||||||
|
'/planning/units/5/edit?mode=debrief'
|
||||||
|
)
|
||||||
|
expect(legacyPlanningUnitDeepLinkTarget('')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('planning hub return roundtrip', () => {
|
||||||
|
const state = buildPlanningHubReturnState({
|
||||||
|
selectedGroupId: '12',
|
||||||
|
planView: 'calendar',
|
||||||
|
calendarMonthStr: '2026-06',
|
||||||
|
assignedToMeOnly: true,
|
||||||
|
})
|
||||||
|
const path = planningHubPathFromReturnState(state)
|
||||||
|
expect(path).toContain('/planning?')
|
||||||
|
expect(path).toContain('group=12')
|
||||||
|
expect(path).toContain('view=calendar')
|
||||||
|
expect(path).toContain('month=2026-06')
|
||||||
|
expect(path).toContain('mine=1')
|
||||||
|
|
||||||
|
const parsed = parsePlanningHubQuery(path.split('?')[1] || '')
|
||||||
|
expect(parsed.selectedGroupId).toBe('12')
|
||||||
|
expect(parsed.planView).toBe('calendar')
|
||||||
|
expect(parsed.calendarMonthStr).toBe('2026-06')
|
||||||
|
expect(parsed.assignedToMeOnly).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/**
|
||||||
|
* Übungspositionen aus GET /api/training-units/:id für die Modul-Erstellung (Reihenfolge = Timeline).
|
||||||
|
* @param {object} unit – hydratisierte Trainingseinheit mit `phases` und/oder `sections`
|
||||||
|
* @returns {Array<{ exercise_id: number, exercise_variant_id: number|null, planned_duration_min: number|null, notes: string|null, exercise_title?: string, contextLabel: string }>}
|
||||||
|
*/
|
||||||
|
export function collectExercisePlacementsForModule(unit) {
|
||||||
|
if (!unit || typeof unit !== 'object') return []
|
||||||
|
|
||||||
|
const rows = []
|
||||||
|
|
||||||
|
const pushFromSection = (sec, ctx) => {
|
||||||
|
const st = (sec?.title || '').trim()
|
||||||
|
for (const it of sec?.items || []) {
|
||||||
|
if ((it?.item_type || 'exercise') !== 'exercise') continue
|
||||||
|
const eid = it.exercise_id
|
||||||
|
if (!eid) continue
|
||||||
|
const labelParts = [ctx, st].filter(Boolean)
|
||||||
|
rows.push({
|
||||||
|
exercise_id: Number(eid),
|
||||||
|
exercise_variant_id:
|
||||||
|
it.exercise_variant_id != null && it.exercise_variant_id !== ''
|
||||||
|
? Number(it.exercise_variant_id)
|
||||||
|
: null,
|
||||||
|
planned_duration_min:
|
||||||
|
it.planned_duration_min != null && it.planned_duration_min !== ''
|
||||||
|
? Number(it.planned_duration_min)
|
||||||
|
: null,
|
||||||
|
notes: it.notes != null && String(it.notes).trim() ? String(it.notes).trim() : null,
|
||||||
|
exercise_title: (it.exercise_title || '').trim() || `Übung #${eid}`,
|
||||||
|
contextLabel: labelParts.length ? labelParts.join(' · ') : '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const phases = Array.isArray(unit.phases) ? unit.phases : []
|
||||||
|
for (const ph of phases) {
|
||||||
|
const pk = String(ph?.phase_kind || '').toLowerCase()
|
||||||
|
const phaseCtx = (ph?.title || '').trim()
|
||||||
|
if (pk === 'parallel') {
|
||||||
|
for (const st of ph.streams || []) {
|
||||||
|
const streamCtx = [phaseCtx, (st?.title || '').trim()].filter(Boolean).join(' · ')
|
||||||
|
for (const sec of st?.sections || []) {
|
||||||
|
pushFromSection(sec, streamCtx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const sec of ph?.sections || []) {
|
||||||
|
pushFromSection(sec, phaseCtx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rows.length && Array.isArray(unit.sections)) {
|
||||||
|
for (const sec of unit.sections) {
|
||||||
|
pushFromSection(sec, '')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rows
|
||||||
|
}
|
||||||
@@ -2,7 +2,15 @@
|
|||||||
* Hilfen für Trainingsplan-Ansicht, Coach-Modus und API-Payload für PUT /training-units/:id.
|
* Hilfen für Trainingsplan-Ansicht, Coach-Modus und API-Payload für PUT /training-units/:id.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { cloneJsonSerializablePlanningProfile } from './trainingUnitSectionsForm'
|
import {
|
||||||
|
buildPlanPayloadForSave,
|
||||||
|
cloneJsonSerializablePlanningProfile,
|
||||||
|
defaultPlanLocWholeGroup,
|
||||||
|
inheritPlanLocForPhasedSave,
|
||||||
|
phaseRunsFromSections,
|
||||||
|
sectionIndicesForParallelStream,
|
||||||
|
streamsForParallelPhaseOrders,
|
||||||
|
} from './trainingUnitSectionsForm'
|
||||||
export function sortedSections(unit) {
|
export function sortedSections(unit) {
|
||||||
const raw = unit?.sections
|
const raw = unit?.sections
|
||||||
if (!Array.isArray(raw)) return []
|
if (!Array.isArray(raw)) return []
|
||||||
@@ -20,11 +28,352 @@ export function itemStableKey(it, secOrder, ix) {
|
|||||||
return `${secOrder}-${it?.item_type || 'row'}-${ix}`
|
return `${secOrder}-${it?.item_type || 'row'}-${ix}`
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Flache Reihenfolge wie auf der Matte: alle Notizen und Übungen nacheinander.
|
export function sumExerciseMinutesInSection(sec) {
|
||||||
* Parallele Streams: aktuell strikt linear (sortedSections × sortedItems); für Breakout phase/stream‑aware erweitern. */
|
let t = 0
|
||||||
export function flattenPlanTimeline(unit) {
|
for (const it of sortedItems(sec)) {
|
||||||
|
if (it.item_type === 'exercise' && it.planned_duration_min != null) {
|
||||||
|
const n = Number(it.planned_duration_min)
|
||||||
|
if (Number.isFinite(n)) t += n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET liefert `planLoc` oft nicht auf flachen `sections`, aber `unit.phases` (verschachtelt).
|
||||||
|
* Baut pro Abschnitt `planLoc` für phaseRuns / Darstellung (camelCase wie im Editor).
|
||||||
|
*/
|
||||||
|
function planLocBySectionIdFromPhases(phases) {
|
||||||
|
const byId = new Map()
|
||||||
|
if (!Array.isArray(phases)) return byId
|
||||||
|
for (const ph of phases) {
|
||||||
|
const po = Number(ph.order_index ?? ph.orderIndex ?? 0) || 0
|
||||||
|
const pk = String(ph.phase_kind ?? ph.phaseKind ?? '')
|
||||||
|
.toLowerCase()
|
||||||
|
.trim()
|
||||||
|
const phaseTitle = ph.title ?? ph.phaseTitle ?? null
|
||||||
|
const phaseGuidanceNotes = ph.guidance_notes ?? ph.guidanceNotes ?? null
|
||||||
|
if (pk === 'whole_group') {
|
||||||
|
for (const sec of ph.sections || []) {
|
||||||
|
const sid = sec.id != null ? Number(sec.id) : NaN
|
||||||
|
if (!Number.isFinite(sid)) continue
|
||||||
|
byId.set(sid, {
|
||||||
|
phaseKind: 'whole_group',
|
||||||
|
phaseOrderIndex: po,
|
||||||
|
parallelStreamOrderIndex: null,
|
||||||
|
phaseTitle,
|
||||||
|
phaseGuidanceNotes,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else if (pk === 'parallel') {
|
||||||
|
for (const st of ph.streams || []) {
|
||||||
|
const so = Number(st.order_index ?? st.orderIndex ?? 0) || 0
|
||||||
|
const streamTitle = st.title ?? st.streamTitle ?? null
|
||||||
|
const streamNotes = st.notes ?? st.streamNotes ?? null
|
||||||
|
const streamAssignedTrainerProfileIds =
|
||||||
|
st.assigned_trainer_profile_ids ?? st.streamAssignedTrainerProfileIds ?? null
|
||||||
|
for (const sec of st.sections || []) {
|
||||||
|
const sid = sec.id != null ? Number(sec.id) : NaN
|
||||||
|
if (!Number.isFinite(sid)) continue
|
||||||
|
byId.set(sid, {
|
||||||
|
phaseKind: 'parallel',
|
||||||
|
phaseOrderIndex: po,
|
||||||
|
parallelStreamOrderIndex: so,
|
||||||
|
phaseTitle,
|
||||||
|
phaseGuidanceNotes,
|
||||||
|
streamTitle,
|
||||||
|
streamNotes,
|
||||||
|
streamAssignedTrainerProfileIds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return byId
|
||||||
|
}
|
||||||
|
|
||||||
|
function maxPhaseOrderIndexFromNestedPhases(phases) {
|
||||||
|
let m = -1
|
||||||
|
if (!Array.isArray(phases)) return m
|
||||||
|
for (const ph of phases) {
|
||||||
|
const po = Number(ph.order_index ?? ph.orderIndex ?? 0)
|
||||||
|
if (Number.isFinite(po)) m = Math.max(m, po)
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sectionsWithPlanLocForDisplay(unit) {
|
||||||
|
const sorted = sortedSections(unit)
|
||||||
|
const byId = planLocBySectionIdFromPhases(unit?.phases)
|
||||||
|
const merged = sorted.map((s) => {
|
||||||
|
const sid = s.id != null ? Number(s.id) : NaN
|
||||||
|
if (Number.isFinite(sid) && byId.has(sid)) {
|
||||||
|
return { ...s, planLoc: { ...byId.get(sid) } }
|
||||||
|
}
|
||||||
|
if (s.planLoc && s.planLoc.phaseKind) return s
|
||||||
|
return { ...s }
|
||||||
|
})
|
||||||
|
const inherited = inheritPlanLocForPhasedSave(merged)
|
||||||
|
const maxPhPo = maxPhaseOrderIndexFromNestedPhases(unit?.phases)
|
||||||
|
return inherited.map((s) => {
|
||||||
|
const sid = s.id != null ? Number(s.id) : NaN
|
||||||
|
if (!Number.isFinite(sid) || byId.has(sid)) return s
|
||||||
|
const pl = s.planLoc
|
||||||
|
if (pl?.phaseKind === 'parallel') {
|
||||||
|
const po = maxPhPo >= 0 ? maxPhPo + 1 : 0
|
||||||
|
return {
|
||||||
|
...s,
|
||||||
|
planLoc: {
|
||||||
|
...defaultPlanLocWholeGroup(po),
|
||||||
|
phaseTitle: pl.phaseTitle ?? null,
|
||||||
|
phaseGuidanceNotes: pl.phaseGuidanceNotes ?? null,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Läuft auf bereits angereichter Abschnittsliste (gleiche Objektreferenzen wie in Slices).
|
||||||
|
*/
|
||||||
|
export function buildPlanRunViewModelFromSections(sections) {
|
||||||
|
if (!sections.length) {
|
||||||
|
return { mode: 'empty', runs: [], totalMin: 0, runCumulativeEnds: [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
const runsMeta = phaseRunsFromSections(sections)
|
||||||
|
const runs = []
|
||||||
|
let cum = 0
|
||||||
|
const runCumulativeEnds = []
|
||||||
|
|
||||||
|
if (runsMeta.length === 0) {
|
||||||
|
const minutes = sections.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
|
||||||
|
cum = minutes
|
||||||
|
runCumulativeEnds.push(cum)
|
||||||
|
runs.push({
|
||||||
|
kind: 'legacy',
|
||||||
|
phaseOrderIndex: 0,
|
||||||
|
phaseTitle: null,
|
||||||
|
minutes,
|
||||||
|
sections,
|
||||||
|
streams: null,
|
||||||
|
globalOrderSections: sections,
|
||||||
|
})
|
||||||
|
return { mode: 'legacy', runs, totalMin: minutes, runCumulativeEnds }
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const r of runsMeta) {
|
||||||
|
const slice = sections.slice(r.start, r.end)
|
||||||
|
if (r.phaseKind === 'whole_group') {
|
||||||
|
const minutes = slice.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
|
||||||
|
cum += minutes
|
||||||
|
runCumulativeEnds.push(cum)
|
||||||
|
const phaseTitle = slice[0]?.planLoc?.phaseTitle ?? null
|
||||||
|
runs.push({
|
||||||
|
kind: 'whole_group',
|
||||||
|
phaseOrderIndex: r.phaseOrderIndex,
|
||||||
|
phaseTitle,
|
||||||
|
minutes,
|
||||||
|
sections: slice,
|
||||||
|
streams: null,
|
||||||
|
globalOrderSections: slice,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const po = r.phaseOrderIndex
|
||||||
|
const streamOrders = streamsForParallelPhaseOrders(slice, po)
|
||||||
|
const streams = streamOrders.map((so) => {
|
||||||
|
const idxs = sectionIndicesForParallelStream(slice, po, so)
|
||||||
|
const streamSecs = idxs
|
||||||
|
.map((i) => slice[i])
|
||||||
|
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
|
||||||
|
const first = streamSecs[0]
|
||||||
|
const streamTitle = first?.planLoc?.streamTitle ?? null
|
||||||
|
const minutes = streamSecs.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
|
||||||
|
return {
|
||||||
|
streamOrder: so,
|
||||||
|
streamTitle,
|
||||||
|
minutes,
|
||||||
|
sections: streamSecs,
|
||||||
|
printStreamId: `p${po}-s${so}`,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const minutes = slice.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
|
||||||
|
cum += minutes
|
||||||
|
runCumulativeEnds.push(cum)
|
||||||
|
const phaseTitle = slice[0]?.planLoc?.phaseTitle ?? null
|
||||||
|
runs.push({
|
||||||
|
kind: 'parallel',
|
||||||
|
phaseOrderIndex: po,
|
||||||
|
phaseTitle,
|
||||||
|
minutes,
|
||||||
|
streams,
|
||||||
|
sections: null,
|
||||||
|
globalOrderSections: slice,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { mode: 'phased', runs, totalMin: cum, runCumulativeEnds }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {object} unit Trainingseinheit inkl. `sections`, optional `phases` (GET) */
|
||||||
|
export function buildPlanRunViewModel(unit) {
|
||||||
|
return buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
|
||||||
|
}
|
||||||
|
|
||||||
|
function coachContextLabelForSection(sec, sectionsList) {
|
||||||
|
const pl = sec?.planLoc
|
||||||
|
if (!pl?.phaseKind) return 'Ablauf'
|
||||||
|
if (pl.phaseKind === 'whole_group') {
|
||||||
|
const pt = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : null
|
||||||
|
return pt ? `Ganzgruppe · ${pt}` : 'Ganzgruppe'
|
||||||
|
}
|
||||||
|
const pt = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : `Phase ${pl.phaseOrderIndex ?? 0}`
|
||||||
|
const so = pl.parallelStreamOrderIndex ?? 0
|
||||||
|
const st = pl.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : `Gruppe ${so + 1}`
|
||||||
|
return `Parallel · ${pt} · ${st}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const COACH_ENTRY_BRANCH_GATE = 'branch_gate'
|
||||||
|
|
||||||
|
/** Normalisierte Stream-Wahl pro paralleler Phase (Phase-Index → Stream-Order). */
|
||||||
|
export function normalizeCoachBranchPicks(raw) {
|
||||||
|
const out = {}
|
||||||
|
if (!raw || typeof raw !== 'object') return out
|
||||||
|
for (const [k, v] of Object.entries(raw)) {
|
||||||
|
const pk = parseInt(String(k), 10)
|
||||||
|
const sv = typeof v === 'number' ? v : parseInt(String(v), 10)
|
||||||
|
if (Number.isFinite(pk) && Number.isFinite(sv)) out[pk] = sv
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL-/Dropdown-Fokus `coachFocus` in Pick-Map mergen (fest gewählter Stream für eine Phase).
|
||||||
|
* @param {object} branchPicks Roh-Picks (z. B. aus Session)
|
||||||
|
* @param {{ phaseOrder: number, streamOrder: number }|null} coachFocusUrl z. B. ?po=&so=
|
||||||
|
*/
|
||||||
|
export function mergeCoachBranchPicksWithUrlFocus(branchPicks, coachFocusUrl) {
|
||||||
|
const m = normalizeCoachBranchPicks(branchPicks)
|
||||||
|
if (
|
||||||
|
coachFocusUrl != null &&
|
||||||
|
Number.isFinite(coachFocusUrl.phaseOrder) &&
|
||||||
|
Number.isFinite(coachFocusUrl.streamOrder)
|
||||||
|
) {
|
||||||
|
m[coachFocusUrl.phaseOrder] = coachFocusUrl.streamOrder
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kurzstring für SessionStorage-Schlüssel (Sortierung stabil). */
|
||||||
|
export function coachBranchPicksStepStorageSuffix(mergedPicks) {
|
||||||
|
const keys = Object.keys(mergedPicks)
|
||||||
|
.map((k) => parseInt(String(k), 10))
|
||||||
|
.filter((n) => Number.isFinite(n))
|
||||||
|
.sort((a, b) => a - b)
|
||||||
|
if (!keys.length) return 'full'
|
||||||
|
return keys.map((k) => `p${k}-s${mergedPicks[k]}`).join('_')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function coachBranchPicksStorageKey(unitId) {
|
||||||
|
return `sj_coach_branches_${unitId}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Index zum Springen: Co-Trainer-Link atBranch+preferSo — Gate falls noch offen, sonst erste Kachel im Stream.
|
||||||
|
*/
|
||||||
|
export function findCoachTimelineJumpIndexForPhase(timeline, phaseOrder, preferStreamOrder = null) {
|
||||||
|
const po = Number(phaseOrder)
|
||||||
|
if (!Number.isFinite(po) || !Array.isArray(timeline)) return -1
|
||||||
|
const hint = preferStreamOrder != null && Number.isFinite(Number(preferStreamOrder)) ? Number(preferStreamOrder) : null
|
||||||
|
if (hint != null) {
|
||||||
|
const ixStream = timeline.findIndex(
|
||||||
|
(e) =>
|
||||||
|
e.entryKind !== COACH_ENTRY_BRANCH_GATE &&
|
||||||
|
e.runMeta?.kind === 'parallel' &&
|
||||||
|
e.runMeta.phaseOrderIndex === po &&
|
||||||
|
e.runMeta.streamOrder === hint
|
||||||
|
)
|
||||||
|
if (ixStream >= 0) return ixStream
|
||||||
|
}
|
||||||
|
const ixGate = timeline.findIndex(
|
||||||
|
(e) => e.entryKind === COACH_ENTRY_BRANCH_GATE && e.branchMeta?.phaseOrderIndex === po
|
||||||
|
)
|
||||||
|
return ixGate
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gruppiert die flache Coach-Timeline für den Trainingsrahmen (Überschriften + Einträge). */
|
||||||
|
export function coachOutlineGroupsFromTimeline(timeline) {
|
||||||
|
const groups = []
|
||||||
|
for (let ix = 0; ix < timeline.length; ix++) {
|
||||||
|
const ent = timeline[ix]
|
||||||
|
let mergeKey = `ix-${ix}`
|
||||||
|
let heading = 'Ablauf'
|
||||||
|
let sub = ''
|
||||||
|
if (ent.entryKind === COACH_ENTRY_BRANCH_GATE) {
|
||||||
|
const po = ent.branchMeta?.phaseOrderIndex ?? 0
|
||||||
|
mergeKey = `gate-${po}`
|
||||||
|
heading = 'Split · Gruppe wählen'
|
||||||
|
const pt = ent.branchMeta?.phaseTitle
|
||||||
|
sub =
|
||||||
|
pt != null && String(pt).trim()
|
||||||
|
? String(pt).trim()
|
||||||
|
: `Parallele Phase ${po}`
|
||||||
|
} else {
|
||||||
|
const rm = ent.runMeta
|
||||||
|
if (rm?.kind === 'whole_group') {
|
||||||
|
mergeKey = `wg-${rm.phaseOrderIndex}`
|
||||||
|
const pl = ent.sec?.planLoc
|
||||||
|
const ptt = pl?.phaseTitle
|
||||||
|
heading = 'Ganzgruppe'
|
||||||
|
sub = ptt != null && String(ptt).trim() ? String(ptt).trim() : ''
|
||||||
|
} else if (rm?.kind === 'parallel' && rm.streamOrder != null) {
|
||||||
|
mergeKey = `par-${rm.phaseOrderIndex}-s${rm.streamOrder}`
|
||||||
|
const pl = ent.sec?.planLoc
|
||||||
|
const ptt = pl?.phaseTitle
|
||||||
|
const stt = pl?.streamTitle
|
||||||
|
const ptl = ptt != null && String(ptt).trim() ? String(ptt).trim() : `Phase ${rm.phaseOrderIndex}`
|
||||||
|
const stl = stt != null && String(stt).trim() ? String(stt).trim() : `Gruppe ${rm.streamOrder + 1}`
|
||||||
|
heading = `Parallel · ${ptl}`
|
||||||
|
sub = stl
|
||||||
|
} else if (rm?.kind === 'legacy') {
|
||||||
|
mergeKey = 'legacy'
|
||||||
|
heading = 'Ablauf'
|
||||||
|
sub = ''
|
||||||
|
} else {
|
||||||
|
mergeKey = `misc-${ix}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const prev = groups[groups.length - 1]
|
||||||
|
if (!prev || prev.mergeKey !== mergeKey) {
|
||||||
|
groups.push({ mergeKey, heading, sub, entries: [{ ix, ent }] })
|
||||||
|
} else {
|
||||||
|
prev.entries.push({ ix, ent })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return groups
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flache Coach-Reihenfolge. Pro paralleler Phase ohne Eintrag in branchPicks: ein sichtbarer branch_gate,
|
||||||
|
* damit keine verschränkten Split-Übungen, bis eine Gruppe gewählt wurde.
|
||||||
|
* @param {object} unit
|
||||||
|
* @param {object} branchPicks z. B. { 0: 1 } = Phase 0 → Stream 1
|
||||||
|
*/
|
||||||
|
export function flattenPlanTimeline(unit, branchPicks = {}) {
|
||||||
|
const sections = sectionsWithPlanLocForDisplay(unit)
|
||||||
|
const model = buildPlanRunViewModelFromSections(sections)
|
||||||
|
if (model.mode === 'empty') return []
|
||||||
|
|
||||||
|
const picks = normalizeCoachBranchPicks(branchPicks)
|
||||||
const list = []
|
const list = []
|
||||||
sortedSections(unit).forEach((sec, si) => {
|
|
||||||
|
const pushSectionItems = (sec, coachCtx, runMeta) => {
|
||||||
|
const si = Math.max(0, sections.indexOf(sec))
|
||||||
const secOrder = sec.order_index ?? si
|
const secOrder = sec.order_index ?? si
|
||||||
sortedItems(sec).forEach((item, ii) => {
|
sortedItems(sec).forEach((item, ii) => {
|
||||||
list.push({
|
list.push({
|
||||||
@@ -34,13 +383,165 @@ export function flattenPlanTimeline(unit) {
|
|||||||
flatIndex: list.length,
|
flatIndex: list.length,
|
||||||
sec,
|
sec,
|
||||||
item,
|
item,
|
||||||
|
coachContext: coachCtx,
|
||||||
|
runMeta: runMeta || null,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
|
|
||||||
|
for (const run of model.runs) {
|
||||||
|
if (run.kind === 'legacy') {
|
||||||
|
const meta = { kind: 'legacy', phaseOrderIndex: 0, streamOrder: null }
|
||||||
|
for (const sec of run.globalOrderSections) {
|
||||||
|
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (run.kind === 'whole_group') {
|
||||||
|
const meta = { kind: 'whole_group', phaseOrderIndex: run.phaseOrderIndex, streamOrder: null }
|
||||||
|
for (const sec of run.globalOrderSections) {
|
||||||
|
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (run.kind === 'parallel') {
|
||||||
|
const po = run.phaseOrderIndex
|
||||||
|
const chosen = picks[po]
|
||||||
|
const hasPick = chosen !== undefined && chosen !== null && Number.isFinite(Number(chosen))
|
||||||
|
if (!hasPick) {
|
||||||
|
list.push({
|
||||||
|
entryKind: COACH_ENTRY_BRANCH_GATE,
|
||||||
|
si: -1,
|
||||||
|
ii: -1,
|
||||||
|
secOrder: -1,
|
||||||
|
flatIndex: list.length,
|
||||||
|
sec: null,
|
||||||
|
item: null,
|
||||||
|
coachContext: '',
|
||||||
|
branchMeta: {
|
||||||
|
phaseOrderIndex: po,
|
||||||
|
phaseTitle: run.phaseTitle,
|
||||||
|
streams: run.streams || [],
|
||||||
|
},
|
||||||
|
runMeta: { kind: 'parallel', phaseOrderIndex: po, streamOrder: null },
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const st = run.streams?.find((x) => x.streamOrder === Number(chosen))
|
||||||
|
const meta = { kind: 'parallel', phaseOrderIndex: po, streamOrder: Number(chosen) }
|
||||||
|
if (st?.sections?.length) {
|
||||||
|
for (const sec of st.sections) {
|
||||||
|
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return list
|
return list
|
||||||
}
|
}
|
||||||
|
|
||||||
export function summarizeTimelineEntry({ item }) {
|
/** Optionen für Coach-Stream-Auswahl (phases · Gruppe). */
|
||||||
|
export function listCoachStreamFocusOptions(unit) {
|
||||||
|
const model = buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
|
||||||
|
const opts = []
|
||||||
|
for (const run of model.runs) {
|
||||||
|
if (run.kind !== 'parallel' || !run.streams?.length) continue
|
||||||
|
const phaseLabel =
|
||||||
|
run.phaseTitle != null && String(run.phaseTitle).trim()
|
||||||
|
? String(run.phaseTitle).trim()
|
||||||
|
: `Phase ${run.phaseOrderIndex}`
|
||||||
|
for (const st of run.streams) {
|
||||||
|
const gl =
|
||||||
|
st.streamTitle != null && String(st.streamTitle).trim()
|
||||||
|
? String(st.streamTitle).trim()
|
||||||
|
: `Gruppe ${st.streamOrder + 1}`
|
||||||
|
opts.push({
|
||||||
|
phaseOrder: run.phaseOrderIndex,
|
||||||
|
streamOrder: st.streamOrder,
|
||||||
|
label: `${phaseLabel} · ${gl}`,
|
||||||
|
valueKey: `${run.phaseOrderIndex}-${st.streamOrder}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return opts
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alle Ist-Minuten-Overrides aus lokalem Delta-State für PUT (unabhängig von gefilterter Coach-Timeline). */
|
||||||
|
export function durationOverridesMapFromDeltas(unit, deltas) {
|
||||||
|
const out = {}
|
||||||
|
if (!unit || !deltas || typeof deltas !== 'object') return out
|
||||||
|
const sections = sortedSections(unit)
|
||||||
|
sections.forEach((sec, si) => {
|
||||||
|
const secOrder = sec.order_index ?? si
|
||||||
|
sortedItems(sec).forEach((it, ii) => {
|
||||||
|
if (it.item_type !== 'exercise' || it.id == null) return
|
||||||
|
const k = itemStableKey(it, secOrder, ii)
|
||||||
|
const dv = deltas[k]?.actual_duration_min
|
||||||
|
if (dv !== undefined && dv !== '' && dv !== null && !Number.isNaN(Number(dv))) {
|
||||||
|
out[String(it.id)] = { actual_duration_min: Number(dv) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT-Body für Coach-Speichern: `phases` wenn Plan Phasen hat, sonst `sections` (wie Planungseditor). */
|
||||||
|
export function buildCoachSavePlanPayload(unit, durationOverridesByItemId = {}) {
|
||||||
|
const withLoc = sectionsWithPlanLocForDisplay(unit)
|
||||||
|
const withDur = withLoc.map((sec) => ({
|
||||||
|
...sec,
|
||||||
|
items: sortedItems(sec).map((it) => {
|
||||||
|
if (it.item_type !== 'exercise' || it.id == null) return it
|
||||||
|
const o = durationOverridesByItemId[String(it.id)]
|
||||||
|
const av = o?.actual_duration_min
|
||||||
|
if (av !== undefined && av !== '' && av !== null && Number.isFinite(Number(av))) {
|
||||||
|
return { ...it, actual_duration_min: Number(av) }
|
||||||
|
}
|
||||||
|
return it
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
return buildPlanPayloadForSave(withDur)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nach dem letzten Block eines Streams: Rückfrage, wenn die parallele Phase mehrere Gruppen hat.
|
||||||
|
*/
|
||||||
|
export function coachShouldPromptSplitRejoin(unit, lastTimelineEntry) {
|
||||||
|
const rm = lastTimelineEntry?.runMeta
|
||||||
|
if (!rm || rm.kind !== 'parallel' || rm.streamOrder == null) return null
|
||||||
|
const model = buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
|
||||||
|
const run = model.runs.find((r) => r.kind === 'parallel' && r.phaseOrderIndex === rm.phaseOrderIndex)
|
||||||
|
if (!run?.streams || run.streams.length <= 1) return null
|
||||||
|
return {
|
||||||
|
phaseOrderIndex: run.phaseOrderIndex,
|
||||||
|
phaseTitle: run.phaseTitle,
|
||||||
|
streams: run.streams,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nach dem letzten Block eines gewählten Streams: Rückfrage vor Ganzgruppenphase oder vor dem nächsten Split,
|
||||||
|
* wenn die aktuelle Parallelphase mehrere Streams hat.
|
||||||
|
*/
|
||||||
|
export function coachShouldPromptSplitRejoinTransition(unit, currentEntry, nextEntry) {
|
||||||
|
if (!currentEntry || !nextEntry) return null
|
||||||
|
const cRm = currentEntry.runMeta
|
||||||
|
if (!cRm || cRm.kind !== 'parallel' || cRm.streamOrder == null) return null
|
||||||
|
const intoWholeGroup = nextEntry.runMeta?.kind === 'whole_group'
|
||||||
|
const intoNextSplit = nextEntry.entryKind === COACH_ENTRY_BRANCH_GATE
|
||||||
|
if (!intoWholeGroup && !intoNextSplit) return null
|
||||||
|
return coachShouldPromptSplitRejoin(unit, currentEntry)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeTimelineEntry(ent) {
|
||||||
|
if (!ent) return ''
|
||||||
|
if (ent.entryKind === COACH_ENTRY_BRANCH_GATE) {
|
||||||
|
const t = ent.branchMeta?.phaseTitle != null && String(ent.branchMeta.phaseTitle).trim()
|
||||||
|
? String(ent.branchMeta.phaseTitle).trim()
|
||||||
|
: ''
|
||||||
|
return t ? `Split wählen · ${t}` : 'Split · Gruppe wählen'
|
||||||
|
}
|
||||||
|
const { item } = ent
|
||||||
if (!item) return ''
|
if (!item) return ''
|
||||||
if (item.item_type === 'note') {
|
if (item.item_type === 'note') {
|
||||||
const t = String(item.note_body || '').trim()
|
const t = String(item.note_body || '').trim()
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { buildPlanPayloadForSave, defaultSection } from './trainingUnitSectionsForm'
|
||||||
|
import { sessionAssignDefaults } from './trainingPlanningPageHelpers'
|
||||||
|
|
||||||
|
/** Leeres Formular für neue Einheit (ohne async Varianten-Anreicherung). */
|
||||||
|
export function createEmptyTrainingUnitFormData({
|
||||||
|
groupId = '',
|
||||||
|
plannedDate = '',
|
||||||
|
timeStart = '',
|
||||||
|
timeEnd = '',
|
||||||
|
} = {}) {
|
||||||
|
return {
|
||||||
|
group_id: groupId != null ? String(groupId) : '',
|
||||||
|
planned_date: plannedDate || '',
|
||||||
|
planned_time_start: timeStart || '',
|
||||||
|
planned_time_end: timeEnd || '',
|
||||||
|
planned_focus: '',
|
||||||
|
actual_date: '',
|
||||||
|
actual_time_start: '',
|
||||||
|
actual_time_end: '',
|
||||||
|
attendance_count: '',
|
||||||
|
status: 'planned',
|
||||||
|
notes: '',
|
||||||
|
trainer_notes: '',
|
||||||
|
debrief_completed: false,
|
||||||
|
sections: [defaultSection('Hauptteil')],
|
||||||
|
...sessionAssignDefaults(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API-Zeile → Formular (sync). `sections` müssen vorher via normalizeUnitToForm + enrich kommen.
|
||||||
|
* @param {object} fullUnit
|
||||||
|
* @param {object} sections — bereits angereicherte Editor-Sections
|
||||||
|
*/
|
||||||
|
export function trainingUnitToFormFields(fullUnit, sections) {
|
||||||
|
const efLead =
|
||||||
|
fullUnit.effective_lead_trainer_profile_id != null
|
||||||
|
? Number(fullUnit.effective_lead_trainer_profile_id)
|
||||||
|
: null
|
||||||
|
let assistantIds = []
|
||||||
|
if (Array.isArray(fullUnit.assistant_trainer_profile_ids)) {
|
||||||
|
assistantIds = fullUnit.assistant_trainer_profile_ids
|
||||||
|
.map((x) => Number(x))
|
||||||
|
.filter((n) => Number.isFinite(n) && n >= 1)
|
||||||
|
}
|
||||||
|
if (efLead != null && Number.isFinite(efLead)) {
|
||||||
|
assistantIds = assistantIds.filter((id) => id !== efLead)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
group_id: fullUnit.group_id,
|
||||||
|
planned_date: fullUnit.planned_date || '',
|
||||||
|
planned_time_start: fullUnit.planned_time_start?.slice?.(0, 5) || fullUnit.planned_time_start || '',
|
||||||
|
planned_time_end: fullUnit.planned_time_end?.slice?.(0, 5) || fullUnit.planned_time_end || '',
|
||||||
|
planned_focus: fullUnit.planned_focus || '',
|
||||||
|
actual_date: fullUnit.actual_date || '',
|
||||||
|
actual_time_start: fullUnit.actual_time_start?.slice?.(0, 5) || fullUnit.actual_time_start || '',
|
||||||
|
actual_time_end: fullUnit.actual_time_end?.slice?.(0, 5) || fullUnit.actual_time_end || '',
|
||||||
|
attendance_count: fullUnit.attendance_count ?? '',
|
||||||
|
status: fullUnit.status || 'planned',
|
||||||
|
notes: fullUnit.notes || '',
|
||||||
|
trainer_notes: fullUnit.trainer_notes || '',
|
||||||
|
debrief_completed: Boolean(fullUnit.debrief_completed_at),
|
||||||
|
sections,
|
||||||
|
lead_trainer_profile_id:
|
||||||
|
fullUnit.lead_trainer_profile_id != null && fullUnit.lead_trainer_profile_id !== ''
|
||||||
|
? String(fullUnit.lead_trainer_profile_id)
|
||||||
|
: '',
|
||||||
|
session_assistants_inherit:
|
||||||
|
fullUnit.assistant_trainer_profile_ids == null ||
|
||||||
|
fullUnit.assistant_trainer_profile_ids === undefined,
|
||||||
|
session_assistant_profile_ids: assistantIds,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formular → API-Payload (identisch zur bisherigen Modal-Logik).
|
||||||
|
* @param {object} formData
|
||||||
|
* @param {{ editingUnit?: object|null, draftPlanTemplateId?: string }} opts
|
||||||
|
*/
|
||||||
|
export function buildTrainingUnitSavePayload(formData, { editingUnit = null, draftPlanTemplateId = '' } = {}) {
|
||||||
|
const planPart = buildPlanPayloadForSave(formData.sections)
|
||||||
|
const payload = {
|
||||||
|
planned_date: formData.planned_date,
|
||||||
|
planned_time_start: formData.planned_time_start || null,
|
||||||
|
planned_time_end: formData.planned_time_end || null,
|
||||||
|
planned_focus: formData.planned_focus || null,
|
||||||
|
actual_date: formData.actual_date || null,
|
||||||
|
actual_time_start: formData.actual_time_start || null,
|
||||||
|
actual_time_end: formData.actual_time_end || null,
|
||||||
|
attendance_count: formData.attendance_count ? parseInt(formData.attendance_count, 10) : null,
|
||||||
|
status: formData.status || 'planned',
|
||||||
|
notes: formData.notes || null,
|
||||||
|
trainer_notes: formData.trainer_notes || null,
|
||||||
|
...planPart,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (editingUnit) {
|
||||||
|
payload.debrief_completed =
|
||||||
|
(formData.status || '') === 'completed' ? !!formData.debrief_completed : false
|
||||||
|
}
|
||||||
|
|
||||||
|
const leadStr = String(formData.lead_trainer_profile_id || '').trim()
|
||||||
|
if (leadStr) {
|
||||||
|
payload.lead_trainer_profile_id = parseInt(leadStr, 10)
|
||||||
|
} else if (editingUnit) {
|
||||||
|
payload.lead_trainer_profile_id = null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.session_assistants_inherit) {
|
||||||
|
if (editingUnit) payload.assistant_trainer_profile_ids = null
|
||||||
|
} else {
|
||||||
|
payload.assistant_trainer_profile_ids = [...(formData.session_assistant_profile_ids || [])].sort(
|
||||||
|
(a, b) => a - b
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!editingUnit) {
|
||||||
|
payload.group_id = parseInt(formData.group_id, 10)
|
||||||
|
if (draftPlanTemplateId) {
|
||||||
|
payload.plan_template_id = parseInt(draftPlanTemplateId, 10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateTrainingUnitFormForSave(formData) {
|
||||||
|
if (!formData?.group_id || !formData?.planned_date) {
|
||||||
|
return { ok: false, message: 'Gruppe und Datum sind Pflichtfelder' }
|
||||||
|
}
|
||||||
|
return { ok: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stabiler Fingerabdruck für Dirty-Check (identisch zum Save-Payload). */
|
||||||
|
export function trainingUnitFormSnapshot(
|
||||||
|
formData,
|
||||||
|
{ editingUnit = null, draftPlanTemplateId = '' } = {}
|
||||||
|
) {
|
||||||
|
return JSON.stringify(buildTrainingUnitSavePayload(formData, { editingUnit, draftPlanTemplateId }))
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
buildTrainingUnitSavePayload,
|
||||||
|
createEmptyTrainingUnitFormData,
|
||||||
|
trainingUnitFormSnapshot,
|
||||||
|
validateTrainingUnitFormForSave,
|
||||||
|
} from './trainingUnitEditorCore.js'
|
||||||
|
|
||||||
|
describe('trainingUnitEditorCore', () => {
|
||||||
|
it('createEmptyTrainingUnitFormData defaults', () => {
|
||||||
|
const fd = createEmptyTrainingUnitFormData({ groupId: '2', plannedDate: '2026-05-01' })
|
||||||
|
expect(fd.group_id).toBe('2')
|
||||||
|
expect(fd.planned_date).toBe('2026-05-01')
|
||||||
|
expect(fd.sections).toHaveLength(1)
|
||||||
|
expect(fd.sections[0].title).toBe('Hauptteil')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('validateTrainingUnitFormForSave', () => {
|
||||||
|
expect(validateTrainingUnitFormForSave({ group_id: '', planned_date: '' }).ok).toBe(false)
|
||||||
|
expect(validateTrainingUnitFormForSave({ group_id: '1', planned_date: '2026-01-01' }).ok).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('buildTrainingUnitSavePayload create includes group and template', () => {
|
||||||
|
const formData = createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' })
|
||||||
|
const payload = buildTrainingUnitSavePayload(formData, { draftPlanTemplateId: '9' })
|
||||||
|
expect(payload.group_id).toBe(5)
|
||||||
|
expect(payload.plan_template_id).toBe(9)
|
||||||
|
expect(payload.planned_date).toBe('2026-05-10')
|
||||||
|
expect(payload.sections).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('buildTrainingUnitSavePayload update sets debrief and clears lead when empty', () => {
|
||||||
|
const formData = {
|
||||||
|
...createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' }),
|
||||||
|
status: 'completed',
|
||||||
|
debrief_completed: true,
|
||||||
|
lead_trainer_profile_id: '',
|
||||||
|
session_assistants_inherit: true,
|
||||||
|
}
|
||||||
|
const payload = buildTrainingUnitSavePayload(formData, { editingUnit: { id: 1 } })
|
||||||
|
expect(payload.debrief_completed).toBe(true)
|
||||||
|
expect(payload.lead_trainer_profile_id).toBeNull()
|
||||||
|
expect(payload.assistant_trainer_profile_ids).toBeNull()
|
||||||
|
expect(payload.group_id).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('trainingUnitFormSnapshot matches save payload', () => {
|
||||||
|
const formData = createEmptyTrainingUnitFormData({ groupId: '5', plannedDate: '2026-05-10' })
|
||||||
|
const snap = trainingUnitFormSnapshot(formData, { draftPlanTemplateId: '3' })
|
||||||
|
const payload = buildTrainingUnitSavePayload(formData, { draftPlanTemplateId: '3' })
|
||||||
|
expect(snap).toBe(JSON.stringify(payload))
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -5,6 +5,201 @@ export function defaultSection(title = 'Hauptteil') {
|
|||||||
return { title, guidance_notes: '', items: [] }
|
return { title, guidance_notes: '', items: [] }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Standard-`planLoc` für eine Ganzgruppen-Phase (Editor-Breakout-UI). */
|
||||||
|
export function defaultPlanLocWholeGroup(phaseOrderIndex = 0) {
|
||||||
|
return {
|
||||||
|
phaseKind: 'whole_group',
|
||||||
|
phaseOrderIndex,
|
||||||
|
parallelStreamOrderIndex: null,
|
||||||
|
phaseTitle: null,
|
||||||
|
phaseGuidanceNotes: null,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Standard-`planLoc` für einen Stream innerhalb einer parallelen Phase. */
|
||||||
|
export function defaultPlanLocParallel(phaseOrderIndex, streamOrderIndex) {
|
||||||
|
return {
|
||||||
|
phaseKind: 'parallel',
|
||||||
|
phaseOrderIndex,
|
||||||
|
parallelStreamOrderIndex: streamOrderIndex,
|
||||||
|
phaseTitle: null,
|
||||||
|
phaseGuidanceNotes: null,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planLocKey(pl) {
|
||||||
|
if (!pl || !pl.phaseKind) return ''
|
||||||
|
if (pl.phaseKind === 'whole_group') return `wg:${pl.phaseOrderIndex ?? 0}`
|
||||||
|
return `par:${pl.phaseOrderIndex ?? 0}:${pl.parallelStreamOrderIndex ?? 0}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function maxPhaseOrderIndexFromSections(sections) {
|
||||||
|
let m = -1
|
||||||
|
for (const s of sections || []) {
|
||||||
|
const pl = s?.planLoc
|
||||||
|
if (!pl || typeof pl.phaseOrderIndex !== 'number') continue
|
||||||
|
if (pl.phaseOrderIndex > m) m = pl.phaseOrderIndex
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Eindeutige Ziele für die Zuordnung eines Abschnitts (Dropdown).
|
||||||
|
* `template` ist ein vollständiges planLoc-Objekt zum Kopieren.
|
||||||
|
*/
|
||||||
|
export function buildPlanTargetOptions(sections) {
|
||||||
|
const map = new Map()
|
||||||
|
for (const s of sections || []) {
|
||||||
|
const pl = s?.planLoc
|
||||||
|
if (!pl?.phaseKind) continue
|
||||||
|
if (pl.phaseKind === 'whole_group') {
|
||||||
|
const po = pl.phaseOrderIndex ?? 0
|
||||||
|
const k = `wg:${po}`
|
||||||
|
if (!map.has(k)) {
|
||||||
|
const title = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : ''
|
||||||
|
map.set(k, {
|
||||||
|
key: k,
|
||||||
|
label: title || `Ganzgruppe · Phase ${po}`,
|
||||||
|
template: { ...pl },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const po = pl.phaseOrderIndex ?? 0
|
||||||
|
const so = pl.parallelStreamOrderIndex ?? 0
|
||||||
|
const k = `par:${po}:${so}`
|
||||||
|
if (!map.has(k)) {
|
||||||
|
const st = pl.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : ''
|
||||||
|
map.set(k, {
|
||||||
|
key: k,
|
||||||
|
label: st || `Parallel · Phase ${po} · Stream ${so}`,
|
||||||
|
template: { ...pl },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...map.values()].sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Max. Streams pro paralleler Phase (UI + API-Schutz). */
|
||||||
|
export const MAX_PARALLEL_STREAMS_PER_PHASE = 5
|
||||||
|
|
||||||
|
/** Farben pro Stream-Index (max. 5 unterschiedliche Farbzyklen). */
|
||||||
|
export function parallelStreamVisual(streamOrderIndex) {
|
||||||
|
const n = Math.max(0, Number(streamOrderIndex) || 0)
|
||||||
|
const hues = [200, 135, 38, 285, 22]
|
||||||
|
const h = hues[n % hues.length]
|
||||||
|
return {
|
||||||
|
border: `hsl(${h} 50% 36%)`,
|
||||||
|
soft: `hsl(${h} 36% 94%)`,
|
||||||
|
tabBg: `hsl(${h} 34% 92%)`,
|
||||||
|
tabBgActive: `hsl(${h} 40% 82%)`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function streamTabLabelFromIndices(sections, globalIndices) {
|
||||||
|
const first = globalIndices?.[0]
|
||||||
|
if (first === undefined || !sections?.[first]) return 'Stream'
|
||||||
|
const pl = sections[first].planLoc
|
||||||
|
const t = pl?.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : ''
|
||||||
|
if (t) return t
|
||||||
|
const so = pl?.parallelStreamOrderIndex ?? 0
|
||||||
|
return `Stream ${so + 1}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sortierte Stream-Indizes innerhalb einer parallelen Phase (für Reiter). */
|
||||||
|
export function streamsForParallelPhaseOrders(sections, phaseOrderIndex) {
|
||||||
|
const set = new Set()
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
for (const s of sections || []) {
|
||||||
|
const L = s?.planLoc
|
||||||
|
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po) {
|
||||||
|
set.add(L.parallelStreamOrderIndex ?? 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...set].sort((a, b) => a - b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Globale Abschnitts-Indizes eines Streams. */
|
||||||
|
export function sectionIndicesForParallelStream(sections, phaseOrderIndex, streamOrderIndex) {
|
||||||
|
const out = []
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const so = Number(streamOrderIndex) || 0
|
||||||
|
;(sections || []).forEach((s, i) => {
|
||||||
|
const L = s?.planLoc
|
||||||
|
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po && (L.parallelStreamOrderIndex ?? 0) === so) {
|
||||||
|
out.push(i)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Abschnitte an den angegebenen globalen Indizes entfernen (mindestens ein Abschnitt bleibt). */
|
||||||
|
export function reorderWithoutIndices(prev, removeGlobalIndices) {
|
||||||
|
const set = new Set(removeGlobalIndices || [])
|
||||||
|
const next = (prev || []).filter((_, i) => !set.has(i))
|
||||||
|
return next.length ? next : [defaultSection()]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ob in den Abschnitten eines Stream-Buckets planerisch etwas steht (Übungen, Text-Anmerkungen).
|
||||||
|
* Trennlinien-Marker (---) zählen nicht als Inhalt.
|
||||||
|
*/
|
||||||
|
export function parallelStreamBucketHasContent(sections, globalIndices, separatorBody = '---') {
|
||||||
|
for (const gi of globalIndices || []) {
|
||||||
|
const sec = (sections || [])[gi]
|
||||||
|
if (!sec) continue
|
||||||
|
for (const it of sec.items || []) {
|
||||||
|
if ((it.item_type || '') === 'note') {
|
||||||
|
const b = (it.note_body || '').trim()
|
||||||
|
if (b && b !== separatorBody) return true
|
||||||
|
} else {
|
||||||
|
if (it.exercise_id) return true
|
||||||
|
if ((it.exercise_title || '').trim()) return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parallele Phase auflösen: alle Abschnitte dieser Phase werden Ganzgruppe (gleicher phaseOrderIndex). */
|
||||||
|
export function dissolveParallelPhaseToWholeGroup(sections, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
return (sections || []).map((s) => {
|
||||||
|
const L = s?.planLoc
|
||||||
|
if (L?.phaseKind !== 'parallel' || (L.phaseOrderIndex ?? 0) !== po) return s
|
||||||
|
return {
|
||||||
|
...s,
|
||||||
|
planLoc: {
|
||||||
|
...defaultPlanLocWholeGroup(po),
|
||||||
|
phaseTitle: L.phaseTitle ?? null,
|
||||||
|
phaseGuidanceNotes: L.phaseGuidanceNotes ?? null,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reorderWithinBucketIndices(prev, bucketGlobalIndicesSorted, oldPos, newPos) {
|
||||||
|
const sortedIdx = [...bucketGlobalIndicesSorted].sort((a, b) => a - b)
|
||||||
|
if (oldPos === newPos || oldPos < 0 || newPos < 0 || oldPos >= sortedIdx.length || newPos >= sortedIdx.length) {
|
||||||
|
return prev
|
||||||
|
}
|
||||||
|
const values = sortedIdx.map((gi) => prev[gi])
|
||||||
|
const arr = [...values]
|
||||||
|
const [x] = arr.splice(oldPos, 1)
|
||||||
|
arr.splice(newPos, 0, x)
|
||||||
|
const next = [...prev]
|
||||||
|
sortedIdx.forEach((gi, k) => {
|
||||||
|
next[gi] = arr[k]
|
||||||
|
})
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeCatalogMethodProfile(cp) {
|
function normalizeCatalogMethodProfile(cp) {
|
||||||
if (cp && typeof cp === 'object' && !Array.isArray(cp)) return { ...cp }
|
if (cp && typeof cp === 'object' && !Array.isArray(cp)) return { ...cp }
|
||||||
return {}
|
return {}
|
||||||
@@ -156,65 +351,132 @@ function parseOptionalSourceTrainingModuleIdForPayload(v) {
|
|||||||
return Number.isFinite(n) && n >= 1 ? n : null
|
return Number.isFinite(n) && n >= 1 ? n : null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sortByOrderIndex(arr) {
|
||||||
|
return [...(arr || [])].sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Katalog-Abschnitt (GET) → Editor-Zeilen inkl. Kombi/Modul-Meta — wird von Legacy `sections` und von `phases` genutzt. */
|
||||||
|
function formItemsFromApiItems(items) {
|
||||||
|
return (items || []).map((it) => {
|
||||||
|
if (it.item_type === 'note') {
|
||||||
|
const sm = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
|
||||||
|
const rowNote = {
|
||||||
|
item_type: 'note',
|
||||||
|
note_body: it.note_body || '',
|
||||||
|
source_training_module_id: '',
|
||||||
|
source_module_title: '',
|
||||||
|
}
|
||||||
|
if (sm != null) {
|
||||||
|
rowNote.source_training_module_id = sm
|
||||||
|
rowNote.source_module_title = (
|
||||||
|
it.source_module_title ||
|
||||||
|
it.source_training_module_title ||
|
||||||
|
''
|
||||||
|
).trim()
|
||||||
|
}
|
||||||
|
return rowNote
|
||||||
|
}
|
||||||
|
const smEx = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
|
||||||
|
const ek = String(it.exercise_kind || 'simple').toLowerCase().trim()
|
||||||
|
const isCombo = ek === 'combination'
|
||||||
|
return {
|
||||||
|
item_type: 'exercise',
|
||||||
|
exercise_id: it.exercise_id,
|
||||||
|
exercise_kind: isCombo ? 'combination' : 'simple',
|
||||||
|
exercise_variant_id: isCombo ? '' : it.exercise_variant_id ?? '',
|
||||||
|
exercise_title: it.exercise_title || '',
|
||||||
|
variants: [],
|
||||||
|
planned_duration_min:
|
||||||
|
it.planned_duration_min !== null && it.planned_duration_min !== undefined
|
||||||
|
? String(it.planned_duration_min)
|
||||||
|
: '',
|
||||||
|
actual_duration_min:
|
||||||
|
it.actual_duration_min !== null && it.actual_duration_min !== undefined
|
||||||
|
? String(it.actual_duration_min)
|
||||||
|
: '',
|
||||||
|
notes: it.notes ?? '',
|
||||||
|
modifications: it.modifications ?? '',
|
||||||
|
catalog_method_archetype: String(it.catalog_method_archetype ?? '').trim(),
|
||||||
|
catalog_method_profile: normalizeCatalogMethodProfile(it.catalog_method_profile),
|
||||||
|
planning_method_profile: normalizePlanningMethodProfile(it.planning_method_profile),
|
||||||
|
...(smEx != null
|
||||||
|
? {
|
||||||
|
source_training_module_id: smEx,
|
||||||
|
source_module_title: (
|
||||||
|
it.source_module_title ||
|
||||||
|
it.source_training_module_title ||
|
||||||
|
''
|
||||||
|
).trim(),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET `phases` → flache Editor-Abschnitte mit `planLoc` (für PUT `phases` Roundtrip). */
|
||||||
|
function normalizePhasesToFormSections(fullUnit) {
|
||||||
|
const phases = sortByOrderIndex(fullUnit.phases || [])
|
||||||
|
const out = []
|
||||||
|
for (const ph of phases) {
|
||||||
|
const pOi = ph.order_index ?? 0
|
||||||
|
const pk = String(ph.phase_kind || 'whole_group').toLowerCase().trim()
|
||||||
|
const basePhaseLoc = {
|
||||||
|
phaseTitle: ph.title ?? null,
|
||||||
|
phaseGuidanceNotes: ph.guidance_notes ?? null,
|
||||||
|
}
|
||||||
|
if (pk === 'parallel') {
|
||||||
|
for (const st of sortByOrderIndex(ph.streams || [])) {
|
||||||
|
const sOi = st.order_index ?? 0
|
||||||
|
const streamLoc = {
|
||||||
|
phaseKind: 'parallel',
|
||||||
|
phaseOrderIndex: pOi,
|
||||||
|
parallelStreamOrderIndex: sOi,
|
||||||
|
...basePhaseLoc,
|
||||||
|
streamTitle: st.title ?? null,
|
||||||
|
streamNotes: st.notes ?? null,
|
||||||
|
streamAssignedTrainerProfileIds: st.assigned_trainer_profile_ids ?? null,
|
||||||
|
}
|
||||||
|
for (const sec of sortByOrderIndex(st.sections || [])) {
|
||||||
|
out.push({
|
||||||
|
title: sec.title,
|
||||||
|
guidance_notes: sec.guidance_notes || '',
|
||||||
|
items: formItemsFromApiItems(sec.items),
|
||||||
|
planLoc: { ...streamLoc },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const loc = {
|
||||||
|
phaseKind: 'whole_group',
|
||||||
|
phaseOrderIndex: pOi,
|
||||||
|
parallelStreamOrderIndex: null,
|
||||||
|
...basePhaseLoc,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
for (const sec of sortByOrderIndex(ph.sections || [])) {
|
||||||
|
out.push({
|
||||||
|
title: sec.title,
|
||||||
|
guidance_notes: sec.guidance_notes || '',
|
||||||
|
items: formItemsFromApiItems(sec.items),
|
||||||
|
planLoc: { ...loc },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.length ? out : [defaultSection()]
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeUnitToForm(fullUnit) {
|
export function normalizeUnitToForm(fullUnit) {
|
||||||
|
if (Array.isArray(fullUnit?.phases) && fullUnit.phases.length > 0) {
|
||||||
|
return normalizePhasesToFormSections(fullUnit)
|
||||||
|
}
|
||||||
if (fullUnit.sections && fullUnit.sections.length) {
|
if (fullUnit.sections && fullUnit.sections.length) {
|
||||||
return fullUnit.sections.map((sec) => ({
|
return fullUnit.sections.map((sec) => ({
|
||||||
title: sec.title,
|
title: sec.title,
|
||||||
guidance_notes: sec.guidance_notes || '',
|
guidance_notes: sec.guidance_notes || '',
|
||||||
items: (sec.items || []).map((it) => {
|
items: formItemsFromApiItems(sec.items),
|
||||||
if (it.item_type === 'note') {
|
|
||||||
const sm = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
|
|
||||||
const rowNote = {
|
|
||||||
item_type: 'note',
|
|
||||||
note_body: it.note_body || '',
|
|
||||||
source_training_module_id: '',
|
|
||||||
source_module_title: '',
|
|
||||||
}
|
|
||||||
if (sm != null) {
|
|
||||||
rowNote.source_training_module_id = sm
|
|
||||||
rowNote.source_module_title = (
|
|
||||||
it.source_module_title ||
|
|
||||||
it.source_training_module_title ||
|
|
||||||
''
|
|
||||||
).trim()
|
|
||||||
}
|
|
||||||
return rowNote
|
|
||||||
}
|
|
||||||
const smEx = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
|
|
||||||
const ek = String(it.exercise_kind || 'simple').toLowerCase().trim()
|
|
||||||
const isCombo = ek === 'combination'
|
|
||||||
return {
|
|
||||||
item_type: 'exercise',
|
|
||||||
exercise_id: it.exercise_id,
|
|
||||||
exercise_kind: isCombo ? 'combination' : 'simple',
|
|
||||||
exercise_variant_id: isCombo ? '' : it.exercise_variant_id ?? '',
|
|
||||||
exercise_title: it.exercise_title || '',
|
|
||||||
variants: [],
|
|
||||||
planned_duration_min:
|
|
||||||
it.planned_duration_min !== null && it.planned_duration_min !== undefined
|
|
||||||
? String(it.planned_duration_min)
|
|
||||||
: '',
|
|
||||||
actual_duration_min:
|
|
||||||
it.actual_duration_min !== null && it.actual_duration_min !== undefined
|
|
||||||
? String(it.actual_duration_min)
|
|
||||||
: '',
|
|
||||||
notes: it.notes ?? '',
|
|
||||||
modifications: it.modifications ?? '',
|
|
||||||
catalog_method_archetype: String(it.catalog_method_archetype ?? '').trim(),
|
|
||||||
catalog_method_profile: normalizeCatalogMethodProfile(it.catalog_method_profile),
|
|
||||||
planning_method_profile: normalizePlanningMethodProfile(it.planning_method_profile),
|
|
||||||
...(smEx != null
|
|
||||||
? {
|
|
||||||
source_training_module_id: smEx,
|
|
||||||
source_module_title: (
|
|
||||||
it.source_module_title ||
|
|
||||||
it.source_training_module_title ||
|
|
||||||
''
|
|
||||||
).trim(),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
if (fullUnit.exercises && fullUnit.exercises.length) {
|
if (fullUnit.exercises && fullUnit.exercises.length) {
|
||||||
@@ -398,10 +660,9 @@ export function parseMin(v) {
|
|||||||
return Number.isFinite(n) ? n : null
|
return Number.isFinite(n) ? n : null
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PUT /api/training-units/:id `sections` — flache order_index pro Einheit; Parallelität bricht am DB-UNIQUE (training_unit_id, order_index) bis Migration. */
|
export function buildOneSectionPayload(sec, orderIndex) {
|
||||||
export function buildSectionsPayload(sections) {
|
return {
|
||||||
return sections.map((sec, si) => ({
|
order_index: orderIndex,
|
||||||
order_index: si,
|
|
||||||
title: (sec.title || '').trim() || 'Abschnitt',
|
title: (sec.title || '').trim() || 'Abschnitt',
|
||||||
guidance_notes: sec.guidance_notes?.trim() ? sec.guidance_notes.trim() : null,
|
guidance_notes: sec.guidance_notes?.trim() ? sec.guidance_notes.trim() : null,
|
||||||
items: (sec.items || [])
|
items: (sec.items || [])
|
||||||
@@ -446,7 +707,566 @@ export function buildSectionsPayload(sections) {
|
|||||||
return rowEx
|
return rowEx
|
||||||
})
|
})
|
||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
}))
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PUT /api/training-units: Legacy `sections` (eine whole_group-Phase) wenn kein `planLoc` gesetzt ist. */
|
||||||
|
export function buildSectionsPayload(sections) {
|
||||||
|
return sections.map((sec, si) => buildOneSectionPayload(sec, si))
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripPlanLoc(sec) {
|
||||||
|
if (!sec || typeof sec !== 'object') return sec
|
||||||
|
const { planLoc: _pl, ...rest } = sec
|
||||||
|
return rest
|
||||||
|
}
|
||||||
|
|
||||||
|
function phaseIndexToInt(v, fallback = 0) {
|
||||||
|
if (v === null || v === undefined || v === '') return fallback
|
||||||
|
const n = typeof v === 'number' ? v : Number(v)
|
||||||
|
return Number.isFinite(n) ? n : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* planLoc für Phasen-PUT kanonisieren (Großschreibung, numerische Indizes).
|
||||||
|
* Verhindert u. a. abgebrochene Phasen-Runs bei "0" !== 0 und falsche whole_group-Zweige.
|
||||||
|
*/
|
||||||
|
function canonicalPlanLocForPhasedSave(pl) {
|
||||||
|
if (!pl || typeof pl !== 'object') return null
|
||||||
|
const rawKind = String(pl.phaseKind || '').toLowerCase().trim()
|
||||||
|
let kind = rawKind === 'parallel' || rawKind === 'whole_group' ? rawKind : null
|
||||||
|
if (
|
||||||
|
!kind &&
|
||||||
|
pl.parallelStreamOrderIndex != null &&
|
||||||
|
pl.parallelStreamOrderIndex !== ''
|
||||||
|
) {
|
||||||
|
kind = 'parallel'
|
||||||
|
}
|
||||||
|
if (!kind) return null
|
||||||
|
const phaseOrderIndex = phaseIndexToInt(pl.phaseOrderIndex, 0)
|
||||||
|
let parallelStreamOrderIndex = null
|
||||||
|
if (kind === 'parallel') {
|
||||||
|
parallelStreamOrderIndex = phaseIndexToInt(pl.parallelStreamOrderIndex, 0)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...pl,
|
||||||
|
phaseKind: kind,
|
||||||
|
phaseOrderIndex,
|
||||||
|
parallelStreamOrderIndex,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inheritPlanLocForPhasedSave(sections) {
|
||||||
|
let prev = { ...defaultPlanLocWholeGroup(0) }
|
||||||
|
return (sections || []).map((s) => {
|
||||||
|
const canon = canonicalPlanLocForPhasedSave(s?.planLoc)
|
||||||
|
if (canon) {
|
||||||
|
prev = { ...canon }
|
||||||
|
return { ...s, planLoc: prev }
|
||||||
|
}
|
||||||
|
return { ...s, planLoc: { ...prev } }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Phasen-„Runs“ in der flachen Abschnittsliste (Reihenfolge wie beim Speichern). */
|
||||||
|
export function phaseRunsFromSections(sections) {
|
||||||
|
const norm = inheritPlanLocForPhasedSave(sections)
|
||||||
|
const runs = []
|
||||||
|
let i = 0
|
||||||
|
while (i < norm.length) {
|
||||||
|
const loc0 = norm[i]?.planLoc
|
||||||
|
if (!loc0?.phaseKind) {
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const pOi = loc0.phaseOrderIndex ?? 0
|
||||||
|
const pk = loc0.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
|
||||||
|
const start = i
|
||||||
|
while (i < norm.length) {
|
||||||
|
const L = norm[i]?.planLoc
|
||||||
|
if (!L?.phaseKind) break
|
||||||
|
const pk2 = L.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
|
||||||
|
if ((L.phaseOrderIndex ?? 0) !== pOi || pk2 !== pk) break
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
runs.push({ phaseKind: pk, phaseOrderIndex: pOi, start, end: i })
|
||||||
|
}
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vertauscht zwei unmittelbar benachbarte Runs (upperRunIndex = erste der beiden). */
|
||||||
|
export function swapAdjacentPhaseRuns(prev, upperRunIndex) {
|
||||||
|
const runs = phaseRunsFromSections(prev)
|
||||||
|
const a = upperRunIndex
|
||||||
|
const b = upperRunIndex + 1
|
||||||
|
if (a < 0 || b >= runs.length) return prev
|
||||||
|
const rgA = runs[a]
|
||||||
|
const rgB = runs[b]
|
||||||
|
const head = prev.slice(0, rgA.start)
|
||||||
|
const blA = prev.slice(rgA.start, rgA.end)
|
||||||
|
const blB = prev.slice(rgB.start, rgB.end)
|
||||||
|
const tail = prev.slice(rgB.end)
|
||||||
|
return [...head, ...blB, ...blA, ...tail]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function movePhaseRunUpByPhaseOrder(prev, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const runs = phaseRunsFromSections(prev)
|
||||||
|
const rIdx = runs.findIndex((r) => r.phaseKind === 'parallel' && r.phaseOrderIndex === po)
|
||||||
|
if (rIdx <= 0) return prev
|
||||||
|
return swapAdjacentPhaseRuns(prev, rIdx - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function movePhaseRunDownByPhaseOrder(prev, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const runs = phaseRunsFromSections(prev)
|
||||||
|
const rIdx = runs.findIndex((r) => r.phaseKind === 'parallel' && r.phaseOrderIndex === po)
|
||||||
|
if (rIdx < 0 || rIdx >= runs.length - 1) return prev
|
||||||
|
return swapAdjacentPhaseRuns(prev, rIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abschnitt verschieben und planLoc an der Einfügestelle an Nachbarn anpassen.
|
||||||
|
* Regel: Einfügen vor Abschnitt X übernimmt X.planLoc; am Listenende nach Parallel → neue Ganzgruppen-Phase.
|
||||||
|
*/
|
||||||
|
export function reorderBlocksImmutableWithPlanLoc(prev, fromI, toBeforeIdx) {
|
||||||
|
const arr = [...prev]
|
||||||
|
if (fromI < 0 || fromI >= arr.length) return prev
|
||||||
|
const [moved] = arr.splice(fromI, 1)
|
||||||
|
let insertAt = toBeforeIdx
|
||||||
|
if (fromI < toBeforeIdx) insertAt = toBeforeIdx - 1
|
||||||
|
insertAt = Math.max(0, Math.min(insertAt, arr.length))
|
||||||
|
|
||||||
|
const below = insertAt < arr.length ? arr[insertAt] : undefined
|
||||||
|
const above = insertAt > 0 ? arr[insertAt - 1] : undefined
|
||||||
|
|
||||||
|
let planLocNext = null
|
||||||
|
const belowKind = below?.planLoc?.phaseKind
|
||||||
|
const aboveKind = above?.planLoc?.phaseKind
|
||||||
|
const movedKind = moved?.planLoc?.phaseKind
|
||||||
|
const belowPo = below?.planLoc?.phaseOrderIndex ?? 0
|
||||||
|
const movedPo = moved?.planLoc?.phaseOrderIndex ?? 0
|
||||||
|
|
||||||
|
if (belowKind === 'parallel' && aboveKind === 'whole_group') {
|
||||||
|
if (movedKind !== 'parallel') {
|
||||||
|
planLocNext = { ...above.planLoc }
|
||||||
|
} else if (movedPo !== belowPo) {
|
||||||
|
planLocNext = { ...below.planLoc }
|
||||||
|
}
|
||||||
|
} else if (belowKind === 'parallel' && !above) {
|
||||||
|
if (movedKind !== 'parallel') {
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!planLocNext && belowKind) {
|
||||||
|
planLocNext = { ...below.planLoc }
|
||||||
|
}
|
||||||
|
if (!planLocNext && insertAt === arr.length) {
|
||||||
|
if (!above) {
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(0)
|
||||||
|
} else if (above.planLoc?.phaseKind === 'parallel') {
|
||||||
|
const mx = maxPhaseOrderIndexFromSections(arr)
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(mx + 1)
|
||||||
|
} else if (above.planLoc?.phaseKind === 'whole_group') {
|
||||||
|
planLocNext = { ...above.planLoc }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!planLocNext && above?.planLoc?.phaseKind === 'whole_group') {
|
||||||
|
planLocNext = { ...above.planLoc }
|
||||||
|
}
|
||||||
|
if (!planLocNext && above?.planLoc?.phaseKind === 'parallel') {
|
||||||
|
const mx = maxPhaseOrderIndexFromSections(arr)
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(mx + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextMoved = { ...moved }
|
||||||
|
if (planLocNext) {
|
||||||
|
nextMoved = { ...moved, planLoc: planLocNext }
|
||||||
|
} else {
|
||||||
|
nextMoved = stripPlanLoc(moved)
|
||||||
|
}
|
||||||
|
arr.splice(insertAt, 0, nextMoved)
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abschnitt direkt vor den Parallel-Lauf setzen (immer Ganzgruppe oberhalb der Split-Phase).
|
||||||
|
*/
|
||||||
|
export function reorderSectionBeforeParallelRunAsWholeGroup(prev, fromI, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const idxs = indicesOfParallelPhase(prev, po)
|
||||||
|
if (!idxs.length || fromI < 0 || fromI >= (prev?.length ?? 0)) return prev
|
||||||
|
const fg = idxs[0]
|
||||||
|
const arr = [...prev]
|
||||||
|
const [moved] = arr.splice(fromI, 1)
|
||||||
|
let insertAt = fg
|
||||||
|
if (fromI < insertAt) insertAt -= 1
|
||||||
|
insertAt = Math.max(0, Math.min(insertAt, arr.length))
|
||||||
|
const above = insertAt > 0 ? arr[insertAt - 1] : undefined
|
||||||
|
let planLocNext
|
||||||
|
if (above?.planLoc?.phaseKind === 'whole_group') {
|
||||||
|
planLocNext = { ...above.planLoc }
|
||||||
|
} else if (!above) {
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(0)
|
||||||
|
} else {
|
||||||
|
const mx = maxPhaseOrderIndexFromSections(arr)
|
||||||
|
planLocNext = defaultPlanLocWholeGroup(mx + 1)
|
||||||
|
}
|
||||||
|
arr.splice(insertAt, 0, { ...moved, planLoc: planLocNext })
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Abschnitt als neuen ersten Eintrag der Parallel-Phase (gleiche Phasen-/Stream-Metadaten wie bisheriger Kopf). */
|
||||||
|
export function reorderSectionAsFirstInParallelPhase(prev, fromI, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const idxs = indicesOfParallelPhase(prev, po)
|
||||||
|
if (!idxs.length || fromI < 0 || fromI >= (prev?.length ?? 0)) return prev
|
||||||
|
let fg = idxs[0]
|
||||||
|
const arr = [...prev]
|
||||||
|
const headTpl = { ...arr[fg].planLoc }
|
||||||
|
const [moved] = arr.splice(fromI, 1)
|
||||||
|
if (fromI < fg) fg -= 1
|
||||||
|
fg = Math.max(0, Math.min(fg, arr.length))
|
||||||
|
arr.splice(fg, 0, { ...moved, planLoc: { ...headTpl } })
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Abschnitt als ersten Eintrag eines parallelen Streams setzen (planLoc wie erster Abschnitt dieses Streams, bzw. leerer Stream wie reorderBlockIntoParallelStreamEnd). */
|
||||||
|
export function reorderSectionAsFirstInParallelStream(prev, fromI, phaseOrderIndex, streamOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const so = Number(streamOrderIndex) || 0
|
||||||
|
const len = prev?.length ?? 0
|
||||||
|
if (fromI < 0 || fromI >= len) return prev
|
||||||
|
|
||||||
|
const arr = [...prev]
|
||||||
|
const [moved] = arr.splice(fromI, 1)
|
||||||
|
|
||||||
|
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
|
||||||
|
let insertAt
|
||||||
|
let headTpl
|
||||||
|
let skipFromIAdjust = false
|
||||||
|
|
||||||
|
if (streamIdx.length) {
|
||||||
|
const first = Math.min(...streamIdx)
|
||||||
|
headTpl = { ...arr[first].planLoc }
|
||||||
|
insertAt = first
|
||||||
|
} else {
|
||||||
|
const phaseIdx = indicesOfParallelPhase(arr, po)
|
||||||
|
if (!phaseIdx.length) {
|
||||||
|
const ml = moved?.planLoc
|
||||||
|
if (ml?.phaseKind !== 'parallel' || (ml.phaseOrderIndex ?? 0) !== po) return prev
|
||||||
|
headTpl = {
|
||||||
|
...ml,
|
||||||
|
parallelStreamOrderIndex: so,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
insertAt = Math.min(fromI, arr.length)
|
||||||
|
skipFromIAdjust = true
|
||||||
|
} else {
|
||||||
|
const ref = arr[phaseIdx[phaseIdx.length - 1]]
|
||||||
|
headTpl = {
|
||||||
|
...ref.planLoc,
|
||||||
|
parallelStreamOrderIndex: so,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
insertAt = phaseIdx[phaseIdx.length - 1] + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!skipFromIAdjust && fromI < insertAt) insertAt -= 1
|
||||||
|
insertAt = Math.max(0, Math.min(insertAt, arr.length))
|
||||||
|
arr.splice(insertAt, 0, { ...moved, planLoc: { ...headTpl } })
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abschnitt ans Ende eines parallelen Streams setzen (planLoc wie dieser Stream).
|
||||||
|
* Leerer Stream: Einfügen hinter den letzten Abschnitt der zugehörigen parallelen Phase, planLoc vom Referenz-Abschnitt mit angepasstem streamIndex.
|
||||||
|
*/
|
||||||
|
export function reorderBlockIntoParallelStreamEnd(prev, fromI, phaseOrderIndex, streamOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const so = Number(streamOrderIndex) || 0
|
||||||
|
const len = prev?.length ?? 0
|
||||||
|
if (fromI < 0 || fromI >= len) return prev
|
||||||
|
const arr = [...prev]
|
||||||
|
const [moved] = arr.splice(fromI, 1)
|
||||||
|
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
|
||||||
|
let insertAt
|
||||||
|
let planLocTemplate
|
||||||
|
|
||||||
|
if (streamIdx.length) {
|
||||||
|
const last = Math.max(...streamIdx)
|
||||||
|
planLocTemplate = { ...arr[last].planLoc }
|
||||||
|
insertAt = last + 1
|
||||||
|
} else {
|
||||||
|
const phaseIdx = indicesOfParallelPhase(arr, po)
|
||||||
|
if (!phaseIdx.length) return prev
|
||||||
|
const ref = arr[phaseIdx[phaseIdx.length - 1]]
|
||||||
|
planLocTemplate = {
|
||||||
|
...ref.planLoc,
|
||||||
|
parallelStreamOrderIndex: so,
|
||||||
|
streamTitle: null,
|
||||||
|
streamNotes: null,
|
||||||
|
streamAssignedTrainerProfileIds: null,
|
||||||
|
}
|
||||||
|
insertAt = phaseIdx[phaseIdx.length - 1] + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
insertAt = Math.max(0, Math.min(insertAt, arr.length))
|
||||||
|
arr.splice(insertAt, 0, { ...moved, planLoc: { ...planLocTemplate } })
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Globales insertBeforeIndex, um einen Abschnitt hinter den letzten des Streams einzufügen (z. B. Rahmen-Slots). */
|
||||||
|
export function globalInsertBeforeIndexForParallelStreamEnd(sections, phaseOrderIndex, streamOrderIndex) {
|
||||||
|
const arr = sections || []
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const so = Number(streamOrderIndex) || 0
|
||||||
|
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
|
||||||
|
if (streamIdx.length) return Math.max(...streamIdx) + 1
|
||||||
|
const phaseIdx = indicesOfParallelPhase(arr, po)
|
||||||
|
if (!phaseIdx.length) return arr.length
|
||||||
|
return Math.max(...phaseIdx) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alle globalen Indizes einer parallelen Phase (alle Streams), sortiert. */
|
||||||
|
export function indicesOfParallelPhase(sections, phaseOrderIndex) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const out = []
|
||||||
|
;(sections || []).forEach((s, i) => {
|
||||||
|
const L = s?.planLoc
|
||||||
|
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po) out.push(i)
|
||||||
|
})
|
||||||
|
return out.sort((a, b) => a - b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gesamten Parallel-Block an neue Position (insertBefore globale Liste) schieben. */
|
||||||
|
export function moveParallelPhaseRunToInsertBefore(prev, phaseOrderIndex, toBeforeIdx) {
|
||||||
|
const po = Number(phaseOrderIndex) || 0
|
||||||
|
const indices = indicesOfParallelPhase(prev, po)
|
||||||
|
if (!indices.length) return prev
|
||||||
|
const indexSet = new Set(indices)
|
||||||
|
const blocks = indices.map((i) => prev[i])
|
||||||
|
const without = prev.filter((_, i) => !indexSet.has(i))
|
||||||
|
let ins = toBeforeIdx
|
||||||
|
for (const i of indices) {
|
||||||
|
if (i < toBeforeIdx) ins -= 1
|
||||||
|
}
|
||||||
|
ins = Math.max(0, Math.min(ins, without.length))
|
||||||
|
return [...without.slice(0, ins), ...blocks, ...without.slice(ins)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nach Drag&Drop: wenn aus einer Parallelphase noch ≤1 Stream übrig ist (vorher ≥2), Rückfrage wie beim Stream-Löschen.
|
||||||
|
*/
|
||||||
|
export function afterSectionReorderParallelGuard(prev, next) {
|
||||||
|
const seenPo = new Set()
|
||||||
|
for (const s of prev || []) {
|
||||||
|
const L = s?.planLoc
|
||||||
|
if (L?.phaseKind !== 'parallel') continue
|
||||||
|
seenPo.add(L.phaseOrderIndex ?? 0)
|
||||||
|
}
|
||||||
|
let out = next
|
||||||
|
for (const po of seenPo) {
|
||||||
|
const prevN = streamsForParallelPhaseOrders(prev, po).length
|
||||||
|
if (prevN < 2) continue
|
||||||
|
const nowN = streamsForParallelPhaseOrders(out, po).length
|
||||||
|
if (nowN <= 1) {
|
||||||
|
if (
|
||||||
|
window.confirm(
|
||||||
|
'In dieser parallelen Phase ist nur noch eine Gruppe übrig. Parallelaufbau auflösen und alle zugehörigen Abschnitte als gemeinsame Ganzgruppen-Phase führen?'
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
out = dissolveParallelPhaseToWholeGroup(out, po)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPhasesPayloadFromFlat(sections) {
|
||||||
|
const norm = inheritPlanLocForPhasedSave(sections)
|
||||||
|
const phases = []
|
||||||
|
let i = 0
|
||||||
|
while (i < norm.length) {
|
||||||
|
const loc0 = norm[i].planLoc
|
||||||
|
const pOi = loc0.phaseOrderIndex ?? 0
|
||||||
|
const pk = loc0.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
|
||||||
|
|
||||||
|
const run = []
|
||||||
|
while (i < norm.length) {
|
||||||
|
const L = norm[i].planLoc
|
||||||
|
const pk2 = L.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
|
||||||
|
if ((L.phaseOrderIndex ?? 0) !== pOi || pk2 !== pk) break
|
||||||
|
run.push(norm[i])
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
const head = run[0].planLoc
|
||||||
|
if (pk === 'whole_group') {
|
||||||
|
phases.push({
|
||||||
|
phase_kind: 'whole_group',
|
||||||
|
order_index: pOi,
|
||||||
|
title: head.phaseTitle ?? null,
|
||||||
|
guidance_notes: head.phaseGuidanceNotes ?? null,
|
||||||
|
sections: run.map((s, idx) => buildOneSectionPayload(stripPlanLoc(s), idx)),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const byStream = new Map()
|
||||||
|
for (const s of run) {
|
||||||
|
const soi = s.planLoc.parallelStreamOrderIndex ?? 0
|
||||||
|
if (!byStream.has(soi)) byStream.set(soi, [])
|
||||||
|
byStream.get(soi).push(s)
|
||||||
|
}
|
||||||
|
const streamOrder = [...byStream.keys()].sort((a, b) => a - b)
|
||||||
|
const streams = streamOrder.map((soi) => {
|
||||||
|
const bucket = byStream.get(soi)
|
||||||
|
const h = bucket[0].planLoc
|
||||||
|
const st = {
|
||||||
|
order_index: soi,
|
||||||
|
title: h.streamTitle ?? null,
|
||||||
|
notes: h.streamNotes ?? null,
|
||||||
|
sections: bucket.map((s, idx) => buildOneSectionPayload(stripPlanLoc(s), idx)),
|
||||||
|
}
|
||||||
|
const asst = h.streamAssignedTrainerProfileIds
|
||||||
|
if (asst !== null && asst !== undefined) st.assigned_trainer_profile_ids = asst
|
||||||
|
return st
|
||||||
|
})
|
||||||
|
phases.push({
|
||||||
|
phase_kind: 'parallel',
|
||||||
|
order_index: pOi,
|
||||||
|
title: head.phaseTitle ?? null,
|
||||||
|
guidance_notes: head.phaseGuidanceNotes ?? null,
|
||||||
|
streams,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { phases }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Speichern einer Einheit: flache `sections` oder verschachtelte `phases`, sobald `planLoc` gesetzt ist.
|
||||||
|
*/
|
||||||
|
export function buildPlanPayloadForSave(sections) {
|
||||||
|
const list = Array.isArray(sections) ? sections : []
|
||||||
|
const anyPhased = list.some((s) => s && canonicalPlanLocForPhasedSave(s.planLoc) != null)
|
||||||
|
if (!anyPhased) {
|
||||||
|
return { sections: buildSectionsPayload(list) }
|
||||||
|
}
|
||||||
|
return buildPhasesPayloadFromFlat(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Payload-Zeilen für POST/PUT /api/training-plan-templates (inkl. Split-/Phasen-Metadaten). */
|
||||||
|
export function templateSectionsPayloadFromFormSections(sections) {
|
||||||
|
const norm = inheritPlanLocForPhasedSave(Array.isArray(sections) ? sections : [])
|
||||||
|
return norm.map((s, si) => {
|
||||||
|
const canon = canonicalPlanLocForPhasedSave(s.planLoc)
|
||||||
|
const pk = canon?.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
|
||||||
|
const poi = canon?.phaseOrderIndex ?? 0
|
||||||
|
const pso = canon?.phaseKind === 'parallel' ? (canon.parallelStreamOrderIndex ?? 0) : null
|
||||||
|
return {
|
||||||
|
order_index: si,
|
||||||
|
title: (s.title || '').trim() || `Abschnitt ${si + 1}`,
|
||||||
|
guidance_text: s.guidance_notes?.trim() ? s.guidance_notes.trim() : null,
|
||||||
|
phase_kind: pk,
|
||||||
|
phase_order_index: poi,
|
||||||
|
parallel_stream_order_index: pso,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Kurzdarstellung der Vorlagen-Gliederung (Ganzgruppe + Split-Streams) für Listen/Übersicht. */
|
||||||
|
export function formatPlanTemplateStructurePreview(templateSections) {
|
||||||
|
const rows = Array.isArray(templateSections) ? [...templateSections] : []
|
||||||
|
if (!rows.length) {
|
||||||
|
return { lines: [], hasSplit: false, isEmpty: true }
|
||||||
|
}
|
||||||
|
rows.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
|
||||||
|
const lines = []
|
||||||
|
let hasSplit = false
|
||||||
|
let i = 0
|
||||||
|
while (i < rows.length) {
|
||||||
|
const r0 = rows[i]
|
||||||
|
const pk0 = String(r0.phase_kind || 'whole_group').toLowerCase().trim()
|
||||||
|
const poi0 = Number(r0.phase_order_index)
|
||||||
|
const phaseOrder = Number.isFinite(poi0) ? poi0 : 0
|
||||||
|
const run = []
|
||||||
|
while (i < rows.length) {
|
||||||
|
const r = rows[i]
|
||||||
|
const pk = String(r.phase_kind || 'whole_group').toLowerCase().trim()
|
||||||
|
const poi = Number(r.phase_order_index)
|
||||||
|
const phaseOi = Number.isFinite(poi) ? poi : 0
|
||||||
|
if (pk !== pk0 || phaseOi !== phaseOrder) break
|
||||||
|
run.push(r)
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
if (pk0 === 'parallel') {
|
||||||
|
hasSplit = true
|
||||||
|
const byStream = new Map()
|
||||||
|
for (const r of run) {
|
||||||
|
const soRaw = r.parallel_stream_order_index
|
||||||
|
const so = soRaw == null || soRaw === '' ? 0 : Number(soRaw)
|
||||||
|
const streamKey = Number.isFinite(so) ? so : 0
|
||||||
|
if (!byStream.has(streamKey)) byStream.set(streamKey, [])
|
||||||
|
byStream.get(streamKey).push(r)
|
||||||
|
}
|
||||||
|
const streamParts = [...byStream.keys()]
|
||||||
|
.sort((a, b) => a - b)
|
||||||
|
.map((so) => {
|
||||||
|
const titles = byStream
|
||||||
|
.get(so)
|
||||||
|
.map((r) => (r.title || '').trim() || 'Abschnitt')
|
||||||
|
return `Gruppe ${so + 1}: ${titles.join(' · ')}`
|
||||||
|
})
|
||||||
|
lines.push({
|
||||||
|
kind: 'parallel',
|
||||||
|
label: phaseOrder > 0 ? `Split · Phase ${phaseOrder}` : 'Split-Session',
|
||||||
|
detail: streamParts.join(' │ '),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const titles = run.map((r) => (r.title || '').trim() || 'Abschnitt')
|
||||||
|
lines.push({
|
||||||
|
kind: 'whole_group',
|
||||||
|
label: phaseOrder > 0 ? `Ganzgruppe · Phase ${phaseOrder}` : 'Ganzgruppe',
|
||||||
|
detail: titles.join(' → '),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { lines, hasSplit, isEmpty: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET-Vorlage → Editor-Abschnitte mit planLoc (Split-Sessions). */
|
||||||
|
export function formSectionsFromPlanTemplateRows(templateSections) {
|
||||||
|
const rows = Array.isArray(templateSections) ? [...templateSections] : []
|
||||||
|
rows.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
|
||||||
|
if (!rows.length) return [defaultSection()]
|
||||||
|
return rows.map((s) => {
|
||||||
|
const pk = String(s.phase_kind || 'whole_group').toLowerCase().trim()
|
||||||
|
const poiRaw = s.phase_order_index
|
||||||
|
const poi = poiRaw == null || poiRaw === '' ? 0 : Number(poiRaw)
|
||||||
|
const phaseOrderIndex = Number.isFinite(poi) ? poi : 0
|
||||||
|
const soRaw = s.parallel_stream_order_index
|
||||||
|
let planLoc
|
||||||
|
if (pk === 'parallel') {
|
||||||
|
const so = soRaw == null || soRaw === '' ? 0 : Number(soRaw)
|
||||||
|
planLoc = {
|
||||||
|
...defaultPlanLocParallel(phaseOrderIndex, Number.isFinite(so) ? so : 0),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
planLoc = { ...defaultPlanLocWholeGroup(phaseOrderIndex) }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: s.title || 'Abschnitt',
|
||||||
|
guidance_notes: s.guidance_text || '',
|
||||||
|
items: [],
|
||||||
|
planLoc,
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fügt die Positionen eines Moduls in lokale Abschnitte ein (wie eine Übung, ohne Zwischenspeichern der Einheit). */
|
/** Fügt die Positionen eines Moduls in lokale Abschnitte ein (wie eine Übung, ohne Zwischenspeichern der Einheit). */
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
test: {
|
||||||
|
environment: 'node',
|
||||||
|
include: ['src/**/*.test.js'],
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -305,6 +305,46 @@ test('13. Trainingsplanung: Rahmen-Import-Dialog öffnet und schließt', async (
|
|||||||
console.log('✓ Trainingsplanung: Rahmen-Import-Dialog Smoke');
|
console.log('✓ Trainingsplanung: Rahmen-Import-Dialog Smoke');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('14. Trainingsplanung: Bearbeiten navigiert zur Edit-Route', async ({ page }, testInfo) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/planning', { waitUntil: 'networkidle' });
|
||||||
|
const main = page.locator('.app-main');
|
||||||
|
await expect(main.locator('.spinner')).toHaveCount(0, { timeout: 25000 });
|
||||||
|
const editBtn = main.getByRole('button', { name: 'Bearbeiten' }).first();
|
||||||
|
if (!(await editBtn.count())) {
|
||||||
|
testInfo.skip(true, 'Keine Trainingseinheit in der Liste');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await editBtn.click();
|
||||||
|
await page.waitForURL(/\/planning\/units\/\d+\/edit/, { timeout: 15000 });
|
||||||
|
await expect(page.getByTestId('planning-unit-form')).toBeVisible({ timeout: 15000 });
|
||||||
|
console.log('✓ Trainingsplanung: Edit-Route aus Hub');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('15. Trainingsplanung: Legacy-Deep-Link ?unit= leitet auf Edit-Route um', async ({ page }, testInfo) => {
|
||||||
|
await login(page);
|
||||||
|
await page.goto('/planning', { waitUntil: 'networkidle' });
|
||||||
|
const main = page.locator('.app-main');
|
||||||
|
await expect(main.locator('.spinner')).toHaveCount(0, { timeout: 25000 });
|
||||||
|
const editBtn = main.getByRole('button', { name: 'Bearbeiten' }).first();
|
||||||
|
if (!(await editBtn.count())) {
|
||||||
|
testInfo.skip(true, 'Keine Trainingseinheit in der Liste');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await editBtn.click();
|
||||||
|
await page.waitForURL(/\/planning\/units\/(\d+)\/edit/, { timeout: 15000 });
|
||||||
|
const m = page.url().match(/\/planning\/units\/(\d+)\/edit/);
|
||||||
|
const unitId = m?.[1];
|
||||||
|
if (!unitId) {
|
||||||
|
testInfo.skip(true, 'Unit-ID aus Edit-URL nicht ermittelbar');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await page.goto(`/planning?unit=${unitId}`, { waitUntil: 'networkidle' });
|
||||||
|
await page.waitForURL(new RegExp(`/planning/units/${unitId}/edit`), { timeout: 15000 });
|
||||||
|
await expect(page.getByTestId('planning-unit-form')).toBeVisible({ timeout: 15000 });
|
||||||
|
console.log('✓ Trainingsplanung: Legacy ?unit= Redirect');
|
||||||
|
});
|
||||||
|
|
||||||
test('P-12: sessionStorage wird bei Logout bereinigt (sj_coach_* Schlüssel)', async ({ page }) => {
|
test('P-12: sessionStorage wird bei Logout bereinigt (sj_coach_* Schlüssel)', async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 1280, height: 800 });
|
await page.setViewportSize({ width: 1280, height: 800 });
|
||||||
await login(page);
|
await login(page);
|
||||||
|
|||||||
Reference in new issue
Block a user