Compare commits
49
Commits
MVP1.5
...
6db31e7312
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6db31e7312 | ||
|
|
a34e748be5 | ||
|
|
16187fbbd0 | ||
|
|
b2157d8a40 | ||
|
|
50aff849d8 | ||
|
|
a0a891e550 | ||
|
|
9ba35dc022 | ||
|
|
46fae3da33 | ||
|
|
f4196c3580 | ||
|
|
d1d8539b42 | ||
|
|
a8633235f2 | ||
|
|
5c882985e0 | ||
|
|
04cc77d501 | ||
|
|
8e68261bc1 | ||
|
|
b0611b9f7f | ||
|
|
614c2dcfaa | ||
|
|
f5c886fc13 | ||
|
|
d019c20338 | ||
|
|
905bce198f | ||
|
|
45e3b5f4f6 | ||
|
|
207817376d | ||
|
|
128a9d752e | ||
|
|
d7d45a8927 | ||
|
|
fc5748bef1 | ||
|
|
9d880e2346 | ||
|
|
c816e50c68 | ||
|
|
294740b780 | ||
|
|
675cfa85f0 | ||
|
|
4725eaa90b | ||
|
|
9f4678f418 | ||
|
|
5331eab39c | ||
|
|
93b8d09d05 | ||
|
|
0551bb3d80 | ||
|
|
3bf012a8f4 | ||
|
|
e22266a18c | ||
|
|
d58db3d5dd | ||
|
|
cdeddc7cec | ||
|
|
2148d0aa7f | ||
|
|
69f238d9b8 | ||
|
|
f9e295bce0 | ||
|
|
888d0bd009 | ||
|
|
1942585546 | ||
|
|
a28a9d399a | ||
|
|
9be69ace5c | ||
|
|
286c36e9d7 | ||
|
|
294b09a5d9 | ||
|
|
e5291256d0 | ||
|
|
4d36bbf634 | ||
|
|
e4451e1362 |
No files matched your search
@@ -83,7 +83,9 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
|
||||
- [x] **Varianten** (CRUD, Reorder, Voraussetzung) + Anzeige im Detail
|
||||
- [x] **Progressionsgraph zwischen Übungen** (Bibliotheks-Container, Kanten, Sequenz-Bulk, Varianten-Knoten — Zwischenstand, siehe TRAINING_FRAMEWORK_SPEC §4)
|
||||
- [x] Medien (Upload/Embed, rollenabhängige Größenlimits)
|
||||
- [x] Suche & Filter (Multi-Filter, Chips, Fokus beim Suchen)
|
||||
- [x] Suche & Filter (Multi-Filter, Chips, Fokus beim Suchen; **Freigabelevel** als UI-Begriff für `visibility`)
|
||||
- [x] **Übungsformular:** Registerkarten (Stammdaten … Medien & Mehr), kompakte Chip-Editoren, Varianten-Speichern über Aktionsleiste
|
||||
- [x] **Fähigkeiten-Intensität** ohne Primär-Flag (`niedrig`/`mittel`/`hoch`; Backend `is_primary` immer false)
|
||||
- [x] Exercise Blocks (Bausteine)
|
||||
- [x] Saved Searches (wo implementiert)
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# KI-Unterstützung bei Übungen – Produkt-Vision
|
||||
|
||||
**Version:** 0.1
|
||||
**Datum:** 2026-05-22
|
||||
**Status:** Zielbild / Anforderungsgrundlage (nicht gleich Ist-Spec – technische Schnittstellen: **`technical/KI_FEATURES_SPEC.md`**, **`technical/AI_PROMPT_SYSTEM_SPEC.md`**, **`technical/AI_TRAINING_PLANNING_CONCEPT.md` §1.1**)
|
||||
**Zielgruppe:** Product, Trainer-UX, später Admin-Werkzeuge
|
||||
|
||||
---
|
||||
|
||||
## 1. Übergeordnete Prinzipien
|
||||
|
||||
1. **Immer Vorschlag, nie blind überschreiben**
|
||||
Die KI liefert **Vorschläge** (Änderungen, Ergänzungen, Strukturen). Bestehende Inhalte werden **nicht** still ersetzt. Übernahme erfolgt durch den Nutzer: **teilweise** (Felder/Stellen/Blöcke) oder **komplett** („Vorschlag gesamt akzeptieren“).
|
||||
|
||||
2. **Granulare Anforderung im Editor**
|
||||
Innerhalb einer Übung soll KI-Unterstützung **feldbasiert oder bereichsbasiert** auslösbar sein (z. B. nur „Anleitung schärfen“, nur „Fähigkeiten“, nur „Variantenrahmen“) **oder** als **Komplettüberarbeitung** mit klarem Warnhinweis (Umfang/transparenter Diff).
|
||||
|
||||
3. **Nachweisliche Herkunft**
|
||||
Übernommene KI-Inhalte werden technisch dort abgebildet, wo bereits vorgesehen (z. B. **`summary_ai_generated`**, **`exercise_skills.ai_suggested`**) und um analogen Hinweis für weitergehende Textfelder/Varianten **erweitert**, sobald Implementierung konkret wird.
|
||||
|
||||
---
|
||||
|
||||
## 2. Funktionsbereiche (Vision)
|
||||
|
||||
### 2.1 Von der Idee zur kompletten Übung („Zielausbau“)
|
||||
|
||||
**Einstieg minimal:** Kurzbeschreibung oder Stichwort, **Ziel** („was soll erreicht werden?“), wenige **Rahmenparameter** (z. B. Fokusbereich, Trainingszeit, Teilnehmerzahl, Alter, Platzausstattung, Sicherheitshinweise – konkrete Dropdowns/Freifelder in UX später festlegen).
|
||||
|
||||
**KI-Aufgabe:** aus diesem dünnen Kontext einen **übernehmbaren Entwurf** einer **ganzen Übung** erzeugen: Titel‑Vorschlag, Ziel-/Durchführungstext, Sicherheit/Organisation, ggf. Trainerhinweise – **immer als Vorschlagspaket**, nicht als Speicher ohne Bestätigung.
|
||||
|
||||
**Abgrenzung:** Kombinationsübungen / komplexe Methodenprofile können **phasenweise** später einbezogen werden (Verweis Fachspez Trainingsmodule).
|
||||
|
||||
### 2.2 Anleitung (Durchführung / „Ausführung“) maximal hilfreich
|
||||
|
||||
**Ziel:** Die **Ausführungs-/Anleitungsbereiche** sollen sich **didaktisch klar**, **teilbar** und **wieder verwendbar** lesen – ohne den Trainer zu entmindigen.
|
||||
|
||||
**KI-Aufgabe:** Überarbeitungsvorschlag für Struktur (nummerierte Schritte, Zeiten pro Block, häufige Fehler, Progressionshinweise innerhalb der Übung wo sinnvoll). **Selektiver** Aufruf: nur diese Felder oder nur ein markierter Abschnitt (wenn UX Textauswahl unterstützt).
|
||||
|
||||
### 2.3 Kurzbeschreibung (`summary`)
|
||||
|
||||
**KI-Aufgabe:** Aus den **relevanten Übungstexten** eine **Liste-/Karte-taugliche** Kurzfassung generieren — wie in **`KI_FEATURES_SPEC.md`** beschrieben, mit **Ablehnen / Bearbeiten / Übernehmen**.
|
||||
|
||||
### 2.4 Einordnung – primär **Fähigkeiten**
|
||||
|
||||
**KI-Aufgabe:** automatische Erkennung und **Zuordnung** zum **globale Skills-Katalog** inklusive:
|
||||
|
||||
- **Intensität** (`exercise_skills`)
|
||||
- **Skill-Level**: `required_level` / `target_level` nach **kanonischen Slugs** (Backend-konform)
|
||||
- **`is_primary`** / Priorisierung wo fachlich sinnvoll
|
||||
|
||||
**Prompt-Kontext für Qualität:** Stammfelder wie `skills.description`, **`karate_relevance`**, **`relevance_level`**, **`focus_areas`**, optional **`skill_level_definitions`** nur für eine **kurze Kandidatenliste** (zweite Runde möglich) – keine vollständigen Romane für den gesamten Katalog auf einmal.
|
||||
|
||||
### 2.5 Varianten (optional, später prioritär erwägenswert)
|
||||
|
||||
**Vision:** Aus Ziel-/Durchführungstext **mehrere sinnvolle Ausprägungen** als **Übungsvarianten** vorschlagen oder einzelne erzeugen (**progression**, **Schwierigkeit**, andere Paararbeit, Gerätevariation) mit **übernehmbarem** Datenmodell gleich dem bestehenden `exercise_variants`.
|
||||
|
||||
**Randbedingungen:** Validierung gegen Übungstyp (Kombinationsübungen ohne Varianten laut Produktstand), keine Halluzination fremder IDs.
|
||||
|
||||
---
|
||||
|
||||
## 3. Kontextbezug später: Nachbearbeitung aus der Trainingsplanung
|
||||
|
||||
**Vision:** Hinweise aus der **Nachbearbeitung** einer Trainingseinheit (Ist‑Minuten, Trainer-Notizen, Abweichungen „was lief nicht?“ – je nach Datenmodell) fließen **optional** als Kontext in eine **erneute KI-Überarbeitung der betroffenen Übung** ein („Übung aus den Erfahrungen der Gruppe verbessern“).
|
||||
|
||||
**Konsequenz technisch später:** Zugriffsrechte, Mandant, keine unzulässige Verknüpfung personenbezogener Sportlerdaten; Aggregation auf **Einheit-/Gruppe** und **bereits dokumentierte Trainer-Insights**.
|
||||
|
||||
---
|
||||
|
||||
## 4. Admin: Massenverarbeitung und Analyse
|
||||
|
||||
**Vision für Plattform-/Vereins-Admins:**
|
||||
|
||||
| Thema | Richtungsziel |
|
||||
|-------|----------------|
|
||||
| **Massenverarbeitung** | Batch: z. B. Zusammenfassungen nachziehen, fehlende Skills vorschlagen, einheitlicher Stil bei importiertem Bestand — immer mit **Review-Queue**, nicht ohne menschliche Freigabe skalierungskritisch. |
|
||||
| **Analyse / Qualität** | Werkzeugkasten oder Berichte: **welche Übungen** sollten überarbeitet werden? z. B. leere/kurze `summary`, fehlende `goal`/`execution`, **fehlende oder widersprüchliche Skill-Zuordnung**, Import-Herkunft ohne Plausibilität, Kombi-Slots unvollständig, sehr alte Imports. |
|
||||
| **Lückenkarten** | Z. B. Abgleich gegen **Skill-Discovery**/Profil-Analysen („keine Übung deckt Fähigkeit X ab“ auf gewähltem Korpus); Verbindung zu **`skill-discovery`** entscheidend später im Detail (kein automatischer Rewrite ohne Policy). |
|
||||
|
||||
**Governance:** Sichtbarkeit (`official`, Verein), Rechte (**Superadmin** vs. Vereinsinhalt), Audit der KI-Anwendung bei Massenjobs.
|
||||
|
||||
---
|
||||
|
||||
## 5. Phasierung (überarbeitungsfähig)
|
||||
|
||||
| Phase | Inhalt |
|
||||
|-------|--------|
|
||||
| **P0** | KI-Service + Prompts aus DB + **Suggestion-only** UX; Kern: **Summary** + **Skills** (wie Spec-Minimum), **ein Feld / Komplettpaket mit Diff** nach UX. |
|
||||
| **P1** | **Anleitung überarbeiten** + **„von Idee zur Übung“** (Zielausbau) mit Rahmenparameter-Form |
|
||||
| **P2** | **Variantenvorschläge** mit strenger Validation |
|
||||
| **P3** | **Planungs-/Nachbereitungskontext** |
|
||||
| **P4** | **Admin** Massen-/Analyse (Queue + Reports + Governance) |
|
||||
|
||||
---
|
||||
|
||||
## 6. Offene Produkt-/Fachfragen
|
||||
|
||||
- Minimaler **Parameterbau** beim Zielausbau (Pflicht vs. optional).
|
||||
- Umgang mit **Medien**/Inline-Verweisen beim KI-Text – nichts zerstören, Platzhalter erhalten (siehe Medien-Spec §11).
|
||||
- **Kombinationsübungen:** welche Teilaspekte dürfen KI anfassen?
|
||||
- Limits: **Tokens**, **Rate-Limits**, Kostenüberwachung pro Verein/global.
|
||||
@@ -57,7 +57,7 @@ Haupt-Kategorie (KARATE / ALLGEMEINE)
|
||||
- Selbstverteidigung ✓
|
||||
- Gewaltschutz ✓
|
||||
|
||||
**Technische Umsetzung:** M:N Beziehungen mit `is_primary` Flag.
|
||||
**Technische Umsetzung:** M:N-Beziehungen mit optionalem `is_primary`-Flag bei **Fokusbereichen, Stilrichtungen, Trainingsstilen und Zielgruppen** — nicht bei `exercise_skills` (dort nur Intensität `niedrig|mittel|hoch`).
|
||||
|
||||
### 3. Hierarchischer Kontext (§8.1)
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ Ausführliche fachliche Inhalte:
|
||||
| [**Trainingsmodule & Kombinationsübungen (Fachspez V3)**](./Shinkan%20Trainingsmodule%20Kombinationsuebungen%20Spezifikation%20V2.md) | Produktlogik Module/Kombinationen, **Methoden-Archetypen**, **Coaching-Stufen (§ 10.4)**, kanonische Archetyp-IDs **§ 10.2.1**, **Anhang A** Implementierungsabgleich |
|
||||
| [**Umsetzungsplan Trainingsmodule & Kombination**](../working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md) | Phase 1–5, Coaching-Pakete 4a–4d, Verweis auf Code-Stand |
|
||||
| [**Technischer Entwurf Module/Kombination**](../technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md) | API/Daten-Ideen; aktueller Coach-/Archetyp-Abgleich im Kopfabschnitt |
|
||||
| [**KI-Unterstützung Übungen (Vision)**](./AI_EXERCISE_ASSISTANT_VISION.md) | Zielbild Zielausbau, Vorschlags-UX (teilweise/komplett), Skills/Varianten, später Planungskontext, Admin-Masse/Qualität |
|
||||
| [**KI Übungen – Umsetzungsplan**](../working/AI_EXERCISE_IMPLEMENTATION_PLAN.md) | Stufen S0–S6, Driftschutz-Regeln, Checkliste gegen Specs |
|
||||
|
||||
**Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) (Abschnitt 12), Repo-Root **`docs/HANDOVER.md`**, **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**.
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
## 5. Frontend – Übungsliste (`ExercisesListPage.jsx`)
|
||||
|
||||
- Tabs **Liste** · **Progressionsgraphen** (`ExerciseProgressionGraphPanel`): Graphen anlegen/bearbeiten, Kanten inkl. Sequenz-Bulk und Tabellenansicht.
|
||||
- **Filter-Modal** (Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeit + Stufen von/bis, Sichtbarkeit, Status).
|
||||
- **Filter-Modal** (Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeit + Stufen von/bis, **Freigabelevel**, Status).
|
||||
- **Filter-Chips** unter der Suchleiste; Klick entfernt einen Filter; Badge am Filter-Button = Anzahl Chips.
|
||||
- **Kein Vollbild-Spinner** bei jeder Suche: nur noch **`listFetching`** — Suchfelder bleiben im DOM (**Fokus/Cursor** bleiben erhalten); Liste zeigt optional „Aktualisiere Treffer…“.
|
||||
- **`<datalist>`** mit Titeln der aktuellen Treffer; **`autoComplete="on"`** für Browser-Vorschläge.
|
||||
@@ -76,14 +76,47 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
|
||||
|
||||
---
|
||||
|
||||
## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`)
|
||||
## 6. Frontend – Übung bearbeiten (`ExerciseFormPageRoot.jsx`)
|
||||
|
||||
**Routing:** `/exercises/new`, `/exercises/:id/edit` — keine separaten Varianten-Routen.
|
||||
|
||||
### 6.1 Tab-Navigation (Registerkarten)
|
||||
|
||||
Horizontale **`PageSectionNav`** über **`ExerciseFormTabBar`** / **`ExerciseFormPanel`** (`ExerciseFormLayout.jsx`); farbige linke Panel-Ränder (CSS `.exercise-form-edit`, `.exercise-form-panel--*`).
|
||||
|
||||
| Tab | Inhalt |
|
||||
|-----|--------|
|
||||
| **Stammdaten** | Titel, Kurztext, Dauer/Gruppe, Equipment, **Freigabelevel** (`visibility`), Status, Verein |
|
||||
| **Anleitung** | Ziel, Durchführung, Vorbereitung, Trainerhinweise (Rich-Text inkl. Inline-Medien) |
|
||||
| **Einordnung** | Fokusbereiche, Stilrichtungen, Trainingsstile, Zielgruppen, Altersgruppen, **Fähigkeiten** (kompakte Chip-Editoren) |
|
||||
| **Kombination** | nur bei `exercise_kind=combination`: Slots, Archetyp, `method_profile` |
|
||||
| **Varianten** | nur nach erstem Speichern; **nicht** bei Kombinationsübungen |
|
||||
| **Medien & Mehr** | Medien, Progressionsgraph, KI-Hilfen, Löschen — nach erstem Speichern |
|
||||
|
||||
Neue Übungen: Tabs **Varianten** und **Medien & Mehr** deaktiviert bis zur ersten Speicherung.
|
||||
|
||||
### 6.2 Freigabelevel (UI-Begriff)
|
||||
|
||||
Feld **`exercises.visibility`** heißt in der UI durchgängig **Freigabelevel** (`frontend/src/constants/exerciseGovernanceLabels.js`) — Liste, Filter, Bulk, Picker, Formular. API/DB-Feldname **`visibility`** unverändert.
|
||||
|
||||
### 6.3 Fähigkeiten am Übungsobjekt
|
||||
|
||||
- Intensität je Fähigkeit: **`niedrig` \| `mittel` \| `hoch`**, Standard **`mittel`** (`exerciseSkillIntensity.js`).
|
||||
- Kein „Primär“-Schalter mehr in der UI; **`is_primary`** bei `exercise_skills` ist Legacy — Backend speichert immer **`false`**, Scoring ignoriert das Feld.
|
||||
- Kompakte **Chip-Editoren** für Katalog-Zuordnungen und Fähigkeiten (`ExerciseCatalogAssocEditor`, `ExerciseSkillsEditor`).
|
||||
|
||||
### 6.4 Varianten-Editor
|
||||
|
||||
- Tab **Varianten**: **eine Variante zur Zeit** (Dropdown oder „Erste Variante anlegen“); Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Löschen pro Variante.
|
||||
- **Speichern über Aktionsleiste:** `performSaveAttempt` ruft zuerst **`persistPendingVariantChanges()`** auf (geänderte Varianten per PUT, danach optional Entwurf **`createVariantFromDraft()`**).
|
||||
- Button **„Variante anlegen“** (`type="button"`, kein verschachteltes `<form>`): legt Entwurf sofort per API an; alternativ mitgesichert über **Speichern** in der Aktionsleiste.
|
||||
- Snapshot **`variantsSavedSnapshotRef`** für Dirty-Erkennung; Hinweis im Panel: Änderungen werden mit Speichern in der Aktionsleiste mitgesichert.
|
||||
|
||||
### 6.5 Medien & Progressionsgraph
|
||||
|
||||
- **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante.
|
||||
- **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
|
||||
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
|
||||
|
||||
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
|
||||
|
||||
---
|
||||
|
||||
## 7. Frontend – Übung Detail (`ExerciseDetailPage.jsx`)
|
||||
@@ -192,7 +225,21 @@ Norm: **`technical/SKILL_SCORING_SPEC.md`**.
|
||||
|
||||
---
|
||||
|
||||
## 16. Verweise
|
||||
## 16. Übungen – Governance & Berechtigungen (Ist, Stand 2026-05-20)
|
||||
|
||||
**Owner:** `exercises.created_by` (Ersteller). **Varianten** haben kein eigenes `created_by` — Rechte leiten sich von der Eltern-Übung ab.
|
||||
|
||||
| Aktion | `private` | `club` | `official` |
|
||||
|--------|-----------|--------|------------|
|
||||
| **Lesen** | Ersteller; Plattform-Admin | Aktive Vereinsmitglieder des Objekt-`club_id`; Plattform-Admin ohne Mitgliedschaft (Audit) | Plattform-weit |
|
||||
| **Bearbeiten** (Übung inkl. Varianten/Medien) | Ersteller; Plattform-Admin | Ersteller; Plattform-Admin; **`can_plan_in_club`** im Objekt-Verein (`trainer`, `content_editor`, `division_lead`, `club_admin`) | Plattform-Admin |
|
||||
| **Löschen** | Ersteller; Vereins-Admin gemeinsamer Vereine mit Ersteller | Nur **`club_admin`** im Objekt-Verein | Nur Plattform-Admin |
|
||||
|
||||
**Code:** `backend/club_tenancy.py` (`exercise_visible_to_profile`, `can_plan_in_club`), `backend/routers/exercises.py` (`_assert_can_edit_exercise`, `_assert_can_delete_exercise`).
|
||||
|
||||
---
|
||||
|
||||
## 17. Verweise
|
||||
|
||||
| Thema | Dokument |
|
||||
|--------|----------|
|
||||
|
||||
@@ -119,8 +119,24 @@ Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
|
||||
|
||||
- `.claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md` – übergeordnetes Zielbild & Begriffe.
|
||||
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` – verbindliche Domänenregeln für **Medien-Assets** (gleiche Sichtbarkeit wie Übungen, Promotion-Kopplung, Copyright, Papierkorb/Lebenszyklus, externer Speicher). Bei Widerspruch zur Sichtbarkeits-Tabelle in §3 dieses Dokuments: §3 für Enums/`library_content_*`-Semantik, Medien-Spez für Asset-spezifische Zusatzregeln.
|
||||
- `backend/club_tenancy.py` – bestehende Bausteine (`assert_club_member`, `exercise_visible_to_profile`, …); Ziel ist Deren schrittweise Zusammenführung unter die neue Zugriffsschicht ohne Big-Bang.
|
||||
- `backend/club_tenancy.py` – bestehende Bausteine (`assert_club_member`, `exercise_visible_to_profile`, `can_plan_in_club`, …); Ziel ist Deren schrittweise Zusammenführung unter die neue Zugriffsschicht ohne Big-Bang.
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-07
|
||||
## 8. Anhang – Übungen (Ist-Implementierung, Referenz)
|
||||
|
||||
**Stand:** 2026-05-20 · **Detail:** `EXERCISES_API_SPEC.md` Permissions, `FEATURES_DELIVERED_2026-Q2.md` §16
|
||||
|
||||
| Feld / Konzept | Semantik |
|
||||
|----------------|----------|
|
||||
| `created_by` | Owner der Übung; Varianten erben Rechte |
|
||||
| `visibility` | UI: **Freigabelevel** — `private` \| `club` \| `official` |
|
||||
| Lesen | `exercise_visible_to_profile` — `official` global; `private` Ersteller + Plattform-Admin; `club` aktive Mitglieder (+ Plattform-Admin Audit) |
|
||||
| Bearbeiten | Ersteller; Plattform-Admin; bei `club` zusätzlich `can_plan_in_club` (Trainer, Content-Editor, Spartenleitung, Vereins-Admin) |
|
||||
| Löschen | `official` → Plattform-Admin; `club` → `club_admin` im Objekt-Verein; `private` → Ersteller oder Vereins-Admin mit gemeinsamem Verein |
|
||||
|
||||
**Hinweis:** Dieser Anhang dokumentiert den **produktiven Code-Pfad** in `exercises.py`; die Roadmap in §4 bleibt für die langfristige Vereinheitlichung aller Bibliotheksartefakte maßgeblich.
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 2026-05-20
|
||||
@@ -1,11 +1,20 @@
|
||||
# KI-Prompt-System – Universelle Admin-Konfiguration
|
||||
|
||||
**Version:** 1.0
|
||||
**Datum:** 2026-04-24
|
||||
**Status:** DRAFT
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-05-30
|
||||
**Status:** Kern umgesetzt (`ai_prompts`, `prompt_resolver`, Superadmin-HTTP-API); Kaskaden geplant (Abschnitt 8)
|
||||
|
||||
**Zielbild (Roadmap):** `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` — Kontext-Arten, Composition, Planung/Rahmen, Phasenplan.
|
||||
|
||||
**Ist-Stand API (Superadmin):**
|
||||
- `GET /api/admin/ai-prompts`, `GET /api/admin/ai-prompts/{id}`, `PUT …`, `POST …/preview`, `POST …/reset-template`, `GET /api/admin/ai-prompts/catalog/placeholders`
|
||||
- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter; **`NULL`/leer ⇒ `OPENROUTER_MODEL`** aus der Umgebung.
|
||||
|
||||
**Autor:** Claude Code
|
||||
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
|
||||
|
||||
**Verwandt (Skill-Katalog in Übungs-KI):** `working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md` — Tabelle **`ai_skill_retrieval_profiles`** (`config`-JSON ergänzt inhaltliche Prompt-/Katalog-Steuerung neben Platzhaltern).
|
||||
|
||||
---
|
||||
|
||||
## 1. Konzept
|
||||
@@ -28,6 +37,7 @@ steuerbar. Kein KI-Aufruf ist fest im Code verdrahtet.
|
||||
|-------------|-----------|
|
||||
| `exercise_summary` | Generiert `exercises.summary` aus goal + execution |
|
||||
| `exercise_skill_suggestions` | Empfiehlt Skills + Stufen für eine Übung |
|
||||
| `exercise_instruction_rewrite` | Überarbeitet Anleitung: goal, execution, preparation, trainer_notes (JSON, prägnantes HTML) |
|
||||
| `exercise_category_suggestions` | Empfiehlt Fokusbereich, Stil, Zielgruppe |
|
||||
| `model_skill_level_description` | Generiert Stufen-Beschreibung in der Fähigkeitsmatrix |
|
||||
| `training_plan_notes` | Erzeugt Trainer-Notizen für Trainingseinheiten |
|
||||
@@ -174,10 +184,9 @@ Wähle maximal 5 passende Fähigkeiten. Für jede gib an:
|
||||
- required_level: Voraussetzung (einsteiger|grundlagen|aufbau|fortgeschritten|experte)
|
||||
- target_level: Ziel nach regelmäßigem Training (gleiche Werte)
|
||||
- intensity: Trainingsintensität (niedrig|mittel|hoch)
|
||||
- is_primary: true wenn Hauptfähigkeit
|
||||
|
||||
Antworte NUR als JSON-Array:
|
||||
[{"skill_id": 1, "required_level": "grundlagen", "target_level": "aufbau", "intensity": "hoch", "is_primary": true}]
|
||||
[{"skill_id": 1, "required_level": "grundlagen", "target_level": "aufbau", "intensity": "hoch"}]
|
||||
|
||||
Wenn keine Fähigkeit passt, antworte mit [].$$,
|
||||
'exercise', 'json', true, NULL, 2),
|
||||
@@ -597,6 +606,19 @@ AI_PROMPT_SYSTEM_SPEC: ai_service.run_ai_prompt("exercise_summary", ...)
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0
|
||||
**Datum:** 2026-04-24
|
||||
**Status:** DRAFT
|
||||
## 8. Prompt-Kaskaden (geplant — nicht implementiert)
|
||||
|
||||
**Ziel:** Vorlagen, die andere Prompts einbinden oder in feste Stufen (System → Fach → Ausgabeformat) zerlegt werden — ohne die DB-Templates mit duplizierten Fliesstexten zu zersplittern.
|
||||
|
||||
**Konzeptskizze:**
|
||||
- Optional neues Feld `base_slug` oder eigene Tabelle `ai_prompt_composition` (Reihenfolge, Rolle: `system|user|prepend`).
|
||||
- Platzhaltersyntax z. B. `{{include_prompt:slug}}` mit **maximaler Verschachtelungstiefe** und Zykluserkennung.
|
||||
- Auflösungsreihenfolge: (1) eingebundene Slugs expandieren, (2) Kontext-Variablen wie heute ersetzen.
|
||||
|
||||
Bis zur Umsetzung bleiben zusammengesetzte Anweisungen im **einen** Template pro Slug (wie `exercise_skill_suggestions` mit `{{skills_catalog}}`).
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.1
|
||||
**Datum:** 2026-05-30
|
||||
**Status:** Teile umgesetzt (DB 067/069, Resolver, Superadmin-API + UI); Kaskaden offen
|
||||
@@ -0,0 +1,166 @@
|
||||
# KI-Prompt-System — Zielarchitektur (Shinkan Jinkendo)
|
||||
|
||||
**Version:** 1.0
|
||||
**Datum:** 2026-05-30
|
||||
**Status:** VERBINDLICHE ZIELRICHTUNG (Roadmap — nicht alles bereits umgesetzt)
|
||||
**Ergänzt:** `AI_PROMPT_SYSTEM_SPEC.md` (aktueller Ist-Stand APIs/DB/UI), Mitai-Anleihen aus gleichnamigen Konzepten (Admin-Prompts, Platzhalter)
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Dieses Dokument beschreibt das **Zielbild**, damit spätere Arbeiten (**Trainingsplanung**, **mehrstufige Rahmenprogramme**, **Phasen/Streams**, weitere KI-Artefakte) **nicht** zu wiederholten Refaktoren von Übungs-KI oder OpenRouter-Anbindung zwingen.
|
||||
|
||||
**Leitkriterien:** wenige stabile Schnittflächen, Kontext pro Domäne, komponierbare Prompts, gültige Ausgaben, Betrieb ohne Code-Deploy für kleine Tweaks.
|
||||
|
||||
---
|
||||
|
||||
## 2. Leitprinzipien
|
||||
|
||||
### 2.1 Eine stabile Ausführungsschicht
|
||||
|
||||
Alle produktiven KI-Aufrufe sollten mittelfristig über eine **einheitliche Fassade** laufen:
|
||||
|
||||
- **Eingabe:** `slug` (+ optional Kontext-Arten-Enum), **serialisierter Domän-Kontext** (Pydantic pro Kind), Konfiguration (Modell, Temperatur, … aus Env/DB).
|
||||
- **Ausgabe:** Text oder validiertes JSON, Metadaten (`model`, `slug`, ggf. `prompt_version`/Hash), strukturierte Fehler.
|
||||
|
||||
Router und Frontend rufen diese Schicht oder schmale Orchestratoren — **nicht** direkt `httpx`/OpenRouter an jeder Ecke verteilt.
|
||||
|
||||
**Frühere Konkretisierung (Umsetzung gestartet):** Modul `backend/ai_prompt_runtime.py` (`load_ai_prompt_row`, `load_and_render_ai_prompt`, Kontext-Arten) sowie `backend/ai_prompt_job.py` (Pydantic `ExerciseFormAiPromptContext` fuer Uebungs-Prompts — Admin-Vorschau + erweiterbare Router-Nutzung); `exercise_ai` orchestriert OpenRouter nach dem Rendern.
|
||||
|
||||
### 2.2 Trennung: Semantik vs. Transport
|
||||
|
||||
- **Semantik:** Was soll das Modell liefern? Das hängt an **Prompt-Definition**, **Ausgabeformat** (`text`/`json`) und nachvollziehbarer Validierung — nicht am HTTP-Client.
|
||||
- **Transport:** OpenRouter, Modellwahl, Retry, Timeouts bleiben in einem oder wenigen Hilfsmodulen.
|
||||
|
||||
### 2.3 Kontext-Namespaces für Platzhalter
|
||||
|
||||
Platzhalter und erlaubte Keys sind **pro logischer Kontext-Art** definiert, z. B.:
|
||||
|
||||
- `exercise_form_ai` — heute: Übungsformular-Vorschläge.
|
||||
- später: `training_unit`, `framework_program_slot`, `import_wiki`, …
|
||||
|
||||
Damit kann der Katalog wachsen, ohne dass alle Keys in einen globalen Soup-Namespace müssen (`exercise_*` vs. `framework_*` ohne Kollisionen). Optional später **präfixierte** Keys (`exercise.title`, `slot.index`).
|
||||
|
||||
### 2.4 Komposition / Kaskade explizit
|
||||
|
||||
**Ziel:** Mehrteilige Prompts („System“–„Nutzer“–Anhänge) und **Einbindung anderer Vorlagen** als **Daten** (Kompositionsmodell), nicht nur als unbearbeiteter Freitext mit `{{include}}`.
|
||||
|
||||
Skizzen (noch nicht vollständig umgesetzt):
|
||||
|
||||
- Tabelle oder JSON-Spalte `composition`/`ai_prompt_segments`: geordnete Segmente mit `role` (`system` \| `user` \| äquivalent zum jeweiligen API-Shape), Quelle (`inline`, `ref_slug`), optional `ref_slug`, Schema-Version.
|
||||
- Einbindungen mit **Maximaltiefe** und **Zykluserkennung** — keine unbegrenzten Makro-Ketten.
|
||||
|
||||
Bis dahin bleiben zusammenhängende Anweisungen in **einem** DB-Template pro Slug tragbar (`exercise_skill_suggestions` + `{{skills_catalog}}` bleiben gültig).
|
||||
|
||||
---
|
||||
|
||||
## 3. Zieldatenmodell (Schichten)
|
||||
|
||||
### 3.1 Definition (`ai_prompts` — bereits vorhanden, evolviert)
|
||||
|
||||
| Konzept | Bedeutung |
|
||||
|--------|-----------|
|
||||
| `slug`, `category`, `output_format`, `active` | Adressierung & Schalter |
|
||||
| `template` | aktueller Inhalt |
|
||||
| `default_template` | Referenz zum Zurücksetzen (Migration **069**) |
|
||||
| `output_schema` (JSONB) | optional: JSON-Outputs validieren |
|
||||
|
||||
**Ausbaustufen:**
|
||||
|
||||
1. Nur `template`-Text (**heute**, plus Mustache über `prompt_resolver`).
|
||||
2. Zusätzlich **Versionierung**: Historie oder `template_version`/Audit (wer hat wann geändert).
|
||||
3. **Segmentierte Composition** wie in Abschnitt 2.4.
|
||||
|
||||
### 3.2 Kontext-Builder pro Domäne
|
||||
|
||||
Pro **Kontext-Art** eine klar genannte Routine (Pattern: registrierbare Builder):
|
||||
|
||||
| Kontext-Art | Beispiel-Input aus der App | Beispiel-Platzhalter / Daten |
|
||||
|-------------|----------------------------|------------------------------|
|
||||
| `exercise_form_ai` | Titel, Ziel/Durchführung (HTML→Plain), Fokuskontext, Retrieval-Profil-Influenza | `exercise_*`, `skills_catalog` |
|
||||
| `training_unit` (geplant) | Sektionen, Zeiten, Phasen/Streams, verknüpfte Übungs-IDs | `unit_*`, `sections_summary_*` |
|
||||
| `framework_program` (geplant) | Ziele pro Woche/Schicht, Slots, bereits geplante Einheiten, Skill-Scores | `framework_*`, `slot_*`, aggregierte KPIs |
|
||||
|
||||
**Regel:** Planungs-UI baut keine Prompt-Strings; sie liefert **Domän-DTOs** → Builder erzeugen **Platzhalter-Map + ggf. Anhänge**.
|
||||
|
||||
### 3.3 Skill-Retrieval und Prompts
|
||||
|
||||
`ai_skill_retrieval_profiles` steuert **Katalog‑Zusammenstellung** vor dem Platzhalter `{{skills_catalog}}` — das bleibt **orthogonal** zur Prompt-Verwaltung: Prompt ändert *Anweisung*, Profil ändert *welche Skills im Kontextfenster sind*.
|
||||
|
||||
---
|
||||
|
||||
## 4. Trainingsplanung & Rahmen — erwartete Komplexität
|
||||
|
||||
Risiken: sehr große Kontexte (viele Slots, Streams, Bibliotheken), wiederholte KI-Anfragen, Token-Limits.
|
||||
|
||||
**Vorbereitende Strategien:**
|
||||
|
||||
1. **Gestufte Kontexte:** Rohdaten → interne Kurzfassungen (optional zweiter Prompt oder heuristisch) → finale Generator-Prompt nur mit komprimierten Summaries.
|
||||
2. **Slug-Pro-Use-Case:** z. B. `training_unit_trainer_notes`, `framework_slot_coach_hint` — jeweils schmaler Vertrag statt „ein Prompt für alles“.
|
||||
3. **Output-Verträge:** JSON-Schema + Server-Validierung vor UI; Fehlermeldungen mit Referenz auf Slug/Version.
|
||||
4. **Feature-Flags / Modell-Overrides** pro Slug (optional in DB oder Env) für Dev/Prod ohne große Codepfade.
|
||||
|
||||
---
|
||||
|
||||
## 5. Mitai (Jinkendo)
|
||||
|
||||
Konzeptionell **gleiche Bausteine** (admin-konfigurierbare Prompts, Platzhalter, Preview), **andere** Kontext-Builder und ggf. andere Mandanten/Overlays. Eine gemeinsame **Resolver-/Mustache-Ebene** ist wünschenswert; **Shinkan-spezifische** Planungs- und Rahmenkontexte bleiben in Shinkan gekapselt.
|
||||
|
||||
---
|
||||
|
||||
## 6. Betrieb, Sicherheit, Observability
|
||||
|
||||
- **Audit:** `updated_by` / Änderungshistorie für Templates (Backlog), heute: Timestamps.
|
||||
- **Prompt-Injection:** System-/User-Segmente trennen; sensible Regeln in `system`/`developer`-äquivalenten Blöcken (wenn API das hergibt).
|
||||
- **Logging:** weiter `SHINKAN_AI_DEBUG`; langfristig Hash/Länge des **aufgelösten** Prompts pro Request (ohne Secrets).
|
||||
- **Kosten/Latenz:** Timeouts, max. Token-Hinweise pro Slug-Konfiguration.
|
||||
|
||||
---
|
||||
|
||||
## 7. Phasenplan (empfohlen, ohne Big-Bang)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph laufzeit
|
||||
A[ai_prompts DB]
|
||||
B[prompt_resolver Mustache]
|
||||
C[ai_prompt_runtime]
|
||||
J[ai_prompt_job Pydantic]
|
||||
D[exercise_ai OpenRouter]
|
||||
end
|
||||
A --> C
|
||||
C --> B
|
||||
J --> D
|
||||
C --> D
|
||||
B --> D
|
||||
```
|
||||
|
||||
| Phase | Inhalt |
|
||||
|-------|--------|
|
||||
| **P0** | `AiPromptContextKind`, `load_ai_prompt_row` zentral; Übungs-KI über Laufzeit. |
|
||||
| **P1** | `load_and_render_ai_prompt`, `AiPromptUnavailableError`, `render_ai_prompt_template_for_row`; **`ExerciseFormAiPromptContext`** in `ai_prompt_context.py`; **`run_exercise_form_ai_suggestion`**; Übungs-API und Admin-Vorschau nutzen denselben Kontext. |
|
||||
| **P2** | Versionierung oder Audit-Spalten; **teilweise:** optionales OpenRouter-Modell pro Zeile (`openrouter_model`, Migration 070, Fallback `OPENROUTER_MODEL`); weitere Overrides (Temperatur) offen. |
|
||||
| **P3** | Composition/Segmente (JSON Schema Version 1) + UI nur für komplexe Slugs. |
|
||||
| **P4** | Erste Planungs-/Rahmen-Slugs mit dedizierten Buildern und Token-Budget-Strategien. |
|
||||
|
||||
---
|
||||
|
||||
## 8. Was bewusst vermieden werden soll
|
||||
|
||||
- Vollständige „Workflow-Engine“ mit beliebigen Graphen, bevor 2–3 konkrete Planungs-Anwendungsfälle live sind.
|
||||
- Pro-Verein-Prompt-Kopien vor klar definierter Produkt-Anforderung (sonst Daten- und Pflege-Spirale).
|
||||
- Unbegrenzte `include`-rekursive Textmakros ohne Tiefenschutz.
|
||||
|
||||
---
|
||||
|
||||
## 9. Querverweise
|
||||
|
||||
- Ist-Implementierung Prompts/UI: `AI_PROMPT_SYSTEM_SPEC.md`
|
||||
- Zugriffsrecht Admin-Prompts: `ACCESS_LAYER_ENDPOINT_AUDIT.md`
|
||||
- Retrieval-Profile: `.claude/docs/working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`
|
||||
- Übungs-KI-Codepfad: `backend/exercise_ai.py`, `backend/prompt_resolver.py`, `backend/ai_prompt_runtime.py`, `backend/ai_prompt_context.py`, `backend/ai_prompt_job.py`
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0 · **Datum:** 2026-05-30
|
||||
@@ -1,12 +1,14 @@
|
||||
# KI-gestützte Trainingsplanung – Zentrales Konzept
|
||||
|
||||
**Version:** 0.1
|
||||
**Datum:** 2026-05-16
|
||||
**Version:** 0.3
|
||||
**Datum:** 2026-05-22
|
||||
**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.
|
||||
**Ziel:** Einheitlicher Rahmen für **stufenweise** KI-Unterstützung – zuerst **Übungsanlage** (Zusammenfassung, Fähigkeiten, Texte), später **Planung** (Abschnitte, Einheiten, Rahmen) – ohne vollständigen Übungskatalog im Prompt.
|
||||
|
||||
**Maßgebende Version zum Abgleich:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, relevante Einträge in `MODULE_VERSIONS`).
|
||||
|
||||
**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`
|
||||
`functional/DOMAIN_MODEL.md` · **`functional/AI_EXERCISE_ASSISTANT_VISION.md`** (Übungs-KI: Zielbild vor Planungs-KI) · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (u. a. CURR-003 zu Progressions-/KI-Automatik) · **`working/AI_PLANNING_KI_MULTISTAGE_FORECAST.md`** (mehrstufige Planungs-KI: Daten-„Graph“, Pipeline-Stufen, Code-Schnitte – Vorschau gegen späteres Refactoring) · `technical/TRAINING_FRAMEWORK_SPEC.md` · **`technical/SKILL_SCORING_SPEC.md`** (Fähigkeits-Profilierung, Discovery) · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `technical/SKILLS_MATRIX_SPEC.md` · `docs/FACHLICHE_NUTZERFUNKTIONEN.md` · `docs/HANDOVER.md`
|
||||
|
||||
---
|
||||
|
||||
@@ -16,13 +18,30 @@
|
||||
- **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.
|
||||
|
||||
### 1.1 Abgleich: aktueller Code- und Schema-Stand (Stand Review 2026-05-22)
|
||||
|
||||
| Thema | Ist im Repo | Konsequenz für dieses Konzept |
|
||||
|--------|-------------|-------------------------------|
|
||||
| **OpenRouter / LLM im Backend** | Produktiver Aufruf für Übungs‑Suggest in `openrouter_chat.py`, `exercise_ai.py`; Endpunkte **`POST …/exercises/ai/suggest`** und **`POST …/{id}/ai/regenerate`**; Migration **067** (`ai_prompts`, `summary_ai_generated`). **`db.py`**-Bootstrap nutzt **`display_name`**. | **Übungs-Assistent (P0)** vorhanden; generalisierter Service + **Planungs-KI** folgen. |
|
||||
| **Übungs-KI laut Spec** | P0: Kurzfassung + Skill‑Vorschläge (`include_summary` / `include_skills`); **kein** Auto-KI beim Speichern (S5 im Umsetzungsplan). | Feinspez: `summary_ai_generated` bei manueller Kurzfassung zurücksetzen; Rate-Limits; Prompt-Admin-UI. |
|
||||
| **Fähigkeiten-Stammdaten** | Migration **`065_skills_wiki_karate_relevance`:** `skills.karate_relevance` (Text), `skills.relevance_level` (1–3, optional); dazu weiterhin `description`, `focus_areas`, Kategorien, `skill_level_definitions` (Level 1–5 je Skill). | Diese Felder sind **expliziter Prompt-Kontext** für Skill-Vorschläge (Disambiguierung Karate vs. universal) – siehe §6. |
|
||||
| **Skill-Scoring & Discovery (ohne LLM)** | Router `skill_profiles.py` + Modul `skill_scoring.py`: u. a. `GET …/skill-profile` für **Rahmenprogramm**, **Trainingsmodul**, **Progressionsgraph**; `POST /skill-profiles/batch-summaries`; **`GET /api/skill-discovery/suggestions`** (Match Bibliotheksartefakte ⇄ `skill_ids`, mit `library_content_visibility_sql`). | Ergänzt §3 **Stufe 3**: deterministische **Skill-Abdeckung / Artefakt-Discovery** ist **bereits vorhanden** und kann später die **Planungs-KI** speisen (Ziel-Skill-Mengen, Vergleich „Profil des Rahmens“) – ersetzt aber **nicht** die Top‑K-Selektion aus dem **Übungskatalog** für eine konkrete Session. |
|
||||
| **Profil / Planungs-Präferenzen** | `profiles.training_planning_prefs` (JSONB, vgl. `MODULE_VERSIONS` → `profiles`), Planungsmodul mit u. a. **Vorlagen inkl. Split-Sessions** (`planning`), `training_units` mit **Publish in Rahmen-Slot-Blueprint**. | Zukünftige KI-Planung kann **Prefs** und **Vorlagen-Struktur** als weiche Constraints einbeziehen; Rahmen↔Einheit-Fluss ist produktiv erweitert – für KI nur relevant, sobald Planungs-Endpunkte angebunden werden. |
|
||||
| **Übungsliste API** | Keyset-Pagination u. a. `cursor_updated_at` + Tie-break `id` (`exercises`-Modul laut `MODULE_VERSIONS`). | Retrieval-Pipelines sollten **cursorbasiert** paginieren, nicht „alle IDs auf einmal“ laden. |
|
||||
|
||||
**Nächster produktiver Fokus:** Prompt-/Admin‑UI zur Pflege von `ai_prompts`, **Rate-Limits**, optional **Auto-KI beim Speichern**; danach Übergang zur **Planungs-KI** laut diesem Dokument.
|
||||
|
||||
**Architektur-Vorschau (Planungs-KI):** Damit die **kleinere, starre** Übungs-Pipeline nicht zur stillen Vorlage für Planung wird, sind **eigenes Modul**, **stufenweise Outputs mit Validierung** und ein **kompaktes Kontext-DTO** vorgesehen — siehe **`working/AI_PLANNING_KI_MULTISTAGE_FORECAST.md`**.
|
||||
|
||||
---
|
||||
|
||||
## 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:
|
||||
**Abgrenzung Übungsanlage (aktueller Prioritätspfad):** Hier geht der Prompt typischerweise von **einzelnen** Freitexten (`title`, `goal`, `execution`, …) und einem **Skills-Katalog-Auszug** aus – nicht vom gesamten Übungsbestand. Trotzdem gilt: Aktive Skills **paginieren** oder **stufig** laden (Subset + zweite Runde nur für Kurzliste), keine vollständigen Romane aus `skill_level_definitions` für hunderte Fähigkeiten auf einmal.
|
||||
|
||||
**Festlegung (Planungs-KI):** Der LLM-Prompt erhält immer nur ein **begrenztes Kontext-Paket** mit:
|
||||
|
||||
| Paketteil | Zweck |
|
||||
|-----------|--------|
|
||||
@@ -69,7 +88,8 @@ 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).
|
||||
4. **Semantische Suche:** Embeddings + **Ähnlichkeitsuche** auf Kurztexte (siehe §5).
|
||||
5. **Skill-Discovery über Planungs-Artefakte (bereits implementiert):** `GET /api/skill-discovery/suggestions` matching **Bibliotheksartefakte** (u. a. Rahmenprogramm, Trainingsmodul, Progressionsgraph) gegen gegebene `skill_ids`; `GET …/skill-profile` liefert **gewichtete Fähigkeitsprofile** aus den dort verknüpften Übungen (siehe `SKILL_SCORING_SPEC.md`). Das ist ein **deterministischer** Baustein für „welche Artefakte passen zu diesen Skills?“, **nicht** der Ersatz für **Top‑K-Übung**-Auswahl in einer konkreten Session – dort weiter Stufen 1–2 + Punkte 1–4/LLM.
|
||||
|
||||
Ergebnis: sortierte Liste, **Top‑K** für den Prompt.
|
||||
|
||||
@@ -128,7 +148,8 @@ Sinnvoller zeitlicher Punkt oder technische Auslöser:
|
||||
|
||||
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);
|
||||
- verlässliche **Skills** (`exercise_skills`, ggf. KI-geholfen bereits laut Spez beim Übungs-Anlegen); `exercise_skills.ai_suggested` und kanonische Stufen (`required_level` / `target_level` als Slugs) für Nachvollziehbarkeit.
|
||||
- **`skills`-Stamm:** `description`, **`karate_relevance`**, **`relevance_level` (1–3)**, **`focus_areas`**, Kategorien/Keywords für **Prompt-Kontext** beim Skill-Mapping bei der Übungsanlage; optional **`skill_level_definitions`** für Stufen 1–5 **gezielt** in die zweite Prompt-Runde (nur Kurzliste Kandidaten).
|
||||
- sinnvolle **`summary`**-Felder für Karten/Liste/KI-Pack;
|
||||
- **Progressionsgraph** dort, wo pädagogische Ketten gefestigt sind;
|
||||
- konsistente **Fokusbereich/Stil**-Zuordnung.
|
||||
@@ -139,15 +160,18 @@ Das fachliche Konzept sollte entscheiden: **wie viel automatische Pflege vs. Tra
|
||||
|
||||
## 7. Produkt-/Release-Stufen (Anknüpfung)
|
||||
|
||||
Priorität **jetzt**: **Übungsanlage**, danach **Planung**.
|
||||
|
||||
| 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 |
|
||||
| **A0** | **Zentraler KI-Service** (ein Modul/Hilfslayer), Prompts aus `ai_prompts` | OpenRouter oder vereinbarter Provider, Timeouts, `503` ohne Key, Parsing/Validation |
|
||||
| **A1** | **Übungsanlage** (vgl. `KI_FEATURES_SPEC`): `summary`, Skill-Vorschläge inkl. Stufen/Intensität, optional Textglättung | `POST /api/exercises/ai/suggest`, `POST /api/exercises/{id}/ai/regenerate`; Prompt-Kontext: Skills mit `description`, `karate_relevance`, `relevance_level`, optional `skill_level_definitions` für Kurzliste; DB: `summary_ai_generated`, `exercise_skills.ai_suggested` |
|
||||
| B | „Übungen für Abschnitt vorschlagen“ | Pipeline §3 Stufen 1–3 + Prompt mit Top‑K (Übungsliste **keyset-pagination** beachten) |
|
||||
| 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 |
|
||||
| D | Ganze Einheit (inkl. Phasen/Streams vereinfacht) | strukturiertes JSON + strikte Schema-Validation gegen bestehende `PUT`-Payloads |
|
||||
| E | Mehreinheiten / Rahmen‑Alignment | Ziele aus Rahmenprogramm, Serie von Slots; **Skill-Profile** (`…/skill-profile`) als Kontextuelle Verstärker |
|
||||
|
||||
Die **Selektions‑Pipeline §3 bleibt** über alle Stufen konsistent und wird nur parametrierbar erweitert.
|
||||
Die **Selektions‑Pipeline §3** bleibt für **Planungs**-KI konsistent und wird parametrierbar erweitert; **§1.1** spiegelt den **aktuellen Implementierungs**-Vorsprung (Skill-Scoring ohne LLM) wider.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# Exercises API Specification
|
||||
|
||||
**Version:** 1.5
|
||||
**Datum:** 2026-05-08
|
||||
**Version:** 1.6
|
||||
**Datum:** 2026-05-20
|
||||
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||
**Änderungen v1.6:** Freigabelevel-UI-Hinweis; `exercise_skills` ohne `is_primary` in Requests (Legacy-Feld wird ignoriert/forciert false); Permissions-Bereich an Ist-Code angeglichen; Intensität kanonisch `niedrig|mittel|hoch`
|
||||
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
|
||||
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
|
||||
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
|
||||
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
|
||||
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
|
||||
@@ -185,11 +186,11 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
"skill_id": 10,
|
||||
"skill_name": "Distanzgefühl",
|
||||
"skill_category": "Kumite",
|
||||
"is_primary": true,
|
||||
"intensity": "hoch",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"ai_suggested": false
|
||||
"ai_suggested": false,
|
||||
"is_primary": false
|
||||
}
|
||||
],
|
||||
|
||||
@@ -307,7 +308,6 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
|
||||
"skills": [
|
||||
{
|
||||
"skill_id": 10,
|
||||
"is_primary": true,
|
||||
"intensity": "hoch",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau"
|
||||
@@ -578,7 +578,6 @@ Wird beim Klick auf „✨ KI-Vorschlag" im Formular aufgerufen.
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"intensity": "hoch",
|
||||
"is_primary": true,
|
||||
"confidence": 0.92
|
||||
},
|
||||
{
|
||||
@@ -588,7 +587,6 @@ Wird beim Klick auf „✨ KI-Vorschlag" im Formular aufgerufen.
|
||||
"required_level": "einsteiger",
|
||||
"target_level": "grundlagen",
|
||||
"intensity": "mittel",
|
||||
"is_primary": false,
|
||||
"confidence": 0.74
|
||||
}
|
||||
]
|
||||
@@ -621,6 +619,38 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
|
||||
## Permissions
|
||||
|
||||
**UI-Hinweis:** Das Feld `visibility` heißt in der Oberfläche **Freigabelevel** (`exerciseGovernanceLabels.js`).
|
||||
|
||||
### Lesen (`GET /exercises`, `GET /exercises/{id}`)
|
||||
|
||||
| `visibility` | Wer darf lesen? |
|
||||
|--------------|-----------------|
|
||||
| `official` | Plattform-weit |
|
||||
| `private` | Ersteller (`created_by`); Plattform-Admin |
|
||||
| `club` | Aktive Mitglieder des Objekt-`club_id`; Plattform-Admin ohne Mitgliedschaft (Audit-Zugang) |
|
||||
|
||||
Implementierung: `library_content_visible_to_profile` / `exercise_visible_to_profile` in `club_tenancy.py`.
|
||||
|
||||
### Bearbeiten (`PUT`, Varianten-CRUD, Medien an Übung)
|
||||
|
||||
| Bedingung | Wer darf bearbeiten? |
|
||||
|-----------|----------------------|
|
||||
| Ersteller | Immer (eigene Übung) |
|
||||
| Plattform-Admin | Immer |
|
||||
| `visibility=club` | Zusätzlich **`can_plan_in_club`** im Objekt-Verein: `club_admin`, `trainer`, `content_editor`, `division_lead` |
|
||||
|
||||
Implementierung: `_assert_can_edit_exercise` in `exercises.py`. **Varianten** haben kein eigenes Owner-Feld — gleiche Prüfung wie Eltern-Übung.
|
||||
|
||||
### Löschen (`DELETE /exercises/{id}`)
|
||||
|
||||
| `visibility` | Wer darf löschen? |
|
||||
|--------------|-------------------|
|
||||
| `official` | Nur Plattform-Admin |
|
||||
| `club` | Nur **`club_admin`** im Objekt-Verein |
|
||||
| `private` | Ersteller; oder Vereins-Admin, der mit dem Ersteller einen gemeinsamen Verein teilt |
|
||||
|
||||
Implementierung: `_assert_can_delete_exercise` in `exercises.py`.
|
||||
|
||||
### Sichtbarkeits-Workflow
|
||||
|
||||
| Von → Nach | Wer darf das? |
|
||||
@@ -638,11 +668,12 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
| `club → official` | Club-Admin, Super-Admin |
|
||||
| `official → club` | Super-Admin |
|
||||
|
||||
### Owner-Checks
|
||||
### Owner-Checks (veraltet — siehe Tabellen oben)
|
||||
|
||||
- **Bearbeiten** (PUT): Nur Ersteller oder Club-Admin
|
||||
- **Löschen** (DELETE): Nur Ersteller oder Super-Admin
|
||||
- **Lesen** (`private`): Nur Ersteller
|
||||
Die folgenden Kurzregeln sind durch die Ist-Implementierung ersetzt; nur zur historischen Einordnung:
|
||||
|
||||
- ~~Bearbeiten (PUT): Nur Ersteller oder Club-Admin~~ → siehe **Bearbeiten**-Tabelle (`can_plan_in_club`)
|
||||
- ~~Löschen (DELETE): Nur Ersteller oder Super-Admin~~ → siehe **Löschen**-Tabelle
|
||||
|
||||
**403 Fehler-Beispiel:**
|
||||
```json
|
||||
@@ -904,7 +935,8 @@ Trainer muss im Frontend aktiv übernehmen.
|
||||
### Exercise Skills
|
||||
- `required_level`: enum – `einsteiger | grundlagen | aufbau | fortgeschritten | experte` (optional/nullable)
|
||||
- `target_level`: enum – gleiche Werte (optional/nullable)
|
||||
- `intensity`: enum – `niedrig | mittel | hoch` (optional/nullable)
|
||||
- `intensity`: enum – **`niedrig | mittel | hoch`** (optional/nullable; Default beim Speichern **`mittel`**)
|
||||
- `is_primary`: **Legacy** — Spalte existiert in DB, wird bei POST/PUT **nicht ausgewertet** (immer `false` gespeichert); UI liefert/speichert kein Primär-Flag mehr; Scoring ignoriert das Feld
|
||||
- `target_level` sollte >= `required_level` sein (Warnung, kein Fehler)
|
||||
|
||||
### Exercise Block Item
|
||||
|
||||
@@ -99,20 +99,21 @@ Exercise Block ──── (N) Block Items ──── (1) Exercise
|
||||
|
||||
### 1.3 M:N Beziehungen (Primary/Secondary Pattern)
|
||||
|
||||
**Regel:** Alle Katalog-Zuordnungen nutzen M:N mit `is_primary` Flag.
|
||||
**Regel:** Katalog-Zuordnungen (Fokus, Stil, Zielgruppe, …) nutzen M:N mit optionalem `is_primary`-Flag.
|
||||
|
||||
**Betroffene Relationen:**
|
||||
**Betroffene Relationen (mit `is_primary`):**
|
||||
- `exercise_focus_areas` (Übung ↔ Fokusbereiche)
|
||||
- `exercise_styles` (Übung ↔ Trainingsstile)
|
||||
- `exercise_styles` / `exercise_style_directions` (Übung ↔ Stilrichtungen)
|
||||
- `exercise_training_types` (Übung ↔ Trainingsstile)
|
||||
- `exercise_target_groups` (Übung ↔ Zielgruppen)
|
||||
- `exercise_training_characters` (Übung ↔ Trainingscharaktere)
|
||||
- `exercise_skills` (Übung ↔ Fähigkeiten)
|
||||
|
||||
**Primary/Secondary Semantik:**
|
||||
**Ausnahme — `exercise_skills`:** Kein Primär-Flag in UI/API mehr; stattdessen **`intensity`** (`niedrig` \| `mittel` \| `hoch`, Default `mittel`). Spalte `is_primary` bleibt Legacy (Backend speichert immer `false`).
|
||||
|
||||
**Primary/Secondary Semantik (Katalog-Dimensionen):**
|
||||
- **Primary:** Hauptzuordnung, entscheidend für Filter/Suche
|
||||
- **Secondary:** Nebenzuordnung, zusätzlicher Kontext
|
||||
- **Regel:** Genau EINE Primary-Zuordnung pro Dimension
|
||||
- **UI:** Primary wird visuell hervorgehoben (z.B. fett, farbig)
|
||||
- **Regel:** Genau EINE Primary-Zuordnung pro Dimension (wo UI das noch anbietet)
|
||||
- **UI:** Primary wird visuell hervorgehoben (z. B. fett, farbig) — Fähigkeiten: Intensitäts-Segmente statt Primary
|
||||
|
||||
**Legacy-Felder (DEPRECATED):**
|
||||
- `exercises.focus_area` → Ignorieren, nutze `exercise_focus_areas`
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# Frontend Routing & Navigation Specification
|
||||
|
||||
**Version:** 1.2
|
||||
**Datum:** 2026-04-30
|
||||
**Version:** 1.3
|
||||
**Datum:** 2026-05-20
|
||||
**Status:** DRAFT - Awaiting Review
|
||||
**Autor:** Claude Code
|
||||
**Änderungen v1.3:** Übungsformular Tab-Navigation unter `/exercises/:id/edit` (Stammdaten … Medien & Mehr); Freigabelevel als UI-Begriff
|
||||
**Änderungen v1.2:** Übersicht **Übungen**: Tabs Liste \| Progressionsgraphen auf `/exercises`; Progressions-Editor ohne neue Routen (Panel + Formularblock unter `/exercises/:id/edit`)
|
||||
**Änderungen v1.1:** Übungsvarianten-Bearbeitung nur unter `/exercises/:id/edit` (keine VariantFormPage-Routen)
|
||||
|
||||
@@ -17,7 +18,7 @@
|
||||
/exercises → ExercisesListPage — Tabs: **Liste** \| **Progressionsgraphen** (`ExerciseProgressionGraphPanel`)
|
||||
/exercises/new → ExerciseFormPage (Create)
|
||||
/exercises/{id} → ExerciseDetailPage (Accordion-Layout)
|
||||
/exercises/{id}/edit → ExerciseFormPage (Edit inkl. Varianten-Editor inline + Block Progressionsgraph)
|
||||
/exercises/{id}/edit → ExerciseFormPage (Edit: Registerkarten + Varianten inline + Progressionsgraph)
|
||||
|
||||
/exercise-blocks → ExerciseBlocksListPage (Meine Blocks)
|
||||
/exercise-blocks/new → ExerciseBlockFormPage (Create)
|
||||
@@ -35,6 +36,25 @@
|
||||
- Pagination: `/exercises?limit=50&offset=100`
|
||||
- Sortierung: `/exercises?sort=created_at&order=desc`
|
||||
|
||||
### 1.2 Übungsformular – Registerkarten (`/exercises/new`, `/exercises/:id/edit`)
|
||||
|
||||
**Implementierung:** `ExerciseFormPageRoot.jsx` + `ExerciseFormLayout.jsx` (`ExerciseFormTabBar`, `ExerciseFormPanel`).
|
||||
|
||||
| Tab-ID | Label | Verfügbarkeit |
|
||||
|--------|-------|---------------|
|
||||
| `stammdaten` | Stammdaten | immer |
|
||||
| `anleitung` | Anleitung | immer |
|
||||
| `einordnung` | Einordnung | immer |
|
||||
| `kombination` | Kombination | nur `exercise_kind=combination` |
|
||||
| `varianten` | Varianten | Edit-Modus; nicht bei Kombination; disabled bei Neuanlage |
|
||||
| `medien` | Medien & Mehr | Edit-Modus; disabled bei Neuanlage |
|
||||
|
||||
**UX-Regeln:**
|
||||
- Nur ein Panel sichtbar (`activeFormTab`); Navigation über `PageSectionNav`.
|
||||
- **Freigabelevel** (Feld `visibility`) in Stammdaten — Konstante `EXERCISE_VISIBILITY_FIELD_LABEL`.
|
||||
- Varianten-Änderungen werden mit **Speichern** in der Aktionsleiste persistiert (`persistPendingVariantChanges`); Button „Variante anlegen“ optional sofort.
|
||||
- Kein URL-Hash pro Tab (Tab-State nur lokal).
|
||||
|
||||
---
|
||||
|
||||
## 2. Navigation-Patterns
|
||||
@@ -673,7 +693,7 @@ function App() {
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.2
|
||||
**Letzte Änderung:** 2026-04-30
|
||||
**Version:** 1.3
|
||||
**Letzte Änderung:** 2026-05-20
|
||||
**Status:** REVIEWED - Pending Implementation
|
||||
**Review-Änderungen:** Progressionsgraphen-UI (Tabs, Formularblock); Exercise Blocks Routes + Navigation (früher)
|
||||
**Review-Änderungen:** Formular-Registerkarten; Progressionsgraphen-UI (Tabs, Formularblock); Exercise Blocks Routes + Navigation (früher)
|
||||
@@ -7,11 +7,16 @@
|
||||
**Änderungen v1.1:** Prompts sind nicht hardcoded – sie werden aus der DB geladen (AI_PROMPT_SYSTEM_SPEC.md)
|
||||
**Verwandte Specs:** AI_PROMPT_SYSTEM_SPEC.md (Prompt-DB + Platzhalter), SKILLS_MATRIX_SPEC.md (Fähigkeitsmatrix)
|
||||
|
||||
**Übergeordnete Produkt-Vision** (breiter Scope: Zielausbau, bereichsweise vs. Gesamtüberarbeitung, Varianten, Planungs-/Nachbereitungskontext, Admin-Masse):
|
||||
`functional/AI_EXERCISE_ASSISTANT_VISION.md`
|
||||
|
||||
---
|
||||
|
||||
## 1. Übersicht
|
||||
|
||||
Zwei KI-gestützte Assistenzfunktionen beim Anlegen und Bearbeiten von Übungen:
|
||||
KI-gestützte Assistenzfunktionen beim Anlegen und Bearbeiten von Übungen (Mindestpaket dieser Spec):
|
||||
|
||||
**Hinweis:** Die beiden folgenden Zeilen entsprechen **P0** der Phasierung in **`AI_EXERCISE_ASSISTANT_VISION.md`**; spätere Funkteile sind dort beschrieben.
|
||||
|
||||
| Funktion | Ziel |
|
||||
|---------|------|
|
||||
@@ -155,7 +160,38 @@ KI gibt Vorschläge
|
||||
Liefert KI-Vorschläge auf Basis von Eingabe-Text, **bevor** die Übung gespeichert wurde.
|
||||
Wird beim Klick auf „KI-Vorschlag" im Formular aufgerufen.
|
||||
|
||||
**Request Body:**
|
||||
**Required Fields:** mindestens `goal` ODER `execution`
|
||||
|
||||
**Optional – Skill-Katalogpriorisierung (Stand 068):**
|
||||
|
||||
```json
|
||||
{
|
||||
"focus_areas_context": [
|
||||
{ "focus_area_id": 3, "is_primary": true },
|
||||
{ "focus_area_id": 1, "is_primary": false }
|
||||
],
|
||||
"focus_area_hint": "Karate, Kumite…"
|
||||
}
|
||||
```
|
||||
|
||||
- `focus_areas_context`: IDs aus Stammdatum **Fokusbereiche**; Primär soll zuerst stehen (`is_primary`). Ohne Feld oder leere Liste gilt das DB-Profil **`is_default`** (`ai_skill_retrieval_profiles`).
|
||||
- `focus_area_hint`: bleibt lesbarer Text für den Prompt (bestehende Prompts).
|
||||
|
||||
|
||||
**Minimal-Beispiel (Mit Fokus für Retrieval):**
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Maai - Distanzübung",
|
||||
"goal": "…",
|
||||
"execution": "…",
|
||||
"focus_areas_context": [ { "focus_area_id": 1, "is_primary": true } ]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Minimal-Beispiel ( ohne Fokus — nur Texts):**
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Maai - Distanzübung",
|
||||
@@ -164,8 +200,6 @@ Wird beim Klick auf „KI-Vorschlag" im Formular aufgerufen.
|
||||
}
|
||||
```
|
||||
|
||||
**Required Fields:** mindestens `goal` ODER `execution` (je länger, desto besser)
|
||||
|
||||
**Response:** `200 OK`
|
||||
```json
|
||||
{
|
||||
@@ -182,7 +216,6 @@ Wird beim Klick auf „KI-Vorschlag" im Formular aufgerufen.
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"intensity": "hoch",
|
||||
"is_primary": true,
|
||||
"confidence": 0.92
|
||||
},
|
||||
{
|
||||
@@ -192,7 +225,6 @@ Wird beim Klick auf „KI-Vorschlag" im Formular aufgerufen.
|
||||
"required_level": "einsteiger",
|
||||
"target_level": "grundlagen",
|
||||
"intensity": "mittel",
|
||||
"is_primary": false,
|
||||
"confidence": 0.74
|
||||
}
|
||||
]
|
||||
|
||||
@@ -13,6 +13,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| exercises | `PATCH /api/exercises/bulk-metadata` | ja | `get_tenant_context` | ja | Liste: UI-Mehrfachwahl; bis 500 IDs; nur Ersteller oder Plattform-Admin |
|
||||
| exercises | `GET .../media/{mid}/file` | ja | `get_tenant_context_flexible` | ja (wie Übung lesen) | Datei oder `?ssetoken`; kein anonymes `/media/` ohne ALLOW_PUBLIC_MEDIA_STATIC |
|
||||
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
|
||||
| exercises | POST `/api/exercises/ai/suggest`, POST `/api/exercises/{id}/ai/regenerate` | ja | `get_tenant_context` | nein | Nur Vorschlags-JSON; keine DB-Schreibung; OpenRouter — suggest optional `focus_areas_context` für Retrieval-Profile |
|
||||
| exercise_progression_graphs | `/api/exercise-progression-graphs*` | ja | `get_tenant_context` | Liste wie Bibliothek; Schreiben Ersteller/Plattform-Admin | Kanten: Lesen wenn Graph lesbar |
|
||||
| training_planning | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Vorlagen-Liste wie Übungen; POST Vorlage Default club_id |
|
||||
| dashboard | `GET /api/dashboard/kpis` | ja | `get_tenant_context` | wie `GET /api/exercises` + `GET /api/training-units` | Aggregat für Dashboard-Kurzüberblick (ein Roundtrip) |
|
||||
@@ -32,18 +33,27 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
||||
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
|
||||
| maturity_models | Admin-Matrix | nein (global) | `require_auth` | Admin für Schreiben; `GET …/{id}` nur Portal-Admin | EXEMPT |
|
||||
| matrix_stack_bundle | Export/Import Bundles | Plattform/Test | `require_auth` | Admin | EXEMPT |
|
||||
| matrix_editor | `/api/admin/matrix-editor/*` (Export/Import Editor-Bundle) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale Fähigkeitsmatrix ohne Mandantenkontext |
|
||||
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
|
||||
| ai_skill_retrieval_admin | `/api/admin/ai-skill-retrieval-profiles*` (CRUD) | Plattform | `require_auth` | nur `superadmin`; JSON `config` | EXEMPT wie `admin_users`; kein Vereinsbezug |
|
||||
| ai_prompts_admin | `/api/admin/ai-prompts*` (Liste, Detail, PUT, Preview, Reset) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale `ai_prompts` ohne Mandantenkontext |
|
||||
| exercise_enrichment_admin | `/api/admin/exercise-enrichment/*` (Kandidaten, Preview, Apply) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; plattformweite Übungsliste + Skill-Schreibung; kein TenantContext |
|
||||
|
||||
**Legende:** Router auf der EXEMPT-Liste des Scripts sind globale oder Auth-only-Pfade; sobald ein Router Vereinsdaten oder Bibliotheks-Sichtbarkeit erhält, EXEMPT entfernen und `get_tenant_context` einführen.
|
||||
|
||||
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
||||
|
||||
Letzte Änderung: 2026-05-13 — `GET /api/dashboard/kpis` (Kurzüberblick-Aggregat).
|
||||
Letzte Änderung: 2026-05-23 — Superadmin `/api/admin/exercise-enrichment/*` (Batch-KI Skills, Status in_review).
|
||||
|
||||
---
|
||||
|
||||
### Changelog (Fortführung)
|
||||
|
||||
- **2026-05-23:** Superadmin-API `exercise_enrichment_admin` (Batch-Übungs-Anreicherung KI) dokumentiert.
|
||||
- **2026-05-30:** Superadmin-API `ai_prompts_admin` (`/api/admin/ai-prompts*`) dokumentiert.
|
||||
- **2026-05-29:** Superadmin-API `ai_skill_retrieval_admin` (Retrieval-Profile) dokumentiert.
|
||||
- **2026-05-22:** Übungs-KI-Endpunkte (Suggest/Regenerate) dokumentiert.
|
||||
|
||||
- **2026-05-13:** Dashboard-KPI-Endpunkt dokumentiert.
|
||||
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Umsetzungsplan – KI bei Übungen (stufenweise, Driftschutz)
|
||||
|
||||
**Version:** 0.2
|
||||
**Datum:** 2026-05-29
|
||||
**Bezüge:** `functional/AI_EXERCISE_ASSISTANT_VISION.md` · **`working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`** · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `technical/AI_TRAINING_PLANNING_CONCEPT.md` (§1.1 Ist-Stand)
|
||||
|
||||
---
|
||||
|
||||
## 1. Drift vermeiden – verbindliche Regeln
|
||||
|
||||
1. **Spec vor Code:** Request/Response-Felder und Statuscodes an `KI_FEATURES_SPEC.md` ausrichten; Abweichungen zuerst Spec oder dieses Dokument anpassen.
|
||||
2. **Prompts in der DB:** Keine produktionskritischen Prompt-Langtexte nur im Code; Defaults per **Migration** in `ai_prompts`, Anpassung durch Admins über vorgesehene Oberfläche (später) oder SQL.
|
||||
3. **Skill-Retrieval-Profile:** Gewichte/Quotes in **`ai_skill_retrieval_profiles.config`** — Spezifikation `working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`; kein zweites gleichzeitiges Truth-Repo im Sourcecode außer defensiver Fallback `_FALLBACK_RETRIEVAL_CONFIG` in `exercise_ai.py`.
|
||||
4. **Stufen-Slugs & Intensität:** Nur **kanonische** Werte wie in `exercises.py` (`basis` … `optimierung`, `niedrig|mittel|hoch`); LLM-Ausgaben **normalisieren**, ungültige `skill_id` verwerfen.
|
||||
5. **Kein stiller DB-Write:** KI liefert **Vorschläge**; Persistenz nur über bestehende **PUT/POST exercises** inkl. Trainer-Aktion (und optional `summary_ai_generated` / `ai_suggested` wie Spec).
|
||||
6. **Mandant:** Übungsbezogene KI-Endpunkte nutzen `Depends(get_tenant_context)`; keine Ausnahme ohne Eintrag in `ACCESS_LAYER_ENDPOINT_AUDIT.md`.
|
||||
7. **Schema:** Neue DB-Objekte nur nummerierte Migration **`backend/migrations/`** (aktuell bis **068**) und `DB_SCHEMA_VERSION` anheben.
|
||||
|
||||
---
|
||||
|
||||
## 2. Stufen (Releases)
|
||||
|
||||
| Stufe | Inhalt | Exit-Kriterium |
|
||||
|-------|--------|------------------|
|
||||
| **S0** | Dieses Dokument + Verweise konsistent | Review abgehakt |
|
||||
| **S1** | Migration `ai_prompts` + Defaults `exercise_summary`, `exercise_skill_suggestions`; `exercises.summary_ai_generated` | Migrierte DB, App startet |
|
||||
| **S2** | `httpx`-Client OpenRouter; Modul lädt Prompt, ersetzt Platzhalter, parst Antwort | Unit-/Smoke: 503 ohne Key |
|
||||
| **S3** | `POST /api/exercises/ai/suggest`, `POST /api/exercises/{id}/ai/regenerate` | OpenAPI/Handtest mit Key |
|
||||
| **S4** | Frontend: KI-Vorschlag, **Änderungsdialog** (Vorschau, Kurzfassung wählbar, Fähigkeiten pro Zeile an-/abwählbar), dann Übernahme ins Formular | Manuelle UX-Prüfung |
|
||||
| **S4b** | **Skill-Retrieval:** Migration **`ai_skill_retrieval_profiles`**, `focus_areas_context` am **`POST …/ai/suggest`**, `exercise_ai` kontextbezogener Katalog (Gewichte, Caps, Keyword-Patches) | Migration 068 angelegt; Smoke mit Gewaltschutz / ohne Fokus |
|
||||
| **S5** | (später) Auto-Fallback beim Speichern laut `KI_FEATURES_SPEC` §7 | Feature-Flag / Config |
|
||||
| **S6** | (später) Zielausbau, Anleitung-only, Varianten, Admin-Masse laut Vision | Separate Epics |
|
||||
|
||||
**Aktueller Implementierungsstand:** **S4 + S4b** im Code (`exercise_ai` + Formular übermittelt `focus_areas_context`).
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementierungs-Checkliste (Technik)
|
||||
|
||||
- [ ] `OPENROUTER_API_KEY` / `OPENROUTER_MODEL` in `.env.example` dokumentiert (bereits teils vorhanden – prüfen).
|
||||
- [ ] Fehlerbilder: `400` zu wenig Inhalt, `503` KI nicht konfiguriert, `502` Upstream-Fehler mit kurzer Message.
|
||||
- [ ] Logging: **keine** vollständigen Prompts mit personenbezogenen Daten in Prod-Logs (optional DEBUG).
|
||||
- [ ] Optional: Rate-Limit KI-Endpunkte (`slowapi`) – nach Bedarf.
|
||||
- [ ] `MODULE_VERSIONS["exercises"]` / Changelog bei API-Erweiterung setzen.
|
||||
|
||||
---
|
||||
|
||||
## 4. Changelog dieses Plans
|
||||
|
||||
- **2026-05-22:** Initial; S1–S4 als erster Umsetzungspfad.
|
||||
- **2026-05-22:** S1–S4 im Code umgesetzt (Migration 067, `exercise_ai` + Router, Übungsformular); S5 weiter offen.
|
||||
- **2026-05-29:** **S4b:** Migration **068**, `ai_skill_retrieval_profiles`; suggest `focus_areas_context`; Frontend sendet gesetzte Fokusbereiche; Spec `working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Umsetzungsstand (Zwischencheckpoint)
|
||||
|
||||
**Erledigt (2026-05-22):** Migration **`067_ai_prompts_exercise_assistant`**, **`openrouter_chat`**, **`exercise_ai`**, **`POST /api/exercises/ai/suggest`** und **`POST /api/exercises/{id}/ai/regenerate`**, Formular-Schaltflächen (Kurzfassung / Fähigkeiten / kombiniert).
|
||||
|
||||
**Erledigt (2026-05-29):** Migration **`068`** / Profil **`ai_skill_retrieval_profiles`** (Standard + Profil Gewaltschutz wenn `focus_areas.name` vorhanden); **`exercise_ai`** — Score/Kategorie-Zapfen/Text-Overlap/Keyword-Zuschläge; **API:** `ExerciseAiSuggestBody.focus_areas_context`; **Regenerate** nutzt DB-Fokuszeilen.
|
||||
|
||||
**Nacharbeit S4 UX:** Übernahmedialog **`ExerciseFormPageRoot`**: keine sofortige Überschreibung; Kurzfassung mit Vergleich + Checkbox; Fähigkeiten mit Neu/Aktualisierung, Checkboxen, „Alle auswählen/abwählen“; **`Escape`** schließt; KI-Schaltflächen blockiert solange Dialog offen.
|
||||
|
||||
**Offen nächste Schritte Pflege/Umsetzung:** weitere Retrieval-Profile (z. B. Karate-/Fitness-Schwerpunkt) per SQL später Admin-UI; optionales Feld **`skills.ai_context`** Kurzbeschreibung für KI; automatische KI beim Speichern (**S5**); Prompt-/Profil-Admin-UI ohne SQL; Rate-Limits.
|
||||
|
||||
**Bewusst noch nicht (`summary_ai_generated`):** zurücksetzen bei manueller Kurzfassung im UI; Admin-Pflege `ai_skill_retrieval_profiles`.
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# Mehrstufige KI für Trainingsplanung – Architektur-Vorschau (Anti-Refactoring)
|
||||
|
||||
**Version:** 0.1
|
||||
**Datum:** 2026-05-22
|
||||
**Status:** Planungs-/Architektur-Arbeitspapier (keine Implementierungspflicht)
|
||||
**Ziel:** Für die **spätere** Planungs-KI bereits **Schnittstellen und Schichten** vorzeichnen, damit die **kleinere, starre** Übungs-KI nicht zur impliziten Vorlage für einen viel größeren Kopf wird — **ohne** jetzt eine Mitai-artige Workflow-Engine zu bauen.
|
||||
|
||||
**Bezüge:** `technical/AI_TRAINING_PLANNING_CONCEPT.md` · `functional/AI_EXERCISE_ASSISTANT_VISION.md` · `technical/SKILL_SCORING_SPEC.md` · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR-003) · Schwesterprojekt Mitai: `c:/dev/mitai-jinkendo` (Referenz: `prompt_executor`, `placeholder_resolver`, `workflow_*` — **nicht** Pflicht-Port).
|
||||
|
||||
---
|
||||
|
||||
## 1. Zwei getrennte Produktlinien (bewusst entkoppelt)
|
||||
|
||||
| Linie | Rolle | Orchestrator |
|
||||
|--------|--------|----------------|
|
||||
| **Übungs-KI** | wenige Eingaben → Kurzfassung / Skills; **starrer** Ablauf (1–2 Calls), kleines Kontextfenster | z. B. `exercise_ai.py` (heute) |
|
||||
| **Planungs-KI** | Gruppe, Zeit, Ziele, Historie, Katalogausschnitt, Phasen/Streams → **strukturierte Planelemente** | **eigenes** Modul + **mehrstufig** (siehe §3) |
|
||||
|
||||
**Regel:** Shared Library nur auf **niedriger Ebene** (`openrouter_chat`-Art: HTTP, Timeouts, Modellname, Fehler-Mapping) und **gemeinsame Prompt-Tabelle** `ai_prompts`. **Keine** Vermischung der Geschäftslogik „Übung erstellen“ mit „Einheit füllen“, um später keine Abhängigkeiten reißen zu müssen.
|
||||
|
||||
---
|
||||
|
||||
## 2. Konzeptioneller „Planungs-Graph“ (Daten, nicht zwingend Graph-DB)
|
||||
|
||||
Für die Planungs-KI ist ein **Graph als Denkmodell** hilfreich — technisch reicht meist **PostgreSQL + bestehende FKs** (+ optional `exercise_progression_graphs`):
|
||||
|
||||
**Knoten-Typen (Auszug):** `training_groups`, `training_units`, `training_unit_sections` / Items, `exercises`, `skills`, `training_framework_programs` / Slots / Goals, ggf. Nachbearbeitungs-/Debrief-Metadaten.
|
||||
|
||||
**Kanten-Typen (Auszug):**
|
||||
|
||||
- **Zeitliche Folge:** Einheiten einer Gruppe nach `planned_date` / Reihenfolge
|
||||
- **Inhalt:** Section-Item → `exercise_id` (± Variante)
|
||||
- **Ziele:** Slot-/Framework-Ziele, Kopf-Notizen, Trainer-Zieltexte
|
||||
- **Progression:** Kanten aus `exercise_progression_graphs` (optional erweitern um „empfohlene Folge im Gruppenkontext“, bleibt Spekulationsfeld)
|
||||
- **Skills:** bereits über `exercise_skills`; aggregiert über `skill_scoring`-Pfad
|
||||
|
||||
**Wichtig:** Für KI **nicht** einen Riesen-Graphen serialisieren, sondern **Projektionen** („letzte *N* Einheiten“, „Nachbarn im Progressionsgraph zu zuletzt verwendeten Übungen“, „Skill-Gap Heuristik“).
|
||||
|
||||
---
|
||||
|
||||
## 3. Mehrstufiger Prozess (Pflichtidee für Planungs-KI)
|
||||
|
||||
Statt einem Prompt „mach den ganzen Plan“ mehrere **Schritte mit kleinen, validierbaren Outputs**:
|
||||
|
||||
| Stufe | Beispiel-Aufgabe | Deterministisch möglich? | Typischer LLM-Einsatz |
|
||||
|-------|-------------------|--------------------------|------------------------|
|
||||
| **S0** | Governance + Filter + Historie + Slot-Ziele zusammenstellen | Ja (SQL/API) | Nein |
|
||||
| **S1** | Kandidaten-Übungen auf Top‑K schrumpfen (Skills, Volltext, Score, Wiederholungsstrafe) | Teilweise | Optional Ranking |
|
||||
| **S2** | Reihenfolge je Section / Phase unter Constraints (Aufwärmen, Graphen-Nachbarn) | Teilweise | Ja (auf kleiner Liste) |
|
||||
| **S3** | Zeiten auf Section/Item vorschlagen oder Plausibilisieren | Teilweise | Ja |
|
||||
| **S4** | Trainer-sprachliche Kurzbegründung / Alternativen | Nein | Ja |
|
||||
|
||||
**Zwischen jeder Stufe:** starkes **Schema / Validierung** (z. B. nur erlaubte `exercise_id`s, nur erlaubte Slot-Struktur zu Phasen/Streams). So bleibt das System auch bei Modell-Fehlern stabil.
|
||||
|
||||
---
|
||||
|
||||
## 4. Schnittstellen-Vorsorge im Code (ohne Big-Bang)
|
||||
|
||||
Minimal-Ausbaustufe später, die Refactoring vermeidet:
|
||||
|
||||
1. **`PlanningContextPack` (internes DTO)** — reines Python-`dict`/`dataclass` oder Pydantic: aggregierte, **tokenbewusst gekürzte** Ansicht (Gruppe, nächste Einheit-Ziele, Historie-IDs, Top‑K-Kandidaten, Constraints).
|
||||
2. **`planning_ai_steps` als rein **funktionale** Pipeline** — jede Stufe `(context) → context` oder `(context) → partial_suggestion`; keine globale „Prompt-String-Bastelei“ überall im Router.
|
||||
3. **Prompt-Slugs pro Stufe** in `ai_prompts` (analog Übung), z. B. `planning_rank_section_items`, `planning_explain_sequence`, mit **eigenem** Platzhalter-Katalog (nicht `{{skills_catalog}}` aus Übungen recyclen).
|
||||
4. **Router** `training_planning.py` (oder neuer `planning_ai.py`): nur **dünne** HTTP-Schicht, ruft Orchestrator.
|
||||
|
||||
Optional **später**, wenn nötig: zweite Tabelle `ai_prompt_chains` oder externe Workflow-Definition — **erst** wenn 3–4 feste Stufen nicht mehr reichen. Mitai-Workflow-Engine dann **bewusste** Option, kein Default.
|
||||
|
||||
---
|
||||
|
||||
## 5. Kontextfenster und „Kaskade“
|
||||
|
||||
**Kerngedanke:** Je Stufe nur **neue** Information hinzufügen, die vorherige Stufen **ersetzen** oder **verdichten**, nicht duplizieren.
|
||||
|
||||
Beispiel:
|
||||
|
||||
- Stufe A (LLM oder Heuristik): „Priorisierte Skill-Ziele für diese Session“ (kurz)
|
||||
- Stufe B: Top‑40 Übungen mit **einer** Zeile pro Übung
|
||||
- Stufe C: Reihenfolge für 8 IDs + 2-Satz-Begründung
|
||||
|
||||
So bleibt dieselbe fachliche Tiefe erreichbar ohne Kontext-Explosion.
|
||||
|
||||
---
|
||||
|
||||
## 6. Schnittstellen zu bereits vorhandenen Bausteinen
|
||||
|
||||
- **`skill_profiles` / `skill-discovery`:** liefern **deterministische** Ziel-/Profil-Signale für S0/S1 (`SKILL_SCORING_SPEC.md`).
|
||||
- **`training_planning_prefs`:** weiche Constraints (Tone, Dauer, Split-Vorlieben).
|
||||
- **`exercise_progression_graphs`:** lokale Nachbarschaft um „zuletzt verwendet“.
|
||||
- **Mitai-Referenz:** Platzhalter-Katalog + Preview-API als **Inspiration** für Admin-UX; Workflow-Graph nur wenn Shinkan **wirklich** viele verzweigte Pipelines braucht.
|
||||
|
||||
---
|
||||
|
||||
## 7. Was wir **nicht** jetzt tun müssen
|
||||
|
||||
- Keine zweite Graph-Datenbank nur für KI.
|
||||
- Keine Workflow-UI-Kopie aus Mitai.
|
||||
- Keine Vereinheitlichung der Übungs-KI mit Planungs-KI über einen „Mega-Orchestrator“.
|
||||
|
||||
---
|
||||
|
||||
## 8. Kurz-Checkliste „Refactoring vermeiden“ vor erster Planungs-KI-Zeile Code
|
||||
|
||||
- [ ] Eigenes Modulbaum-„Root“ für Planung (nicht `exercise_ai` erweitern).
|
||||
- [ ] Prompt-Slugs mit **Planungs-**Präfix und **eigenem** Platzhalter-Set dokumentieren.
|
||||
- [ ] Outputs pro Stufe **JSON-Schema** oder Pydantic validieren.
|
||||
- [ ] Kandidatenlisten **immer** serverseitig auf erlaubte IDs begrenzen.
|
||||
|
||||
---
|
||||
|
||||
## 9. Changelog
|
||||
|
||||
- **2026-05-22:** Erstfassung als Vorschau-Dokument für mehrstufige Planungs-KI.
|
||||
@@ -0,0 +1,121 @@
|
||||
# KI Skill-Retrieval-Profile (`ai_skill_retrieval_profiles`)
|
||||
|
||||
**Version:** 0.1
|
||||
**Datum:** 2026-05-29
|
||||
**Status:** Umsetzung gestartet (Migration **068**)
|
||||
**Ziel:** Für `POST /api/exercises/ai/suggest` (Skill-Katalogauszug) **Gewichte und Quoten** steuerbar machen:
|
||||
|
||||
- gebunden an **Übungs-Fokusbereich** (`focus_areas.id`),
|
||||
- ein **Standardprofil** ohne Fokus,
|
||||
- **optional zusammengeführte** Profile bei mehreren Fokusbereichen,
|
||||
- **optional Keyword-Übersteuerungen** aus Ziel/Durchführung (z. B. Rollenspiel vs. Befreiung).
|
||||
|
||||
**Technische Basis:** Skills mit `skills.main_category_id` → `skill_main_categories.slug` (`karate` | `allgemeine`) und `skills.category_id` → `skill_categories.slug` (`kondition`, `selbstverteidigung`, …).
|
||||
|
||||
**Bezüge:** `.claude/docs/working/AI_EXERCISE_IMPLEMENTATION_PLAN.md` · `backend/exercise_ai.py`
|
||||
|
||||
---
|
||||
|
||||
## 1. Datenmodell
|
||||
|
||||
### Tabelle `ai_skill_retrieval_profiles`
|
||||
|
||||
| Spalte | Typ | Beschreibung |
|
||||
|--------|-----|--------------|
|
||||
| `id` | serial | Primärschlüssel |
|
||||
| `focus_area_id` | int NULL FK → `focus_areas(id)` ON DELETE SET NULL | **`NULL`** nur für Standardeintrag möglich (siehe `is_default`) |
|
||||
| `is_default` | boolean | Genau **eine** Zeile mit `true` |
|
||||
| `name` | varchar | Kurzer Name (Admin später) |
|
||||
| `description` | text | Hinweise für Pflege |
|
||||
| `active` | boolean | Nur aktive werden geladen |
|
||||
| `config` | jsonb | Siehe §2 |
|
||||
|
||||
**Constraints / Indizes**
|
||||
|
||||
- Eindeutig: `(focus_area_id)` WHERE `focus_area_id IS NOT NULL`
|
||||
- Eindeutig: `(is_default)` WHERE `is_default = true`
|
||||
|
||||
---
|
||||
|
||||
## 2. JSON-Konfiguration `config.version = 1`
|
||||
|
||||
Alle Schlüssel **optional**; fehlende Werte fallen auf **einprogrammierten Fallback** in `exercise_ai.py` zurück (entspricht bisher grob „neutral“).
|
||||
|
||||
### 2.1 Gewichtungen (Ranking)
|
||||
|
||||
| Schlüssel | Typ | Bedeutung |
|
||||
|-----------|-----|------------|
|
||||
| `main_slug_weights` | `object[str, float]` | Multiplikator pro Hauptkategorie-Slug (`karate`, `allgemeine`) |
|
||||
| `category_slug_weights` | `object[str, float]` | Multiplikator pro `skill_categories.slug` |
|
||||
|
||||
Basis-Score (vereinfacht):
|
||||
`(importance oder 3) × main_w × cat_w × text_overlap_bonus × importance_multiplier`
|
||||
|
||||
### 2.2 Kapazitätsbegrenzung (Liste)
|
||||
|
||||
`_MAX_SKILLS_CATALOG_LINES` (aktuell **240**) Zeilen Gesamt:
|
||||
|
||||
| Schlüssel | Typ | Bedeutung |
|
||||
|-----------|-----|------------|
|
||||
| `category_max_share` | `object[str, float]` | Max. Anteil dieser **Unterkategorie** am Endergebnis (0–1), z. B. `{ "kondition": 0.25 }` |
|
||||
| `main_min_share` | `object[str, float]` | Mindest-Zielanteil Hauptkategorie beim **Auswahl-Greedy** (weich; Rest nach Score aufgefüllt) |
|
||||
|
||||
### 2.3 Text / Token-Sparen
|
||||
|
||||
| Schlüssel | Typ | Standard | Bedeutung |
|
||||
|-----------|-----|----------|------------|
|
||||
| `description_plain_max_len` | int | 160 | Gekürzte Beschreibung pro Zeile |
|
||||
| `karate_relevance_max_len` | int | **0** oder 80 | **`0`** = Feld `karate_relevance`/`relevance_level` in der Promptzeile **weglassen** |
|
||||
|
||||
### 2.4 Keyword-Overrides (optional)
|
||||
|
||||
Liste `keyword_overrides`: jedes Element:
|
||||
|
||||
```json
|
||||
{
|
||||
"keywords_any": ["befreiung", "haltegriff"],
|
||||
"case_insensitive": true,
|
||||
"patch": {
|
||||
"category_slug_weights": { "selbstverteidigung": 2.5 },
|
||||
"category_max_share": { "koordination": 0.1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Textsuche in verkettetem Korpus **Titel, Ziel, Durchführung, Focus-Hint** (bereits plaintext). Reihenfolge: erst Basis-Profile zusammenmergen, dann **alle treffenden Overrides**‑`patch`‑Objekte **flach zusammenführen** (Gewichte multiplikativ übereinander, Caps den strengsten Wert nehmen – aktuelle Implementierung im Code dokumentiert).
|
||||
|
||||
---
|
||||
|
||||
## 3. Mehrere Fokusbereiche auf der Übung
|
||||
|
||||
Request-Body: `focus_areas_context: [{ "focus_area_id": n, "is_primary": bool }, …]`
|
||||
|
||||
**Aktuelle Merge-Strategie (v1):** Profile laden → **gleichgewichtete Mittelwert-Bildung** der numerischen Gewichte / Caps (implementiert für `main_slug_weights`, `category_slug_weights`, `category_max_share`, `main_min_share`, `*_max_len`). Anschließend **Keyword-Overrides** anwenden.
|
||||
|
||||
**Primär-Fokus:** Im Frontend soll die **primäre** Zeile aus `focus_areas_multi` **zuerst** in der Liste stehen; die Merge-Strategie kann später zu „Primär dominate“ erweitert werden.
|
||||
|
||||
Ohne Kontext oder ohne Treffer auf aktive Profile: **nur Standardprofil** (`is_default`).
|
||||
|
||||
---
|
||||
|
||||
## 4. Seed-Daten (Migration)
|
||||
|
||||
- **`is_default=true`:** ausgewogene Standard-Gewichte, moderate Caps auf `kondition`/`koordination`, Karate-Relevanz gekürzt.
|
||||
- **`Gewaltschutz`:** `focus_area_id` per `(SELECT id FROM focus_areas WHERE name = 'Gewaltschutz' LIMIT 1)` — höhere Gewichte für `kognition`, `psychische_faehigkeiten`, `soziale_faehigkeiten`, `selbstverteidigung`; gedrosseltes `kondition`/`koordination`; `karate_relevance_max_len`: 0; Keyword-Patches wie oben können nachgeschärft werden.
|
||||
|
||||
Weitere Profile (Karate-Schwerpunkt etc.) später per Admin-SQL oder UI.
|
||||
|
||||
---
|
||||
|
||||
## 5. API
|
||||
|
||||
`ExerciseAiSuggestBody` erweitert um **`focus_areas_context`** (Liste). Feld **`focus_area_hint`** bleibt für den **Prompt-Kontext** (bestehende Prompts).
|
||||
|
||||
`POST …/ai/regenerate` nutzt gespeicherte `exercise_focus_areas` zur gleichen Retrieval-Logik wie Suggest.
|
||||
|
||||
**Pflege der Profile:** Superadmin ohne Mandantenwahl — **`GET|POST /api/admin/ai-skill-retrieval-profiles`**, **`GET|PUT|DELETE /api/admin/ai-skill-retrieval-profiles/{id}`** (`routers/ai_skill_retrieval_admin.py`); Web-UI Superadmin unter **`/admin/ai-skill-retrieval`**.
|
||||
|
||||
## 6. Changelog
|
||||
|
||||
- **2026-05-29:** Superadmin-Pflege-Endpoints + UI‑Route dokumentiert (`/admin/ai-skill-retrieval`).
|
||||
- **2026-05-29:** Erstellt; gekoppelt an Migration **068** und erste `exercise_ai`-Integration.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Superadmin: Übungs-Anreicherung per KI
|
||||
|
||||
Stand: 2026-05-23 · App 0.8.178
|
||||
|
||||
## Zweck
|
||||
|
||||
Plattform-weites Werkzeug für Superadmins, um Übungen (typisch `draft`, ohne Skills) **batchweise** per KI mit Fähigkeiten anzureichern und kontrolliert auf `in_review` zu setzen.
|
||||
|
||||
Verbessert indirekt die Planungs-KI (`POST /api/planning/exercise-suggest`), die gegen Skill-Profile rankt — unvollständige `exercise_skills` führen dort zu Volltext-dominiertem Ranking.
|
||||
|
||||
## UI
|
||||
|
||||
- Route: `/admin/exercise-enrichment` (nur Superadmin)
|
||||
- Admin-Menü: „Übungs-Anreicherung“
|
||||
|
||||
## API
|
||||
|
||||
Prefix: `/api/admin/exercise-enrichment`
|
||||
|
||||
| Methode | Pfad | Beschreibung |
|
||||
|---------|------|--------------|
|
||||
| GET | `/candidates` | Paginierte Kandidaten (Filter: status, visibility, focus_area, without_skills, with_ai_suggested_skills, include_club, search) |
|
||||
| POST | `/preview` | Dry-Run — `{ exercise_ids[], modes: { skills, summary }, merge_mode }` |
|
||||
| POST | `/apply` | `{ items: [{ exercise_id, merged_skills }], merge_mode, set_status }` |
|
||||
|
||||
Auth: `require_auth` + `is_superadmin` — **kein** `TenantContext` (EXEMPT, siehe ACCESS_LAYER_ENDPOINT_AUDIT.md).
|
||||
|
||||
## KI
|
||||
|
||||
Wiederverwendet `run_exercise_form_ai_suggestion` → Prompts `exercise_skill_suggestions` (MVP Pflicht), optional `exercise_summary`. Skill-Katalog via `build_contextual_skills_catalog_block` / `ai_skill_retrieval_profiles`.
|
||||
|
||||
## Merge-Modi (Skills)
|
||||
|
||||
- `additive` (Default): manuelle Skills bleiben; KI ergänzt neue; bestehende `ai_suggested`-Links werden aktualisiert
|
||||
- `replace_ai_only`: nur `ai_suggested=true` entfernen, dann KI-Set anwenden
|
||||
- `replace_all`: alle Skills ersetzen (explizit)
|
||||
|
||||
## Defaults
|
||||
|
||||
- Kandidaten: **Status** primär (Default `draft`); Sichtbarkeit Default **`private`**, wählbar bis „Alle“
|
||||
- Skill-Merge Default: **`replace_all`** (alle Skills KI-neu, `ai_suggested=true` — unterscheidbar von manuell)
|
||||
- Nach Apply: `set_status=in_review` (nie automatisch `approved`)
|
||||
- Batch: keine Gesamtgrenze (bis 10.000 IDs); **Analyze** + explizite Nutzerbestätigung
|
||||
- **Preview:** max. **3 Übungen/HTTP-Request** (parallel LLM), Frontend chunked — vermeidet Gateway-504 (~60s Fritz!Box)
|
||||
- **Apply:** HTTP-Chunks à 25 (nur DB, kein LLM)
|
||||
|
||||
## Inhalte (modular)
|
||||
|
||||
| Modus | Prompt | Apply-Felder |
|
||||
|-------|--------|--------------|
|
||||
| Skills | `exercise_skill_suggestions` | `exercise_skills` inkl. Intensität, required/target_level, `ai_suggested` |
|
||||
| Summary | `exercise_summary` | `summary`, `summary_ai_generated=true` |
|
||||
| Anleitung | `exercise_instruction_rewrite` | `goal`, `execution`, `preparation`, `trainer_notes` |
|
||||
|
||||
## API (ergänzt)
|
||||
|
||||
| Methode | Pfad | Beschreibung |
|
||||
|---------|------|--------------|
|
||||
| GET | `/candidate-ids` | Alle IDs zum Filter (Select-all) |
|
||||
| POST | `/analyze` | `{ exercise_ids[], modes }` → Kosten-Schätzung vor Start |
|
||||
|
||||
## Keine Migration
|
||||
|
||||
Bestehende Spalte `exercise_skills.ai_suggested` reicht; kein Enrichment-Log in MVP.
|
||||
|
||||
## Tests
|
||||
|
||||
`backend/tests/test_exercise_enrichment_admin.py` — 403, Merge-Logik, Status draft→in_review.
|
||||
@@ -0,0 +1,432 @@
|
||||
# Planungs-KI: Übungssuche & Kontext für Neu-Anlage
|
||||
|
||||
**Version:** 0.2
|
||||
**Datum:** 2026-05-23
|
||||
**Status:** P0–P2 ✅ · Phase A/B/B2 ✅ · **Phase C1 ✅** (Graph auto-match + variantenbewusste Nachfolger) · C2–C3 geplant
|
||||
**Bezüge:** `AI_PLANNING_KI_MULTISTAGE_FORECAST.md` · `AI_PROMPT_TARGET_ARCHITECTURE.md` · `SKILL_SCORING_SPEC.md` · `TRAINING_FRAMEWORK_SPEC.md` §3 (Progressionsgraph)
|
||||
|
||||
---
|
||||
|
||||
## 1. Ziel
|
||||
|
||||
Trainer in der **Trainingsplanung** sollen Übungen finden oder anlegen können mit natürlichen Anfragen wie:
|
||||
|
||||
- „Vertiefung zu Übung XY“
|
||||
- „Nächste sinnvolle Übung im Progressionsgraph Z“
|
||||
- „Baut auf der bisherigen Planung auf — Reaktionsschnelligkeit mit Partnern“
|
||||
- **Preset:** „Schlage mir die nächste Übung vor“
|
||||
|
||||
**Suche** (Bibliothek) und **Neu mit KI-Assistent** (Anlage) nutzen dasselbe **`PlanningExerciseContextPack`** — unterschiedliches Ergebnis (Treffer vs. Entwurf).
|
||||
|
||||
---
|
||||
|
||||
## 2. Architektur (Mehrstufig)
|
||||
|
||||
| Stufe | Name | Technik | P0 |
|
||||
|-------|------|---------|-----|
|
||||
| **S0** | Kontext-Pack | SQL/API, deterministisch | ✅ |
|
||||
| **S1a** | Intent strukturieren | LLM `planning_exercise_search_intent` (Szenario-Pipeline) | ✅ P1 |
|
||||
| **S1b** | Hybrid-Retrieval | Score: Volltext + Graph + Skills + Plan + **Profil** | ✅ |
|
||||
| **S1b+** | Profil-Vorselektion | `ExerciseMatchProfile` × `PlanningTargetProfile` | ✅ `profile_v1` |
|
||||
| **S1c** | Rerank + Begründung | Optional LLM `planning_exercise_search_rank` | Regelbasierte `reasons[]` |
|
||||
| **S2** | Neu-Anlage | Bestehende `suggestExerciseAi` + Pack als Zusatzkontext | Später |
|
||||
|
||||
Zwischen jeder Stufe: **nur erlaubte `exercise_id`s** (Governance / Sichtbarkeit).
|
||||
|
||||
---
|
||||
|
||||
## 3. Intent-Typen
|
||||
|
||||
| `intent_hint` | Bedeutung | Retrieval-Gewichtung (P0) |
|
||||
|---------------|-----------|---------------------------|
|
||||
| `suggest_next` | Nächste Übung (Default bei leerer/kurzer Query) | Progression + Skill-Overlap + Plan-Kontinuität |
|
||||
| `progression_next` | Explizit Graph-Folge | Progression hoch |
|
||||
| `deepen_exercise` | Vertiefung zu Anker-Übung | Skill-Overlap hoch, ähnlicher Fokus |
|
||||
| `continue_plan_goal` | Auf bisherigen Plan aufbauen | Plan-Kontinuität, Wiederholungsstrafe |
|
||||
| `free_search` | Freitext / Stichwort | Volltext hoch |
|
||||
|
||||
**S1a (später):** Freitext → JSON `{ intent, skill_hints[], requires_partner, level_hint, … }` validiert per Pydantic.
|
||||
|
||||
**P0:** `intent_hint` vom Client oder Keyword-Heuristik auf `query`.
|
||||
|
||||
---
|
||||
|
||||
## 4. PlanningExerciseContextPack (S0)
|
||||
|
||||
Serverseitig aus Request + DB (tokenbewusst für spätere LLM-Stufen):
|
||||
|
||||
| Feld | Quelle | UI-Chip |
|
||||
|------|--------|---------|
|
||||
| `unit_id`, Titel, `group_id`, Gruppenname | `training_units` + `training_groups` | Gruppe · Einheit |
|
||||
| `section_order_index`, Abschnittstitel | `training_unit_sections` | Abschnitt |
|
||||
| `planned_exercise_ids[]` | Items der Einheit (Reihenfolge) | „N Übungen im Plan“ |
|
||||
| `anchor_exercise_id`, Titel | Request oder letzte Übung vor Einfügepunkt | Anker |
|
||||
| `anchor_skill_ids[]` | `exercise_skills` | (intern) |
|
||||
| `progression_graph_id` | Request oder **Auto-Match** vom Anker (sichtbarer Graph mit passenden Ausgangskanten) | Graph |
|
||||
| `progression_graph_name`, `progression_graph_auto_resolved` | Response `context_summary` | Graph (auto) |
|
||||
| `anchor_exercise_variant_id` | Request / Abschnitt-Item / DB | (intern) |
|
||||
| `progression_successor_ids[]` | `exercise_progression_edges` ab Anker (variantenbewusst, Migration **034**) | (intern) |
|
||||
| `progression_successor_variants` | `to_exercise_variant_id` pro Nachfolger | (intern) |
|
||||
| `group_recent_exercise_ids[]` | Letzte Einheiten derselben Gruppe | Wiederholungsstrafe |
|
||||
| `framework_slot_notes` | Rahmen-Slot falls `framework_slot_id` | (später) |
|
||||
|
||||
**Berechtigung:** `get_tenant_context` + `_assert_training_unit_permission` wie `GET /training-units/{id}`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Hybrid-Retrieval (S1b, P0)
|
||||
|
||||
Kandidaten: sichtbare Übungen (`library_content_visibility_sql`), ohne `archived`, max. ~400 (recent).
|
||||
|
||||
**Score** (0–1, gewichtet nach Intent):
|
||||
|
||||
```
|
||||
score = w_ft * fulltext_rank
|
||||
+ w_prog * progression_hit
|
||||
+ w_skill * skill_jaccard(anchor, candidate)
|
||||
+ w_plan * plan_affinity
|
||||
+ w_profile * profile_match(exercise, target)
|
||||
+ w_repeat * (candidate in unit_plan ? -1 : 0)
|
||||
+ w_group_repeat * (candidate in group_recent ? -0.5 : 0)
|
||||
```
|
||||
|
||||
**`profile_match`** (0–1): siehe §12–§13 — Katalog-Dimensionen + Skill-Gewichte + Skill-Gap.
|
||||
|
||||
**`reasons[]`** (regelbasiert, Deutsch): z. B. „Nachfolger im Progressionsgraph“, „Fähigkeiten passen zur Anker-Übung“, „Fokusbereich passend zum Planungsziel“, „Deckt Skill-Lücke im bisherigen Plan“, „Volltext-Treffer“.
|
||||
|
||||
---
|
||||
|
||||
## 6. API
|
||||
|
||||
### `POST /api/planning/exercise-suggest`
|
||||
|
||||
**Body:**
|
||||
|
||||
```json
|
||||
{
|
||||
"unit_id": 123,
|
||||
"section_order_index": 0,
|
||||
"phase_order_index": null,
|
||||
"parallel_stream_order_index": null,
|
||||
"anchor_exercise_id": 456,
|
||||
"anchor_exercise_variant_id": 12,
|
||||
"progression_graph_id": 7,
|
||||
"query": "Schlage mir die nächste Übung vor",
|
||||
"intent_hint": "suggest_next",
|
||||
"limit": 20,
|
||||
"exercise_kind_any": ["simple"]
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"context_summary": {
|
||||
"unit_title": "…",
|
||||
"group_name": "…",
|
||||
"section_title": "Hauptteil",
|
||||
"planned_count": 4,
|
||||
"anchor_title": "Partner-Fangspiel"
|
||||
},
|
||||
"target_profile_summary": {
|
||||
"sources": ["framework_catalog", "current_unit_plan", "anchor_exercise"],
|
||||
"focus_areas": ["Reaktion & Abwehr"],
|
||||
"top_skills": [{ "skill_id": 12, "name": "Reaktionsgeschwindigkeit", "weight": 1.0 }],
|
||||
"has_skill_gap": true
|
||||
},
|
||||
"retrieval_phase": "profile_v1",
|
||||
"intent_resolved": "suggest_next",
|
||||
"hits": [
|
||||
{
|
||||
"id": 99,
|
||||
"title": "…",
|
||||
"summary": "…",
|
||||
"score": 0.78,
|
||||
"reasons": ["Nachfolger im Progressionsgraph", "Fokusbereich passend zum Planungsziel"],
|
||||
"focus_area": "…"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Modul:** `backend/planning_exercise_suggest.py` · `backend/planning_exercise_profiles.py` · Router `backend/routers/planning_exercise_suggest.py`
|
||||
|
||||
---
|
||||
|
||||
## 7. Frontend
|
||||
|
||||
| Ort | Verhalten |
|
||||
|-----|-----------|
|
||||
| `ExercisePickerModal` | Prop `planningContext` → Planungs-API statt reiner `listExercises`; Kontext-Chips; `reasons` unter Treffer |
|
||||
| `TrainingUnitEditPage` | `planningContext` aus Einheit + Picker-Ziel (Anker = letzte Übung im Abschnitt) |
|
||||
| **`ExercisesListPageRoot`** | Schalter **„Neu mit KI-Assistent“**: Planungs-KI-Suche (frei, ohne `unit_id`) + Neuanlage im Modal; **„+ Neu“** ausgeblendet |
|
||||
| Rahmen / Kombi-Formular | analog, sobald `unit_id` / Slot-Blueprint bekannt |
|
||||
| Übungsliste (ohne KI-Schalter) | weiter Volltext |
|
||||
|
||||
**Zweites Suchfeld** im Picker: Query = Volltext + ergänzender Begriff (ODER in P0 als Konkatenation an Backend).
|
||||
|
||||
---
|
||||
|
||||
## 8. Neu-Anlage (Anbindung, Phase P1)
|
||||
|
||||
Wenn `hits` leer oder Trainer wählt „Mit KI anlegen“:
|
||||
|
||||
- Gleiches `context_summary` an `suggestExerciseAi` anhängen (Felder `planning_context_json` o. ä. — noch offen)
|
||||
- Kurzbeschreibung optional leer (freier Vorschlag) oder aus Intent/Skizze
|
||||
|
||||
---
|
||||
|
||||
## 9. Phasen-Roadmap
|
||||
|
||||
| Phase | Inhalt | Status |
|
||||
|-------|--------|--------|
|
||||
| **P0** | Context-Pack, Hybrid-Score, API, Picker in Planung | ✅ |
|
||||
| **P0.1** | `ExerciseMatchProfile` / `PlanningTargetProfile`, `profile_v1` | ✅ |
|
||||
| **P1** | Szenario-Pipeline + LLM Query-Intent → Erwartungsprofil | ✅ |
|
||||
| **P2 / B2** | LLM-Rerank bei engem Top-Feld (max. 2 Calls) | ✅ |
|
||||
| **P3** | Skill-Discovery / Framework-Ziele im Pack | 🔲 |
|
||||
| **A** | Voll-Library Hybrid-Ranking | ✅ **0.8.177** |
|
||||
| **B** | Text-Signale guidance/Rahmen-Ziele | ✅ **0.8.181** |
|
||||
| **C1** | Graph auto-match + variantenbewusste Nachfolger | ✅ **0.8.183** |
|
||||
| **C2** | Varianten in Trefferliste / Picker | ✅ **0.8.184** |
|
||||
| **C3** | Graph-Builder (Ziel → Pfad → speichern) | 🔲 |
|
||||
| **D** | Neu-Anlage: Pack an `suggestExerciseAi` | 🔲 |
|
||||
|
||||
---
|
||||
|
||||
## 10. Changelog
|
||||
|
||||
- **2026-05-23:** Phase C1 — Graph auto-match, variantenbewusste Nachfolger (`planning_exercise_progression.py`).
|
||||
- **2026-05-23:** Phase B2 — Rerank bei engem Top-Feld; Phase B — Text-Signale; Phase A — Voll-Library (siehe §17–§19).
|
||||
- **2026-05-22:** Erstfassung; P0 API + Planungs-Picker.
|
||||
- **2026-05-22:** P0 implementiert (`planning_exercise_suggest.py`, Router, Picker); unsaved Formular-Plan noch nicht an API (nur persistierte Einheit).
|
||||
- **2026-05-22:** P0.1 — `planning_exercise_profiles.py`, Profil-Score in Hybrid-Retrieval, `retrieval_phase: profile_v1`, `target_profile_summary`.
|
||||
- **2026-05-22:** P2 — LLM-Rerank optional (`include_llm_rank`); Client `planned_exercise_ids[]`; Prompt Migration 072.
|
||||
|
||||
---
|
||||
|
||||
## 11. Bekannte Lücken & Backlog
|
||||
|
||||
- **Ungespeicherte Plan-Änderungen:** ✅ Client übergibt `planned_exercise_ids[]` aus Formular (TrainingUnitEditPage).
|
||||
- **Progressionsgraph-ID:** ✅ Auto-Match vom Anker (**C1**); manuelle Auswahl in UI noch offen.
|
||||
- **Anker-Variante:** ✅ Client + DB (**C1**); Picker wählt Variante bei Treffer (**C2** — Dropdown + Graph-Vorschlag).
|
||||
- **Graph-Builder:** Ziel eingeben → aufbauende Übungen → in Graph speichern (**C3**) — Compound-Nutzen über viele Pläne.
|
||||
- **Varianten-Suche:** Library-Picker nutzt `include_variants`; Planungs-KI rankt primär **Übungsebene** — Varianten-Expansion nur gezielt (**C2**).
|
||||
- **Enrichment:** Superadmin-Tool für Skills; Datenqualität der Bibliothek entscheidend für Profil-Score.
|
||||
- **LLM-Intent:** ✅ P1 Szenario-Pipeline + `planning_exercise_search_intent` (Migration 073).
|
||||
- **Preset + LLM:** ✅ Erwartungs-LLM (074) bei Planungsbezug; Preset ohne Plan = kein Erwartungs-LLM.
|
||||
|
||||
---
|
||||
|
||||
## 16. Szenario-Pipeline & Query-Erwartungsprofil (P1)
|
||||
|
||||
Komplexe Planungsanfragen brauchen **Schritte vor** dem Profil-Match — nicht jede Query ist gleich.
|
||||
|
||||
### 16.1 Szenario-Klassen
|
||||
|
||||
| `scenario_kind` | Typische Anfrage | LLM Intent? |
|
||||
|-----------------|------------------|-------------|
|
||||
| `preset_next` | „Nächste Übung vorschlagen“ (Preset) | Erwartungs-LLM (074) wenn Planungsbezug |
|
||||
| `progression` | Progressionsgraph / Pfad | Ja (wenn Freitext) |
|
||||
| `deepen` | Vertiefung Anker | Ja |
|
||||
| `continue_plan` | Auf bisherigen Plan aufbauen | Ja |
|
||||
| `additive_constraint` | Plan **+** Zusatz (z. B. Schnellkraft) | Ja |
|
||||
| `free_search` | Offene Stichwortsuche | Ja |
|
||||
|
||||
**Routing:** `planning_exercise_target_pipeline.classify_planning_scenario()` → `should_run_llm_intent_pipeline()`.
|
||||
|
||||
### 16.2 Pipeline (Reihenfolge)
|
||||
|
||||
```
|
||||
S0 Kontext-Pack
|
||||
→ Heuristik-Intent + Szenario
|
||||
→ [optional] LLM planning_exercise_search_intent
|
||||
→ Basis PlanningTargetProfile (Rahmen, Plan, Anker, Gap)
|
||||
→ Merge Query-Overlay (Katalog-IDs aus Hints)
|
||||
→ Hybrid-Retrieval + Profil-Score
|
||||
→ [optional] LLM-Rerank
|
||||
```
|
||||
|
||||
Module: `planning_exercise_target_pipeline.py` · `planning_exercise_intent.py`
|
||||
|
||||
### 16.3 API (Erweiterung)
|
||||
|
||||
| Request | Default | Bedeutung |
|
||||
|---------|---------|-----------|
|
||||
| `include_llm_intent` | `true` | LLM nur wenn Szenario ≠ preset_next und Query nicht leer |
|
||||
|
||||
| Response | Bedeutung |
|
||||
|----------|-----------|
|
||||
| `scenario_kind` | Szenario-Klasse |
|
||||
| `query_intent_summary` | intent, llm_applied, rationale, skill_hints_resolved |
|
||||
| `intent_heuristic` | Heuristik vor LLM |
|
||||
| `retrieval_phase` | z. B. `profile_v1+query_intent+llm_rank` |
|
||||
|
||||
**Prompt 073:** `planning_exercise_search_intent` — Ausgabe JSON mit `skill_hints`, `focus_hints`, `emphasis` (`additive`|`replace`).
|
||||
|
||||
---
|
||||
|
||||
## 15. LLM-Rerank (P2)
|
||||
|
||||
**Request:**
|
||||
|
||||
| Feld | Typ | Default | Bedeutung |
|
||||
|------|-----|---------|-----------|
|
||||
| `planned_exercise_ids` | `int[]` | — | Optional: Reihenfolge aus Formular (überschreibt DB-Plan) |
|
||||
| `include_llm_rank` | `bool` | `true` (Client) | Backend gated (B2): Rerank nur bei engem Top-Feld, max. 2 LLM-Calls |
|
||||
|
||||
**Response:**
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| `retrieval_phase` | `profile_v1` oder `profile_v1+llm_rank` |
|
||||
| `llm_rank_applied` | `true` wenn LLM erfolgreich sortiert hat |
|
||||
| `hits[].llm_rank` | optional: Position nach LLM (1…n) |
|
||||
|
||||
**Fallback:** Kein API-Key, inaktiver Prompt oder Parse-Fehler → Hybrid-Reihenfolge unverändert, `llm_rank_applied: false`.
|
||||
|
||||
**Prompt:** Migration **072**, Slug `planning_exercise_search_rank` — Kandidaten als JSON mit Titel, summary, goal (Plaintext), skills; Ausgabe `{ ranked_ids, reasons }`.
|
||||
|
||||
---
|
||||
|
||||
## 12. ExerciseMatchProfile & PlanningTargetProfile (Phase 1)
|
||||
|
||||
Ziel: deterministische Vorselektion über **Profil-Dimensionen** statt nur Titel/Jaccard.
|
||||
|
||||
### 12.1 ExerciseMatchProfile (pro Übung)
|
||||
|
||||
| Feld | Quelle |
|
||||
|------|--------|
|
||||
| `focus_area_ids` | `exercise_focus_areas` (Primary = 1.0, sonst 0.85) |
|
||||
| `style_direction_ids` | `exercise_style_directions` |
|
||||
| `training_type_ids` | `exercise_training_types` |
|
||||
| `target_group_ids` | `exercise_target_groups` |
|
||||
| `skill_weights` | `exercise_skills` × Intensitäts-Multiplikator (`skill_scoring._skill_link_multiplier`) |
|
||||
|
||||
Bulk-Lader: `load_exercise_match_profiles_bulk(cur, exercise_ids)`.
|
||||
|
||||
### 12.2 PlanningTargetProfile (Planungsziel)
|
||||
|
||||
Zusammensetzung aus mehreren Quellen (`sources[]`):
|
||||
|
||||
| Quelle | Inhalt |
|
||||
|--------|--------|
|
||||
| `framework_catalog` | Fokus/Stil/Trainingsstil/Zielgruppe aus `training_framework_program_*` |
|
||||
| `framework_slot_skill_profile` | Skill-Profil des Slot-Blueprints (`profile_for_occurrences`) |
|
||||
| `framework_overall_skill_profile` | Fallback: alle Blueprint-Einheiten des Rahmens |
|
||||
| `current_unit_plan` | Skill-Profil der bereits eingeplanten Übungen dieser Einheit |
|
||||
| `anchor_exercise` | Katalog + Skills der Anker-Übung (Intent-abhängig) |
|
||||
| `skill_gap_vs_plan` | `target_skills − plan_skills` (normalisiert, Schwelle > 0.08) |
|
||||
|
||||
Builder: `build_planning_target_profile(cur, unit=…, planned_exercise_ids=…, anchor_exercise_id=…, intent=…)`.
|
||||
|
||||
Rahmen-Anbindung über `unit.framework_slot_id` oder `origin_framework_slot_id`.
|
||||
|
||||
---
|
||||
|
||||
## 13. Profil-Score (Formeln)
|
||||
|
||||
**Gewichtete Überlappung** (Katalog + Skills):
|
||||
|
||||
```
|
||||
overlap(a, b) = Σ min(a[k], b[k]) / Σ max(a[k], b[k])
|
||||
```
|
||||
|
||||
**Skill-Gap-Abdeckung:**
|
||||
|
||||
```
|
||||
gap_coverage(gap, candidate) = Σ min(gap[k], candidate[k]) / Σ gap[k]
|
||||
```
|
||||
|
||||
**Profil-Score** (intent-gewichtet, Summe Dimensionen = 1.0):
|
||||
|
||||
```
|
||||
profile_score = w_focus * overlap(focus)
|
||||
+ w_style * overlap(style)
|
||||
+ w_tt * overlap(training_type)
|
||||
+ w_tg * overlap(target_group)
|
||||
+ w_skill * overlap(skill_weights)
|
||||
+ w_gap * gap_coverage(skill_gap)
|
||||
```
|
||||
|
||||
Intent-Gewichte (Auszug): `deepen_exercise` → Skill hoch; `continue_plan_goal` → Gap hoch; `free_search` → Gap + Skill moderat.
|
||||
|
||||
Scorer: `score_exercise_against_target(exercise_profile, target_profile, intent=…) → (score, reasons[])`.
|
||||
|
||||
---
|
||||
|
||||
## 14. Hybrid + Profil (P0.1)
|
||||
|
||||
Im Hybrid-Score kommt **`w_profile * profile_score`** hinzu (Intent-abhängig ~0.15–0.35). Jaccard auf Anker-Skills bleibt parallel (schneller Anker-Fokus).
|
||||
|
||||
**Response-Felder:**
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|------|-----------|
|
||||
| `retrieval_phase` | `"profile_v1"` — Phase-1 aktiv, kein LLM-Rerank |
|
||||
| `target_profile_summary` | Lesbare Kurzinfo für UI-Chips (Fokus, Top-Skills, Quellen) |
|
||||
|
||||
**Phase 2 (P2 / B2):** siehe §15 und §18 — `include_llm_rank: true` vom Client, Backend entscheidet.
|
||||
|
||||
---
|
||||
|
||||
## 17. Phase A — Voll-Library-Ranking (0.8.177)
|
||||
|
||||
- Kein OR-Profil-Pool (~500 Übungen) mehr.
|
||||
- Alle sichtbaren Übungen (bis 8000) werden hybrid gescored (`fetch_all_visible_exercise_rows` + `rank_visible_library_hits`).
|
||||
- API: `full_library_ranked: true`, `retrieval_phase` enthält `+full_library+`.
|
||||
|
||||
---
|
||||
|
||||
## 18. Phase B / B2 — Text-Signale & Rerank-Gates (0.8.181–0.8.182)
|
||||
|
||||
**B — Text-Signale (`planning_exercise_text_signals.py`):**
|
||||
|
||||
- `section_guidance_notes`, Rahmen-Ziele/Notizen → Skill-/Katalog-Gewichte ohne LLM.
|
||||
- `requires_partner` aus Intent filtert Kandidaten.
|
||||
- `retrieval_phase +text_signals`.
|
||||
|
||||
**B2 — Rerank bei unklarem Ranking:**
|
||||
|
||||
- `hybrid_ranking_ambiguous(hits)` (Top-4-/Top-10-Gap).
|
||||
- Rerank auch nach Erwartungs-/Intent-LLM, wenn Scores eng beieinander.
|
||||
- Budget: max. **2** LLM-Calls (Profil + optional Rerank).
|
||||
|
||||
---
|
||||
|
||||
## 19. Phase C1 — Progressionsgraph im Planungskontext (0.8.183)
|
||||
|
||||
**Modul:** `planning_exercise_progression.py`
|
||||
|
||||
### Auto-Match Graph
|
||||
|
||||
Wenn `progression_graph_id` fehlt und Anker-Übung gesetzt: sichtbarer Graph mit passender `next_exercise`-Kante vom Anker (variantenbewusst). Bevorzugung: variantenspezifische Kanten > Anzahl Kanten.
|
||||
|
||||
### Variantenbewusste Nachfolger (Migration 034)
|
||||
|
||||
Generische Kante (`from_exercise_variant_id IS NULL`) gilt für jeden Anker; variantenspezifische Kante nur bei passender Anker-Variante.
|
||||
|
||||
Treffer: optional `hits[].suggested_variant_id`.
|
||||
|
||||
### Request / Response
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|------|-----------|
|
||||
| `anchor_exercise_variant_id` | Request — Variante der Anker-Übung |
|
||||
| `progression_graph_name` | Response — Name des (auto-)Graphs |
|
||||
| `progression_graph_auto_resolved` | Response — Auto-Match aktiv |
|
||||
|
||||
---
|
||||
|
||||
## 20. Phase C2 — Varianten in Treffern (0.8.184) ✅
|
||||
|
||||
- API: `variants[]`, `suggested_variant_name` pro Treffer (Batch aus `exercise_variants`).
|
||||
- **`ExercisePickerModal`:** Dropdown pro Treffer; Graph-`suggested_variant_id` vorausgewählt; Übernahme setzt `exercise_variant_id`.
|
||||
- **`hydrateExercisePlanningRow`:** übernimmt `exercise_variant_id` / `suggested_variant_id` in die Planungszeile.
|
||||
|
||||
---
|
||||
|
||||
## 21. Phase C3 — Graph-Builder (Roadmap, offen)
|
||||
|
||||
Ziel eingeben → aufbauende Übungen vorschlagen → nach Review in Graph speichern (`POST …/edges/sequence`). Nutzen über viele Pläne hinweg.
|
||||
@@ -34,6 +34,12 @@ DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
||||
|
||||
OPENROUTER_API_KEY=your_api_key_here
|
||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
||||
# Standard-OpenRouter-Modell (alle Aufrufe). Optional pro Prompt in ai_prompts.openrouter_model
|
||||
# ueberschreibbar (Migration 070, Superadmin unter „KI Prompts“).
|
||||
|
||||
# Übungs-KI (Docker): ohne Eintrag im compose „environment:“ landet keine .env-Zeile im Container.
|
||||
# Hier ist SHINKAN_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs (exercise_ai, openrouter).
|
||||
# SHINKAN_AI_DEBUG=1
|
||||
|
||||
SMTP_HOST=smtp.example.com
|
||||
SMTP_PORT=587
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
> | Fachlicher Nutzerüberblick (Design/Product) | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
||||
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
||||
> | KI-Prompt-System — Zielarchitektur | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
|
||||
|
||||
## Projekt-Übersicht
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Gemeinsame Pydantic-Modelle fuer Uebungs-KI-Kontext (Formularfelder → Prompt-Platzhalter).
|
||||
|
||||
Keine Imports aus exercise_ai — vermeidet Zirkelimporte mit ai_prompt_job / exercise_ai.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ExerciseFormAiFocusRow(BaseModel):
|
||||
"""Fokusbereich fuer Skill-Retrieval (ai_skill_retrieval_profiles)."""
|
||||
|
||||
focus_area_id: int = Field(..., ge=1)
|
||||
is_primary: Optional[bool] = False
|
||||
|
||||
|
||||
class ExerciseFormAiPromptContext(BaseModel):
|
||||
"""
|
||||
Inhaltliche Eingabe fuer Uebungs-Prompts (Kurzfassung / Skills / Anleitung).
|
||||
|
||||
Wird genutzt von Admin-Prompt-Vorschau und POST /exercises/ai/suggest (via Mapping).
|
||||
"""
|
||||
|
||||
title: Optional[str] = ""
|
||||
goal: Optional[str] = None
|
||||
execution: Optional[str] = None
|
||||
preparation: Optional[str] = None
|
||||
trainer_notes: Optional[str] = None
|
||||
focus_hint: Optional[str] = None
|
||||
focus_areas_context: Optional[List[ExerciseFormAiFocusRow]] = None
|
||||
|
||||
def focus_area_tuples(self) -> Optional[List[Tuple[int, bool]]]:
|
||||
if not self.focus_areas_context:
|
||||
return None
|
||||
return [(int(x.focus_area_id), bool(x.is_primary)) for x in self.focus_areas_context]
|
||||
|
||||
def has_instruction_source_text(self) -> bool:
|
||||
"""Mindestens ein Anleitungsfeld oder Titel fuer instruction_rewrite."""
|
||||
if (self.title or "").strip():
|
||||
return True
|
||||
for val in (self.goal, self.execution, self.preparation, self.trainer_notes):
|
||||
if val and str(val).strip():
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def from_api_suggest(
|
||||
cls,
|
||||
*,
|
||||
title: Optional[str] = None,
|
||||
goal: Optional[str] = None,
|
||||
execution: Optional[str] = None,
|
||||
preparation: Optional[str] = None,
|
||||
trainer_notes: Optional[str] = None,
|
||||
focus_area_hint: Optional[str] = None,
|
||||
focus_areas_context: Optional[Sequence[ExerciseFormAiFocusRow]] = None,
|
||||
) -> ExerciseFormAiPromptContext:
|
||||
"""Mappt Felder aus POST /exercises/ai/suggest (focus_area_hint → focus_hint)."""
|
||||
hint = (focus_area_hint or "").strip() or None
|
||||
return cls(
|
||||
title=(title or "").strip(),
|
||||
goal=goal,
|
||||
execution=execution,
|
||||
preparation=preparation,
|
||||
trainer_notes=trainer_notes,
|
||||
focus_hint=hint,
|
||||
focus_areas_context=list(focus_areas_context) if focus_areas_context else None,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_focus_tuples(
|
||||
cls,
|
||||
*,
|
||||
title: str = "",
|
||||
goal: Optional[str] = None,
|
||||
execution: Optional[str] = None,
|
||||
preparation: Optional[str] = None,
|
||||
trainer_notes: Optional[str] = None,
|
||||
focus_hint: Optional[str] = None,
|
||||
focus_tuples: Optional[Sequence[Tuple[int, bool]]] = None,
|
||||
) -> ExerciseFormAiPromptContext:
|
||||
rows = None
|
||||
if focus_tuples:
|
||||
rows = [
|
||||
ExerciseFormAiFocusRow(focus_area_id=int(fid), is_primary=bool(prim))
|
||||
for fid, prim in focus_tuples
|
||||
]
|
||||
return cls(
|
||||
title=(title or "").strip(),
|
||||
goal=goal,
|
||||
execution=execution,
|
||||
preparation=preparation,
|
||||
trainer_notes=trainer_notes,
|
||||
focus_hint=(focus_hint or "").strip() or None,
|
||||
focus_areas_context=rows,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ExerciseFormAiFocusRow",
|
||||
"ExerciseFormAiPromptContext",
|
||||
]
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
KI-Prompt Jobs: Resolver + oeffentliche Fassade fuer Uebungs-KI-Aufrufe.
|
||||
|
||||
Importiert exercise_ai fuer Platzhalter-Builder und OpenRouter-Orchestrierung.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContext
|
||||
from exercise_ai import build_exercise_placeholder_variables
|
||||
|
||||
|
||||
def resolve_exercise_form_variables(cur, slug: str, ctx: ExerciseFormAiPromptContext) -> Dict[str, str]:
|
||||
"""Baut die Mustache-Map fuer exercise_summary / exercise_skill_suggestions."""
|
||||
return build_exercise_placeholder_variables(
|
||||
cur,
|
||||
slug=slug,
|
||||
title=(ctx.title or "").strip(),
|
||||
goal=ctx.goal,
|
||||
execution=ctx.execution,
|
||||
focus_area_hint=ctx.focus_hint,
|
||||
focus_areas_context=ctx.focus_area_tuples(),
|
||||
preparation=ctx.preparation,
|
||||
trainer_notes=ctx.trainer_notes,
|
||||
)
|
||||
|
||||
|
||||
def run_exercise_form_ai_suggestion(
|
||||
cur,
|
||||
ctx: ExerciseFormAiPromptContext,
|
||||
*,
|
||||
want_summary: bool,
|
||||
want_skills: bool,
|
||||
want_instructions: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Fuehrt Uebungs-KI aus (OpenRouter) — ein Einstieg fuer Router und kuenftige Jobs.
|
||||
|
||||
``ctx`` = Formularinhalt; ``want_*`` = welche Prompt-Slugs angefragt werden.
|
||||
"""
|
||||
from exercise_ai import run_exercise_ai_suggestion
|
||||
|
||||
return run_exercise_ai_suggestion(
|
||||
cur,
|
||||
form_ctx=ctx,
|
||||
want_summary=want_summary,
|
||||
want_skills=want_skills,
|
||||
want_instructions=want_instructions,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ExerciseFormAiFocusRow",
|
||||
"ExerciseFormAiPromptContext",
|
||||
"resolve_exercise_form_variables",
|
||||
"run_exercise_form_ai_suggestion",
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
Gemeinsame KI-Prompt-Laufzeit (Shinkan): DB-Lesezugriff ai_prompts + Kontext-Arten.
|
||||
|
||||
Bleibt ohne Import von exercise_ai (kein Zirkel). Domänen wie exercise_ai nutzen
|
||||
load_ai_prompt_row und die Enum; Platzhalter bauen sie selbst oder über geteilte Builder.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Mapping, Optional, Tuple
|
||||
|
||||
from prompt_resolver import MustacheRenderResult, render_mustache_template
|
||||
|
||||
_PLANNING_AI_SLUGS = frozenset(
|
||||
{
|
||||
"planning_exercise_search_rank",
|
||||
"planning_exercise_search_intent",
|
||||
"planning_exercise_expectation_profile",
|
||||
}
|
||||
)
|
||||
|
||||
_EXERCISE_AI_SLUGS = frozenset(
|
||||
{
|
||||
"exercise_summary",
|
||||
"exercise_skill_suggestions",
|
||||
"exercise_instruction_rewrite",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class AiPromptContextKind(str, Enum):
|
||||
"""
|
||||
Logischer Kontext fuer Platzhalter/Builder — erweiterbar fuer Planung/Rahmen
|
||||
ohne bestehende Slugs zu invalidieren.
|
||||
"""
|
||||
|
||||
PLANNING_EXERCISE_SEARCH = "planning_exercise_search"
|
||||
EXERCISE_FORM_AI = "exercise_form_ai"
|
||||
|
||||
|
||||
def context_kind_for_slug(slug: str) -> Optional[AiPromptContextKind]:
|
||||
"""Ordnet einen DB-Slug einer Kontext-Art zu, sofern registriert."""
|
||||
s = (slug or "").strip().lower()
|
||||
if s in _PLANNING_AI_SLUGS:
|
||||
return AiPromptContextKind.PLANNING_EXERCISE_SEARCH
|
||||
if s in _EXERCISE_AI_SLUGS:
|
||||
return AiPromptContextKind.EXERCISE_FORM_AI
|
||||
return None
|
||||
|
||||
|
||||
def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Laedt eine Zeile ai_prompts fuer Laufzeit-Orchestrierung.
|
||||
|
||||
active_only=True: inaktive Prompts werden wie fehlend behandelt (503 im Aufrufer).
|
||||
"""
|
||||
if active_only:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
||||
FROM ai_prompts
|
||||
WHERE slug = %s AND active = true
|
||||
""",
|
||||
(slug,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
||||
FROM ai_prompts
|
||||
WHERE slug = %s
|
||||
""",
|
||||
(slug,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = dict(row)
|
||||
if active_only and not d.get("active", True):
|
||||
return None
|
||||
return d
|
||||
|
||||
|
||||
class AiPromptUnavailableError(LookupError):
|
||||
"""Kein aktiver Prompt fuer slug (oder Zeile fehlt)."""
|
||||
|
||||
def __init__(self, slug: str) -> None:
|
||||
self.slug = (slug or "").strip()
|
||||
super().__init__(self.slug)
|
||||
|
||||
|
||||
def render_ai_prompt_template_for_row(
|
||||
row: Mapping[str, Any],
|
||||
variables: Mapping[str, str],
|
||||
) -> MustacheRenderResult:
|
||||
"""Ersetzt Platzhalter anhand einer bereits geladenen ai_prompts-Zeile (z. B. Admin-Vorschauch, inkl. inaktiv)."""
|
||||
return render_mustache_template(str(row.get("template") or ""), variables)
|
||||
|
||||
|
||||
def load_and_render_ai_prompt(
|
||||
cur,
|
||||
slug: str,
|
||||
variables: Mapping[str, str],
|
||||
*,
|
||||
active_only: bool = True,
|
||||
) -> Tuple[Dict[str, Any], MustacheRenderResult]:
|
||||
"""
|
||||
Laedt einen aktiven Prompt und wendet Mustache-Variablen an.
|
||||
Wirft AiPromptUnavailableError, wenn die Zeile fehlt oder (bei active_only) inaktiv ist.
|
||||
"""
|
||||
row = load_ai_prompt_row(cur, slug, active_only=active_only)
|
||||
if not row:
|
||||
raise AiPromptUnavailableError(slug)
|
||||
rr = render_ai_prompt_template_for_row(row, variables)
|
||||
return dict(row), rr
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AiPromptContextKind",
|
||||
"AiPromptUnavailableError",
|
||||
"context_kind_for_slug",
|
||||
"load_ai_prompt_row",
|
||||
"load_and_render_ai_prompt",
|
||||
"render_ai_prompt_template_for_row",
|
||||
]
|
||||
+7
-2
@@ -180,12 +180,17 @@ def init_db():
|
||||
cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'")
|
||||
if cur.fetchone()['count'] == 0:
|
||||
cur.execute("""
|
||||
INSERT INTO ai_prompts (slug, name, description, template, active, sort_order)
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, active, sort_order
|
||||
)
|
||||
VALUES (
|
||||
'pipeline',
|
||||
'Mehrstufige Gesamtanalyse',
|
||||
'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.',
|
||||
'Master-Schalter fuer die gesamte Pipeline. Deaktiviere diese Zeile um die Pipeline zu verstecken.',
|
||||
'PIPELINE_MASTER',
|
||||
'admin',
|
||||
'text',
|
||||
true,
|
||||
-10
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,536 @@
|
||||
"""
|
||||
Superadmin-Werkzeug: Übungs-Anreicherung per KI (Skills + optional Metadaten).
|
||||
|
||||
Wiederverwendet run_exercise_form_ai_suggestion / exercise_ai — keine neue OpenRouter-Pipeline.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Literal, Optional
|
||||
|
||||
from ai_prompt_context import ExerciseFormAiPromptContext
|
||||
from ai_prompt_job import run_exercise_form_ai_suggestion
|
||||
from exercise_ai import strip_html_to_plain
|
||||
from exercise_rich_text import normalize_inline_exercise_media_markup
|
||||
|
||||
from routers.exercises import (
|
||||
enrich_exercise_detail,
|
||||
normalize_exercise_skill_intensity,
|
||||
normalize_exercise_skill_level,
|
||||
)
|
||||
|
||||
SkillMergeMode = Literal["additive", "replace_ai_only", "replace_all"]
|
||||
|
||||
SKILL_MERGE_MODES = frozenset({"additive", "replace_ai_only", "replace_all"})
|
||||
DEFAULT_SET_STATUS = "in_review"
|
||||
# Max. IDs pro Apply-HTTP-Anfrage (kein LLM).
|
||||
MAX_BATCH_EXERCISES = 50
|
||||
# Preview: pro Request nur wenige Übungen — sonst Gateway-504 (Fritz!Box o.ä. ~60s).
|
||||
MAX_PREVIEW_BATCH_EXERCISES = 3
|
||||
|
||||
_INSTRUCTION_FIELDS = ("goal", "execution", "preparation", "trainer_notes")
|
||||
_SKILL_COMPARE_KEYS = ("intensity", "required_level", "target_level", "is_primary")
|
||||
|
||||
|
||||
def _focus_areas_ai_ctx_from_detail(exercise: Dict[str, Any]) -> list[tuple[int, bool]]:
|
||||
rows: list[tuple[int, bool]] = []
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
try:
|
||||
fid = int(row.get("focus_area_id"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if fid < 1:
|
||||
continue
|
||||
rows.append((fid, bool(row.get("is_primary"))))
|
||||
rows.sort(key=lambda x: (not x[1], x[0]))
|
||||
return rows
|
||||
|
||||
|
||||
def _focus_area_hint_from_detail(exercise: Dict[str, Any]) -> str:
|
||||
parts: List[str] = []
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if isinstance(row, dict):
|
||||
nm = (row.get("name") or "").strip()
|
||||
if nm:
|
||||
parts.append(nm)
|
||||
txt = ", ".join(parts).strip()
|
||||
if len(txt) > 900:
|
||||
return txt[:899] + "…"
|
||||
return txt
|
||||
|
||||
|
||||
def build_form_context_from_exercise(exercise: Dict[str, Any]) -> ExerciseFormAiPromptContext:
|
||||
focus = _focus_area_hint_from_detail(exercise)
|
||||
fctx = _focus_areas_ai_ctx_from_detail(exercise)
|
||||
return ExerciseFormAiPromptContext.from_focus_tuples(
|
||||
title=str(exercise.get("title") or "").strip(),
|
||||
goal=exercise.get("goal"),
|
||||
execution=exercise.get("execution"),
|
||||
preparation=exercise.get("preparation"),
|
||||
trainer_notes=exercise.get("trainer_notes"),
|
||||
focus_hint=focus or None,
|
||||
focus_tuples=fctx or None,
|
||||
)
|
||||
|
||||
|
||||
def validate_exercise_for_enrichment(
|
||||
exercise: Dict[str, Any],
|
||||
*,
|
||||
want_skills: bool = False,
|
||||
want_summary: bool = False,
|
||||
want_instructions: bool = False,
|
||||
) -> Optional[str]:
|
||||
title = str(exercise.get("title") or "").strip()
|
||||
if not title:
|
||||
return "Titel fehlt"
|
||||
|
||||
ctx = build_form_context_from_exercise(exercise)
|
||||
g_plain = strip_html_to_plain(exercise.get("goal"))
|
||||
e_plain = strip_html_to_plain(exercise.get("execution"))
|
||||
|
||||
if want_skills or want_summary:
|
||||
if not (g_plain.strip() or e_plain.strip()):
|
||||
return "Mindestens Ziel oder Durchführung muss Inhalt liefern (für Skills/Kurzfassung)"
|
||||
|
||||
if want_instructions and not ctx.has_instruction_source_text():
|
||||
return "Für Anleitungs-Überarbeitung fehlt Ausgangstext (Titel oder Anleitungsfeld)"
|
||||
|
||||
if not (want_skills or want_summary or want_instructions):
|
||||
return "Kein Anreicherungsmodus aktiv"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_skill_row(raw: Dict[str, Any], *, ai_suggested: bool) -> Dict[str, Any]:
|
||||
return {
|
||||
"skill_id": int(raw["skill_id"]),
|
||||
"skill_name": (raw.get("skill_name") or "").strip() or f"Skill #{raw['skill_id']}",
|
||||
"skill_category": raw.get("skill_category"),
|
||||
"is_primary": bool(raw.get("is_primary")),
|
||||
"intensity": normalize_exercise_skill_intensity(raw.get("intensity")),
|
||||
"required_level": normalize_exercise_skill_level(raw.get("required_level")),
|
||||
"target_level": normalize_exercise_skill_level(raw.get("target_level")),
|
||||
"ai_suggested": ai_suggested,
|
||||
}
|
||||
|
||||
|
||||
def _skill_meta_differs(a: Dict[str, Any], b: Dict[str, Any]) -> bool:
|
||||
for k in _SKILL_COMPARE_KEYS:
|
||||
av = a.get(k)
|
||||
bv = b.get(k)
|
||||
if k in ("required_level", "target_level"):
|
||||
av = normalize_exercise_skill_level(av)
|
||||
bv = normalize_exercise_skill_level(bv)
|
||||
elif k == "intensity":
|
||||
av = normalize_exercise_skill_intensity(av)
|
||||
bv = normalize_exercise_skill_intensity(bv)
|
||||
elif k == "is_primary":
|
||||
av = bool(av)
|
||||
bv = bool(bv)
|
||||
if av != bv:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def merge_skills(
|
||||
existing: List[Dict[str, Any]],
|
||||
suggested: List[Dict[str, Any]],
|
||||
mode: SkillMergeMode,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Merge-Modi: additive | replace_ai_only | replace_all (alle KI-Skills mit ai_suggested=true)."""
|
||||
existing_norm = [_normalize_skill_row(s, ai_suggested=bool(s.get("ai_suggested"))) for s in existing]
|
||||
suggested_norm = [_normalize_skill_row(s, ai_suggested=True) for s in suggested]
|
||||
|
||||
suggested_by_id = {int(s["skill_id"]): s for s in suggested_norm}
|
||||
|
||||
if mode == "replace_all":
|
||||
return list(suggested_norm)
|
||||
|
||||
if mode == "replace_ai_only":
|
||||
manual = [s for s in existing_norm if not s.get("ai_suggested")]
|
||||
manual_ids = {int(s["skill_id"]) for s in manual}
|
||||
result = list(manual)
|
||||
for s in suggested_norm:
|
||||
sid = int(s["skill_id"])
|
||||
if sid in manual_ids:
|
||||
continue
|
||||
result.append(s)
|
||||
return result
|
||||
|
||||
# additive
|
||||
result: List[Dict[str, Any]] = []
|
||||
seen: set[int] = set()
|
||||
for s in existing_norm:
|
||||
sid = int(s["skill_id"])
|
||||
seen.add(sid)
|
||||
if sid in suggested_by_id and s.get("ai_suggested"):
|
||||
merged = {**s, **suggested_by_id[sid], "ai_suggested": True}
|
||||
result.append(merged)
|
||||
else:
|
||||
result.append(dict(s))
|
||||
for s in suggested_norm:
|
||||
sid = int(s["skill_id"])
|
||||
if sid not in seen:
|
||||
result.append(s)
|
||||
seen.add(sid)
|
||||
return result
|
||||
|
||||
|
||||
def compute_skill_diff(
|
||||
before: List[Dict[str, Any]],
|
||||
after: List[Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
before_ids = {int(s["skill_id"]): s for s in before}
|
||||
after_ids = {int(s["skill_id"]): s for s in after}
|
||||
added = [after_ids[i] for i in sorted(after_ids) if i not in before_ids]
|
||||
removed = [before_ids[i] for i in sorted(before_ids) if i not in after_ids]
|
||||
changed: List[Dict[str, Any]] = []
|
||||
for sid in before_ids:
|
||||
if sid in after_ids and _skill_meta_differs(before_ids[sid], after_ids[sid]):
|
||||
changed.append(
|
||||
{
|
||||
"skill_id": sid,
|
||||
"skill_name": after_ids[sid].get("skill_name") or before_ids[sid].get("skill_name"),
|
||||
"before": before_ids[sid],
|
||||
"after": after_ids[sid],
|
||||
}
|
||||
)
|
||||
kept = [
|
||||
before_ids[i]
|
||||
for i in sorted(before_ids)
|
||||
if i in after_ids and i not in {c["skill_id"] for c in changed}
|
||||
]
|
||||
return {"added": added, "removed": removed, "changed": changed, "kept": kept}
|
||||
|
||||
|
||||
def _skills_from_ai_payload(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
rows = payload.get("skills")
|
||||
if not isinstance(rows, list):
|
||||
return []
|
||||
return [_normalize_skill_row(r, ai_suggested=True) for r in rows if isinstance(r, dict) and r.get("skill_id")]
|
||||
|
||||
|
||||
def _summary_from_ai_payload(payload: Dict[str, Any]) -> Optional[str]:
|
||||
block = payload.get("summary")
|
||||
if isinstance(block, dict):
|
||||
text = (block.get("text") or "").strip()
|
||||
return text or None
|
||||
if isinstance(block, str) and block.strip():
|
||||
return block.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _instructions_from_ai_payload(payload: Dict[str, Any]) -> Dict[str, str]:
|
||||
block = payload.get("instructions")
|
||||
if not isinstance(block, dict):
|
||||
return {}
|
||||
fields = block.get("fields")
|
||||
if not isinstance(fields, dict):
|
||||
return {}
|
||||
out: Dict[str, str] = {}
|
||||
for key in _INSTRUCTION_FIELDS:
|
||||
val = fields.get(key)
|
||||
if val is not None and str(val).strip():
|
||||
out[key] = str(val).strip()
|
||||
return out
|
||||
|
||||
|
||||
def _instruction_snapshot(exercise: Dict[str, Any]) -> Dict[str, str]:
|
||||
out: Dict[str, str] = {}
|
||||
for key in _INSTRUCTION_FIELDS:
|
||||
raw = exercise.get(key)
|
||||
plain = strip_html_to_plain(raw, max_len=400) if raw else ""
|
||||
if plain.strip():
|
||||
out[key] = plain.strip()
|
||||
return out
|
||||
|
||||
|
||||
def compute_instruction_diff(
|
||||
before: Dict[str, str],
|
||||
after: Dict[str, str],
|
||||
) -> Dict[str, Any]:
|
||||
changed: List[Dict[str, Any]] = []
|
||||
added: List[str] = []
|
||||
for key in _INSTRUCTION_FIELDS:
|
||||
b = (before.get(key) or "").strip()
|
||||
a = (after.get(key) or "").strip()
|
||||
if not a:
|
||||
continue
|
||||
if not b:
|
||||
added.append(key)
|
||||
elif b != strip_html_to_plain(a, max_len=400).strip() and b != a:
|
||||
changed.append({"field": key, "before_plain": b, "after_html": a})
|
||||
return {"changed_fields": changed, "added_fields": added}
|
||||
|
||||
|
||||
def preview_exercise_enrichment(
|
||||
cur,
|
||||
exercise_id: int,
|
||||
*,
|
||||
want_skills: bool = True,
|
||||
want_summary: bool = False,
|
||||
want_instructions: bool = False,
|
||||
merge_mode: SkillMergeMode = "additive",
|
||||
) -> Dict[str, Any]:
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
if not exercise:
|
||||
return {"exercise_id": exercise_id, "ok": False, "error": "Übung nicht gefunden"}
|
||||
|
||||
skip_reason = validate_exercise_for_enrichment(
|
||||
exercise,
|
||||
want_skills=want_skills,
|
||||
want_summary=want_summary,
|
||||
want_instructions=want_instructions,
|
||||
)
|
||||
if skip_reason:
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": False,
|
||||
"skipped": True,
|
||||
"error": skip_reason,
|
||||
"title": exercise.get("title"),
|
||||
"status": exercise.get("status"),
|
||||
}
|
||||
|
||||
existing = exercise.get("skills") or []
|
||||
suggested: List[Dict[str, Any]] = []
|
||||
ai_meta: Dict[str, Any] = {}
|
||||
payload: Dict[str, Any] = {}
|
||||
suggested_summary: Optional[str] = None
|
||||
suggested_instructions: Dict[str, str] = {}
|
||||
|
||||
if want_skills or want_summary or want_instructions:
|
||||
ctx = build_form_context_from_exercise(exercise)
|
||||
payload = run_exercise_form_ai_suggestion(
|
||||
cur,
|
||||
ctx,
|
||||
want_summary=want_summary,
|
||||
want_skills=want_skills,
|
||||
want_instructions=want_instructions,
|
||||
)
|
||||
if want_skills:
|
||||
suggested = _skills_from_ai_payload(payload)
|
||||
if want_summary:
|
||||
suggested_summary = _summary_from_ai_payload(payload)
|
||||
if want_instructions:
|
||||
suggested_instructions = _instructions_from_ai_payload(payload)
|
||||
ai_meta = {
|
||||
"models": payload.get("models_by_slug") or {},
|
||||
"llm_calls": sum([want_skills, want_summary, want_instructions]),
|
||||
}
|
||||
|
||||
merged = merge_skills(existing, suggested, merge_mode) if want_skills else list(existing)
|
||||
diff = compute_skill_diff(existing, merged) if want_skills else None
|
||||
|
||||
existing_summary = (exercise.get("summary") or "").strip() or None
|
||||
instr_before = _instruction_snapshot(exercise)
|
||||
instr_after_plain = {
|
||||
k: strip_html_to_plain(v, max_len=400) for k, v in suggested_instructions.items()
|
||||
}
|
||||
instruction_diff = (
|
||||
compute_instruction_diff(instr_before, instr_after_plain) if want_instructions else None
|
||||
)
|
||||
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": True,
|
||||
"title": exercise.get("title"),
|
||||
"status": exercise.get("status"),
|
||||
"visibility": exercise.get("visibility"),
|
||||
"primary_focus_name": _primary_focus_from_exercise(exercise),
|
||||
"existing_skills": existing,
|
||||
"suggested_skills": suggested,
|
||||
"merged_skills": merged,
|
||||
"diff": diff,
|
||||
"existing_summary": existing_summary,
|
||||
"suggested_summary": suggested_summary,
|
||||
"existing_instructions": instr_before,
|
||||
"suggested_instructions": suggested_instructions,
|
||||
"instruction_diff": instruction_diff,
|
||||
"ai_meta": ai_meta,
|
||||
}
|
||||
|
||||
|
||||
def _primary_focus_from_exercise(exercise: Dict[str, Any]) -> Optional[str]:
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if isinstance(row, dict) and row.get("is_primary"):
|
||||
return (row.get("name") or "").strip() or None
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if isinstance(row, dict):
|
||||
nm = (row.get("name") or "").strip()
|
||||
if nm:
|
||||
return nm
|
||||
return None
|
||||
|
||||
|
||||
def persist_merged_skills(cur, exercise_id: int, merged: List[Dict[str, Any]], merge_mode: SkillMergeMode) -> None:
|
||||
if merge_mode == "replace_all":
|
||||
cur.execute("DELETE FROM exercise_skills WHERE exercise_id = %s", (exercise_id,))
|
||||
elif merge_mode == "replace_ai_only":
|
||||
cur.execute(
|
||||
"DELETE FROM exercise_skills WHERE exercise_id = %s AND ai_suggested = true",
|
||||
(exercise_id,),
|
||||
)
|
||||
|
||||
for sk in merged:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO exercise_skills
|
||||
(exercise_id, skill_id, is_primary, intensity, required_level, target_level, ai_suggested)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (exercise_id, skill_id) DO UPDATE SET
|
||||
intensity = CASE
|
||||
WHEN exercise_skills.ai_suggested = false AND %s = 'additive'
|
||||
THEN exercise_skills.intensity ELSE EXCLUDED.intensity END,
|
||||
required_level = CASE
|
||||
WHEN exercise_skills.ai_suggested = false AND %s = 'additive'
|
||||
THEN exercise_skills.required_level ELSE EXCLUDED.required_level END,
|
||||
target_level = CASE
|
||||
WHEN exercise_skills.ai_suggested = false AND %s = 'additive'
|
||||
THEN exercise_skills.target_level ELSE EXCLUDED.target_level END,
|
||||
is_primary = CASE
|
||||
WHEN exercise_skills.ai_suggested = false AND %s = 'additive'
|
||||
THEN exercise_skills.is_primary ELSE EXCLUDED.is_primary END,
|
||||
ai_suggested = CASE
|
||||
WHEN exercise_skills.ai_suggested = false AND %s = 'additive'
|
||||
THEN exercise_skills.ai_suggested ELSE EXCLUDED.ai_suggested END
|
||||
""",
|
||||
(
|
||||
exercise_id,
|
||||
int(sk["skill_id"]),
|
||||
bool(sk.get("is_primary")),
|
||||
normalize_exercise_skill_intensity(sk.get("intensity")),
|
||||
normalize_exercise_skill_level(sk.get("required_level")),
|
||||
normalize_exercise_skill_level(sk.get("target_level")),
|
||||
bool(sk.get("ai_suggested")),
|
||||
merge_mode,
|
||||
merge_mode,
|
||||
merge_mode,
|
||||
merge_mode,
|
||||
merge_mode,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _normalize_instruction_fields(fields: Optional[Dict[str, Any]]) -> Dict[str, str]:
|
||||
if not fields:
|
||||
return {}
|
||||
out: Dict[str, str] = {}
|
||||
for key in _INSTRUCTION_FIELDS:
|
||||
if key not in fields:
|
||||
continue
|
||||
raw = fields.get(key)
|
||||
if raw is None or not str(raw).strip():
|
||||
continue
|
||||
out[key] = normalize_inline_exercise_media_markup(str(raw).strip())
|
||||
return out
|
||||
|
||||
|
||||
def apply_exercise_enrichment(
|
||||
cur,
|
||||
exercise_id: int,
|
||||
*,
|
||||
merged_skills: Optional[List[Dict[str, Any]]] = None,
|
||||
merge_mode: SkillMergeMode = "additive",
|
||||
set_status: Optional[str] = DEFAULT_SET_STATUS,
|
||||
apply_skills: bool = False,
|
||||
summary_text: Optional[str] = None,
|
||||
apply_summary: bool = False,
|
||||
instruction_fields: Optional[Dict[str, Any]] = None,
|
||||
apply_instructions: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
if not exercise:
|
||||
return {"exercise_id": exercise_id, "ok": False, "error": "Übung nicht gefunden"}
|
||||
|
||||
skip_reason = validate_exercise_for_enrichment(
|
||||
exercise,
|
||||
want_skills=apply_skills,
|
||||
want_summary=apply_summary,
|
||||
want_instructions=apply_instructions,
|
||||
)
|
||||
if skip_reason:
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": False,
|
||||
"skipped": True,
|
||||
"error": skip_reason,
|
||||
}
|
||||
|
||||
skills_list = merged_skills or []
|
||||
if apply_skills:
|
||||
if not skills_list and merge_mode != "replace_all":
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": False,
|
||||
"error": "Keine Skills zum Anwenden",
|
||||
}
|
||||
persist_merged_skills(cur, exercise_id, skills_list, merge_mode)
|
||||
|
||||
sets: List[str] = []
|
||||
vals: List[Any] = []
|
||||
|
||||
if apply_summary and summary_text is not None:
|
||||
text = str(summary_text).strip()
|
||||
if text:
|
||||
sets.extend(["summary = %s", "summary_ai_generated = true"])
|
||||
vals.append(text[:220])
|
||||
|
||||
if apply_instructions:
|
||||
norm = _normalize_instruction_fields(instruction_fields)
|
||||
for key, val in norm.items():
|
||||
sets.append(f"{key} = %s")
|
||||
vals.append(val)
|
||||
|
||||
new_status = (set_status or "").strip().lower() or None
|
||||
if new_status:
|
||||
if new_status == "approved":
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": False,
|
||||
"error": "Automatisches Freigeben (approved) ist nicht erlaubt",
|
||||
}
|
||||
if new_status not in ("draft", "in_review", "archived"):
|
||||
return {"exercise_id": exercise_id, "ok": False, "error": "Ungültiger Ziel-Status"}
|
||||
sets.append("status = %s")
|
||||
vals.append(new_status)
|
||||
|
||||
if sets:
|
||||
sets.append("updated_at = NOW()")
|
||||
vals.append(exercise_id)
|
||||
cur.execute(
|
||||
f"UPDATE exercises SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
elif not apply_skills:
|
||||
return {"exercise_id": exercise_id, "ok": False, "error": "Nichts anzuwenden"}
|
||||
|
||||
return {
|
||||
"exercise_id": exercise_id,
|
||||
"ok": True,
|
||||
"status": new_status or exercise.get("status"),
|
||||
"skills_applied": len(skills_list) if apply_skills else 0,
|
||||
"summary_applied": apply_summary and bool(summary_text and str(summary_text).strip()),
|
||||
"instructions_applied": apply_instructions and bool(_normalize_instruction_fields(instruction_fields)),
|
||||
}
|
||||
|
||||
|
||||
def estimate_llm_calls(
|
||||
*,
|
||||
exercise_count: int,
|
||||
want_skills: bool,
|
||||
want_summary: bool,
|
||||
want_instructions: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
per_skills = exercise_count if want_skills else 0
|
||||
per_summary = exercise_count if want_summary else 0
|
||||
per_instructions = exercise_count if want_instructions else 0
|
||||
total = per_skills + per_summary + per_instructions
|
||||
return {
|
||||
"total": total,
|
||||
"per_exercise": sum([want_skills, want_summary, want_instructions]),
|
||||
"skills": per_skills,
|
||||
"summary": per_summary,
|
||||
"instructions": per_instructions,
|
||||
}
|
||||
+6
-1
@@ -193,7 +193,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, skill_profiles, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -210,16 +210,21 @@ app.include_router(media_assets.admin_legal_hold_router)
|
||||
app.include_router(skills.router)
|
||||
app.include_router(skill_profiles.router)
|
||||
app.include_router(training_planning.router)
|
||||
app.include_router(planning_exercise_suggest.router)
|
||||
app.include_router(dashboard.router)
|
||||
app.include_router(training_modules.router)
|
||||
app.include_router(training_framework_programs.router)
|
||||
app.include_router(catalogs.router)
|
||||
app.include_router(maturity_models.router)
|
||||
app.include_router(matrix_stack_bundle.router)
|
||||
app.include_router(matrix_editor.router)
|
||||
app.include_router(import_wiki.router)
|
||||
app.include_router(import_wiki_admin.router)
|
||||
app.include_router(legal_documents.router)
|
||||
app.include_router(content_reports.router)
|
||||
app.include_router(ai_prompts_admin.router)
|
||||
app.include_router(ai_skill_retrieval_admin.router)
|
||||
app.include_router(exercise_enrichment_admin.router)
|
||||
|
||||
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
-- Migration 067: Konfigurierbare KI-Prompts + Tracking-Feld fuer Uebungs-Zusammenfassung
|
||||
-- Datum: 2026-05-22
|
||||
-- Spec: technical/KI_FEATURES_SPEC.md, AI_PROMPT_SYSTEM_SPEC.md
|
||||
|
||||
-- ============================================================================
|
||||
-- AI PROMPTS
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ai_prompts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slug VARCHAR(100) NOT NULL UNIQUE,
|
||||
display_name VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
template TEXT NOT NULL,
|
||||
|
||||
category VARCHAR(50) DEFAULT 'exercise'
|
||||
CHECK (category IN ('exercise', 'training', 'matrix', 'import', 'admin')),
|
||||
|
||||
output_format VARCHAR(10) DEFAULT 'text'
|
||||
CHECK (output_format IN ('text', 'json')),
|
||||
|
||||
output_schema JSONB,
|
||||
is_system_default BOOLEAN DEFAULT false,
|
||||
default_template TEXT,
|
||||
|
||||
active BOOLEAN DEFAULT true,
|
||||
sort_order INT DEFAULT 0,
|
||||
|
||||
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_slug ON ai_prompts(slug);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_category ON ai_prompts(category);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_active ON ai_prompts(active, sort_order);
|
||||
|
||||
DROP TRIGGER IF EXISTS ai_prompts_update ON ai_prompts;
|
||||
CREATE TRIGGER ai_prompts_update
|
||||
BEFORE UPDATE ON ai_prompts
|
||||
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
|
||||
|
||||
-- ============================================================================
|
||||
-- TRACKING SUMMARY (KI)
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE exercises ADD COLUMN IF NOT EXISTS summary_ai_generated BOOLEAN DEFAULT false;
|
||||
|
||||
COMMENT ON COLUMN exercises.summary_ai_generated IS 'TRUE wenn Kurzbeschreibung zuletzt von KI vorgeschlagen und uebernommen (UI setzt bei manueller Aenderung false)';
|
||||
|
||||
-- ============================================================================
|
||||
-- SEED PROMPTS (idempotent)
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'pipeline',
|
||||
'Mehrstufige Gesamtanalyse',
|
||||
'Master-Schalter fuer die Pipeline-Anzeige.',
|
||||
'PIPELINE_MASTER',
|
||||
'admin',
|
||||
'text',
|
||||
false,
|
||||
'PIPELINE_MASTER',
|
||||
true,
|
||||
-10
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'pipeline');
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'exercise_summary',
|
||||
'Uebungs-Zusammenfassung',
|
||||
'Erzeugt eine kurze Kurzbeschreibung fuer Listen/Galerie.',
|
||||
$s$Du bist Assistent fuer Kampfsport-Trainer.
|
||||
Erstelle eine kurze Kurzbeschreibung fuer Listen und Trainingsplaene.
|
||||
|
||||
Anforderungen:
|
||||
- Hochstens etwa 200 Zeichen (bei Bedarf gekuerzt fuer Mobile)
|
||||
- Kern: Welche Trainingsqualitaeten? Wie fuehrt man die Uebung kurz aus?
|
||||
- Sachlich, auf Deutsch
|
||||
|
||||
Uebung: {{exercise_title}}
|
||||
Fokuskontext: {{exercise_focus_area}}
|
||||
Ziel (Fliesstext, kann HTML sein): {{exercise_goal}}
|
||||
Durchfuehrung (Fliesstext, kann HTML sein): {{exercise_execution}}
|
||||
|
||||
Antworte NUR mit der Kurzbeschreibung als einfachen Text (keine Markdown-Codeblocks, keine Anfuehrungszeichen um den ganzen Text).$s$,
|
||||
'exercise',
|
||||
'text',
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
1
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'exercise_summary');
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'exercise_skill_suggestions',
|
||||
'Faehigkeiten-Empfehlungen',
|
||||
'Schlaegt passende Skills mit Stufen/Intensitaet vor (JSON-Ausgabe-Prompt).',
|
||||
$j$Du bist Assistent fuer Kampfsport-Trainer.
|
||||
Ordne diese Uebung dem globalen Skill-Katalog zu.
|
||||
|
||||
Daten zur Uebung:
|
||||
Titel: {{exercise_title}}
|
||||
Fokuskontext (optional): {{exercise_focus_area}}
|
||||
Ziel (gekuerzt_plain): {{exercise_goal}}
|
||||
Durchfuehrung (gekuerzt_plain): {{exercise_execution}}
|
||||
|
||||
Verfuegbare Faehigkeiten (Auswahl NUR ueber diese IDs — keine anderen IDs verwenden):
|
||||
{{skills_catalog}}
|
||||
|
||||
Waehle hoechstens 5 passende Skills. Für jede Faehigkeit:
|
||||
- skill_id: ganze Zahl aus der Liste
|
||||
- required_level: eines von basis, grundlagen, aufbau, fortgeschritten, optimierung
|
||||
- target_level: derselbe Wertvorrat
|
||||
- intensity: eines von niedrig, mittel, hoch
|
||||
- is_primary (optional): true fuer die Hauptfaehigkeit der Uebung, sondern false/weglassen
|
||||
|
||||
Antworte NUR mit einem JSON-Array ohne Erklaertext, keine Markdown-Fences.
|
||||
|
||||
Beispielformat:
|
||||
[{"skill_id": 1, "required_level": "grundlagen", "target_level": "aufbau", "intensity": "hoch", "is_primary": true}]
|
||||
|
||||
Wenn nichts gut passt, antworte mit [].$j$,
|
||||
'exercise',
|
||||
'json',
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
2
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'exercise_skill_suggestions');
|
||||
@@ -0,0 +1,125 @@
|
||||
-- Migration 068: KI Skill-Retrieval-Profile pro Fokusbereich (+ Standardprofil)
|
||||
-- Purpose: Gewichtungen/Quota fuer exercise_ai Skill-Katalog (OpenRouter Kontext)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ai_skill_retrieval_profiles (
|
||||
id SERIAL PRIMARY KEY,
|
||||
focus_area_id INT REFERENCES focus_areas(id) ON DELETE CASCADE,
|
||||
is_default BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
config JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_ai_skill_retrieval_profile_focus_area
|
||||
ON ai_skill_retrieval_profiles (focus_area_id)
|
||||
WHERE focus_area_id IS NOT NULL AND active = TRUE;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_ai_skill_retrieval_profile_default_only
|
||||
ON ai_skill_retrieval_profiles (is_default)
|
||||
WHERE is_default IS TRUE AND active = TRUE;
|
||||
|
||||
COMMENT ON TABLE ai_skill_retrieval_profiles IS
|
||||
'Gewichte/Quota fuer Skill-Katalog in exercise_ai; optional gebunden an focus_areas, genau eine is_default=TRUE';
|
||||
|
||||
INSERT INTO ai_skill_retrieval_profiles (focus_area_id, is_default, name, description, active, config)
|
||||
VALUES (
|
||||
NULL,
|
||||
TRUE,
|
||||
'Standard',
|
||||
'Kein/Undefinierter Fokusbereich: neutrale Gewichte mit sanften Caps auf sehr breite Unterkategorien.',
|
||||
TRUE,
|
||||
'{
|
||||
"version": 1,
|
||||
"importance_multiplier": 1,
|
||||
"text_overlap_bonus": 2,
|
||||
"main_slug_weights": { "karate": 1, "allgemeine": 1 },
|
||||
"category_slug_weights": {},
|
||||
"category_max_share": {
|
||||
"kondition": 0.38,
|
||||
"koordination": 0.35
|
||||
},
|
||||
"main_min_share": {},
|
||||
"description_plain_max_len": 160,
|
||||
"karate_relevance_max_len": 72,
|
||||
"keyword_overrides": [
|
||||
{
|
||||
"keywords_any": ["rollenspiel", "szenario", "deesk", "diskussion"],
|
||||
"case_insensitive": true,
|
||||
"patch": {
|
||||
"category_slug_weights": {
|
||||
"psychische_faehigkeiten": 1.65,
|
||||
"soziale_faehigkeiten": 1.65,
|
||||
"kognition": 1.4
|
||||
},
|
||||
"category_max_share": {
|
||||
"kondition": 0.08,
|
||||
"koordination": 0.1
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"keywords_any": ["befreiung", "haltegriff", "greifer", "umklammer"],
|
||||
"case_insensitive": true,
|
||||
"patch": {
|
||||
"category_slug_weights": {
|
||||
"selbstverteidigung": 2.2,
|
||||
"koordination": 0.9
|
||||
},
|
||||
"main_slug_weights": { "karate": 1.35 }
|
||||
}
|
||||
}
|
||||
]
|
||||
}'::jsonb
|
||||
);
|
||||
|
||||
INSERT INTO ai_skill_retrieval_profiles (focus_area_id, is_default, name, description, active, config)
|
||||
SELECT
|
||||
fa.id,
|
||||
FALSE,
|
||||
'Gewaltschutz',
|
||||
'Kaum klassische Sportfaehigkeit; Gewicht auf Deeskalation, Kognition/Soziales; SV-Schwerpunkt per Keywords verstaerken.',
|
||||
TRUE,
|
||||
'{
|
||||
"version": 1,
|
||||
"importance_multiplier": 1,
|
||||
"text_overlap_bonus": 2.25,
|
||||
"main_slug_weights": { "karate": 1.08, "allgemeine": 1.06 },
|
||||
"category_slug_weights": {
|
||||
"kognition": 1.72,
|
||||
"psychische_faehigkeiten": 1.78,
|
||||
"soziale_faehigkeiten": 1.78,
|
||||
"selbstverteidigung": 1.82,
|
||||
"kondition": 0.32,
|
||||
"koordination": 0.4
|
||||
},
|
||||
"category_max_share": {
|
||||
"kondition": 0.12,
|
||||
"koordination": 0.16
|
||||
},
|
||||
"main_min_share": {},
|
||||
"description_plain_max_len": 150,
|
||||
"karate_relevance_max_len": 0,
|
||||
"keyword_overrides": [
|
||||
{
|
||||
"keywords_any": ["befreiung", "haltegriff", "greifer"],
|
||||
"case_insensitive": true,
|
||||
"patch": {
|
||||
"category_slug_weights": {
|
||||
"selbstverteidigung": 3.25,
|
||||
"koordination": 1.08
|
||||
},
|
||||
"main_slug_weights": { "karate": 1.5 }
|
||||
}
|
||||
}
|
||||
]
|
||||
}'::jsonb
|
||||
FROM focus_areas fa
|
||||
WHERE fa.name = 'Gewaltschutz'
|
||||
AND (fa.status IS NULL OR fa.status = 'active')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ai_skill_retrieval_profiles p
|
||||
WHERE p.focus_area_id = fa.id AND p.active = TRUE
|
||||
)
|
||||
LIMIT 1;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Migration 069: ai_prompts default_template fuer Ruecksetzen & Transparenz
|
||||
-- Setzt fuer bestehende System-Prompt-Zeilen default_template aus dem aktuellen template,
|
||||
-- sofern noch kein Referenzinhalt gespeichert war (Migration 067 hatte NULL fuer exercise_*).
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET default_template = template,
|
||||
updated_at = NOW()
|
||||
WHERE default_template IS NULL
|
||||
AND template IS NOT NULL
|
||||
AND LENGTH(TRIM(template)) > 0;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Migration 070: optionales OpenRouter-Modell pro Prompt-Zeile
|
||||
-- Leer/NULL → Umgebungsvariable OPENROUTER_MODEL (wie bisher).
|
||||
|
||||
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS openrouter_model VARCHAR(200);
|
||||
|
||||
COMMENT ON COLUMN ai_prompts.openrouter_model IS
|
||||
'Optional: OpenRouter model id (z.B. anthropic/claude-3.5-haiku); NULL = OPENROUTER_MODEL aus Env';
|
||||
@@ -0,0 +1,59 @@
|
||||
-- Migration 071: KI-Prompt fuer Anleitungs-Ueberarbeitung (Ziel, Durchfuehrung, Vorbereitung, Trainer-Hinweise)
|
||||
-- JSON-Ausgabe; praezise HTML-Fragmente fuer RichTextEditor.
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, output_schema, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'exercise_instruction_rewrite',
|
||||
'Anleitung ueberarbeiten',
|
||||
'Ueberarbeitet Ziel, Durchfuehrung, Vorbereitung und Trainer-Hinweise — praezise, strukturiert, ohne Aufblaehen.',
|
||||
$t$Du bist Assistent fuer Kampfsport-Trainer.
|
||||
Ueberarbeite die Anleitung dieser Uebung: verbessere Formulierung, ergaenze fehlende Kernpunkte, kuerze ueberfluessige Passagen.
|
||||
Wichtig: Texte sollen praezise und nachvollziehbar bleiben — keine Fuellsaetze, keine Wiederholungen, kein Marketing.
|
||||
|
||||
Stil:
|
||||
- Deutsch, sachlich, direkt an Trainer gerichtet (Durchfuehrung: Imperativ oder klare Schritte)
|
||||
- Ziel: 1–3 kurze Absaetze (Kern des Trainingsziels)
|
||||
- Durchfuehrung: klare Schritte (nummerierte Liste oder kurze Absaetze)
|
||||
- Vorbereitung/Aufbau: nur wenn noetig (Raum, Material, Aufbau) — sonst leerer String
|
||||
- Trainer-Hinweise: Sicherheit, typische Fehler, Coaching-Tipps — knapp, Stichpunkte oder kurze Absaetze
|
||||
|
||||
Format (HTML fuer Rich-Text-Editor):
|
||||
- Erlaubt: <p>, <ul>, <ol>, <li>, <strong>, <em>, <br>
|
||||
- Keine Ueberschriften (h1–h6), keine Tabellen, kein Markdown, keine Code-Fences
|
||||
- Medienverweise {{exerciseMedia:ID}} aus den Eingabetexten UNVERAENDERT an passender Stelle uebernehmen
|
||||
|
||||
Eingabe:
|
||||
Titel: {{exercise_title}}
|
||||
Fokuskontext: {{exercise_focus_area}}
|
||||
|
||||
Ziel (Plaintext, Ausgang): {{exercise_goal}}
|
||||
Durchfuehrung (Plaintext, Ausgang): {{exercise_execution}}
|
||||
Vorbereitung/Aufbau (Plaintext, Ausgang): {{exercise_preparation}}
|
||||
Trainer-Hinweise (Plaintext, Ausgang): {{exercise_trainer_notes}}
|
||||
|
||||
Antworte NUR mit einem JSON-Objekt (kein Text davor/danach):
|
||||
{
|
||||
"goal": "<p>…</p>",
|
||||
"execution": "<ol><li>…</li></ol>",
|
||||
"preparation": "<p>…</p> oder \"\"",
|
||||
"trainer_notes": "<ul><li>…</li></ul> oder \"\""
|
||||
}
|
||||
|
||||
Leere Felder als leerer String "" wenn nichts Sinnvolles ergibt.$t$,
|
||||
'exercise',
|
||||
'json',
|
||||
'{"type":"object","required":["goal","execution","preparation","trainer_notes"],"properties":{"goal":{"type":"string"},"execution":{"type":"string"},"preparation":{"type":"string"},"trainer_notes":{"type":"string"}}}'::jsonb,
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
3
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'exercise_instruction_rewrite');
|
||||
|
||||
-- Referenztext fuer Admin-Ruecksetzen (wie 069)
|
||||
UPDATE ai_prompts
|
||||
SET default_template = template
|
||||
WHERE slug = 'exercise_instruction_rewrite'
|
||||
AND (default_template IS NULL OR TRIM(default_template) = '');
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Migration 072: KI-Prompt Planungs-Übungssuche — LLM-Rerank (Phase 2)
|
||||
-- Spec: .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md §14
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, output_schema, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'planning_exercise_search_rank',
|
||||
'Planungs-Übungssuche Rerank',
|
||||
'Ordnet Kandidaten für die Trainingsplanung nach Intent und Kontext; nur IDs aus candidates_json.',
|
||||
$t$Du bist Assistent für Kampfsport-Trainer bei der Trainingsplanung.
|
||||
Ordne die vorgegebenen Übungs-Kandidaten nach Eignung für die aktuelle Planungssituation.
|
||||
|
||||
Regeln:
|
||||
- Verwende NUR exercise_id-Werte aus candidates_json (keine erfundenen IDs).
|
||||
- Berücksichtige search_query, intent, planning_context_json und target_profile_json.
|
||||
- Bewerte anhand von Titel, summary, goal und skills jedes Kandidaten.
|
||||
- Gib maximal {{result_limit}} IDs in sinnvoller Reihenfolge zurück (beste zuerst).
|
||||
- Kurze Begründung pro Top-Treffer auf Deutsch (1 Satz, sachlich).
|
||||
|
||||
Intent-Hinweise:
|
||||
- suggest_next / progression_next: logische Fortsetzung, Progression, passende Skills
|
||||
- deepen_exercise: Vertiefung zum Anker, ähnlicher Fokus
|
||||
- continue_plan_goal: schließt an bisherigen Plan und Skill-Lücken an
|
||||
- free_search: Freitext-Relevanz
|
||||
|
||||
Kontext:
|
||||
Intent: {{intent}}
|
||||
Suchanfrage: {{search_query}}
|
||||
Planung: {{planning_context_json}}
|
||||
Zielprofil: {{target_profile_json}}
|
||||
|
||||
Kandidaten (JSON):
|
||||
{{candidates_json}}
|
||||
|
||||
Antworte NUR mit JSON (kein Text davor/danach):
|
||||
{
|
||||
"ranked_ids": [123, 456],
|
||||
"reasons": { "123": "…", "456": "…" }
|
||||
}$t$,
|
||||
'training',
|
||||
'json',
|
||||
'{"type":"object","required":["ranked_ids"],"properties":{"ranked_ids":{"type":"array","items":{"type":"integer"}},"reasons":{"type":"object"}}}'::jsonb,
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
10
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'planning_exercise_search_rank');
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET default_template = template
|
||||
WHERE slug = 'planning_exercise_search_rank'
|
||||
AND (default_template IS NULL OR TRIM(default_template) = '');
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Migration 073: KI-Prompt Planungs-Übungssuche — Intent/Query-Overlay (P1)
|
||||
-- Spec: .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md §16
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, output_schema, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'planning_exercise_search_intent',
|
||||
'Planungs-Übungssuche Intent',
|
||||
'Strukturiert Freitext-Anfrage in Intent, Szenario und Katalog-Hints für Erwartungsprofil-Overlay.',
|
||||
$t$Du bist Assistent für Kampfsport-Trainer in der Trainingsplanung.
|
||||
Analysiere die Suchanfrage im Kontext der Einheit und des bisherigen Plans.
|
||||
|
||||
Ziel: JSON für ein Erwartungsprofil-Overlay (Fähigkeiten, Fokus, Stil …) — NICHT Übungs-IDs erfinden.
|
||||
|
||||
Szenario-Klassen (scenario):
|
||||
- preset_next: nur „nächste Übung“ ohne Zusatz — selten bei Freitext
|
||||
- progression: Progressionsgraph / Pfad / Folgeübung im Graph
|
||||
- deepen: Vertiefung zur Anker-Übung
|
||||
- continue_plan: baut auf bisherigem Plan der Einheit auf
|
||||
- additive_constraint: Plan beibehalten UND zusätzliche Anforderung (z. B. „außerdem Schnellkraft“)
|
||||
- free_search: offene Stichwortsuche / neues Thema
|
||||
|
||||
Intent (intent): suggest_next | progression_next | deepen_exercise | continue_plan_goal | free_search
|
||||
|
||||
emphasis:
|
||||
- additive: Zusatz zur bestehenden Planung (Default bei „zusätzlich/auch/dazu“)
|
||||
- replace: Suchanfrage soll Schwerpunkt eher ersetzen
|
||||
- neutral: nur leichte Gewichtung
|
||||
|
||||
Nutze skill_hints/focus_hints etc. mit Namen aus den Katalog-JSONs (beste Übereinstimmung).
|
||||
Bei requires_partner: true/false/null wenn Partnerbezug erkennbar.
|
||||
|
||||
Eingabe:
|
||||
Suchanfrage: {{search_query}}
|
||||
Heuristik-Intent: {{heuristic_intent}}
|
||||
Szenario-Hinweis (Server): {{scenario_hint}}
|
||||
Planungskontext: {{planning_context_json}}
|
||||
Basis-Zielprofil (deterministisch): {{target_profile_json}}
|
||||
|
||||
Kataloge (Auszug — nur diese Namen/IDs verwenden):
|
||||
Skills: {{skills_catalog_json}}
|
||||
Fokus: {{focus_areas_catalog_json}}
|
||||
Trainingsstil: {{training_types_catalog_json}}
|
||||
Stilrichtung: {{style_directions_catalog_json}}
|
||||
Zielgruppe: {{target_groups_catalog_json}}
|
||||
|
||||
Antworte NUR mit JSON:
|
||||
{
|
||||
"intent": "continue_plan_goal",
|
||||
"scenario": "additive_constraint",
|
||||
"skill_hints": [{"name": "Schnellkraft", "weight": 1.0}],
|
||||
"focus_hints": [],
|
||||
"style_hints": [],
|
||||
"training_type_hints": [],
|
||||
"target_group_hints": [],
|
||||
"requires_partner": null,
|
||||
"emphasis": "additive",
|
||||
"rationale": "Kurz auf Deutsch, 1 Satz"
|
||||
}$t$,
|
||||
'training',
|
||||
'json',
|
||||
'{"type":"object","required":["intent","scenario"],"properties":{"intent":{"type":"string"},"scenario":{"type":"string"},"skill_hints":{"type":"array"},"emphasis":{"type":"string"},"rationale":{"type":"string"}}}'::jsonb,
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
11
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'planning_exercise_search_intent');
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET default_template = template
|
||||
WHERE slug = 'planning_exercise_search_intent'
|
||||
AND (default_template IS NULL OR TRIM(default_template) = '');
|
||||
@@ -0,0 +1,70 @@
|
||||
-- Migration 074: KI-Prompt Planungs-Übungssuche — Erwartungsprofil aus Planungskontext (Preset)
|
||||
-- Spec: .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md §16
|
||||
|
||||
INSERT INTO ai_prompts (
|
||||
slug, display_name, description, template,
|
||||
category, output_format, output_schema, is_system_default, default_template, active, sort_order
|
||||
)
|
||||
SELECT
|
||||
'planning_exercise_expectation_profile',
|
||||
'Planungs-Übungssuche Erwartungsprofil',
|
||||
'Leitet aus Einheit, Abschnitt, Anker und bisherigem Plan ein Erwartungsprofil für die nächste Übung ab (ohne Freitext-Anfrage).',
|
||||
$t$Du bist Assistent für Kampfsport-Trainer in der Trainingsplanung.
|
||||
Der Trainer wählt „nächste Übung aus Kontext“ — es gibt KEINE zusätzliche Freitext-Suchanfrage.
|
||||
|
||||
Deine Aufgabe: Aus dem Planungskontext und dem deterministischen Basis-Zielprofil ein präzises Erwartungsprofil ableiten:
|
||||
- Was soll die nächste Übung fachlich leisten (Fortsetzen, Vertiefen, Lücke schließen, Abwechslung)?
|
||||
- Welche Fähigkeiten, Fokus-Bereiche, Trainingsstile passen dazu?
|
||||
- Berücksichtige: Rahmen/Einheit, Abschnittsziel (guidance_notes), letzte Übung im Abschnitt, Anker-Übung, Skill-Profile Einheit vs. Abschnitt, Skill-Lücken im Basisprofil.
|
||||
|
||||
Intent (intent): meist suggest_next oder continue_plan_goal; progression_next nur wenn Progressionsgraph/Anker klar nahelegt; deepen_exercise nur bei klarer Vertiefungslage.
|
||||
|
||||
continuation (optional, Kurzlabel):
|
||||
- build_on_section: nahtlos an Abschnitt/letzte Übung anknüpfen
|
||||
- close_skill_gap: fehlende Fähigkeiten aus Plan/Rahmen nachziehen
|
||||
- deepen_anchor: Anker-Übung vertiefen
|
||||
- variety: bewusst variieren nach bisherigem Block
|
||||
- balance_load: Belastung ausgleichen / Tempo wechseln
|
||||
|
||||
Nutze skill_hints/focus_hints etc. mit Namen aus den Katalog-JSONs (beste Übereinstimmung).
|
||||
emphasis: fast immer additive (baut auf Basisprofil auf), nur replace wenn Kontext eindeutig neuen Schwerpunkt verlangt.
|
||||
|
||||
Eingabe:
|
||||
Heuristik-Intent: {{heuristic_intent}}
|
||||
Planungskontext: {{planning_context_json}}
|
||||
Basis-Zielprofil (deterministisch): {{target_profile_json}}
|
||||
|
||||
Kataloge (Auszug — nur diese Namen/IDs verwenden):
|
||||
Skills: {{skills_catalog_json}}
|
||||
Fokus: {{focus_areas_catalog_json}}
|
||||
Trainingsstil: {{training_types_catalog_json}}
|
||||
Stilrichtung: {{style_directions_catalog_json}}
|
||||
Zielgruppe: {{target_groups_catalog_json}}
|
||||
|
||||
Antworte NUR mit JSON:
|
||||
{
|
||||
"intent": "suggest_next",
|
||||
"scenario": "preset_next",
|
||||
"continuation": "build_on_section",
|
||||
"skill_hints": [{"name": "Kime", "weight": 0.9}],
|
||||
"focus_hints": [],
|
||||
"style_hints": [],
|
||||
"training_type_hints": [],
|
||||
"target_group_hints": [],
|
||||
"requires_partner": null,
|
||||
"emphasis": "additive",
|
||||
"rationale": "Kurz auf Deutsch, 1–2 Sätze: warum diese nächste Übung sinnvoll ist"
|
||||
}$t$,
|
||||
'training',
|
||||
'json',
|
||||
'{"type":"object","required":["intent","scenario","rationale"],"properties":{"intent":{"type":"string"},"scenario":{"type":"string"},"continuation":{"type":"string"},"skill_hints":{"type":"array"},"emphasis":{"type":"string"},"rationale":{"type":"string"}}}'::jsonb,
|
||||
true,
|
||||
NULL,
|
||||
true,
|
||||
12
|
||||
WHERE NOT EXISTS (SELECT 1 FROM ai_prompts WHERE slug = 'planning_exercise_expectation_profile');
|
||||
|
||||
UPDATE ai_prompts
|
||||
SET default_template = template
|
||||
WHERE slug = 'planning_exercise_expectation_profile'
|
||||
AND (default_template IS NULL OR TRIM(default_template) = '');
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
Minimal OpenRouter REST client (sync). Reads OPENROUTER_API_KEY / OPENROUTER_MODEL / OPENROUTER_BASE_URL from env.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Dict, List, Mapping, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
_logger = logging.getLogger("shinkan.openrouter")
|
||||
|
||||
_SKIP_ANTHROPIC_BLOCK_TYPES = frozenset(
|
||||
{
|
||||
"thinking",
|
||||
"redacted_thinking",
|
||||
"reasoning",
|
||||
"tool_use",
|
||||
"tool_calls",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _shinkan_ai_debug() -> bool:
|
||||
return os.getenv("SHINKAN_AI_DEBUG", "").strip().lower() in ("1", "true", "yes", "full")
|
||||
|
||||
|
||||
def _coerce_nested_text(val: Any) -> str:
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, str):
|
||||
return val.strip()
|
||||
if isinstance(val, bool) or isinstance(val, (int, float)):
|
||||
return str(val).strip()
|
||||
if isinstance(val, list):
|
||||
return "".join(_coerce_nested_text(x) for x in val).strip()
|
||||
if isinstance(val, dict):
|
||||
# OpenRouter/Anthropic: verschachtelte text/content-Hüllen
|
||||
for key in ("text", "content", "value"):
|
||||
if key in val:
|
||||
nested = _coerce_nested_text(val.get(key))
|
||||
if nested:
|
||||
return nested
|
||||
return ""
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _flatten_message_content(content: Any) -> str:
|
||||
"""
|
||||
Chat-Completion: `content` als String oder als Liste strukturierter Blöcke
|
||||
(Anthropic Claude über OpenRouter/Bedrock, teils verschachtelt).
|
||||
"""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
if isinstance(content, list):
|
||||
parts: List[str] = []
|
||||
for block in content:
|
||||
if isinstance(block, str):
|
||||
bits = _coerce_nested_text(block)
|
||||
if bits:
|
||||
parts.append(bits)
|
||||
elif isinstance(block, dict):
|
||||
t_raw = block.get("type")
|
||||
ts = str(t_raw or "").strip().lower()
|
||||
if ts and (ts in _SKIP_ANTHROPIC_BLOCK_TYPES or ts.endswith("_thinking")):
|
||||
continue
|
||||
txt = None
|
||||
if ts in ("text", "output_text", ""):
|
||||
txt = block.get("text")
|
||||
if txt is None:
|
||||
txt = block.get("content")
|
||||
else:
|
||||
# unbekannten Typ weiter versuchen (Provider-Varianten), aber tool-use überspringen
|
||||
low = ts
|
||||
if "tool_use" in low or low.startswith("tool_"):
|
||||
continue
|
||||
txt = block.get("text") if block.get("text") is not None else block.get("content")
|
||||
bits = _coerce_nested_text(txt)
|
||||
if bits:
|
||||
parts.append(bits)
|
||||
return "".join(parts).strip()
|
||||
if isinstance(content, dict):
|
||||
return _coerce_nested_text(content)
|
||||
return str(content).strip()
|
||||
|
||||
|
||||
class OpenRouterError(Exception):
|
||||
"""Upstream or transport failure."""
|
||||
|
||||
|
||||
def openrouter_chat_completion(
|
||||
*,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_content: str,
|
||||
system_content: Optional[str] = None,
|
||||
timeout_sec: float = 120.0,
|
||||
temperature: float = 0.25,
|
||||
site_url: Optional[str] = None,
|
||||
app_title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Returns assistant message content (plain string). Caller validates empty responses.
|
||||
"""
|
||||
base = (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1"
|
||||
url = f"{base}/chat/completions"
|
||||
|
||||
headers: Dict[str, str] = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
referer = (site_url or os.getenv("APP_URL") or "").strip()
|
||||
if referer:
|
||||
headers["HTTP-Referer"] = referer
|
||||
title = (app_title or os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip()
|
||||
if title:
|
||||
headers["X-Title"] = title
|
||||
|
||||
messages: List[Dict[str, str]] = []
|
||||
if system_content and str(system_content).strip():
|
||||
messages.append({"role": "system", "content": str(system_content).strip()})
|
||||
messages.append({"role": "user", "content": user_content})
|
||||
|
||||
payload: Dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
}
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=timeout_sec) as client:
|
||||
resp = client.post(url, headers=headers, json=payload)
|
||||
except httpx.RequestError as e:
|
||||
raise OpenRouterError(str(e)) from e
|
||||
|
||||
if resp.status_code >= 400:
|
||||
detail = ""
|
||||
try:
|
||||
j = resp.json()
|
||||
detail = (
|
||||
str(j.get("error", {}).get("message"))
|
||||
if isinstance(j.get("error"), dict)
|
||||
else str(j.get("message") or j)
|
||||
)
|
||||
except Exception:
|
||||
detail = (resp.text or "")[:600]
|
||||
raise OpenRouterError(f"HTTP {resp.status_code}: {detail}".strip())
|
||||
|
||||
try:
|
||||
data = resp.json()
|
||||
except json.JSONDecodeError as e:
|
||||
raise OpenRouterError("Ungueltige JSON-Antwort von OpenRouter") from e
|
||||
|
||||
choices = data.get("choices") if isinstance(data, dict) else None
|
||||
if not choices or not isinstance(choices, list):
|
||||
raise OpenRouterError("OpenRouter: keine choices in Antwort")
|
||||
|
||||
msg0 = choices[0] if choices else {}
|
||||
inner = msg0.get("message") if isinstance(msg0, dict) else None
|
||||
|
||||
blobs: List[Any] = []
|
||||
if isinstance(inner, dict):
|
||||
if inner.get("content") is not None:
|
||||
blobs.append(inner.get("content"))
|
||||
if inner.get("refusal") is not None:
|
||||
blobs.append(inner.get("refusal"))
|
||||
elif isinstance(inner, str):
|
||||
blobs.append(inner)
|
||||
if isinstance(msg0, dict) and msg0.get("content") is not None and msg0.get("content") not in blobs:
|
||||
blobs.append(msg0.get("content"))
|
||||
|
||||
pieces = [_flatten_message_content(b).strip() for b in blobs if b is not None]
|
||||
joined = ("\n".join(p for p in pieces if p)).strip()
|
||||
|
||||
if _shinkan_ai_debug():
|
||||
fr = str(msg0.get("finish_reason") or "") if isinstance(msg0, dict) else ""
|
||||
fu = data.get("usage") if isinstance(data.get("usage"), dict) else {}
|
||||
pu = str(fu.get("prompt_tokens") or "")
|
||||
pc = str(fu.get("completion_tokens") or "")
|
||||
pt = str(fu.get("total_tokens") or "")
|
||||
raw_cls = type(blobs[0]).__name__ if blobs else "none"
|
||||
cc = str(len(joined))
|
||||
_logger.warning(
|
||||
"[AI_DEBUG/openrouter] model=%s finish_reason=%s usage_prompt=%s usage_completion=%s usage_total=%s "
|
||||
"raw_content_cls=%s out_chars=%s",
|
||||
model,
|
||||
fr,
|
||||
pu,
|
||||
pc,
|
||||
pt,
|
||||
raw_cls,
|
||||
cc,
|
||||
)
|
||||
|
||||
return joined
|
||||
|
||||
|
||||
def normalize_openrouter_env() -> tuple[str, str]:
|
||||
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||
model = (os.getenv("OPENROUTER_MODEL") or "anthropic/claude-sonnet-4").strip()
|
||||
return key, model
|
||||
|
||||
|
||||
def default_openrouter_model_id() -> str:
|
||||
"""Standard-Modell aus OPENROUTER_MODEL (ohne API-Key zu pruefen)."""
|
||||
_, model = normalize_openrouter_env()
|
||||
return model
|
||||
|
||||
|
||||
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
|
||||
"""
|
||||
Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Env-Default.
|
||||
|
||||
`row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …).
|
||||
"""
|
||||
if row:
|
||||
custom = str(row.get("openrouter_model") or "").strip()
|
||||
if custom:
|
||||
return custom
|
||||
return default_openrouter_model_id()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
Preset „Nächste aus Kontext“: LLM leitet Erwartungsprofil aus Planungskontext ab.
|
||||
|
||||
Prompt: planning_exercise_expectation_profile (Migration 074)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Mapping, Optional, Tuple
|
||||
|
||||
from planning_exercise_intent import (
|
||||
PlanningQueryIntentParsed,
|
||||
_compact_json,
|
||||
_load_compact_catalog,
|
||||
_load_skills_catalog_compact,
|
||||
parse_planning_query_intent_response,
|
||||
)
|
||||
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
||||
from openrouter_chat import (
|
||||
effective_openrouter_model_for_prompt_row,
|
||||
normalize_openrouter_env,
|
||||
openrouter_chat_completion,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger("shinkan.planning_exercise_expectation")
|
||||
|
||||
|
||||
def try_build_planning_expectation_from_context(
|
||||
cur,
|
||||
*,
|
||||
heuristic_intent: str,
|
||||
context_summary: Mapping[str, Any],
|
||||
target_profile_summary: Mapping[str, Any],
|
||||
) -> Tuple[Optional[PlanningQueryIntentParsed], bool]:
|
||||
"""
|
||||
LLM-Erwartungsprofil für preset_next / leere Anfrage mit Planungsbezug.
|
||||
Returns (parsed overlay, applied).
|
||||
"""
|
||||
api_key, _ = normalize_openrouter_env()
|
||||
if not api_key:
|
||||
return None, False
|
||||
|
||||
variables = {
|
||||
"heuristic_intent": heuristic_intent or "suggest_next",
|
||||
"planning_context_json": _compact_json(dict(context_summary or {})),
|
||||
"target_profile_json": _compact_json(dict(target_profile_summary or {})),
|
||||
"skills_catalog_json": _compact_json(_load_skills_catalog_compact(cur)),
|
||||
"focus_areas_catalog_json": _compact_json(_load_compact_catalog(cur, "focus_areas", "id")),
|
||||
"training_types_catalog_json": _compact_json(_load_compact_catalog(cur, "training_types", "id")),
|
||||
"style_directions_catalog_json": _compact_json(_load_compact_catalog(cur, "style_directions", "id")),
|
||||
"target_groups_catalog_json": _compact_json(_load_compact_catalog(cur, "target_groups", "id")),
|
||||
}
|
||||
|
||||
try:
|
||||
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_expectation_profile", variables)
|
||||
model = effective_openrouter_model_for_prompt_row(prow)
|
||||
raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text)
|
||||
parsed = parse_planning_query_intent_response(raw)
|
||||
if parsed.scenario not in ("preset_next", "continue_plan", "free_search"):
|
||||
parsed = parsed.model_copy(update={"scenario": "preset_next"})
|
||||
return parsed, True
|
||||
except AiPromptUnavailableError:
|
||||
return None, False
|
||||
except Exception as exc:
|
||||
_logger.warning("Planungs-Erwartungsprofil-LLM fehlgeschlagen: %s", exc)
|
||||
return None, False
|
||||
|
||||
|
||||
__all__ = ["try_build_planning_expectation_from_context"]
|
||||
@@ -0,0 +1,272 @@
|
||||
"""
|
||||
P1: LLM-Intent aus Planungs-Suchfrage → strukturiertes Query-Overlay für PlanningTargetProfile.
|
||||
|
||||
Prompt: planning_exercise_search_intent (Migration 073)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
||||
from openrouter_chat import (
|
||||
effective_openrouter_model_for_prompt_row,
|
||||
normalize_openrouter_env,
|
||||
openrouter_chat_completion,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger("shinkan.planning_exercise_intent")
|
||||
|
||||
VALID_PARSED_INTENTS = {
|
||||
"suggest_next",
|
||||
"progression_next",
|
||||
"deepen_exercise",
|
||||
"continue_plan_goal",
|
||||
"free_search",
|
||||
}
|
||||
|
||||
VALID_SCENARIOS = {
|
||||
"preset_next",
|
||||
"progression",
|
||||
"deepen",
|
||||
"continue_plan",
|
||||
"additive_constraint",
|
||||
"free_search",
|
||||
}
|
||||
|
||||
VALID_EMPHASIS = {"additive", "replace", "neutral"}
|
||||
|
||||
|
||||
class SkillHint(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=120)
|
||||
weight: float = Field(default=1.0, ge=0.1, le=1.0)
|
||||
|
||||
|
||||
class PlanningQueryIntentParsed(BaseModel):
|
||||
intent: str = "free_search"
|
||||
scenario: str = "free_search"
|
||||
skill_hints: List[SkillHint] = Field(default_factory=list)
|
||||
focus_hints: List[str] = Field(default_factory=list)
|
||||
style_hints: List[str] = Field(default_factory=list)
|
||||
training_type_hints: List[str] = Field(default_factory=list)
|
||||
target_group_hints: List[str] = Field(default_factory=list)
|
||||
requires_partner: Optional[bool] = None
|
||||
emphasis: str = "additive"
|
||||
rationale: Optional[str] = Field(default=None, max_length=400)
|
||||
|
||||
@field_validator("intent")
|
||||
@classmethod
|
||||
def _intent(cls, v: str) -> str:
|
||||
s = (v or "").strip().lower()
|
||||
return s if s in VALID_PARSED_INTENTS else "free_search"
|
||||
|
||||
@field_validator("scenario")
|
||||
@classmethod
|
||||
def _scenario(cls, v: str) -> str:
|
||||
s = (v or "").strip().lower()
|
||||
return s if s in VALID_SCENARIOS else "free_search"
|
||||
|
||||
@field_validator("emphasis")
|
||||
@classmethod
|
||||
def _emphasis(cls, v: str) -> str:
|
||||
s = (v or "").strip().lower()
|
||||
return s if s in VALID_EMPHASIS else "additive"
|
||||
|
||||
@field_validator("focus_hints", "style_hints", "training_type_hints", "target_group_hints", mode="before")
|
||||
@classmethod
|
||||
def _str_list(cls, v: Any) -> List[str]:
|
||||
if not v:
|
||||
return []
|
||||
if isinstance(v, str):
|
||||
return [v.strip()] if v.strip() else []
|
||||
out: List[str] = []
|
||||
for item in v:
|
||||
s = str(item or "").strip()
|
||||
if s and s not in out:
|
||||
out.append(s[:120])
|
||||
return out[:8]
|
||||
|
||||
|
||||
def _extract_json_object(text: str) -> Dict[str, Any]:
|
||||
s = (text or "").strip()
|
||||
if s.startswith("```"):
|
||||
s = re.sub(r"^```[a-zA-Z0-9]*\s*", "", s)
|
||||
if s.endswith("```"):
|
||||
s = s[:-3].strip()
|
||||
start = s.find("{")
|
||||
end = s.rfind("}")
|
||||
if start < 0 or end <= start:
|
||||
raise ValueError("Kein JSON-Objekt in LLM-Antwort")
|
||||
obj = json.loads(s[start : end + 1])
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("LLM-Antwort ist kein JSON-Objekt")
|
||||
return obj
|
||||
|
||||
|
||||
def parse_planning_query_intent_response(text: str) -> PlanningQueryIntentParsed:
|
||||
obj = _extract_json_object(text)
|
||||
return PlanningQueryIntentParsed.model_validate(obj)
|
||||
|
||||
|
||||
def _compact_json(obj: Any) -> str:
|
||||
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _load_compact_catalog(cur, table: str, id_col: str, name_col: str = "name", limit: int = 80) -> List[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {id_col} AS id, {name_col} AS name
|
||||
FROM {table}
|
||||
ORDER BY {name_col} ASC NULLS LAST
|
||||
LIMIT %s
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
return [{"id": int(r["id"]), "name": str(r["name"] or "")[:80]} for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _load_skills_catalog_compact(cur, limit: int = 120) -> List[Dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name, category
|
||||
FROM skills
|
||||
WHERE status IS NULL OR status = 'active'
|
||||
ORDER BY name ASC
|
||||
LIMIT %s
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": int(r["id"]),
|
||||
"name": str(r["name"] or "")[:80],
|
||||
"category": str(r.get("category") or "")[:40],
|
||||
}
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
|
||||
def _resolve_name_hint(cur, table: str, hint: str, *, extra_where: str = "") -> Optional[int]:
|
||||
h = (hint or "").strip()
|
||||
if len(h) < 2:
|
||||
return None
|
||||
q = h.lower()
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, name
|
||||
FROM {table}
|
||||
WHERE LOWER(name) LIKE %s {extra_where}
|
||||
ORDER BY CASE WHEN LOWER(name) = %s THEN 0 WHEN LOWER(name) LIKE %s THEN 1 ELSE 2 END,
|
||||
LENGTH(name) ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(f"%{q}%", q, f"{q}%"),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return int(row["id"]) if row else None
|
||||
|
||||
|
||||
def resolve_query_intent_catalog_ids(
|
||||
cur,
|
||||
parsed: PlanningQueryIntentParsed,
|
||||
) -> Tuple[Dict[int, float], Dict[int, float], Dict[int, float], Dict[int, float], Dict[int, float], List[Dict[str, Any]]]:
|
||||
"""
|
||||
Mappt Text-Hints auf Katalog-IDs. Returns (focus, style, tt, tg, skills, resolved_skills_meta).
|
||||
"""
|
||||
focus: Dict[int, float] = {}
|
||||
style: Dict[int, float] = {}
|
||||
tt: Dict[int, float] = {}
|
||||
tg: Dict[int, float] = {}
|
||||
skills: Dict[int, float] = {}
|
||||
resolved_skills: List[Dict[str, Any]] = []
|
||||
|
||||
for hint in parsed.focus_hints:
|
||||
fid = _resolve_name_hint(cur, "focus_areas", hint)
|
||||
if fid:
|
||||
focus[fid] = max(focus.get(fid, 0.0), 0.9)
|
||||
|
||||
for hint in parsed.style_hints:
|
||||
sid = _resolve_name_hint(cur, "style_directions", hint)
|
||||
if sid:
|
||||
style[sid] = max(style.get(sid, 0.0), 0.85)
|
||||
|
||||
for hint in parsed.training_type_hints:
|
||||
tid = _resolve_name_hint(cur, "training_types", hint)
|
||||
if tid:
|
||||
tt[tid] = max(tt.get(tid, 0.0), 0.85)
|
||||
|
||||
for hint in parsed.target_group_hints:
|
||||
gid = _resolve_name_hint(cur, "target_groups", hint)
|
||||
if gid:
|
||||
tg[gid] = max(tg.get(gid, 0.0), 0.85)
|
||||
|
||||
for sh in parsed.skill_hints[:8]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name FROM skills
|
||||
WHERE (status IS NULL OR status = 'active')
|
||||
AND LOWER(name) LIKE %s
|
||||
ORDER BY CASE WHEN LOWER(name) = %s THEN 0 WHEN LOWER(name) LIKE %s THEN 1 ELSE 2 END,
|
||||
LENGTH(name) ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(f"%{sh.name.lower()}%", sh.name.lower(), f"{sh.name.lower()}%"),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
sid = int(row["id"])
|
||||
skills[sid] = max(skills.get(sid, 0.0), float(sh.weight))
|
||||
resolved_skills.append({"skill_id": sid, "name": str(row["name"] or sh.name), "weight": skills[sid]})
|
||||
|
||||
return focus, style, tt, tg, skills, resolved_skills
|
||||
|
||||
|
||||
def try_parse_planning_query_intent(
|
||||
cur,
|
||||
*,
|
||||
query: str,
|
||||
heuristic_intent: str,
|
||||
scenario_hint: str,
|
||||
context_summary: Mapping[str, Any],
|
||||
target_profile_summary: Mapping[str, Any],
|
||||
) -> Tuple[Optional[PlanningQueryIntentParsed], bool]:
|
||||
api_key, _ = normalize_openrouter_env()
|
||||
if not api_key or not (query or "").strip():
|
||||
return None, False
|
||||
|
||||
variables = {
|
||||
"search_query": (query or "").strip(),
|
||||
"heuristic_intent": heuristic_intent or "",
|
||||
"scenario_hint": scenario_hint or "",
|
||||
"planning_context_json": _compact_json(dict(context_summary or {})),
|
||||
"target_profile_json": _compact_json(dict(target_profile_summary or {})),
|
||||
"skills_catalog_json": _compact_json(_load_skills_catalog_compact(cur)),
|
||||
"focus_areas_catalog_json": _compact_json(_load_compact_catalog(cur, "focus_areas", "id")),
|
||||
"training_types_catalog_json": _compact_json(_load_compact_catalog(cur, "training_types", "id")),
|
||||
"style_directions_catalog_json": _compact_json(_load_compact_catalog(cur, "style_directions", "id")),
|
||||
"target_groups_catalog_json": _compact_json(_load_compact_catalog(cur, "target_groups", "id")),
|
||||
}
|
||||
|
||||
try:
|
||||
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_search_intent", variables)
|
||||
model = effective_openrouter_model_for_prompt_row(prow)
|
||||
raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text)
|
||||
parsed = parse_planning_query_intent_response(raw)
|
||||
return parsed, True
|
||||
except AiPromptUnavailableError:
|
||||
return None, False
|
||||
except Exception as exc:
|
||||
_logger.warning("Planungs-Intent-LLM fehlgeschlagen: %s", exc)
|
||||
return None, False
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PlanningQueryIntentParsed",
|
||||
"parse_planning_query_intent_response",
|
||||
"resolve_query_intent_catalog_ids",
|
||||
"try_parse_planning_query_intent",
|
||||
]
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
Phase 2 Planungs-Übungssuche: LLM-Rerank über Hybrid-Kandidaten.
|
||||
|
||||
Prompt-Slug: planning_exercise_search_rank (Migration 072)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||
|
||||
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
||||
from exercise_ai import strip_html_to_plain
|
||||
from openrouter_chat import (
|
||||
effective_openrouter_model_for_prompt_row,
|
||||
normalize_openrouter_env,
|
||||
openrouter_chat_completion,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger("shinkan.planning_exercise_llm_rank")
|
||||
|
||||
_LLM_RERANK_POOL = 32
|
||||
_MAX_GOAL_PLAIN = 480
|
||||
_MAX_SUMMARY_PLAIN = 320
|
||||
_MAX_REASON_LEN = 160
|
||||
|
||||
|
||||
def _compact_json(obj: Any) -> str:
|
||||
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _extract_json_object(text: str) -> Dict[str, Any]:
|
||||
s = (text or "").strip()
|
||||
if s.startswith("```"):
|
||||
s = re.sub(r"^```[a-zA-Z0-9]*\s*", "", s)
|
||||
if s.endswith("```"):
|
||||
s = s[:-3].strip()
|
||||
start = s.find("{")
|
||||
end = s.rfind("}")
|
||||
if start < 0 or end <= start:
|
||||
raise ValueError("Kein JSON-Objekt in LLM-Antwort")
|
||||
obj = json.loads(s[start : end + 1])
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("LLM-Antwort ist kein JSON-Objekt")
|
||||
return obj
|
||||
|
||||
|
||||
def parse_planning_exercise_rank_response(
|
||||
text: str,
|
||||
allowed_ids: Set[int],
|
||||
) -> Tuple[List[int], Dict[int, str]]:
|
||||
"""
|
||||
Validiert LLM-Ranking: nur erlaubte exercise_id, dedupliziert, Reihenfolge beibehalten.
|
||||
"""
|
||||
obj = _extract_json_object(text)
|
||||
ranked_raw = obj.get("ranked_ids") or obj.get("ranked") or obj.get("ids")
|
||||
if not isinstance(ranked_raw, list):
|
||||
raise ValueError("ranked_ids fehlt oder ist keine Liste")
|
||||
|
||||
ranked: List[int] = []
|
||||
seen: Set[int] = set()
|
||||
for raw in ranked_raw:
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid not in allowed_ids or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
ranked.append(eid)
|
||||
|
||||
reasons_out: Dict[int, str] = {}
|
||||
reasons_raw = obj.get("reasons") or obj.get("reasons_by_id") or {}
|
||||
if isinstance(reasons_raw, dict):
|
||||
for k, v in reasons_raw.items():
|
||||
try:
|
||||
eid = int(k)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid not in allowed_ids:
|
||||
continue
|
||||
txt = str(v or "").strip()
|
||||
if txt:
|
||||
reasons_out[eid] = txt[:_MAX_REASON_LEN]
|
||||
|
||||
return ranked, reasons_out
|
||||
|
||||
|
||||
def _build_candidate_payload(
|
||||
hit: Mapping[str, Any],
|
||||
*,
|
||||
goal_plain: str,
|
||||
skill_names: Sequence[str],
|
||||
) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": int(hit["id"]),
|
||||
"title": str(hit.get("title") or "").strip()[:200],
|
||||
"summary": strip_html_to_plain(hit.get("summary"), max_len=_MAX_SUMMARY_PLAIN),
|
||||
"goal": goal_plain,
|
||||
"skills": list(skill_names)[:8],
|
||||
"retrieval_score": float(hit.get("score") or 0.0),
|
||||
}
|
||||
|
||||
|
||||
def _load_exercise_goals(cur, exercise_ids: Sequence[int]) -> Dict[int, str]:
|
||||
ids = [int(x) for x in exercise_ids if int(x) > 0]
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"SELECT id, goal FROM exercises WHERE id IN ({ph})",
|
||||
ids,
|
||||
)
|
||||
return {int(r["id"]): str(r.get("goal") or "") for r in cur.fetchall()}
|
||||
|
||||
|
||||
def _load_skill_names(cur, skill_ids: Sequence[int]) -> Dict[int, str]:
|
||||
ids = sorted({int(x) for x in skill_ids if int(x) > 0})
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(f"SELECT id, name FROM skills WHERE id IN ({ph})", ids)
|
||||
return {int(r["id"]): str(r.get("name") or "") for r in cur.fetchall()}
|
||||
|
||||
|
||||
def try_llm_rerank_planning_hits(
|
||||
cur,
|
||||
*,
|
||||
hits: List[Dict[str, Any]],
|
||||
skills_by_ex: Mapping[int, Set[int]],
|
||||
query: str,
|
||||
intent: str,
|
||||
context_summary: Mapping[str, Any],
|
||||
target_profile_summary: Mapping[str, Any],
|
||||
limit: int,
|
||||
) -> Tuple[List[Dict[str, Any]], bool]:
|
||||
"""
|
||||
Optionaler LLM-Rerank der Top-Kandidaten. Bei Fehler: Original-Reihenfolge, llm_applied=False.
|
||||
"""
|
||||
if not hits:
|
||||
return hits, False
|
||||
|
||||
api_key, _ = normalize_openrouter_env()
|
||||
if not api_key:
|
||||
return hits, False
|
||||
|
||||
pool = hits[:_LLM_RERANK_POOL]
|
||||
allowed_ids = {int(h["id"]) for h in pool}
|
||||
goals = _load_exercise_goals(cur, list(allowed_ids))
|
||||
|
||||
all_skill_ids: Set[int] = set()
|
||||
for eid in allowed_ids:
|
||||
all_skill_ids.update(skills_by_ex.get(eid) or set())
|
||||
skill_name_map = _load_skill_names(cur, list(all_skill_ids))
|
||||
|
||||
candidates: List[Dict[str, Any]] = []
|
||||
for hit in pool:
|
||||
eid = int(hit["id"])
|
||||
sk_ids = sorted(skills_by_ex.get(eid) or set())
|
||||
sk_names = [skill_name_map.get(sid, f"#{sid}") for sid in sk_ids[:8]]
|
||||
goal_plain = strip_html_to_plain(goals.get(eid), max_len=_MAX_GOAL_PLAIN)
|
||||
candidates.append(
|
||||
_build_candidate_payload(hit, goal_plain=goal_plain, skill_names=sk_names)
|
||||
)
|
||||
|
||||
variables = {
|
||||
"search_query": query or "",
|
||||
"intent": intent or "",
|
||||
"planning_context_json": _compact_json(dict(context_summary or {})),
|
||||
"target_profile_json": _compact_json(dict(target_profile_summary or {})),
|
||||
"candidates_json": _compact_json(candidates),
|
||||
"result_limit": str(max(1, min(int(limit), 50))),
|
||||
}
|
||||
|
||||
try:
|
||||
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_search_rank", variables)
|
||||
model = effective_openrouter_model_for_prompt_row(prow)
|
||||
raw = openrouter_chat_completion(
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
user_content=rendered.text,
|
||||
)
|
||||
ranked_ids, llm_reasons = parse_planning_exercise_rank_response(raw, allowed_ids)
|
||||
except AiPromptUnavailableError:
|
||||
return hits, False
|
||||
except Exception as exc:
|
||||
_logger.warning("Planungs-LLM-Rerank fehlgeschlagen: %s", exc)
|
||||
return hits, False
|
||||
|
||||
if not ranked_ids:
|
||||
return hits, False
|
||||
|
||||
hit_by_id = {int(h["id"]): h for h in hits}
|
||||
reranked: List[Dict[str, Any]] = []
|
||||
used: Set[int] = set()
|
||||
for eid in ranked_ids:
|
||||
hit = hit_by_id.get(eid)
|
||||
if not hit:
|
||||
continue
|
||||
used.add(eid)
|
||||
new_hit = dict(hit)
|
||||
reasons = list(hit.get("reasons") or [])
|
||||
llm_reason = llm_reasons.get(eid)
|
||||
if llm_reason and llm_reason not in reasons:
|
||||
reasons.insert(0, llm_reason)
|
||||
new_hit["reasons"] = reasons
|
||||
new_hit["llm_rank"] = len(reranked) + 1
|
||||
reranked.append(new_hit)
|
||||
|
||||
for hit in hits:
|
||||
eid = int(hit["id"])
|
||||
if eid in used:
|
||||
continue
|
||||
reranked.append(dict(hit))
|
||||
|
||||
return reranked[: max(int(limit), len(reranked))], True
|
||||
|
||||
|
||||
__all__ = [
|
||||
"parse_planning_exercise_rank_response",
|
||||
"try_llm_rerank_planning_hits",
|
||||
]
|
||||
@@ -0,0 +1,530 @@
|
||||
"""
|
||||
ExerciseMatchProfile / PlanningTargetProfile — Phase-1-Vorselektion Planungs-Übungssuche.
|
||||
|
||||
Siehe .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md §12–§14
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
||||
|
||||
from planning_exercise_text_signals import (
|
||||
load_framework_planning_text_parts,
|
||||
resolve_planning_text_to_catalog_weights,
|
||||
)
|
||||
from skill_scoring import (
|
||||
ExerciseOccurrence,
|
||||
collect_unit_exercise_occurrences,
|
||||
fetch_exercise_skills_bulk,
|
||||
profile_for_occurrences,
|
||||
_skill_link_multiplier,
|
||||
DEFAULT_ITEM_MINUTES,
|
||||
)
|
||||
|
||||
|
||||
def _ids_to_weights(ids: Sequence[int], primary_id: Optional[int] = None) -> Dict[int, float]:
|
||||
out: Dict[int, float] = {}
|
||||
for raw in ids or []:
|
||||
try:
|
||||
fid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if fid < 1:
|
||||
continue
|
||||
w = 1.0 if primary_id is not None and fid == int(primary_id) else 0.85
|
||||
out[fid] = max(out.get(fid, 0.0), w)
|
||||
return out
|
||||
|
||||
|
||||
def _merge_weight_maps(*maps: Optional[Dict[int, float]], scale: float = 1.0) -> Dict[int, float]:
|
||||
out: Dict[int, float] = {}
|
||||
for m in maps:
|
||||
if not m:
|
||||
continue
|
||||
for k, v in m.items():
|
||||
try:
|
||||
kid = int(k)
|
||||
val = float(v) * scale
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if kid < 1 or val <= 0:
|
||||
continue
|
||||
out[kid] = max(out.get(kid, 0.0), val)
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_weight_map(m: Dict[int, float]) -> Dict[int, float]:
|
||||
if not m:
|
||||
return {}
|
||||
mx = max(m.values())
|
||||
if mx <= 0:
|
||||
return {}
|
||||
return {k: v / mx for k, v in m.items() if v > 0}
|
||||
|
||||
|
||||
def weighted_overlap(a: Dict[int, float], b: Dict[int, float]) -> float:
|
||||
"""Gewichtete Überlappung 0..1 (min-Summe / max-Summe)."""
|
||||
if not a or not b:
|
||||
return 0.0
|
||||
keys = set(a) | set(b)
|
||||
num = sum(min(a.get(k, 0.0), b.get(k, 0.0)) for k in keys)
|
||||
den = sum(max(a.get(k, 0.0), b.get(k, 0.0)) for k in keys)
|
||||
return num / den if den > 0 else 0.0
|
||||
|
||||
|
||||
def gap_coverage(gap: Dict[int, float], candidate: Dict[int, float]) -> float:
|
||||
"""Anteil der Skill-Lücke, den der Kandidat abdeckt (0..1)."""
|
||||
if not gap:
|
||||
return 0.0
|
||||
total_gap = sum(gap.values())
|
||||
if total_gap <= 0:
|
||||
return 0.0
|
||||
covered = sum(min(gap.get(k, 0.0), candidate.get(k, 0.0)) for k in gap)
|
||||
return covered / total_gap
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExerciseMatchProfile:
|
||||
exercise_id: int
|
||||
focus_area_ids: Dict[int, float] = field(default_factory=dict)
|
||||
style_direction_ids: Dict[int, float] = field(default_factory=dict)
|
||||
training_type_ids: Dict[int, float] = field(default_factory=dict)
|
||||
target_group_ids: Dict[int, float] = field(default_factory=dict)
|
||||
skill_weights: Dict[int, float] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"exercise_id": self.exercise_id,
|
||||
"focus_area_ids": self.focus_area_ids,
|
||||
"style_direction_ids": self.style_direction_ids,
|
||||
"training_type_ids": self.training_type_ids,
|
||||
"target_group_ids": self.target_group_ids,
|
||||
"skill_weights": self.skill_weights,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlanningTargetProfile:
|
||||
focus_area_ids: Dict[int, float] = field(default_factory=dict)
|
||||
style_direction_ids: Dict[int, float] = field(default_factory=dict)
|
||||
training_type_ids: Dict[int, float] = field(default_factory=dict)
|
||||
target_group_ids: Dict[int, float] = field(default_factory=dict)
|
||||
skill_weights: Dict[int, float] = field(default_factory=dict)
|
||||
skill_gap_weights: Dict[int, float] = field(default_factory=dict)
|
||||
skill_plan_weights: Dict[int, float] = field(default_factory=dict)
|
||||
sources: List[str] = field(default_factory=list)
|
||||
|
||||
def to_summary_dict(self, cur, limit_skills: int = 5) -> Dict[str, Any]:
|
||||
focus_labels = _load_focus_labels(cur, list(self.focus_area_ids.keys())[:6])
|
||||
top_skills = sorted(self.skill_weights.items(), key=lambda x: -x[1])[:limit_skills]
|
||||
skill_names = _load_skill_names(cur, [s[0] for s in top_skills])
|
||||
return {
|
||||
"sources": list(self.sources),
|
||||
"focus_areas": focus_labels,
|
||||
"top_skills": [
|
||||
{"skill_id": sid, "name": skill_names.get(sid, f"#{sid}"), "weight": round(w, 2)}
|
||||
for sid, w in top_skills
|
||||
],
|
||||
"has_skill_gap": bool(self.skill_gap_weights),
|
||||
}
|
||||
|
||||
|
||||
def _load_focus_labels(cur, ids: Sequence[int]) -> List[str]:
|
||||
if not ids:
|
||||
return []
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"SELECT id, name FROM focus_areas WHERE id IN ({ph}) ORDER BY name",
|
||||
list(ids),
|
||||
)
|
||||
return [f"{r['name'] or r['id']}" for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _load_skill_names(cur, ids: Sequence[int]) -> Dict[int, str]:
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(f"SELECT id, name FROM skills WHERE id IN ({ph})", list(ids))
|
||||
return {int(r["id"]): str(r["name"] or "") for r in cur.fetchall()}
|
||||
|
||||
|
||||
def _skill_weights_from_profile(skills_out: Sequence[Dict[str, Any]]) -> Dict[int, float]:
|
||||
out: Dict[int, float] = {}
|
||||
for row in skills_out or []:
|
||||
sid = row.get("skill_id")
|
||||
if sid is None:
|
||||
continue
|
||||
w = float(row.get("weight") or row.get("score") or 0)
|
||||
if w > 0:
|
||||
out[int(sid)] = w
|
||||
return out
|
||||
|
||||
|
||||
def _single_exercise_skill_weights(
|
||||
skill_rows: Sequence[Dict[str, Any]],
|
||||
*,
|
||||
minutes: float = DEFAULT_ITEM_MINUTES,
|
||||
) -> Dict[int, float]:
|
||||
out: Dict[int, float] = {}
|
||||
for link in skill_rows or []:
|
||||
sid = link.get("skill_id")
|
||||
if sid is None:
|
||||
continue
|
||||
sid = int(sid)
|
||||
mult = _skill_link_multiplier(
|
||||
intensity=link.get("intensity"),
|
||||
required_level=link.get("required_level"),
|
||||
target_level=link.get("target_level"),
|
||||
)
|
||||
w = minutes * mult
|
||||
if w > 0:
|
||||
out[sid] = out.get(sid, 0.0) + w
|
||||
return out
|
||||
|
||||
|
||||
def _load_relation_maps_bulk(
|
||||
cur,
|
||||
exercise_ids: Sequence[int],
|
||||
table: str,
|
||||
id_column: str,
|
||||
) -> Dict[int, Dict[int, float]]:
|
||||
ids = [int(x) for x in exercise_ids if int(x) > 0]
|
||||
if not ids:
|
||||
return {}
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT exercise_id, {id_column} AS rel_id, is_primary
|
||||
FROM {table}
|
||||
WHERE exercise_id IN ({ph})
|
||||
""",
|
||||
ids,
|
||||
)
|
||||
out: Dict[int, Dict[int, float]] = {eid: {} for eid in ids}
|
||||
for row in cur.fetchall():
|
||||
eid = int(row["exercise_id"])
|
||||
rid = int(row["rel_id"])
|
||||
w = 1.0 if row.get("is_primary") else 0.85
|
||||
out.setdefault(eid, {})[rid] = max(out[eid].get(rid, 0.0), w)
|
||||
return out
|
||||
|
||||
|
||||
def load_exercise_match_profiles_bulk(cur, exercise_ids: Sequence[int]) -> Dict[int, ExerciseMatchProfile]:
|
||||
ids = sorted({int(x) for x in exercise_ids if int(x) > 0})
|
||||
if not ids:
|
||||
return {}
|
||||
|
||||
focus_map = _load_relation_maps_bulk(cur, ids, "exercise_focus_areas", "focus_area_id")
|
||||
style_map = _load_relation_maps_bulk(cur, ids, "exercise_style_directions", "style_direction_id")
|
||||
type_map = _load_relation_maps_bulk(cur, ids, "exercise_training_types", "training_type_id")
|
||||
tg_map = _load_relation_maps_bulk(cur, ids, "exercise_target_groups", "target_group_id")
|
||||
skills_bulk = fetch_exercise_skills_bulk(cur, ids)
|
||||
|
||||
profiles: Dict[int, ExerciseMatchProfile] = {}
|
||||
for eid in ids:
|
||||
profiles[eid] = ExerciseMatchProfile(
|
||||
exercise_id=eid,
|
||||
focus_area_ids=focus_map.get(eid, {}),
|
||||
style_direction_ids=style_map.get(eid, {}),
|
||||
training_type_ids=type_map.get(eid, {}),
|
||||
target_group_ids=tg_map.get(eid, {}),
|
||||
skill_weights=_single_exercise_skill_weights(skills_bulk.get(eid, [])),
|
||||
)
|
||||
return profiles
|
||||
|
||||
|
||||
def _resolve_framework_for_unit(cur, unit: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
slot_id = unit.get("framework_slot_id") or unit.get("origin_framework_slot_id")
|
||||
if not slot_id:
|
||||
return None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id AS slot_id, s.framework_program_id, s.sort_order, s.title AS slot_title,
|
||||
fp.title AS framework_title, fp.focus_area_id AS header_focus_area_id
|
||||
FROM training_framework_slots s
|
||||
JOIN training_framework_programs fp ON fp.id = s.framework_program_id
|
||||
WHERE s.id = %s
|
||||
""",
|
||||
(int(slot_id),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _framework_catalog_weights(cur, framework_id: int) -> Tuple[Dict[int, float], Dict[int, float], Dict[int, float], Dict[int, float]]:
|
||||
cur.execute(
|
||||
"SELECT focus_area_id FROM training_framework_programs WHERE id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
hdr = cur.fetchone()
|
||||
header_fa = int(hdr["focus_area_id"]) if hdr and hdr.get("focus_area_id") else None
|
||||
|
||||
cur.execute(
|
||||
"SELECT focus_area_id FROM training_framework_program_focus_areas WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
fa_ids = [int(r["focus_area_id"]) for r in cur.fetchall()]
|
||||
if header_fa and header_fa not in fa_ids:
|
||||
fa_ids.insert(0, header_fa)
|
||||
focus = _ids_to_weights(fa_ids, primary_id=header_fa)
|
||||
|
||||
cur.execute(
|
||||
"SELECT style_direction_id FROM training_framework_program_style_directions WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
style = _ids_to_weights([int(r["style_direction_id"]) for r in cur.fetchall()])
|
||||
|
||||
cur.execute(
|
||||
"SELECT training_type_id FROM training_framework_program_training_types WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
tt = _ids_to_weights([int(r["training_type_id"]) for r in cur.fetchall()])
|
||||
|
||||
cur.execute(
|
||||
"SELECT target_group_id FROM training_framework_program_target_groups WHERE framework_program_id = %s",
|
||||
(framework_id,),
|
||||
)
|
||||
tg = _ids_to_weights([int(r["target_group_id"]) for r in cur.fetchall()])
|
||||
|
||||
return focus, style, tt, tg
|
||||
|
||||
|
||||
def _profile_from_unit_occurrences(cur, unit_id: int) -> Dict[int, float]:
|
||||
occ = collect_unit_exercise_occurrences(cur, int(unit_id))
|
||||
if not occ:
|
||||
return {}
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=None)
|
||||
return _skill_weights_from_profile(prof.get("skills") or [])
|
||||
|
||||
|
||||
def _profile_from_exercise_ids(cur, exercise_ids: Sequence[int]) -> Dict[int, float]:
|
||||
ids = [int(x) for x in exercise_ids if int(x) > 0]
|
||||
if not ids:
|
||||
return {}
|
||||
occ = [ExerciseOccurrence(exercise_id=eid) for eid in ids]
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=None)
|
||||
return _skill_weights_from_profile(prof.get("skills") or [])
|
||||
|
||||
|
||||
def skill_profile_summary_from_exercise_ids(
|
||||
cur,
|
||||
exercise_ids: Sequence[int],
|
||||
*,
|
||||
limit_skills: int = 8,
|
||||
) -> Dict[str, Any]:
|
||||
"""Kompaktes Fähigkeitenprofil für LLM-Kontext und UI."""
|
||||
ids = [int(x) for x in exercise_ids if int(x) > 0]
|
||||
if not ids:
|
||||
return {"exercise_count": 0, "skills": []}
|
||||
occ = [ExerciseOccurrence(exercise_id=eid) for eid in ids]
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=None)
|
||||
skills_out = prof.get("skills") or []
|
||||
top = sorted(skills_out, key=lambda s: -float(s.get("weight") or s.get("score") or 0))[:limit_skills]
|
||||
names = _load_skill_names(cur, [int(s["skill_id"]) for s in top if s.get("skill_id") is not None])
|
||||
return {
|
||||
"exercise_count": len(ids),
|
||||
"skills": [
|
||||
{
|
||||
"skill_id": int(s["skill_id"]),
|
||||
"name": names.get(int(s["skill_id"]), f"#{s['skill_id']}"),
|
||||
"weight": round(float(s.get("weight") or s.get("score") or 0), 3),
|
||||
}
|
||||
for s in top
|
||||
if s.get("skill_id") is not None
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def build_planning_target_profile(
|
||||
cur,
|
||||
*,
|
||||
unit: Dict[str, Any],
|
||||
planned_exercise_ids: Sequence[int],
|
||||
section_planned_exercise_ids: Optional[Sequence[int]] = None,
|
||||
anchor_exercise_id: Optional[int],
|
||||
intent: str,
|
||||
section_guidance_notes: Optional[str] = None,
|
||||
section_title: Optional[str] = None,
|
||||
) -> PlanningTargetProfile:
|
||||
sources: List[str] = []
|
||||
focus: Dict[int, float] = {}
|
||||
style: Dict[int, float] = {}
|
||||
tt: Dict[int, float] = {}
|
||||
tg: Dict[int, float] = {}
|
||||
skill_target: Dict[int, float] = {}
|
||||
skill_plan: Dict[int, float] = {}
|
||||
|
||||
fw = _resolve_framework_for_unit(cur, unit)
|
||||
if fw:
|
||||
fid = int(fw["framework_program_id"])
|
||||
f_focus, f_style, f_tt, f_tg = _framework_catalog_weights(cur, fid)
|
||||
focus = _merge_weight_maps(focus, f_focus)
|
||||
style = _merge_weight_maps(style, f_style)
|
||||
tt = _merge_weight_maps(tt, f_tt)
|
||||
tg = _merge_weight_maps(tg, f_tg)
|
||||
sources.append("framework_catalog")
|
||||
|
||||
slot_id = fw.get("slot_id")
|
||||
cur.execute(
|
||||
"SELECT id FROM training_units WHERE framework_slot_id = %s LIMIT 1",
|
||||
(int(slot_id),),
|
||||
)
|
||||
bp = cur.fetchone()
|
||||
if bp and bp.get("id"):
|
||||
slot_skills = _profile_from_unit_occurrences(cur, int(bp["id"]))
|
||||
if slot_skills:
|
||||
skill_target = _merge_weight_maps(skill_target, slot_skills, scale=1.0)
|
||||
sources.append("framework_slot_skill_profile")
|
||||
if not skill_target:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tu.id FROM training_framework_slots s
|
||||
LEFT JOIN training_units tu ON tu.framework_slot_id = s.id
|
||||
WHERE s.framework_program_id = %s AND tu.id IS NOT NULL
|
||||
""",
|
||||
(fid,),
|
||||
)
|
||||
all_occ: List[ExerciseOccurrence] = []
|
||||
for r in cur.fetchall():
|
||||
all_occ.extend(collect_unit_exercise_occurrences(cur, int(r["id"])))
|
||||
if all_occ:
|
||||
prof = profile_for_occurrences(cur, all_occ, reference_max_by_skill=None)
|
||||
skill_target = _merge_weight_maps(
|
||||
skill_target, _skill_weights_from_profile(prof.get("skills") or []), scale=0.85
|
||||
)
|
||||
sources.append("framework_overall_skill_profile")
|
||||
|
||||
if planned_exercise_ids:
|
||||
occ = [ExerciseOccurrence(exercise_id=int(eid)) for eid in planned_exercise_ids]
|
||||
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=None)
|
||||
skill_plan = _skill_weights_from_profile(prof.get("skills") or [])
|
||||
if skill_plan:
|
||||
sources.append("current_unit_plan")
|
||||
|
||||
section_ids = [int(x) for x in (section_planned_exercise_ids or []) if int(x) > 0]
|
||||
if section_ids:
|
||||
section_skills = _profile_from_exercise_ids(cur, section_ids)
|
||||
if section_skills:
|
||||
skill_target = _merge_weight_maps(skill_target, section_skills, scale=1.0)
|
||||
sources.append("current_section_plan")
|
||||
|
||||
if anchor_exercise_id:
|
||||
anchor_profiles = load_exercise_match_profiles_bulk(cur, [int(anchor_exercise_id)])
|
||||
ap = anchor_profiles.get(int(anchor_exercise_id))
|
||||
if ap:
|
||||
if intent in ("deepen_exercise", "suggest_next", "progression_next", "continue_plan_goal"):
|
||||
skill_target = _merge_weight_maps(skill_target, ap.skill_weights, scale=1.0)
|
||||
focus = _merge_weight_maps(focus, ap.focus_area_ids, scale=0.9)
|
||||
style = _merge_weight_maps(style, ap.style_direction_ids, scale=0.75)
|
||||
tt = _merge_weight_maps(tt, ap.training_type_ids, scale=0.75)
|
||||
tg = _merge_weight_maps(tg, ap.target_group_ids, scale=0.75)
|
||||
sources.append("anchor_exercise")
|
||||
|
||||
text_parts: List[str] = []
|
||||
if (section_title or "").strip():
|
||||
text_parts.append(str(section_title).strip())
|
||||
if (section_guidance_notes or "").strip():
|
||||
text_parts.append(str(section_guidance_notes).strip())
|
||||
if fw:
|
||||
text_parts.extend(
|
||||
load_framework_planning_text_parts(
|
||||
cur,
|
||||
int(fw["framework_program_id"]),
|
||||
slot_id=int(fw["slot_id"]) if fw.get("slot_id") else None,
|
||||
)
|
||||
)
|
||||
if text_parts:
|
||||
blob = "\n".join(text_parts)
|
||||
tf, ts, ttt, ttg, tsk = resolve_planning_text_to_catalog_weights(cur, blob)
|
||||
if tf or ts or ttt or ttg or tsk:
|
||||
focus = _merge_weight_maps(focus, tf, scale=0.88)
|
||||
style = _merge_weight_maps(style, ts, scale=0.8)
|
||||
tt = _merge_weight_maps(tt, ttt, scale=0.8)
|
||||
tg = _merge_weight_maps(tg, ttg, scale=0.8)
|
||||
skill_target = _merge_weight_maps(skill_target, tsk, scale=0.92)
|
||||
sources.append("planning_text_signals")
|
||||
|
||||
skill_target = _normalize_weight_map(skill_target)
|
||||
skill_plan_norm = _normalize_weight_map(skill_plan)
|
||||
skill_gap: Dict[int, float] = {}
|
||||
for sid, tw in skill_target.items():
|
||||
pw = skill_plan_norm.get(sid, 0.0)
|
||||
gap = tw - pw * 0.85
|
||||
if gap > 0.08:
|
||||
skill_gap[sid] = gap
|
||||
if skill_gap:
|
||||
sources.append("skill_gap_vs_plan")
|
||||
|
||||
return PlanningTargetProfile(
|
||||
focus_area_ids=_normalize_weight_map(focus) if focus else focus,
|
||||
style_direction_ids=_normalize_weight_map(style) if style else style,
|
||||
training_type_ids=_normalize_weight_map(tt) if tt else tt,
|
||||
target_group_ids=_normalize_weight_map(tg) if tg else tg,
|
||||
skill_weights=skill_target,
|
||||
skill_gap_weights=_normalize_weight_map(skill_gap) if skill_gap else skill_gap,
|
||||
skill_plan_weights=skill_plan_norm,
|
||||
sources=sources,
|
||||
)
|
||||
|
||||
|
||||
def score_exercise_against_target(
|
||||
exercise: ExerciseMatchProfile,
|
||||
target: PlanningTargetProfile,
|
||||
*,
|
||||
intent: str,
|
||||
) -> Tuple[float, List[str]]:
|
||||
"""Profil-Match 0..1 + deutschsprachige Gründe."""
|
||||
reasons: List[str] = []
|
||||
|
||||
focus_sim = weighted_overlap(exercise.focus_area_ids, target.focus_area_ids)
|
||||
style_sim = weighted_overlap(exercise.style_direction_ids, target.style_direction_ids)
|
||||
tt_sim = weighted_overlap(exercise.training_type_ids, target.training_type_ids)
|
||||
tg_sim = weighted_overlap(exercise.target_group_ids, target.target_group_ids)
|
||||
skill_sim = weighted_overlap(
|
||||
_normalize_weight_map(exercise.skill_weights),
|
||||
target.skill_weights,
|
||||
)
|
||||
gap_sim = gap_coverage(target.skill_gap_weights, _normalize_weight_map(exercise.skill_weights))
|
||||
|
||||
if focus_sim >= 0.5 and target.focus_area_ids:
|
||||
reasons.append("Fokusbereich passend zum Planungsziel")
|
||||
if style_sim >= 0.5 and target.style_direction_ids:
|
||||
reasons.append("Stilrichtung passend")
|
||||
if tt_sim >= 0.5 and target.training_type_ids:
|
||||
reasons.append("Trainingsstil passend")
|
||||
if tg_sim >= 0.5 and target.target_group_ids:
|
||||
reasons.append("Zielgruppe passend")
|
||||
if skill_sim >= 0.35 and target.skill_weights:
|
||||
reasons.append("Fähigkeiten-Schwerpunkt passend (Profilmetrik)")
|
||||
if gap_sim >= 0.25 and target.skill_gap_weights:
|
||||
reasons.append("Deckt Skill-Lücke im bisherigen Plan")
|
||||
if "query_intent" in (target.sources or []):
|
||||
reasons.append("Passt zur KI-interpretierten Suchanfrage")
|
||||
if "planning_text_signals" in (target.sources or []):
|
||||
reasons.append("Passt zu Abschnitts- oder Rahmen-Zieltext")
|
||||
|
||||
# Intent-gewichtete Dimensionen (Summe = 1.0)
|
||||
if intent == INTENT_FREE_SEARCH:
|
||||
weights = {"focus": 0.15, "style": 0.10, "tt": 0.10, "tg": 0.10, "skill": 0.25, "gap": 0.30}
|
||||
elif intent == INTENT_DEEPEN_EXERCISE:
|
||||
weights = {"focus": 0.15, "style": 0.10, "tt": 0.10, "tg": 0.05, "skill": 0.45, "gap": 0.15}
|
||||
elif intent == INTENT_PROGRESSION_NEXT:
|
||||
weights = {"focus": 0.20, "style": 0.10, "tt": 0.10, "tg": 0.05, "skill": 0.35, "gap": 0.20}
|
||||
else:
|
||||
weights = {"focus": 0.20, "style": 0.10, "tt": 0.10, "tg": 0.10, "skill": 0.30, "gap": 0.20}
|
||||
|
||||
score = (
|
||||
weights["focus"] * focus_sim
|
||||
+ weights["style"] * style_sim
|
||||
+ weights["tt"] * tt_sim
|
||||
+ weights["tg"] * tg_sim
|
||||
+ weights["skill"] * skill_sim
|
||||
+ weights["gap"] * gap_sim
|
||||
)
|
||||
return max(0.0, min(1.0, score)), reasons
|
||||
|
||||
|
||||
# Re-export intent constants for typing (avoid circular import at runtime in suggest module)
|
||||
INTENT_FREE_SEARCH = "free_search"
|
||||
INTENT_DEEPEN_EXERCISE = "deepen_exercise"
|
||||
INTENT_PROGRESSION_NEXT = "progression_next"
|
||||
@@ -0,0 +1,210 @@
|
||||
"""
|
||||
Progressionsgraph-Auflösung für Planungs-KI (Phase C1).
|
||||
|
||||
Variantenbewusste Nachfolger-Kanten (Migration 034) und Auto-Match eines sichtbaren Graphen
|
||||
anhand der Anker-Übung, wenn der Client keine graph_id sendet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||
|
||||
from tenant_context import TenantContext, library_content_visibility_sql
|
||||
|
||||
ProgressionSuccessorBundle = Tuple[Set[int], Dict[int, str], Dict[int, Optional[int]]]
|
||||
|
||||
|
||||
def edge_matches_anchor_from(
|
||||
edge: Mapping[str, Any],
|
||||
from_variant_id: Optional[int],
|
||||
) -> bool:
|
||||
"""Kante gilt als Ausgang vom Anker: generische Kante oder passende Varianten-Kante."""
|
||||
edge_var = edge.get("from_exercise_variant_id")
|
||||
if edge_var is None:
|
||||
return True
|
||||
if from_variant_id is None:
|
||||
return False
|
||||
try:
|
||||
return int(edge_var) == int(from_variant_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def filter_outgoing_progression_edges(
|
||||
edges: Sequence[Mapping[str, Any]],
|
||||
*,
|
||||
from_variant_id: Optional[int],
|
||||
) -> List[Mapping[str, Any]]:
|
||||
return [e for e in edges if edge_matches_anchor_from(e, from_variant_id)]
|
||||
|
||||
|
||||
def parse_successors_from_edges(
|
||||
edges: Sequence[Mapping[str, Any]],
|
||||
) -> ProgressionSuccessorBundle:
|
||||
ids: Set[int] = set()
|
||||
notes: Dict[int, str] = {}
|
||||
variants: Dict[int, Optional[int]] = {}
|
||||
for row in edges:
|
||||
tid = int(row["to_exercise_id"])
|
||||
ids.add(tid)
|
||||
n = (row.get("notes") or "").strip()
|
||||
if n:
|
||||
notes[tid] = n
|
||||
raw_v = row.get("to_exercise_variant_id")
|
||||
variants[tid] = int(raw_v) if raw_v is not None else None
|
||||
return ids, notes, variants
|
||||
|
||||
|
||||
def rank_progression_graph_rows(rows: Sequence[Mapping[str, Any]]) -> Optional[Mapping[str, Any]]:
|
||||
if not rows:
|
||||
return None
|
||||
|
||||
def _key(row: Mapping[str, Any]) -> Tuple[int, int, int]:
|
||||
var_match = int(row.get("variant_match_count") or 0)
|
||||
out_count = int(row.get("outgoing_count") or 0)
|
||||
gid = int(row.get("id") or 0)
|
||||
return (var_match, out_count, gid)
|
||||
|
||||
return max(rows, key=_key)
|
||||
|
||||
|
||||
def resolve_progression_graph_for_planning(
|
||||
cur,
|
||||
tenant: TenantContext,
|
||||
*,
|
||||
from_exercise_id: Optional[int],
|
||||
from_variant_id: Optional[int],
|
||||
explicit_graph_id: Optional[int],
|
||||
) -> Tuple[Optional[int], Optional[str], bool]:
|
||||
"""
|
||||
Liefert (graph_id, graph_name, auto_resolved).
|
||||
|
||||
Bei explicit_graph_id: Sichtbarkeit prüfen, kein Auto-Match.
|
||||
Sonst: sichtbarer Graph mit passenden Ausgangskanten vom Anker.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="g",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
|
||||
if explicit_graph_id and int(explicit_graph_id) > 0:
|
||||
gid = int(explicit_graph_id)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.id, g.name
|
||||
FROM exercise_progression_graphs g
|
||||
WHERE g.id = %s AND ({vis_sql})
|
||||
""",
|
||||
[gid, *vis_params],
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None, None, False
|
||||
name = (row.get("name") or "").strip() or None
|
||||
return gid, name, False
|
||||
|
||||
if not from_exercise_id or int(from_exercise_id) < 1:
|
||||
return None, None, False
|
||||
|
||||
anchor_var = int(from_variant_id) if from_variant_id is not None else None
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT g.id, g.name,
|
||||
COUNT(*)::int AS outgoing_count,
|
||||
COUNT(*) FILTER (
|
||||
WHERE e.from_exercise_variant_id IS NOT NULL
|
||||
AND (%s IS NOT NULL)
|
||||
AND e.from_exercise_variant_id = %s
|
||||
)::int AS variant_match_count
|
||||
FROM exercise_progression_edges e
|
||||
INNER JOIN exercise_progression_graphs g ON g.id = e.graph_id
|
||||
WHERE e.from_exercise_id = %s
|
||||
AND LOWER(TRIM(e.edge_type)) = 'next_exercise'
|
||||
AND ({vis_sql})
|
||||
AND (
|
||||
e.from_exercise_variant_id IS NULL
|
||||
OR (%s IS NULL)
|
||||
OR e.from_exercise_variant_id = %s
|
||||
)
|
||||
GROUP BY g.id, g.name
|
||||
""",
|
||||
[anchor_var, anchor_var, int(from_exercise_id), *vis_params, anchor_var, anchor_var],
|
||||
)
|
||||
picked = rank_progression_graph_rows(cur.fetchall())
|
||||
if not picked:
|
||||
return None, None, False
|
||||
gid = int(picked["id"])
|
||||
name = (picked.get("name") or "").strip() or None
|
||||
return gid, name, True
|
||||
|
||||
|
||||
def load_progression_successors_for_anchor(
|
||||
cur,
|
||||
*,
|
||||
graph_id: Optional[int],
|
||||
from_exercise_id: Optional[int],
|
||||
from_variant_id: Optional[int],
|
||||
) -> ProgressionSuccessorBundle:
|
||||
if not graph_id or not from_exercise_id:
|
||||
return set(), {}, {}
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT to_exercise_id, to_exercise_variant_id, notes, from_exercise_variant_id
|
||||
FROM exercise_progression_edges
|
||||
WHERE graph_id = %s AND from_exercise_id = %s
|
||||
AND LOWER(TRIM(edge_type)) = 'next_exercise'
|
||||
""",
|
||||
(int(graph_id), int(from_exercise_id)),
|
||||
)
|
||||
rows = [dict(r) for r in cur.fetchall()]
|
||||
filtered = filter_outgoing_progression_edges(rows, from_variant_id=from_variant_id)
|
||||
return parse_successors_from_edges(filtered)
|
||||
|
||||
|
||||
def apply_progression_context_to_pack(
|
||||
cur,
|
||||
tenant: TenantContext,
|
||||
pack: Dict[str, Any],
|
||||
*,
|
||||
explicit_graph_id: Optional[int],
|
||||
anchor_variant_id: Optional[int],
|
||||
) -> Dict[str, Any]:
|
||||
"""Pack um aufgelösten Graph und Nachfolger anreichern."""
|
||||
anchor_id = pack.get("anchor_exercise_id")
|
||||
pack["anchor_exercise_variant_id"] = anchor_variant_id
|
||||
|
||||
graph_id, graph_name, auto_resolved = resolve_progression_graph_for_planning(
|
||||
cur,
|
||||
tenant,
|
||||
from_exercise_id=anchor_id,
|
||||
from_variant_id=anchor_variant_id,
|
||||
explicit_graph_id=explicit_graph_id,
|
||||
)
|
||||
pack["progression_graph_id"] = graph_id
|
||||
pack["progression_graph_name"] = graph_name
|
||||
pack["progression_graph_auto_resolved"] = bool(auto_resolved)
|
||||
|
||||
succ_ids, notes, succ_variants = load_progression_successors_for_anchor(
|
||||
cur,
|
||||
graph_id=graph_id,
|
||||
from_exercise_id=anchor_id,
|
||||
from_variant_id=anchor_variant_id,
|
||||
)
|
||||
pack["progression_successor_ids"] = sorted(succ_ids)
|
||||
pack["progression_edge_notes"] = notes
|
||||
pack["progression_successor_variants"] = succ_variants
|
||||
return pack
|
||||
|
||||
|
||||
__all__ = [
|
||||
"apply_progression_context_to_pack",
|
||||
"edge_matches_anchor_from",
|
||||
"filter_outgoing_progression_edges",
|
||||
"load_progression_successors_for_anchor",
|
||||
"parse_successors_from_edges",
|
||||
"rank_progression_graph_rows",
|
||||
"resolve_progression_graph_for_planning",
|
||||
]
|
||||
@@ -0,0 +1,329 @@
|
||||
"""
|
||||
Mehrstufiges Retrieval für Planungs-Übungssuche (Phase A).
|
||||
|
||||
Stufen:
|
||||
S1b-0 Gesamte sichtbare Bibliothek (Governance + Hard-Filter, kein Profil-OR-Pool)
|
||||
S1b-1 Deterministischer Hybrid-Score auf allen Kandidaten → sortiert
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||
|
||||
from planning_exercise_profiles import (
|
||||
PlanningTargetProfile,
|
||||
load_exercise_match_profiles_bulk,
|
||||
score_exercise_against_target,
|
||||
)
|
||||
|
||||
_MAX_LIBRARY_ROWS = 8000
|
||||
_PROFILE_LOAD_BATCH = 400
|
||||
_PARTNER_TEXT_MARKERS = ("partner", "paar", "paarweise", "zu zweit")
|
||||
|
||||
|
||||
def _exercise_looks_partner_related(row: Mapping[str, Any]) -> bool:
|
||||
parts = [
|
||||
str(row.get("method_archetype") or ""),
|
||||
str(row.get("title") or ""),
|
||||
str(row.get("summary") or ""),
|
||||
]
|
||||
blob = " ".join(parts).lower()
|
||||
return any(m in blob for m in _PARTNER_TEXT_MARKERS)
|
||||
|
||||
|
||||
def _skill_jaccard(a: Set[int], b: Set[int]) -> float:
|
||||
if not a or not b:
|
||||
return 0.0
|
||||
inter = len(a & b)
|
||||
union = len(a | b)
|
||||
return inter / union if union else 0.0
|
||||
|
||||
|
||||
def _normalize_exercise_kind_filter(exercise_kind_any: Optional[List[str]]) -> List[str]:
|
||||
out: List[str] = []
|
||||
if not exercise_kind_any:
|
||||
return out
|
||||
for raw in exercise_kind_any:
|
||||
s = str(raw or "").strip().lower()
|
||||
if s in ("simple", "combination") and s not in out:
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
def fetch_all_visible_exercise_rows(
|
||||
cur,
|
||||
*,
|
||||
vis_sql: str,
|
||||
vis_params: Sequence[Any],
|
||||
query: str,
|
||||
exercise_kind_any: Optional[List[str]],
|
||||
max_rows: int = _MAX_LIBRARY_ROWS,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
S1b-0: Alle sichtbaren Übungen (ohne Profil-/Volltext-Pool-Vorselektion).
|
||||
|
||||
Hard-Filter: Governance, nicht archiviert, optional exercise_kind.
|
||||
Volltext-Rank nur als Score-Signal in SELECT, nicht als WHERE-Filter.
|
||||
"""
|
||||
where = [vis_sql, "COALESCE(e.status, '') <> %s"]
|
||||
params: List[Any] = []
|
||||
|
||||
if query:
|
||||
ft_select = "ts_rank_cd(e.search_vector, plainto_tsquery('german', %s)) AS ft_rank"
|
||||
params.append(query)
|
||||
else:
|
||||
ft_select = "0.0::float AS ft_rank"
|
||||
|
||||
params.extend(vis_params)
|
||||
params.append("archived")
|
||||
|
||||
ek_filtered = _normalize_exercise_kind_filter(exercise_kind_any)
|
||||
if ek_filtered:
|
||||
ph = ",".join(["%s"] * len(ek_filtered))
|
||||
where.append(f"(LOWER(TRIM(COALESCE(e.exercise_kind::text,''))) IN ({ph}))")
|
||||
params.extend(ek_filtered)
|
||||
|
||||
sql = f"""
|
||||
SELECT e.id, e.title, e.summary, e.method_archetype,
|
||||
(
|
||||
SELECT fa.name FROM exercise_focus_areas efa
|
||||
JOIN focus_areas fa ON fa.id = efa.focus_area_id
|
||||
WHERE efa.exercise_id = e.id
|
||||
ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC
|
||||
LIMIT 1
|
||||
) AS primary_focus_name,
|
||||
{ft_select}
|
||||
FROM exercises e
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY e.id ASC
|
||||
LIMIT %s
|
||||
"""
|
||||
params.append(int(max_rows))
|
||||
cur.execute(sql, params)
|
||||
return [dict(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _load_match_profiles_chunked(cur, exercise_ids: Sequence[int], *, batch: int = _PROFILE_LOAD_BATCH):
|
||||
ids = sorted({int(x) for x in exercise_ids if int(x) > 0})
|
||||
if not ids:
|
||||
return {}
|
||||
out: Dict[int, Any] = {}
|
||||
for i in range(0, len(ids), batch):
|
||||
chunk = ids[i : i + batch]
|
||||
out.update(load_exercise_match_profiles_bulk(cur, chunk))
|
||||
return out
|
||||
|
||||
|
||||
def _load_skill_sets_chunked(cur, exercise_ids: Sequence[int], *, batch: int = _PROFILE_LOAD_BATCH) -> Dict[int, Set[int]]:
|
||||
ids = sorted({int(x) for x in exercise_ids if int(x) > 0})
|
||||
out: Dict[int, Set[int]] = {eid: set() for eid in ids}
|
||||
if not ids:
|
||||
return out
|
||||
for i in range(0, len(ids), batch):
|
||||
chunk = ids[i : i + batch]
|
||||
ph = ",".join(["%s"] * len(chunk))
|
||||
cur.execute(
|
||||
f"SELECT exercise_id, skill_id FROM exercise_skills WHERE exercise_id IN ({ph})",
|
||||
chunk,
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
eid = int(row["exercise_id"])
|
||||
sid = row.get("skill_id")
|
||||
if sid is not None:
|
||||
out.setdefault(eid, set()).add(int(sid))
|
||||
return out
|
||||
|
||||
|
||||
def rank_visible_library_hits(
|
||||
cur,
|
||||
rows: Sequence[Dict[str, Any]],
|
||||
*,
|
||||
query: str,
|
||||
intent: str,
|
||||
intent_weights: Mapping[str, float],
|
||||
target: PlanningTargetProfile,
|
||||
pack: Mapping[str, Any],
|
||||
) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]]]:
|
||||
"""S1b-1: Hybrid-Score auf der gesamten sichtbaren Bibliothek."""
|
||||
planned_set = set(pack.get("planned_exercise_ids") or [])
|
||||
group_recent_set = set(pack.get("group_recent_exercise_ids") or [])
|
||||
progression_set = set(pack.get("progression_successor_ids") or [])
|
||||
anchor_skills = set(pack.get("anchor_skill_ids") or [])
|
||||
anchor_id = pack.get("anchor_exercise_id")
|
||||
progression_notes = pack.get("progression_edge_notes") or {}
|
||||
requires_partner = pack.get("requires_partner")
|
||||
|
||||
last_planned_skills: Set[int] = set()
|
||||
planned_ids = pack.get("planned_exercise_ids") or []
|
||||
if planned_ids:
|
||||
cur.execute(
|
||||
"SELECT skill_id FROM exercise_skills WHERE exercise_id = %s",
|
||||
(int(planned_ids[-1]),),
|
||||
)
|
||||
last_planned_skills = {int(r["skill_id"]) for r in cur.fetchall() if r.get("skill_id")}
|
||||
|
||||
cand_rows: List[Dict[str, Any]] = []
|
||||
for row in rows:
|
||||
eid = int(row["id"])
|
||||
if anchor_id and eid == int(anchor_id):
|
||||
continue
|
||||
if requires_partner is True and not _exercise_looks_partner_related(row):
|
||||
continue
|
||||
if requires_partner is False and _exercise_looks_partner_related(row):
|
||||
continue
|
||||
cand_rows.append(row)
|
||||
|
||||
cand_ids = [int(r["id"]) for r in cand_rows]
|
||||
match_profiles = _load_match_profiles_chunked(cur, cand_ids)
|
||||
skills_by_ex = _load_skill_sets_chunked(cur, cand_ids)
|
||||
|
||||
max_ft = 0.0
|
||||
scored_items: List[Dict[str, Any]] = []
|
||||
for row in cand_rows:
|
||||
eid = int(row["id"])
|
||||
ft = float(row.get("ft_rank") or 0.0)
|
||||
if ft > max_ft:
|
||||
max_ft = ft
|
||||
scored_items.append(
|
||||
{
|
||||
"row": row,
|
||||
"eid": eid,
|
||||
"ft": ft,
|
||||
"skills": skills_by_ex.get(eid, set()),
|
||||
}
|
||||
)
|
||||
|
||||
weights = dict(intent_weights)
|
||||
hits: List[Dict[str, Any]] = []
|
||||
for item in scored_items:
|
||||
eid = item["eid"]
|
||||
row = item["row"]
|
||||
ft_norm = (item["ft"] / max_ft) if max_ft > 0 else 0.0
|
||||
prog_hit = 1.0 if eid in progression_set else 0.0
|
||||
skill_sim = _skill_jaccard(anchor_skills, item["skills"]) if anchor_skills else 0.0
|
||||
plan_aff = 0.0
|
||||
if last_planned_skills and item["skills"]:
|
||||
plan_aff = _skill_jaccard(last_planned_skills, item["skills"])
|
||||
repeat_unit = 1.0 if eid in planned_set else 0.0
|
||||
repeat_group = 1.0 if eid in group_recent_set else 0.0
|
||||
profile_score = 0.0
|
||||
profile_reasons: List[str] = []
|
||||
emp = match_profiles.get(eid)
|
||||
if emp:
|
||||
profile_score, profile_reasons = score_exercise_against_target(
|
||||
emp, target, intent=intent
|
||||
)
|
||||
|
||||
score = (
|
||||
weights["fulltext"] * ft_norm
|
||||
+ weights["progression"] * prog_hit
|
||||
+ weights["skill"] * skill_sim
|
||||
+ weights["plan"] * plan_aff
|
||||
+ weights["profile"] * profile_score
|
||||
+ weights["repeat_unit"] * repeat_unit
|
||||
+ weights["repeat_group"] * repeat_group
|
||||
)
|
||||
|
||||
reasons: List[str] = []
|
||||
if query and ft_norm >= 0.35:
|
||||
reasons.append("Volltext-Treffer")
|
||||
if prog_hit > 0:
|
||||
note = progression_notes.get(eid)
|
||||
reasons.append(
|
||||
f"Nachfolger im Progressionsgraph{f': {note}' if note else ''}"
|
||||
)
|
||||
if skill_sim >= 0.2 and anchor_id:
|
||||
reasons.append("Fähigkeiten passen zur Anker-Übung")
|
||||
if plan_aff >= 0.25:
|
||||
reasons.append("Schließt an Skills der letzten geplanten Übung an")
|
||||
if repeat_unit > 0:
|
||||
reasons.append("Bereits in dieser Einheit eingeplant")
|
||||
if repeat_group > 0 and repeat_unit <= 0:
|
||||
reasons.append("Kürzlich in der Gruppe verwendet")
|
||||
for pr in profile_reasons:
|
||||
if pr not in reasons:
|
||||
reasons.append(pr)
|
||||
|
||||
if score <= 0 and not reasons and not query:
|
||||
if prog_hit or skill_sim or plan_aff or profile_score:
|
||||
score = 0.05 + prog_hit * 0.3 + skill_sim * 0.2 + profile_score * 0.25
|
||||
|
||||
hits.append(
|
||||
{
|
||||
"id": eid,
|
||||
"title": row.get("title"),
|
||||
"summary": row.get("summary"),
|
||||
"focus_area": row.get("primary_focus_name"),
|
||||
"score": round(max(0.0, min(1.0, score)), 4),
|
||||
"reasons": reasons,
|
||||
}
|
||||
)
|
||||
succ_variants = pack.get("progression_successor_variants") or {}
|
||||
suggested_vid = succ_variants.get(eid)
|
||||
if suggested_vid:
|
||||
hits[-1]["suggested_variant_id"] = int(suggested_vid)
|
||||
|
||||
hits.sort(key=lambda h: (-h["score"], h.get("title") or ""))
|
||||
return hits, skills_by_ex
|
||||
|
||||
|
||||
def run_multistage_planning_retrieval(
|
||||
cur,
|
||||
*,
|
||||
vis_sql: str,
|
||||
vis_params: Sequence[Any],
|
||||
query: str,
|
||||
exercise_kind_any: Optional[List[str]],
|
||||
target: PlanningTargetProfile,
|
||||
intent: str,
|
||||
intent_weights: Mapping[str, float],
|
||||
pack: Mapping[str, Any],
|
||||
) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]], bool]:
|
||||
"""Orchestriert S1b-0 → S1b-1 (Voll-Library-Ranking)."""
|
||||
rows = fetch_all_visible_exercise_rows(
|
||||
cur,
|
||||
vis_sql=vis_sql,
|
||||
vis_params=vis_params,
|
||||
query=query,
|
||||
exercise_kind_any=exercise_kind_any,
|
||||
)
|
||||
hits, skills_by_ex = rank_visible_library_hits(
|
||||
cur,
|
||||
rows,
|
||||
query=query,
|
||||
intent=intent,
|
||||
intent_weights=intent_weights,
|
||||
target=target,
|
||||
pack=pack,
|
||||
)
|
||||
full_library_ranked = len(rows) > 0
|
||||
return hits, skills_by_ex, full_library_ranked
|
||||
|
||||
|
||||
# Legacy-Alias für Tests / externe Imports
|
||||
fetch_retrieval_candidate_rows = fetch_all_visible_exercise_rows
|
||||
hybrid_score_planning_hits = rank_visible_library_hits
|
||||
|
||||
|
||||
def profile_preselect_rows(
|
||||
cur,
|
||||
rows: Sequence[Dict[str, Any]],
|
||||
*,
|
||||
target: PlanningTargetProfile,
|
||||
intent: str,
|
||||
progression_successor_ids: Set[int],
|
||||
query: str,
|
||||
preselect_limit: int = 160,
|
||||
) -> Tuple[List[Dict[str, Any]], bool]:
|
||||
"""Deprecated: Phase A rankt die volle Library — keine separate Vorselektion."""
|
||||
_ = (cur, target, intent, progression_successor_ids, query, preselect_limit)
|
||||
return list(rows), False
|
||||
|
||||
|
||||
__all__ = [
|
||||
"fetch_all_visible_exercise_rows",
|
||||
"fetch_retrieval_candidate_rows",
|
||||
"hybrid_score_planning_hits",
|
||||
"profile_preselect_rows",
|
||||
"rank_visible_library_hits",
|
||||
"run_multistage_planning_retrieval",
|
||||
]
|
||||
@@ -0,0 +1,845 @@
|
||||
"""
|
||||
Planungs-KI P0: Kontext-Pack + Hybrid-Retrieval für Übungssuche in der Trainingsplanung.
|
||||
|
||||
Siehe .claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||
|
||||
from fastapi import HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from tenant_context import TenantContext, library_content_visibility_sql
|
||||
from planning_exercise_profiles import skill_profile_summary_from_exercise_ids
|
||||
from planning_exercise_retrieval import run_multistage_planning_retrieval
|
||||
from planning_exercise_llm_rank import try_llm_rerank_planning_hits
|
||||
from planning_exercise_progression import apply_progression_context_to_pack
|
||||
from planning_exercise_target_pipeline import (
|
||||
build_planning_target_with_query_pipeline,
|
||||
compose_retrieval_phase,
|
||||
should_run_llm_rank_pipeline,
|
||||
)
|
||||
|
||||
# Planungs-Berechtigung + Sektionen (bestehende Implementierung)
|
||||
from routers.training_planning import (
|
||||
_assert_training_unit_permission,
|
||||
_fetch_sections,
|
||||
_has_planning_role,
|
||||
)
|
||||
|
||||
INTENT_SUGGEST_NEXT = "suggest_next"
|
||||
INTENT_PROGRESSION_NEXT = "progression_next"
|
||||
INTENT_DEEPEN_EXERCISE = "deepen_exercise"
|
||||
INTENT_CONTINUE_PLAN = "continue_plan_goal"
|
||||
INTENT_FREE_SEARCH = "free_search"
|
||||
|
||||
VALID_INTENTS = {
|
||||
INTENT_SUGGEST_NEXT,
|
||||
INTENT_PROGRESSION_NEXT,
|
||||
INTENT_DEEPEN_EXERCISE,
|
||||
INTENT_CONTINUE_PLAN,
|
||||
INTENT_FREE_SEARCH,
|
||||
}
|
||||
|
||||
|
||||
_LLM_RERANK_PRE_LIMIT = 32
|
||||
|
||||
|
||||
class PlanningExerciseSuggestRequest(BaseModel):
|
||||
unit_id: Optional[int] = Field(default=None, ge=1)
|
||||
group_id: Optional[int] = Field(default=None, ge=1)
|
||||
section_order_index: Optional[int] = Field(default=None, ge=0)
|
||||
phase_order_index: Optional[int] = Field(default=None, ge=0)
|
||||
parallel_stream_order_index: Optional[int] = Field(default=None, ge=0)
|
||||
anchor_exercise_id: Optional[int] = Field(default=None, ge=1)
|
||||
anchor_exercise_variant_id: Optional[int] = Field(default=None, ge=1)
|
||||
progression_graph_id: Optional[int] = Field(default=None, ge=1)
|
||||
query: Optional[str] = ""
|
||||
intent_hint: Optional[str] = None
|
||||
planned_exercise_ids: Optional[List[int]] = None
|
||||
section_title: Optional[str] = None
|
||||
section_guidance_notes: Optional[str] = None
|
||||
section_planned_exercise_ids: Optional[List[int]] = None
|
||||
include_llm_intent: bool = True
|
||||
include_llm_rank: bool = False
|
||||
limit: int = Field(default=20, ge=1, le=50)
|
||||
exercise_kind_any: Optional[List[str]] = None
|
||||
|
||||
|
||||
def resolve_planning_exercise_intent(query: Optional[str], intent_hint: Optional[str]) -> str:
|
||||
hint = (intent_hint or "").strip().lower()
|
||||
if hint in VALID_INTENTS:
|
||||
return hint
|
||||
q = (query or "").strip().lower()
|
||||
if not q:
|
||||
return INTENT_SUGGEST_NEXT
|
||||
if any(w in q for w in ("nächste", "naechste", "vorschlag", "vorschlagen", "empfehl")):
|
||||
return INTENT_SUGGEST_NEXT
|
||||
if "vertief" in q:
|
||||
return INTENT_DEEPEN_EXERCISE
|
||||
if "progression" in q or "graph" in q or "pfad" in q:
|
||||
return INTENT_PROGRESSION_NEXT
|
||||
if "aufbau" in q or "planung" in q or "bisher" in q:
|
||||
return INTENT_CONTINUE_PLAN
|
||||
return INTENT_FREE_SEARCH
|
||||
|
||||
|
||||
def _intent_weights(intent: str) -> Dict[str, float]:
|
||||
base = {
|
||||
"fulltext": 0.18,
|
||||
"progression": 0.18,
|
||||
"skill": 0.12,
|
||||
"plan": 0.08,
|
||||
"profile": 0.22,
|
||||
"repeat_unit": -0.30,
|
||||
"repeat_group": -0.15,
|
||||
}
|
||||
if intent == INTENT_SUGGEST_NEXT:
|
||||
return {
|
||||
**base,
|
||||
"progression": 0.28,
|
||||
"skill": 0.12,
|
||||
"plan": 0.10,
|
||||
"profile": 0.25,
|
||||
"fulltext": 0.08,
|
||||
}
|
||||
if intent == INTENT_PROGRESSION_NEXT:
|
||||
return {**base, "progression": 0.42, "fulltext": 0.12, "skill": 0.10, "profile": 0.20}
|
||||
if intent == INTENT_DEEPEN_EXERCISE:
|
||||
return {**base, "skill": 0.15, "profile": 0.35, "fulltext": 0.15, "progression": 0.10}
|
||||
if intent == INTENT_CONTINUE_PLAN:
|
||||
return {**base, "plan": 0.12, "skill": 0.10, "profile": 0.30, "fulltext": 0.10, "progression": 0.08}
|
||||
if intent == INTENT_FREE_SEARCH:
|
||||
return {**base, "fulltext": 0.45, "progression": 0.08, "skill": 0.08, "profile": 0.15}
|
||||
return base
|
||||
|
||||
|
||||
def _collect_planned_exercise_ids(sections: Sequence[Dict[str, Any]]) -> List[int]:
|
||||
out: List[int] = []
|
||||
seen: Set[int] = set()
|
||||
for sec in sorted(sections, key=lambda s: int(s.get("order_index") or 0)):
|
||||
items = sec.get("items") or []
|
||||
for it in sorted(items, key=lambda x: int(x.get("order_index") or 0)):
|
||||
if str(it.get("item_type") or "").strip().lower() == "note":
|
||||
continue
|
||||
raw = it.get("exercise_id")
|
||||
if raw is None:
|
||||
continue
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
out.append(eid)
|
||||
return out
|
||||
|
||||
|
||||
def _resolve_anchor_from_plan(
|
||||
planned_ids: Sequence[int],
|
||||
anchor_exercise_id: Optional[int],
|
||||
) -> Optional[int]:
|
||||
if anchor_exercise_id and int(anchor_exercise_id) > 0:
|
||||
return int(anchor_exercise_id)
|
||||
if planned_ids:
|
||||
return int(planned_ids[-1])
|
||||
return None
|
||||
|
||||
|
||||
def _load_exercise_titles(cur, exercise_ids: Sequence[int]) -> Dict[int, str]:
|
||||
if not exercise_ids:
|
||||
return {}
|
||||
ids = list(dict.fromkeys(int(x) for x in exercise_ids if int(x) > 0))
|
||||
ph = ",".join(["%s"] * len(ids))
|
||||
cur.execute(
|
||||
f"SELECT id, title FROM exercises WHERE id IN ({ph})",
|
||||
ids,
|
||||
)
|
||||
return {int(r["id"]): str(r["title"] or "").strip() for r in cur.fetchall()}
|
||||
|
||||
|
||||
def _load_skill_ids_for_exercise(cur, exercise_id: Optional[int]) -> Set[int]:
|
||||
if not exercise_id:
|
||||
return set()
|
||||
cur.execute(
|
||||
"SELECT skill_id FROM exercise_skills WHERE exercise_id = %s",
|
||||
(int(exercise_id),),
|
||||
)
|
||||
return {int(r["skill_id"]) for r in cur.fetchall() if r.get("skill_id")}
|
||||
|
||||
|
||||
def _resolve_anchor_variant_id(
|
||||
pack: Mapping[str, Any],
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
sections: Optional[Sequence[Dict[str, Any]]] = None,
|
||||
) -> Optional[int]:
|
||||
raw = body.anchor_exercise_variant_id
|
||||
if raw is not None:
|
||||
try:
|
||||
vid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
vid = 0
|
||||
if vid > 0:
|
||||
return vid
|
||||
anchor_id = pack.get("anchor_exercise_id")
|
||||
if not anchor_id or not sections:
|
||||
return None
|
||||
sec = _section_for_context(sections, pack.get("section_order_index"))
|
||||
if not sec:
|
||||
return None
|
||||
target = int(anchor_id)
|
||||
for it in sorted(sec.get("items") or [], key=lambda x: int(x.get("order_index") or 0), reverse=True):
|
||||
if str(it.get("item_type") or "").strip().lower() == "note":
|
||||
continue
|
||||
try:
|
||||
eid = int(it.get("exercise_id"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid != target:
|
||||
continue
|
||||
raw_v = it.get("exercise_variant_id")
|
||||
if raw_v is None:
|
||||
return None
|
||||
try:
|
||||
vid = int(raw_v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return vid if vid > 0 else None
|
||||
return None
|
||||
|
||||
|
||||
def _enrich_planning_hits_with_variant_meta(
|
||||
cur,
|
||||
hits: Sequence[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Variantennamen und -listen für Treffer mit suggested_variant_id (Phase C2)."""
|
||||
if not hits:
|
||||
return []
|
||||
variant_ids: Set[int] = set()
|
||||
exercise_ids: Set[int] = set()
|
||||
for h in hits:
|
||||
exercise_ids.add(int(h["id"]))
|
||||
raw = h.get("suggested_variant_id")
|
||||
if raw is not None:
|
||||
try:
|
||||
vid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
vid = 0
|
||||
if vid > 0:
|
||||
variant_ids.add(vid)
|
||||
|
||||
names_by_variant: Dict[int, str] = {}
|
||||
if variant_ids:
|
||||
ph = ",".join(["%s"] * len(variant_ids))
|
||||
cur.execute(
|
||||
f"SELECT id, variant_name FROM exercise_variants WHERE id IN ({ph})",
|
||||
list(variant_ids),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
n = (row.get("variant_name") or "").strip()
|
||||
if n:
|
||||
names_by_variant[int(row["id"])] = n
|
||||
|
||||
variants_by_exercise: Dict[int, List[Dict[str, Any]]] = {}
|
||||
if exercise_ids:
|
||||
ph = ",".join(["%s"] * len(exercise_ids))
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT exercise_id, id, variant_name, sequence_order
|
||||
FROM exercise_variants
|
||||
WHERE exercise_id IN ({ph})
|
||||
ORDER BY exercise_id, sequence_order NULLS LAST, id
|
||||
""",
|
||||
list(exercise_ids),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
eid = int(row["exercise_id"])
|
||||
variants_by_exercise.setdefault(eid, []).append(
|
||||
{
|
||||
"id": int(row["id"]),
|
||||
"variant_name": (row.get("variant_name") or "").strip() or None,
|
||||
"sequence_order": row.get("sequence_order"),
|
||||
}
|
||||
)
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
for h in hits:
|
||||
item = dict(h)
|
||||
eid = int(item["id"])
|
||||
vars_for_ex = variants_by_exercise.get(eid) or []
|
||||
if vars_for_ex:
|
||||
item["variants"] = vars_for_ex
|
||||
raw_vid = item.get("suggested_variant_id")
|
||||
if raw_vid is not None:
|
||||
try:
|
||||
vid = int(raw_vid)
|
||||
except (TypeError, ValueError):
|
||||
vid = 0
|
||||
if vid > 0:
|
||||
item["suggested_variant_name"] = names_by_variant.get(vid)
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _finalize_progression_context(
|
||||
cur,
|
||||
tenant: TenantContext,
|
||||
pack: Dict[str, Any],
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
*,
|
||||
sections: Optional[Sequence[Dict[str, Any]]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
anchor_variant = _resolve_anchor_variant_id(pack, body, sections)
|
||||
return apply_progression_context_to_pack(
|
||||
cur,
|
||||
tenant,
|
||||
pack,
|
||||
explicit_graph_id=body.progression_graph_id,
|
||||
anchor_variant_id=anchor_variant,
|
||||
)
|
||||
|
||||
|
||||
def _load_group_recent_exercise_ids(
|
||||
cur,
|
||||
group_id: Optional[int],
|
||||
exclude_unit_id: Optional[int] = None,
|
||||
limit: int = 40,
|
||||
) -> Set[int]:
|
||||
if not group_id:
|
||||
return set()
|
||||
if exclude_unit_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tusi.exercise_id AS eid
|
||||
FROM training_units tu
|
||||
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
|
||||
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
|
||||
WHERE tu.group_id = %s
|
||||
AND tu.id <> %s
|
||||
AND tusi.exercise_id IS NOT NULL
|
||||
AND COALESCE(tu.status, '') <> 'cancelled'
|
||||
ORDER BY tu.planned_date DESC NULLS LAST, tu.id DESC, tusi.order_index DESC
|
||||
LIMIT 200
|
||||
""",
|
||||
(int(group_id), int(exclude_unit_id)),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tusi.exercise_id AS eid
|
||||
FROM training_units tu
|
||||
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
|
||||
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
|
||||
WHERE tu.group_id = %s
|
||||
AND tusi.exercise_id IS NOT NULL
|
||||
AND COALESCE(tu.status, '') <> 'cancelled'
|
||||
ORDER BY tu.planned_date DESC NULLS LAST, tu.id DESC, tusi.order_index DESC
|
||||
LIMIT 200
|
||||
""",
|
||||
(int(group_id),),
|
||||
)
|
||||
out: Set[int] = set()
|
||||
for r in cur.fetchall():
|
||||
if r.get("eid") is None:
|
||||
continue
|
||||
out.add(int(r["eid"]))
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _section_for_context(
|
||||
sections: Sequence[Dict[str, Any]],
|
||||
section_order_index: Optional[int],
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if section_order_index is None:
|
||||
return None
|
||||
target = int(section_order_index)
|
||||
for sec in sections:
|
||||
if int(sec.get("order_index") or -1) == target:
|
||||
return sec
|
||||
if 0 <= target < len(sections):
|
||||
return sections[target]
|
||||
return None
|
||||
|
||||
|
||||
def _collect_exercise_ids_from_section(sec: Optional[Dict[str, Any]]) -> List[int]:
|
||||
if not sec:
|
||||
return []
|
||||
out: List[int] = []
|
||||
seen: Set[int] = set()
|
||||
for it in sorted(sec.get("items") or [], key=lambda x: int(x.get("order_index") or 0)):
|
||||
if str(it.get("item_type") or "").strip().lower() == "note":
|
||||
continue
|
||||
raw = it.get("exercise_id")
|
||||
if raw is None:
|
||||
continue
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
out.append(eid)
|
||||
return out
|
||||
|
||||
|
||||
def _resolve_last_exercise_in_section(sec: Optional[Dict[str, Any]]) -> Tuple[Optional[int], Optional[str]]:
|
||||
if not sec:
|
||||
return None, None
|
||||
last_id: Optional[int] = None
|
||||
last_title: Optional[str] = None
|
||||
for it in sorted(sec.get("items") or [], key=lambda x: int(x.get("order_index") or 0)):
|
||||
if str(it.get("item_type") or "").strip().lower() == "note":
|
||||
continue
|
||||
raw = it.get("exercise_id")
|
||||
if raw is None:
|
||||
continue
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1:
|
||||
continue
|
||||
last_id = eid
|
||||
t = (it.get("exercise_title") or "").strip()
|
||||
last_title = t or None
|
||||
return last_id, last_title
|
||||
|
||||
|
||||
def _attach_planning_context_details(
|
||||
cur,
|
||||
pack: Dict[str, Any],
|
||||
*,
|
||||
sections: Optional[Sequence[Dict[str, Any]]] = None,
|
||||
body: Optional[PlanningExerciseSuggestRequest] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Abschnitt, Fähigkeitenprofile und letzte Übung anreichern."""
|
||||
sec: Optional[Dict[str, Any]] = None
|
||||
section_idx = pack.get("section_order_index")
|
||||
if sections is not None and section_idx is not None:
|
||||
sec = _section_for_context(sections, section_idx)
|
||||
|
||||
section_ids = _collect_exercise_ids_from_section(sec)
|
||||
if body and body.section_planned_exercise_ids:
|
||||
section_ids = []
|
||||
seen: Set[int] = set()
|
||||
for raw in body.section_planned_exercise_ids:
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
section_ids.append(eid)
|
||||
elif pack.get("section_planned_exercise_ids"):
|
||||
section_ids = list(pack.get("section_planned_exercise_ids") or [])
|
||||
|
||||
section_title = pack.get("section_title")
|
||||
if body and (body.section_title or "").strip():
|
||||
section_title = (body.section_title or "").strip()
|
||||
elif sec and (sec.get("title") or "").strip():
|
||||
section_title = (sec.get("title") or "").strip()
|
||||
|
||||
guidance = None
|
||||
if body and (body.section_guidance_notes or "").strip():
|
||||
guidance = (body.section_guidance_notes or "").strip()
|
||||
elif sec and (sec.get("guidance_notes") or "").strip():
|
||||
guidance = (sec.get("guidance_notes") or "").strip()
|
||||
|
||||
last_in_section_id, last_in_section_title = _resolve_last_exercise_in_section(sec)
|
||||
if body and not last_in_section_id and pack.get("anchor_exercise_id"):
|
||||
last_in_section_id = pack.get("anchor_exercise_id")
|
||||
last_in_section_title = pack.get("anchor_title")
|
||||
|
||||
unit_ids = list(pack.get("planned_exercise_ids") or [])
|
||||
pack["section_title"] = section_title
|
||||
pack["section_guidance_notes"] = guidance
|
||||
pack["section_planned_exercise_ids"] = section_ids
|
||||
pack["section_exercise_count"] = len(section_ids)
|
||||
pack["last_section_exercise_id"] = last_in_section_id
|
||||
pack["last_section_exercise_title"] = last_in_section_title
|
||||
pack["unit_skill_profile_summary"] = skill_profile_summary_from_exercise_ids(cur, unit_ids)
|
||||
pack["section_skill_profile_summary"] = skill_profile_summary_from_exercise_ids(cur, section_ids)
|
||||
pack["has_planning_reference"] = bool(
|
||||
unit_ids
|
||||
or section_ids
|
||||
or pack.get("anchor_exercise_id")
|
||||
or (pack.get("unit") or {}).get("framework_slot_id")
|
||||
or (pack.get("unit") or {}).get("origin_framework_slot_id")
|
||||
)
|
||||
return pack
|
||||
|
||||
|
||||
def _section_title_for_index(sections: Sequence[Dict[str, Any]], section_order_index: Optional[int]) -> Optional[str]:
|
||||
if section_order_index is None:
|
||||
return None
|
||||
for sec in sections:
|
||||
if int(sec.get("order_index") or -1) == int(section_order_index):
|
||||
t = (sec.get("title") or "").strip()
|
||||
return t or None
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_query(query: Optional[str]) -> str:
|
||||
return re.sub(r"\s+", " ", (query or "").strip())
|
||||
|
||||
|
||||
def _apply_client_planned_override(
|
||||
cur,
|
||||
pack: Dict[str, Any],
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
) -> Dict[str, Any]:
|
||||
"""Client-Plan (ungespeichertes Formular) überschreibt DB-Stand."""
|
||||
if not body.planned_exercise_ids:
|
||||
return pack
|
||||
planned_ids: List[int] = []
|
||||
seen: Set[int] = set()
|
||||
for raw in body.planned_exercise_ids:
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
planned_ids.append(eid)
|
||||
if not planned_ids:
|
||||
return pack
|
||||
|
||||
pack["planned_exercise_ids"] = planned_ids
|
||||
if not body.anchor_exercise_id:
|
||||
anchor_id = _resolve_anchor_from_plan(planned_ids, None)
|
||||
pack["anchor_exercise_id"] = anchor_id
|
||||
if anchor_id:
|
||||
titles = _load_exercise_titles(cur, [anchor_id])
|
||||
pack["anchor_title"] = titles.get(anchor_id)
|
||||
pack["anchor_skill_ids"] = sorted(_load_skill_ids_for_exercise(cur, anchor_id))
|
||||
else:
|
||||
pack["anchor_title"] = None
|
||||
pack["anchor_skill_ids"] = []
|
||||
return pack
|
||||
|
||||
|
||||
def build_planning_exercise_context_pack(
|
||||
cur,
|
||||
*,
|
||||
tenant: TenantContext,
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
) -> Dict[str, Any]:
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Planungs-Vorschläge abrufen")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tu.*, tg.name AS group_name
|
||||
FROM training_units tu
|
||||
LEFT JOIN training_groups tg ON tg.id = tu.group_id
|
||||
WHERE tu.id = %s
|
||||
""",
|
||||
(body.unit_id,),
|
||||
)
|
||||
unit_row = cur.fetchone()
|
||||
if not unit_row:
|
||||
raise HTTPException(status_code=404, detail="Trainingseinheit nicht gefunden")
|
||||
unit = dict(unit_row)
|
||||
|
||||
if unit.get("framework_slot_id"):
|
||||
if role not in ("admin", "superadmin"):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT fp.created_by FROM training_framework_slots s
|
||||
JOIN training_framework_programs fp ON fp.id = s.framework_program_id
|
||||
WHERE s.id = %s
|
||||
""",
|
||||
(unit["framework_slot_id"],),
|
||||
)
|
||||
fr = cur.fetchone()
|
||||
cb = fr["created_by"] if fr else None
|
||||
if unit.get("created_by") != profile_id and cb != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||
else:
|
||||
if not unit.get("group_id"):
|
||||
raise HTTPException(status_code=404, detail="Trainingseinheit nicht gefunden")
|
||||
_assert_training_unit_permission(cur, unit, profile_id, role)
|
||||
|
||||
sections = _fetch_sections(cur, int(body.unit_id))
|
||||
planned_ids = _collect_planned_exercise_ids(sections)
|
||||
anchor_id = _resolve_anchor_from_plan(planned_ids, body.anchor_exercise_id)
|
||||
anchor_skills = _load_skill_ids_for_exercise(cur, anchor_id)
|
||||
group_recent = _load_group_recent_exercise_ids(cur, unit.get("group_id"), int(body.unit_id))
|
||||
|
||||
titles = _load_exercise_titles(cur, [x for x in [anchor_id] if x])
|
||||
anchor_title = titles.get(anchor_id) if anchor_id else None
|
||||
|
||||
pack = {
|
||||
"unit_id": int(body.unit_id),
|
||||
"unit": {
|
||||
"id": int(body.unit_id),
|
||||
"framework_slot_id": unit.get("framework_slot_id"),
|
||||
"origin_framework_slot_id": unit.get("origin_framework_slot_id"),
|
||||
},
|
||||
"unit_title": (unit.get("title") or unit.get("planned_focus") or "").strip() or None,
|
||||
"group_id": unit.get("group_id"),
|
||||
"group_name": (unit.get("group_name") or "").strip() or None,
|
||||
"section_order_index": body.section_order_index,
|
||||
"section_title": _section_title_for_index(sections, body.section_order_index),
|
||||
"planned_exercise_ids": planned_ids,
|
||||
"anchor_exercise_id": anchor_id,
|
||||
"anchor_title": anchor_title,
|
||||
"anchor_skill_ids": sorted(anchor_skills),
|
||||
"group_recent_exercise_ids": sorted(group_recent),
|
||||
}
|
||||
return _attach_planning_context_details(cur, pack, sections=sections, body=body)
|
||||
|
||||
|
||||
def build_client_planning_context_pack(
|
||||
cur,
|
||||
*,
|
||||
tenant: TenantContext,
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
) -> Dict[str, Any]:
|
||||
"""Freie / Client-Kontext-Suche ohne persistierte training_units.id (Formular, Rahmen-Slot)."""
|
||||
role = tenant.global_role
|
||||
if not _has_planning_role(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Planungs-Vorschläge abrufen")
|
||||
|
||||
planned_ids: List[int] = []
|
||||
if body.planned_exercise_ids:
|
||||
seen: Set[int] = set()
|
||||
for raw in body.planned_exercise_ids:
|
||||
try:
|
||||
eid = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if eid < 1 or eid in seen:
|
||||
continue
|
||||
seen.add(eid)
|
||||
planned_ids.append(eid)
|
||||
|
||||
anchor_id = _resolve_anchor_from_plan(planned_ids, body.anchor_exercise_id)
|
||||
anchor_skills = _load_skill_ids_for_exercise(cur, anchor_id)
|
||||
|
||||
group_id = body.group_id
|
||||
group_name = None
|
||||
if group_id:
|
||||
cur.execute("SELECT name FROM training_groups WHERE id = %s", (int(group_id),))
|
||||
gr = cur.fetchone()
|
||||
if gr:
|
||||
group_name = (gr.get("name") or "").strip() or None
|
||||
|
||||
group_recent = _load_group_recent_exercise_ids(cur, group_id, exclude_unit_id=None)
|
||||
titles = _load_exercise_titles(cur, [x for x in [anchor_id] if x])
|
||||
anchor_title = titles.get(anchor_id) if anchor_id else None
|
||||
|
||||
pack = {
|
||||
"unit_id": None,
|
||||
"unit": {
|
||||
"id": None,
|
||||
"framework_slot_id": None,
|
||||
"origin_framework_slot_id": None,
|
||||
},
|
||||
"unit_title": None,
|
||||
"group_id": group_id,
|
||||
"group_name": group_name,
|
||||
"section_order_index": body.section_order_index,
|
||||
"section_title": (body.section_title or "").strip() or None,
|
||||
"planned_exercise_ids": planned_ids,
|
||||
"anchor_exercise_id": anchor_id,
|
||||
"anchor_title": anchor_title,
|
||||
"anchor_skill_ids": sorted(anchor_skills),
|
||||
"group_recent_exercise_ids": sorted(group_recent),
|
||||
"context_mode": "client_free",
|
||||
}
|
||||
return _attach_planning_context_details(cur, pack, sections=None, body=body)
|
||||
|
||||
|
||||
def suggest_planning_exercises(
|
||||
cur,
|
||||
*,
|
||||
tenant: TenantContext,
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
) -> Dict[str, Any]:
|
||||
if body.unit_id:
|
||||
pack = build_planning_exercise_context_pack(cur, tenant=tenant, body=body)
|
||||
else:
|
||||
pack = build_client_planning_context_pack(cur, tenant=tenant, body=body)
|
||||
pack = _apply_client_planned_override(cur, pack, body)
|
||||
pack = _attach_planning_context_details(cur, pack, body=body)
|
||||
sections_for_variant = None
|
||||
if body.unit_id and not (body.anchor_exercise_variant_id and int(body.anchor_exercise_variant_id) > 0):
|
||||
sections_for_variant = _fetch_sections(cur, int(body.unit_id))
|
||||
pack = _finalize_progression_context(
|
||||
cur, tenant, pack, body, sections=sections_for_variant
|
||||
)
|
||||
query = _normalize_query(body.query)
|
||||
heuristic_intent = resolve_planning_exercise_intent(query, body.intent_hint)
|
||||
|
||||
has_plan_ref = bool(pack.get("has_planning_reference"))
|
||||
expectation_mode = "planning_hybrid" if has_plan_ref else "query_only"
|
||||
|
||||
pipeline_context = {
|
||||
"unit_title": pack.get("unit_title"),
|
||||
"group_name": pack.get("group_name"),
|
||||
"section_title": pack.get("section_title"),
|
||||
"section_guidance_notes": pack.get("section_guidance_notes"),
|
||||
"section_exercise_count": pack.get("section_exercise_count"),
|
||||
"planned_count": len(pack.get("planned_exercise_ids") or []),
|
||||
"anchor_title": pack.get("anchor_title"),
|
||||
"anchor_exercise_id": pack.get("anchor_exercise_id"),
|
||||
"last_section_exercise_title": pack.get("last_section_exercise_title"),
|
||||
"progression_graph_id": pack.get("progression_graph_id"),
|
||||
"unit_skill_profile": pack.get("unit_skill_profile_summary"),
|
||||
"section_skill_profile": pack.get("section_skill_profile_summary"),
|
||||
"has_planning_reference": has_plan_ref,
|
||||
"expectation_mode": expectation_mode,
|
||||
}
|
||||
target_profile, intent, scenario_kind, query_intent_summary = build_planning_target_with_query_pipeline(
|
||||
cur,
|
||||
unit=pack["unit"],
|
||||
planned_exercise_ids=pack["planned_exercise_ids"],
|
||||
section_planned_exercise_ids=pack.get("section_planned_exercise_ids") or [],
|
||||
anchor_exercise_id=pack.get("anchor_exercise_id"),
|
||||
query=query,
|
||||
heuristic_intent=heuristic_intent,
|
||||
include_llm_intent=body.include_llm_intent,
|
||||
context_summary=pipeline_context,
|
||||
has_planning_reference=has_plan_ref,
|
||||
)
|
||||
weights = _intent_weights(intent)
|
||||
target_profile_summary = target_profile.to_summary_dict(cur)
|
||||
query_intent_applied = bool(query_intent_summary.get("llm_applied"))
|
||||
llm_expectation_applied = bool(query_intent_summary.get("llm_expectation_applied"))
|
||||
profile_llm_applied = bool(query_intent_summary.get("profile_llm_applied"))
|
||||
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
vis_sql, vis_params = library_content_visibility_sql(
|
||||
alias="e",
|
||||
profile_id=profile_id,
|
||||
role=role,
|
||||
effective_club_id=tenant.effective_club_id,
|
||||
)
|
||||
|
||||
hits, skills_by_ex, full_library_ranked = run_multistage_planning_retrieval(
|
||||
cur,
|
||||
vis_sql=vis_sql,
|
||||
vis_params=vis_params,
|
||||
query=query,
|
||||
exercise_kind_any=body.exercise_kind_any,
|
||||
target=target_profile,
|
||||
intent=intent,
|
||||
intent_weights=weights,
|
||||
pack={
|
||||
**pack,
|
||||
"requires_partner": query_intent_summary.get("requires_partner"),
|
||||
},
|
||||
)
|
||||
|
||||
text_signals_applied = "planning_text_signals" in (target_profile.sources or [])
|
||||
|
||||
planned_set = set(pack["planned_exercise_ids"])
|
||||
|
||||
llm_rank_applied = False
|
||||
retrieval_phase = compose_retrieval_phase(
|
||||
full_library=full_library_ranked,
|
||||
text_signals=text_signals_applied,
|
||||
query_intent=query_intent_applied,
|
||||
llm_expectation=llm_expectation_applied,
|
||||
llm_rank=False,
|
||||
)
|
||||
run_llm_rank = should_run_llm_rank_pipeline(
|
||||
query,
|
||||
scenario_kind,
|
||||
include_llm_rank=body.include_llm_rank,
|
||||
query_intent_applied=query_intent_applied,
|
||||
llm_expectation_applied=llm_expectation_applied,
|
||||
has_planning_reference=has_plan_ref,
|
||||
hits=hits,
|
||||
)
|
||||
if run_llm_rank:
|
||||
pre_limit = max(int(body.limit), _LLM_RERANK_PRE_LIMIT)
|
||||
pool_hits = hits[:pre_limit]
|
||||
pool_hits, llm_rank_applied = try_llm_rerank_planning_hits(
|
||||
cur,
|
||||
hits=pool_hits,
|
||||
skills_by_ex=skills_by_ex,
|
||||
query=query,
|
||||
intent=intent,
|
||||
context_summary={
|
||||
"unit_title": pack.get("unit_title"),
|
||||
"group_name": pack.get("group_name"),
|
||||
"section_title": pack.get("section_title"),
|
||||
"planned_count": len(planned_set),
|
||||
"anchor_title": pack.get("anchor_title"),
|
||||
"intent": intent,
|
||||
},
|
||||
target_profile_summary=target_profile_summary,
|
||||
limit=int(body.limit),
|
||||
)
|
||||
if llm_rank_applied:
|
||||
retrieval_phase = compose_retrieval_phase(
|
||||
full_library=full_library_ranked,
|
||||
text_signals=text_signals_applied,
|
||||
query_intent=query_intent_applied,
|
||||
llm_expectation=llm_expectation_applied,
|
||||
llm_rank=True,
|
||||
)
|
||||
tail = hits[pre_limit:]
|
||||
hits = pool_hits + tail
|
||||
else:
|
||||
hits = pool_hits[: int(body.limit)]
|
||||
else:
|
||||
hits = hits[: int(body.limit)]
|
||||
|
||||
hits = hits[: int(body.limit)]
|
||||
hits = _enrich_planning_hits_with_variant_meta(cur, hits)
|
||||
|
||||
context_summary = {
|
||||
"unit_title": pack.get("unit_title"),
|
||||
"group_name": pack.get("group_name"),
|
||||
"section_title": pack.get("section_title"),
|
||||
"section_guidance_notes": pack.get("section_guidance_notes"),
|
||||
"section_exercise_count": pack.get("section_exercise_count"),
|
||||
"planned_count": len(planned_set),
|
||||
"anchor_title": pack.get("anchor_title"),
|
||||
"anchor_exercise_id": pack.get("anchor_exercise_id"),
|
||||
"last_section_exercise_title": pack.get("last_section_exercise_title"),
|
||||
"progression_graph_id": pack.get("progression_graph_id"),
|
||||
"progression_graph_name": pack.get("progression_graph_name"),
|
||||
"progression_graph_auto_resolved": pack.get("progression_graph_auto_resolved"),
|
||||
"anchor_exercise_variant_id": pack.get("anchor_exercise_variant_id"),
|
||||
"context_mode": pack.get("context_mode") or ("unit" if pack.get("unit_id") else "client_free"),
|
||||
"unit_skill_profile": pack.get("unit_skill_profile_summary"),
|
||||
"section_skill_profile": pack.get("section_skill_profile_summary"),
|
||||
"has_planning_reference": pack.get("has_planning_reference"),
|
||||
"expectation_mode": expectation_mode,
|
||||
}
|
||||
|
||||
return {
|
||||
"context_summary": context_summary,
|
||||
"target_profile_summary": target_profile_summary,
|
||||
"scenario_kind": scenario_kind,
|
||||
"query_intent_summary": query_intent_summary,
|
||||
"retrieval_phase": retrieval_phase,
|
||||
"full_library_ranked": full_library_ranked,
|
||||
"text_signals_applied": text_signals_applied,
|
||||
"profile_preselect_applied": False,
|
||||
"llm_rank_applied": llm_rank_applied,
|
||||
"llm_intent_applied": query_intent_applied,
|
||||
"llm_expectation_applied": llm_expectation_applied,
|
||||
"profile_llm_applied": profile_llm_applied,
|
||||
"intent_resolved": intent,
|
||||
"intent_heuristic": heuristic_intent,
|
||||
"query_normalized": query or None,
|
||||
"expectation_mode": expectation_mode,
|
||||
"hits": hits,
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
"""
|
||||
Szenario-Routing und Erwartungsprofil-Pipeline für Planungs-Übungssuche (P1).
|
||||
|
||||
Ablauf:
|
||||
1. Heuristik: Intent + Szenario-Klasse aus Query/Kontext
|
||||
2. Optional LLM (planning_exercise_search_intent) bei komplexen Anfragen
|
||||
3. Deterministisches Basis-Profil (Rahmen, Plan, Anker)
|
||||
4. Query-Overlay mergen → PlanningTargetProfile für Vorselektion
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
||||
|
||||
from planning_exercise_expectation import try_build_planning_expectation_from_context
|
||||
from planning_exercise_intent import (
|
||||
PlanningQueryIntentParsed,
|
||||
resolve_query_intent_catalog_ids,
|
||||
try_parse_planning_query_intent,
|
||||
)
|
||||
from planning_exercise_profiles import (
|
||||
PlanningTargetProfile,
|
||||
_merge_weight_maps,
|
||||
_normalize_weight_map,
|
||||
build_planning_target_profile,
|
||||
)
|
||||
|
||||
SCENARIO_PRESET_NEXT = "preset_next"
|
||||
SCENARIO_PROGRESSION = "progression"
|
||||
SCENARIO_DEEPEN = "deepen"
|
||||
SCENARIO_CONTINUE_PLAN = "continue_plan"
|
||||
SCENARIO_ADDITIVE = "additive_constraint"
|
||||
SCENARIO_FREE_SEARCH = "free_search"
|
||||
|
||||
_SIMPLE_PRESET_PATTERNS = (
|
||||
r"^(schlage?\s+(mir\s+)?(die\s+)?(n[aä]chste|naechste)\s+(sinnvolle\s+)?(übung|uebung)\s*(vor)?\.?)$",
|
||||
r"^(n[aä]chste|naechste)\s+(übung|uebung)\s*(vorschlag|vorschlagen|empfehl\w*)?\.?$",
|
||||
r"^(vorschlag|vorschlagen|empfehl\w*)\s*(für|fuer)?\s*(die\s+)?(n[aä]chste|naechste)?\s*(übung|uebung)?\.?$",
|
||||
r"^n[aä]chste\s+übung$",
|
||||
r"^n[aä]chste\s+uebung$",
|
||||
r"^(n[aä]chste|naechste)\s+(übung|uebung)\s+planen\.?$",
|
||||
)
|
||||
|
||||
_ADDITIVE_MARKERS = (
|
||||
"zusätzlich",
|
||||
"zusaetzlich",
|
||||
"auch ",
|
||||
" außerdem",
|
||||
" ausserdem",
|
||||
" dazu",
|
||||
" extra",
|
||||
" mehr ",
|
||||
" und dabei",
|
||||
" sowie ",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_query(q: Optional[str]) -> str:
|
||||
return re.sub(r"\s+", " ", (q or "").strip())
|
||||
|
||||
|
||||
def is_simple_preset_query(query: Optional[str]) -> bool:
|
||||
q = _normalize_query(query).lower()
|
||||
if not q:
|
||||
return True
|
||||
for pat in _SIMPLE_PRESET_PATTERNS:
|
||||
if re.match(pat, q, flags=re.IGNORECASE):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def classify_planning_scenario(
|
||||
query: Optional[str],
|
||||
heuristic_intent: str,
|
||||
) -> str:
|
||||
q = _normalize_query(query).lower()
|
||||
if not q or is_simple_preset_query(q):
|
||||
return SCENARIO_PRESET_NEXT
|
||||
if heuristic_intent == "progression_next":
|
||||
return SCENARIO_PROGRESSION
|
||||
if heuristic_intent == "deepen_exercise":
|
||||
return SCENARIO_DEEPEN
|
||||
if any(m in f" {q} " for m in _ADDITIVE_MARKERS):
|
||||
return SCENARIO_ADDITIVE
|
||||
if heuristic_intent == "continue_plan_goal":
|
||||
return SCENARIO_CONTINUE_PLAN
|
||||
if heuristic_intent == "free_search":
|
||||
return SCENARIO_FREE_SEARCH
|
||||
if heuristic_intent == "suggest_next":
|
||||
return SCENARIO_CONTINUE_PLAN
|
||||
return SCENARIO_FREE_SEARCH
|
||||
|
||||
|
||||
def should_run_llm_expectation_pipeline(
|
||||
scenario: str,
|
||||
*,
|
||||
include_llm_intent: bool,
|
||||
has_planning_reference: bool,
|
||||
) -> bool:
|
||||
"""Preset/leere Anfrage mit Planungsbezug → LLM-Erwartungsprofil statt Query-Intent."""
|
||||
if not include_llm_intent:
|
||||
return False
|
||||
if not has_planning_reference:
|
||||
return False
|
||||
return scenario == SCENARIO_PRESET_NEXT
|
||||
|
||||
|
||||
def should_run_llm_intent_pipeline(
|
||||
query: Optional[str],
|
||||
scenario: str,
|
||||
*,
|
||||
include_llm_intent: bool,
|
||||
) -> bool:
|
||||
if not include_llm_intent:
|
||||
return False
|
||||
if scenario == SCENARIO_PRESET_NEXT:
|
||||
return False
|
||||
q = _normalize_query(query)
|
||||
if not q:
|
||||
return False
|
||||
# Kurze Stichwortsuche: Volltext + Profil reichen — kein Intent-LLM
|
||||
if scenario == SCENARIO_FREE_SEARCH and len(q) < 14:
|
||||
return False
|
||||
if scenario in (SCENARIO_CONTINUE_PLAN, SCENARIO_PROGRESSION) and len(q) < 18:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def deterministic_rank_confident(hits: Sequence[Mapping[str, Any]], *, gap_threshold: float = 0.12) -> bool:
|
||||
"""True wenn Hybrid-Ranking schon klar genug ist — LLM-Rerank sparen."""
|
||||
if len(hits) < 4:
|
||||
return True
|
||||
top = float(hits[0].get("score") or 0.0)
|
||||
fourth = float(hits[3].get("score") or 0.0)
|
||||
return (top - fourth) >= gap_threshold
|
||||
|
||||
|
||||
def hybrid_ranking_ambiguous(
|
||||
hits: Sequence[Mapping[str, Any]],
|
||||
*,
|
||||
top_four_gap: float = 0.08,
|
||||
top_ten_gap: float = 0.055,
|
||||
) -> bool:
|
||||
"""True wenn Top-Kandidaten scores zu nah beieinander liegen — Rerank lohnt sich."""
|
||||
if len(hits) < 3:
|
||||
return False
|
||||
top = float(hits[0].get("score") or 0.0)
|
||||
if len(hits) >= 4:
|
||||
fourth = float(hits[3].get("score") or 0.0)
|
||||
if (top - fourth) < top_four_gap:
|
||||
return True
|
||||
if len(hits) >= 10:
|
||||
tenth = float(hits[9].get("score") or 0.0)
|
||||
if (top - tenth) < top_ten_gap:
|
||||
return True
|
||||
elif len(hits) >= 2:
|
||||
tail = float(hits[min(len(hits) - 1, 9)].get("score") or 0.0)
|
||||
if (top - tail) < top_four_gap:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def should_run_llm_rank_pipeline(
|
||||
query: Optional[str],
|
||||
scenario: str,
|
||||
*,
|
||||
include_llm_rank: bool,
|
||||
query_intent_applied: bool,
|
||||
llm_expectation_applied: bool = False,
|
||||
has_planning_reference: bool = True,
|
||||
hits: Sequence[Mapping[str, Any]],
|
||||
) -> bool:
|
||||
"""
|
||||
Phase B2: Rerank bei unklarem Hybrid-Ranking — auch nach Erwartungs-/Intent-LLM.
|
||||
|
||||
Budget: max. 2 LLM-Calls pro Suche (Profil-LLM + optional Rerank).
|
||||
"""
|
||||
if not include_llm_rank:
|
||||
return False
|
||||
if len(hits) < 3:
|
||||
return False
|
||||
if not hybrid_ranking_ambiguous(hits):
|
||||
return False
|
||||
|
||||
q = _normalize_query(query)
|
||||
profile_llm = query_intent_applied or llm_expectation_applied
|
||||
|
||||
if scenario == SCENARIO_PRESET_NEXT:
|
||||
return has_planning_reference
|
||||
|
||||
if scenario == SCENARIO_FREE_SEARCH:
|
||||
if len(q) < 10 and not profile_llm:
|
||||
return False
|
||||
return True
|
||||
|
||||
if scenario == SCENARIO_ADDITIVE:
|
||||
return len(q) >= 8 or profile_llm
|
||||
|
||||
if profile_llm:
|
||||
return True
|
||||
return len(q) >= 14
|
||||
|
||||
|
||||
def _recalculate_skill_gap(target: PlanningTargetProfile) -> PlanningTargetProfile:
|
||||
skill_target = _normalize_weight_map(dict(target.skill_weights))
|
||||
skill_plan_norm = _normalize_weight_map(dict(target.skill_plan_weights))
|
||||
skill_gap: Dict[int, float] = {}
|
||||
for sid, tw in skill_target.items():
|
||||
pw = skill_plan_norm.get(sid, 0.0)
|
||||
gap = tw - pw * 0.85
|
||||
if gap > 0.08:
|
||||
skill_gap[sid] = gap
|
||||
sources = list(target.sources)
|
||||
if skill_gap and "skill_gap_vs_plan" not in sources:
|
||||
sources.append("skill_gap_vs_plan")
|
||||
elif not skill_gap:
|
||||
sources = [s for s in sources if s != "skill_gap_vs_plan"]
|
||||
return PlanningTargetProfile(
|
||||
focus_area_ids=target.focus_area_ids,
|
||||
style_direction_ids=target.style_direction_ids,
|
||||
training_type_ids=target.training_type_ids,
|
||||
target_group_ids=target.target_group_ids,
|
||||
skill_weights=skill_target,
|
||||
skill_gap_weights=_normalize_weight_map(skill_gap) if skill_gap else {},
|
||||
skill_plan_weights=target.skill_plan_weights,
|
||||
sources=sources,
|
||||
)
|
||||
|
||||
|
||||
def merge_query_overlay_into_target(
|
||||
base: PlanningTargetProfile,
|
||||
*,
|
||||
focus: Dict[int, float],
|
||||
style: Dict[int, float],
|
||||
tt: Dict[int, float],
|
||||
tg: Dict[int, float],
|
||||
skills: Dict[int, float],
|
||||
emphasis: str = "additive",
|
||||
scenario: str,
|
||||
) -> PlanningTargetProfile:
|
||||
sources = list(base.sources)
|
||||
if "query_intent" not in sources:
|
||||
sources.append("query_intent")
|
||||
|
||||
if emphasis == "replace" or scenario == SCENARIO_FREE_SEARCH:
|
||||
skill_w = _merge_weight_maps({}, skills, scale=1.0)
|
||||
if skills:
|
||||
skill_w = _normalize_weight_map(_merge_weight_maps(base.skill_weights, skills, scale=0.55))
|
||||
if emphasis == "replace":
|
||||
skill_w = _normalize_weight_map(skills)
|
||||
focus_w = _merge_weight_maps(base.focus_area_ids, focus, scale=0.5 if emphasis == "replace" else 0.85)
|
||||
style_w = _merge_weight_maps(base.style_direction_ids, style, scale=0.5)
|
||||
tt_w = _merge_weight_maps(base.training_type_ids, tt, scale=0.5)
|
||||
tg_w = _merge_weight_maps(base.target_group_ids, tg, scale=0.5)
|
||||
else:
|
||||
skill_scale = 1.0 if scenario == SCENARIO_ADDITIVE else 0.85
|
||||
skill_w = _merge_weight_maps(base.skill_weights, skills, scale=skill_scale)
|
||||
focus_w = _merge_weight_maps(base.focus_area_ids, focus, scale=0.9)
|
||||
style_w = _merge_weight_maps(base.style_direction_ids, style, scale=0.75)
|
||||
tt_w = _merge_weight_maps(base.training_type_ids, tt, scale=0.75)
|
||||
tg_w = _merge_weight_maps(base.target_group_ids, tg, scale=0.75)
|
||||
|
||||
out = PlanningTargetProfile(
|
||||
focus_area_ids=_normalize_weight_map(focus_w) if focus_w else focus_w,
|
||||
style_direction_ids=_normalize_weight_map(style_w) if style_w else style_w,
|
||||
training_type_ids=_normalize_weight_map(tt_w) if tt_w else tt_w,
|
||||
target_group_ids=_normalize_weight_map(tg_w) if tg_w else tg_w,
|
||||
skill_weights=_normalize_weight_map(skill_w) if skill_w else skill_w,
|
||||
skill_gap_weights=dict(base.skill_gap_weights),
|
||||
skill_plan_weights=dict(base.skill_plan_weights),
|
||||
sources=sources,
|
||||
)
|
||||
return _recalculate_skill_gap(out)
|
||||
|
||||
|
||||
def build_planning_target_with_query_pipeline(
|
||||
cur,
|
||||
*,
|
||||
unit: Dict[str, Any],
|
||||
planned_exercise_ids: List[int],
|
||||
section_planned_exercise_ids: Optional[List[int]] = None,
|
||||
anchor_exercise_id: Optional[int],
|
||||
query: Optional[str],
|
||||
heuristic_intent: str,
|
||||
include_llm_intent: bool,
|
||||
context_summary: Mapping[str, Any],
|
||||
has_planning_reference: bool = True,
|
||||
) -> Tuple[PlanningTargetProfile, str, str, Dict[str, Any]]:
|
||||
"""
|
||||
Returns: target_profile, resolved_intent, scenario_kind, query_intent_summary dict
|
||||
|
||||
Ohne Planungsbezug (keine Übungen/Anker/Rahmen): Erwartungsprofil primär aus Suchtext (query_only).
|
||||
Mit Planungsbezug: hybrid aus Plan + optional Query-Overlay.
|
||||
"""
|
||||
scenario = classify_planning_scenario(query, heuristic_intent)
|
||||
resolved_intent = heuristic_intent
|
||||
llm_applied = False
|
||||
llm_expectation_applied = False
|
||||
parsed: Optional[PlanningQueryIntentParsed] = None
|
||||
expectation_parsed: Optional[PlanningQueryIntentParsed] = None
|
||||
resolved_skills: List[Dict[str, Any]] = []
|
||||
|
||||
if has_planning_reference:
|
||||
base = build_planning_target_profile(
|
||||
cur,
|
||||
unit=unit,
|
||||
planned_exercise_ids=planned_exercise_ids,
|
||||
section_planned_exercise_ids=section_planned_exercise_ids or [],
|
||||
anchor_exercise_id=anchor_exercise_id,
|
||||
intent=heuristic_intent,
|
||||
section_guidance_notes=(context_summary.get("section_guidance_notes") or None),
|
||||
section_title=(context_summary.get("section_title") or None),
|
||||
)
|
||||
else:
|
||||
base = PlanningTargetProfile(sources=["query_only"])
|
||||
|
||||
base_summary = base.to_summary_dict(cur)
|
||||
target = base
|
||||
|
||||
if should_run_llm_expectation_pipeline(
|
||||
scenario,
|
||||
include_llm_intent=include_llm_intent,
|
||||
has_planning_reference=has_planning_reference,
|
||||
):
|
||||
expectation_parsed, llm_expectation_applied = try_build_planning_expectation_from_context(
|
||||
cur,
|
||||
heuristic_intent=heuristic_intent,
|
||||
context_summary=context_summary,
|
||||
target_profile_summary=base_summary,
|
||||
)
|
||||
parsed = expectation_parsed
|
||||
if parsed and llm_expectation_applied:
|
||||
if parsed.intent in {
|
||||
"suggest_next",
|
||||
"progression_next",
|
||||
"deepen_exercise",
|
||||
"continue_plan_goal",
|
||||
"free_search",
|
||||
}:
|
||||
resolved_intent = parsed.intent
|
||||
focus, style, tt, tg, skills, resolved_skills = resolve_query_intent_catalog_ids(cur, parsed)
|
||||
if focus or style or tt or tg or skills or parsed.rationale:
|
||||
target = merge_query_overlay_into_target(
|
||||
base,
|
||||
focus=focus,
|
||||
style=style,
|
||||
tt=tt,
|
||||
tg=tg,
|
||||
skills=skills,
|
||||
emphasis=parsed.emphasis or "additive",
|
||||
scenario=SCENARIO_PRESET_NEXT,
|
||||
)
|
||||
if "context_expectation" not in target.sources:
|
||||
target.sources.append("context_expectation")
|
||||
elif should_run_llm_intent_pipeline(query, scenario, include_llm_intent=include_llm_intent):
|
||||
parsed, llm_applied = try_parse_planning_query_intent(
|
||||
cur,
|
||||
query=_normalize_query(query),
|
||||
heuristic_intent=heuristic_intent,
|
||||
scenario_hint=scenario,
|
||||
context_summary=context_summary,
|
||||
target_profile_summary=base_summary,
|
||||
)
|
||||
|
||||
if parsed and llm_applied and not llm_expectation_applied:
|
||||
if parsed.intent in {
|
||||
"suggest_next",
|
||||
"progression_next",
|
||||
"deepen_exercise",
|
||||
"continue_plan_goal",
|
||||
"free_search",
|
||||
}:
|
||||
resolved_intent = parsed.intent
|
||||
if parsed.scenario in VALID_SCENARIOS_SET:
|
||||
scenario = parsed.scenario
|
||||
|
||||
focus, style, tt, tg, skills, resolved_skills = resolve_query_intent_catalog_ids(cur, parsed)
|
||||
if focus or style or tt or tg or skills:
|
||||
overlay_scenario = scenario
|
||||
overlay_emphasis = parsed.emphasis
|
||||
if not has_planning_reference:
|
||||
overlay_scenario = SCENARIO_FREE_SEARCH
|
||||
overlay_emphasis = "replace"
|
||||
target = merge_query_overlay_into_target(
|
||||
base,
|
||||
focus=focus,
|
||||
style=style,
|
||||
tt=tt,
|
||||
tg=tg,
|
||||
skills=skills,
|
||||
emphasis=overlay_emphasis,
|
||||
scenario=overlay_scenario,
|
||||
)
|
||||
elif not has_planning_reference and _normalize_query(query):
|
||||
# Kein LLM, aber Freitext: leichtes Profil bleibt leer — Retrieval nutzt Volltext
|
||||
target = PlanningTargetProfile(sources=["query_only"])
|
||||
|
||||
query_intent_summary: Dict[str, Any] = {
|
||||
"scenario": scenario,
|
||||
"intent": resolved_intent,
|
||||
"heuristic_intent": heuristic_intent,
|
||||
"llm_applied": llm_applied,
|
||||
"llm_expectation_applied": llm_expectation_applied,
|
||||
"profile_llm_applied": llm_applied or llm_expectation_applied,
|
||||
"emphasis": parsed.emphasis if parsed else None,
|
||||
"rationale": (parsed.rationale if parsed else None),
|
||||
"skill_hints_resolved": resolved_skills,
|
||||
"requires_partner": parsed.requires_partner if parsed else None,
|
||||
"expectation_mode": "planning_hybrid" if has_planning_reference else "query_only",
|
||||
}
|
||||
|
||||
return target, resolved_intent, scenario, query_intent_summary
|
||||
|
||||
|
||||
VALID_SCENARIOS_SET = {
|
||||
SCENARIO_PRESET_NEXT,
|
||||
SCENARIO_PROGRESSION,
|
||||
SCENARIO_DEEPEN,
|
||||
SCENARIO_CONTINUE_PLAN,
|
||||
SCENARIO_ADDITIVE,
|
||||
SCENARIO_FREE_SEARCH,
|
||||
}
|
||||
|
||||
|
||||
def compose_retrieval_phase(
|
||||
*,
|
||||
full_library: bool = False,
|
||||
profile_preselect: bool = False,
|
||||
text_signals: bool = False,
|
||||
query_intent: bool = False,
|
||||
llm_expectation: bool = False,
|
||||
llm_rank: bool = False,
|
||||
) -> str:
|
||||
parts = ["profile_v1"]
|
||||
if full_library or profile_preselect:
|
||||
parts.append("full_library")
|
||||
if text_signals:
|
||||
parts.append("text_signals")
|
||||
if llm_expectation:
|
||||
parts.append("llm_expectation")
|
||||
elif query_intent:
|
||||
parts.append("query_intent")
|
||||
if llm_rank:
|
||||
parts.append("llm_rank")
|
||||
return "+".join(parts)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SCENARIO_ADDITIVE",
|
||||
"SCENARIO_PRESET_NEXT",
|
||||
"build_planning_target_with_query_pipeline",
|
||||
"classify_planning_scenario",
|
||||
"compose_retrieval_phase",
|
||||
"is_simple_preset_query",
|
||||
"merge_query_overlay_into_target",
|
||||
"should_run_llm_expectation_pipeline",
|
||||
"should_run_llm_intent_pipeline",
|
||||
"should_run_llm_rank_pipeline",
|
||||
"deterministic_rank_confident",
|
||||
"hybrid_ranking_ambiguous",
|
||||
]
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
Phase B: Deterministische Text→Katalog-Signale für PlanningTargetProfile.
|
||||
|
||||
Mappt Abschnitts-guidance, Rahmen-Ziele/-Notizen und Programmbeschreibung
|
||||
auf Skill-/Katalog-Gewichte (ohne LLM).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
||||
|
||||
_MIN_SKILL_NAME_LEN = 3
|
||||
_MAX_SKILL_MATCHES = 12
|
||||
_MAX_CATALOG_MATCHES = 6
|
||||
|
||||
|
||||
def _normalize_text_blob(*parts: Optional[str]) -> str:
|
||||
chunks: List[str] = []
|
||||
for p in parts:
|
||||
s = (p or "").strip()
|
||||
if s:
|
||||
chunks.append(s)
|
||||
return "\n".join(chunks).lower()
|
||||
|
||||
|
||||
def _load_skills_for_text_match(cur) -> List[Tuple[int, str, int]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name FROM skills
|
||||
WHERE (status IS NULL OR status = 'active')
|
||||
AND name IS NOT NULL AND TRIM(name) <> ''
|
||||
ORDER BY LENGTH(name) DESC, name ASC
|
||||
"""
|
||||
)
|
||||
out: List[Tuple[int, str, int]] = []
|
||||
for row in cur.fetchall():
|
||||
name = str(row.get("name") or "").strip()
|
||||
if len(name) < _MIN_SKILL_NAME_LEN:
|
||||
continue
|
||||
out.append((int(row["id"]), name.lower(), len(name)))
|
||||
return out
|
||||
|
||||
|
||||
def _load_catalog_names(cur, table: str, id_col: str = "id", name_col: str = "name") -> List[Tuple[int, str, int]]:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {id_col} AS id, {name_col} AS name
|
||||
FROM {table}
|
||||
WHERE {name_col} IS NOT NULL AND TRIM({name_col}) <> ''
|
||||
ORDER BY LENGTH({name_col}) DESC, {name_col} ASC
|
||||
"""
|
||||
)
|
||||
out: List[Tuple[int, str, int]] = []
|
||||
for row in cur.fetchall():
|
||||
name = str(row.get("name") or "").strip()
|
||||
if len(name) < 2:
|
||||
continue
|
||||
out.append((int(row["id"]), name.lower(), len(name)))
|
||||
return out
|
||||
|
||||
|
||||
def _match_catalog_names_in_text(
|
||||
text: str,
|
||||
catalog_rows: Sequence[Tuple[int, str, int]],
|
||||
*,
|
||||
weight: float = 0.85,
|
||||
limit: int = _MAX_CATALOG_MATCHES,
|
||||
) -> Dict[int, float]:
|
||||
if not text or not catalog_rows:
|
||||
return {}
|
||||
out: Dict[int, float] = {}
|
||||
for cid, name_lower, _ in catalog_rows:
|
||||
if len(out) >= limit:
|
||||
break
|
||||
if len(name_lower) < 2:
|
||||
continue
|
||||
if name_lower in text:
|
||||
out[cid] = max(out.get(cid, 0.0), weight)
|
||||
return out
|
||||
|
||||
|
||||
def _match_skills_in_text(
|
||||
text: str,
|
||||
skill_rows: Sequence[Tuple[int, str, int]],
|
||||
*,
|
||||
limit: int = _MAX_SKILL_MATCHES,
|
||||
) -> Dict[int, float]:
|
||||
if not text or not skill_rows:
|
||||
return {}
|
||||
out: Dict[int, float] = {}
|
||||
for sid, name_lower, name_len in skill_rows:
|
||||
if len(out) >= limit:
|
||||
break
|
||||
if name_len < _MIN_SKILL_NAME_LEN:
|
||||
continue
|
||||
if name_lower in text:
|
||||
w = min(1.0, 0.72 + min(name_len, 20) * 0.012)
|
||||
out[sid] = max(out.get(sid, 0.0), w)
|
||||
return out
|
||||
|
||||
|
||||
def load_framework_planning_text_parts(
|
||||
cur,
|
||||
framework_program_id: int,
|
||||
*,
|
||||
slot_id: Optional[int] = None,
|
||||
) -> List[str]:
|
||||
"""Sammelt Rahmen-Texte für Text-Signal-Matching."""
|
||||
parts: List[str] = []
|
||||
cur.execute(
|
||||
"SELECT description FROM training_framework_programs WHERE id = %s",
|
||||
(int(framework_program_id),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row and (row.get("description") or "").strip():
|
||||
parts.append(str(row["description"]).strip())
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT title, notes FROM training_framework_goals
|
||||
WHERE framework_program_id = %s
|
||||
ORDER BY sort_order ASC
|
||||
""",
|
||||
(int(framework_program_id),),
|
||||
)
|
||||
for g in cur.fetchall():
|
||||
t = (g.get("title") or "").strip()
|
||||
n = (g.get("notes") or "").strip()
|
||||
if t:
|
||||
parts.append(t)
|
||||
if n:
|
||||
parts.append(n)
|
||||
|
||||
if slot_id:
|
||||
cur.execute(
|
||||
"SELECT title, notes FROM training_framework_slots WHERE id = %s",
|
||||
(int(slot_id),),
|
||||
)
|
||||
srow = cur.fetchone()
|
||||
if srow:
|
||||
st = (srow.get("title") or "").strip()
|
||||
sn = (srow.get("notes") or "").strip()
|
||||
if st:
|
||||
parts.append(st)
|
||||
if sn:
|
||||
parts.append(sn)
|
||||
|
||||
return parts
|
||||
|
||||
|
||||
def resolve_planning_text_to_catalog_weights(
|
||||
cur,
|
||||
text_blob: str,
|
||||
) -> Tuple[Dict[int, float], Dict[int, float], Dict[int, float], Dict[int, float], Dict[int, float]]:
|
||||
"""
|
||||
Returns: focus, style, training_type, target_group, skill weight maps.
|
||||
"""
|
||||
text = _normalize_text_blob(text_blob)
|
||||
if not text or len(text) < 3:
|
||||
return {}, {}, {}, {}, {}
|
||||
|
||||
skill_rows = _load_skills_for_text_match(cur)
|
||||
focus_rows = _load_catalog_names(cur, "focus_areas")
|
||||
style_rows = _load_catalog_names(cur, "style_directions")
|
||||
tt_rows = _load_catalog_names(cur, "training_types")
|
||||
tg_rows = _load_catalog_names(cur, "target_groups")
|
||||
|
||||
skills = _match_skills_in_text(text, skill_rows)
|
||||
focus = _match_catalog_names_in_text(text, focus_rows, weight=0.88)
|
||||
style = _match_catalog_names_in_text(text, style_rows, weight=0.82)
|
||||
tt = _match_catalog_names_in_text(text, tt_rows, weight=0.82)
|
||||
tg = _match_catalog_names_in_text(text, tg_rows, weight=0.8)
|
||||
|
||||
if re.search(r"\bpartner\b|\bpaar\b|\bpaarweise\b|\bzu zweit\b", text):
|
||||
for gid, name_lower, _ in tg_rows:
|
||||
if "partner" in name_lower or "paar" in name_lower:
|
||||
tg[gid] = max(tg.get(gid, 0.0), 0.9)
|
||||
break
|
||||
|
||||
return focus, style, tt, tg, skills
|
||||
|
||||
|
||||
def merge_text_signal_summary(
|
||||
summary: Mapping[str, Any],
|
||||
*,
|
||||
text_sources: Sequence[str],
|
||||
matched_skills: Sequence[Mapping[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
out = dict(summary)
|
||||
if text_sources:
|
||||
out["text_signal_sources"] = list(text_sources)
|
||||
if matched_skills:
|
||||
out["text_signal_skills"] = list(matched_skills)[:8]
|
||||
return out
|
||||
|
||||
|
||||
__all__ = [
|
||||
"load_framework_planning_text_parts",
|
||||
"merge_text_signal_summary",
|
||||
"resolve_planning_text_to_catalog_weights",
|
||||
]
|
||||
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
Mustache-aehnliche Platzhalter {{schluessel}} fuer KI-Templates aus ai_prompts.
|
||||
|
||||
Kein Vereinsbezug — reine Textersetzung; Aufrufe aus exercise_ai und Admin-Vorschau.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Mapping
|
||||
|
||||
_PLACEHOLDER_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_]+)\s*\}\}")
|
||||
|
||||
|
||||
def _placeholder_pattern_for_key(key: str) -> re.Pattern[str]:
|
||||
return re.compile(r"\{\{\s*" + re.escape(str(key).strip()) + r"\s*\}\}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MustacheRenderResult:
|
||||
"""Ergebnis von render_mustache_template."""
|
||||
|
||||
text: str
|
||||
keys_in_template: List[str]
|
||||
keys_substituted: List[str]
|
||||
keys_missing_variables: List[str]
|
||||
placeholders_remaining: List[str]
|
||||
|
||||
|
||||
def extract_mustache_keys(template: str) -> List[str]:
|
||||
"""Platzhalter-Namen in Vorkommensreihenfolge, ohne erstes Duplikat."""
|
||||
seen: set[str] = set()
|
||||
ordered: List[str] = []
|
||||
for m in _PLACEHOLDER_RE.finditer(template or ""):
|
||||
k = str(m.group(1) or "").strip()
|
||||
if not k or k in seen:
|
||||
continue
|
||||
seen.add(k)
|
||||
ordered.append(k)
|
||||
return ordered
|
||||
|
||||
|
||||
def render_mustache_template(template: str, variables: Mapping[str, str]) -> MustacheRenderResult:
|
||||
"""
|
||||
Ersetzt {{keys}} durch die passenden Strings.
|
||||
Variablen, die fuer einen im Template genutzten Key fehlen, werden als Leerstring ersetzt.
|
||||
|
||||
Rueckgabe-liste keys_missing_variables: Keys, die im Template vorkommen, aber nicht als Map-Keys
|
||||
uebergeben wurden (oder None-Wert entsprachen Leerung).
|
||||
"""
|
||||
tpl_in = template or ""
|
||||
vars_norm: Dict[str, str] = {}
|
||||
for k, v in variables.items():
|
||||
vars_norm[str(k)] = "" if v is None else str(v)
|
||||
keys_in = extract_mustache_keys(tpl_in)
|
||||
missing_known: List[str] = []
|
||||
out = tpl_in
|
||||
substituted: List[str] = []
|
||||
|
||||
for key in keys_in:
|
||||
pat = _placeholder_pattern_for_key(key)
|
||||
repl = vars_norm.get(key)
|
||||
if key not in vars_norm:
|
||||
missing_known.append(key)
|
||||
repl = ""
|
||||
substituted.append(key)
|
||||
out = pat.sub(repl, out)
|
||||
|
||||
still = extract_mustache_keys(out)
|
||||
|
||||
return MustacheRenderResult(
|
||||
text=out,
|
||||
keys_in_template=keys_in,
|
||||
keys_substituted=substituted,
|
||||
keys_missing_variables=missing_known,
|
||||
placeholders_remaining=still,
|
||||
)
|
||||
|
||||
|
||||
def exercise_placeholder_catalog() -> dict:
|
||||
"""
|
||||
Statischer Platzhalter-Katalog fuer Uebungs-KI-Templates — deckt aktuelle Seeds ab.
|
||||
(Erweiterung andere Kontexte: matrix/import folgen separat.)
|
||||
"""
|
||||
defs = [
|
||||
{
|
||||
"key": "exercise_title",
|
||||
"placeholder": "{{exercise_title}}",
|
||||
"description": "Titel der Uebung (oder Platzhalter, wenn leer).",
|
||||
"used_by_slugs": ["exercise_summary", "exercise_skill_suggestions", "exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "exercise_focus_area",
|
||||
"placeholder": "{{exercise_focus_area}}",
|
||||
"description": "Fokuskontext (Text-Hinweis aus Formular, optional).",
|
||||
"used_by_slugs": ["exercise_summary", "exercise_skill_suggestions", "exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "exercise_goal",
|
||||
"placeholder": "{{exercise_goal}}",
|
||||
"description": "Ziel aus dem Formular, als Plaintext ohne HTML-Zeichen.",
|
||||
"used_by_slugs": ["exercise_summary", "exercise_skill_suggestions", "exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "exercise_execution",
|
||||
"placeholder": "{{exercise_execution}}",
|
||||
"description": "Durchfuehrung als Plaintext ohne HTML-Zeichen.",
|
||||
"used_by_slugs": ["exercise_summary", "exercise_skill_suggestions", "exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "exercise_preparation",
|
||||
"placeholder": "{{exercise_preparation}}",
|
||||
"description": "Vorbereitung/Aufbau als Plaintext ohne HTML.",
|
||||
"used_by_slugs": ["exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "exercise_trainer_notes",
|
||||
"placeholder": "{{exercise_trainer_notes}}",
|
||||
"description": "Trainer-Hinweise als Plaintext ohne HTML.",
|
||||
"used_by_slugs": ["exercise_instruction_rewrite"],
|
||||
},
|
||||
{
|
||||
"key": "skills_catalog",
|
||||
"placeholder": "{{skills_catalog}}",
|
||||
"description": (
|
||||
"Gewichtete, kontextbezogene Liste aus dem Skill-Katalog (retrieval_profiles). "
|
||||
"Nur fuer exercise_skill_suggestions."
|
||||
),
|
||||
"used_by_slugs": ["exercise_skill_suggestions"],
|
||||
},
|
||||
]
|
||||
return {"context": "exercise", "placeholders": defs}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MustacheRenderResult",
|
||||
"exercise_placeholder_catalog",
|
||||
"extract_mustache_keys",
|
||||
"render_mustache_template",
|
||||
]
|
||||
@@ -1,3 +1,4 @@
|
||||
httpx==0.27.2
|
||||
fastapi==0.111.0
|
||||
uvicorn[standard]==0.29.0
|
||||
anthropic==0.26.0
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
Superadmin-API: Verwaltung von ai_prompts (Templates, Aktivierung, Vorschau).
|
||||
|
||||
Kein Vereinsbezug — require_auth + is_superadmin; kein TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from ai_prompt_context import ExerciseFormAiPromptContext
|
||||
from ai_prompt_job import resolve_exercise_form_variables
|
||||
from ai_prompt_runtime import render_ai_prompt_template_for_row
|
||||
from db import get_cursor, get_db, r2d
|
||||
from prompt_resolver import exercise_placeholder_catalog
|
||||
|
||||
router = APIRouter(tags=["admin_ai_prompts"])
|
||||
|
||||
|
||||
def _require_superadmin(session: dict = Depends(require_auth)) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
def _prompts_table_ready(cur) -> bool:
|
||||
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.ai_prompts",))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
val = row.get("t") if isinstance(row, dict) else row[0]
|
||||
return val is not None and str(val).strip() != ""
|
||||
|
||||
|
||||
def _fetch_prompt_any(cur, prompt_id: int) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order, created_at, updated_at
|
||||
FROM ai_prompts WHERE id = %s
|
||||
""",
|
||||
(prompt_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||
return dict(row)
|
||||
|
||||
|
||||
class AiPromptUpdateBody(BaseModel):
|
||||
template: Optional[str] = None
|
||||
active: Optional[bool] = None
|
||||
display_name: Optional[str] = Field(None, max_length=200)
|
||||
description: Optional[str] = Field(None, max_length=8000)
|
||||
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||
|
||||
|
||||
class AiPromptPreviewBody(ExerciseFormAiPromptContext):
|
||||
"""Preview-POST: gleiche Felder wie ExerciseFormAiPromptContext (focus_hint, nicht focus_area_hint)."""
|
||||
|
||||
|
||||
@router.get("/api/admin/ai-prompts/catalog/placeholders")
|
||||
def get_ai_prompt_placeholders_catalog(session: dict = Depends(_require_superadmin)):
|
||||
return exercise_placeholder_catalog()
|
||||
|
||||
|
||||
@router.get("/api/admin/ai-prompts")
|
||||
def list_ai_prompts(session: dict = Depends(_require_superadmin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _prompts_table_ready(cur):
|
||||
raise HTTPException(status_code=503, detail="Tabelle ai_prompts fehlt.")
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, slug, display_name, description, category, output_format, active,
|
||||
sort_order, is_system_default, default_template, openrouter_model
|
||||
FROM ai_prompts
|
||||
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||
"""
|
||||
)
|
||||
rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
|
||||
out = []
|
||||
for r in rows:
|
||||
dt = (r.get("default_template") or "").strip()
|
||||
tmpl = (r.get("template") or "").strip()
|
||||
is_modified = bool(dt and tmpl != dt)
|
||||
rr = {k: v for k, v in r.items() if k != "default_template"}
|
||||
rr["is_modified"] = is_modified if dt else False
|
||||
rr["has_reference_template"] = bool(dt)
|
||||
out.append(rr)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/api/admin/ai-prompts/{prompt_id:int}")
|
||||
def get_ai_prompt(prompt_id: int, session: dict = Depends(_require_superadmin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _prompts_table_ready(cur):
|
||||
raise HTTPException(status_code=503, detail="Tabelle ai_prompts fehlt.")
|
||||
row = _fetch_prompt_any(cur, prompt_id)
|
||||
dt = (row.get("default_template") or "").strip()
|
||||
tmpl = (row.get("template") or "").strip()
|
||||
row_out = dict(row)
|
||||
row_out["is_modified"] = bool(dt and tmpl != dt) if dt else False
|
||||
row_out["has_reference_template"] = bool(dt)
|
||||
return row_out
|
||||
|
||||
|
||||
@router.put("/api/admin/ai-prompts/{prompt_id:int}")
|
||||
def update_ai_prompt(
|
||||
prompt_id: int,
|
||||
body: AiPromptUpdateBody,
|
||||
session: dict = Depends(_require_superadmin),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _prompts_table_ready(cur):
|
||||
raise HTTPException(status_code=503, detail="Tabelle ai_prompts fehlt.")
|
||||
old = _fetch_prompt_any(cur, prompt_id)
|
||||
|
||||
next_template = old["template"]
|
||||
if body.template is not None:
|
||||
tpl = body.template.strip() if isinstance(body.template, str) else ""
|
||||
if not tpl:
|
||||
raise HTTPException(status_code=400, detail="template darf nicht leer sein.")
|
||||
next_template = tpl
|
||||
|
||||
next_active = bool(old.get("active", True))
|
||||
if body.active is not None:
|
||||
next_active = body.active
|
||||
|
||||
next_name = body.display_name if body.display_name is not None else old.get("display_name") or ""
|
||||
next_name = (next_name or "").strip()
|
||||
if not next_name:
|
||||
raise HTTPException(status_code=400, detail="display_name darf nicht leer sein.")
|
||||
|
||||
next_desc = body.description if body.description is not None else old.get("description") or ""
|
||||
next_desc = (next_desc or "").strip()
|
||||
|
||||
next_openrouter = old.get("openrouter_model")
|
||||
if body.openrouter_model is not None:
|
||||
cand = body.openrouter_model.strip() if isinstance(body.openrouter_model, str) else ""
|
||||
if any(c in cand for c in ("\r", "\n", "\t")):
|
||||
raise HTTPException(status_code=400, detail="openrouter_model: keine Steuerzeichen erlaubt.")
|
||||
next_openrouter = cand or None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE ai_prompts
|
||||
SET template = %s, active = %s, display_name = %s, description = %s,
|
||||
openrouter_model = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order,
|
||||
created_at, updated_at
|
||||
""",
|
||||
(next_template, next_active, next_name, next_desc, next_openrouter, prompt_id),
|
||||
)
|
||||
row = dict(cur.fetchone())
|
||||
conn.commit()
|
||||
dt = (row.get("default_template") or "").strip()
|
||||
tmpl = (row.get("template") or "").strip()
|
||||
row["is_modified"] = bool(dt and tmpl != dt) if dt else False
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/api/admin/ai-prompts/{prompt_id:int}/reset-template")
|
||||
def reset_ai_prompt_template(prompt_id: int, session: dict = Depends(_require_superadmin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _prompts_table_ready(cur):
|
||||
raise HTTPException(status_code=503, detail="Tabelle ai_prompts fehlt.")
|
||||
old = _fetch_prompt_any(cur, prompt_id)
|
||||
dt_old = old.get("default_template")
|
||||
if dt_old is None or not str(dt_old).strip():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Kein gespeicherter Referenztext (default_template) — Ruecksetzen nicht möglich.",
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE ai_prompts
|
||||
SET template = default_template, updated_at = NOW()
|
||||
WHERE id = %s AND default_template IS NOT NULL
|
||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||
output_schema, is_system_default, default_template, openrouter_model,
|
||||
active, sort_order,
|
||||
created_at, updated_at
|
||||
""",
|
||||
(prompt_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||
rr = dict(row)
|
||||
conn.commit()
|
||||
tmpl = (rr.get("template") or "").strip()
|
||||
dt = (rr.get("default_template") or "").strip()
|
||||
rr["is_modified"] = bool(dt and tmpl != dt) if dt else False
|
||||
return rr
|
||||
|
||||
|
||||
@router.post("/api/admin/ai-prompts/{prompt_id:int}/preview")
|
||||
def preview_ai_prompt(prompt_id: int, body: AiPromptPreviewBody, session: dict = Depends(_require_superadmin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not _prompts_table_ready(cur):
|
||||
raise HTTPException(status_code=503, detail="Tabelle ai_prompts fehlt.")
|
||||
row = _fetch_prompt_any(cur, prompt_id)
|
||||
slug = (row.get("slug") or "").strip().lower()
|
||||
|
||||
vars_map: Dict[str, str]
|
||||
warn: Optional[str] = None
|
||||
if slug in ("exercise_summary", "exercise_skill_suggestions", "exercise_instruction_rewrite"):
|
||||
try:
|
||||
vars_map = resolve_exercise_form_variables(cur, slug, body)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
elif slug == "pipeline":
|
||||
vars_map = {}
|
||||
warn = "Pipeline-Slug: keine Kontextsubstitution fuer Vorschau."
|
||||
else:
|
||||
vars_map = {}
|
||||
warn = f"Slug {slug!r}: noch kein Vorschau-Kontext definiert — Roh-Template ohne Ersetzung."
|
||||
|
||||
rendered = render_ai_prompt_template_for_row(row, vars_map)
|
||||
return {
|
||||
"slug": slug,
|
||||
"resolved_template": rendered.text,
|
||||
"keys_in_template": rendered.keys_in_template,
|
||||
"keys_missing_variables": rendered.keys_missing_variables,
|
||||
"placeholders_remaining": rendered.placeholders_remaining,
|
||||
"warning": warn,
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
"""
|
||||
Superadmin API: Pflege von ai_skill_retrieval_profiles (KI Skill-Katalog / exercise_ai).
|
||||
|
||||
Kein Vereinsbezug — require_auth + is_superadmin; kein TenantContext.
|
||||
Siehe ACCESS_LAYER_ENDPOINT_AUDIT.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db, r2d
|
||||
|
||||
router = APIRouter(tags=["admin_ai_skill_retrieval"])
|
||||
|
||||
|
||||
def _require_superadmin(session: dict) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
def _table_ready(cur) -> bool:
|
||||
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.ai_skill_retrieval_profiles",))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
val = row.get("t") if isinstance(row, dict) else row[0]
|
||||
return val is not None and str(val).strip() != ""
|
||||
|
||||
|
||||
def _assert_table(cur) -> None:
|
||||
if not _table_ready(cur):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Tabelle ai_skill_retrieval_profiles fehlt — Migration 068 ausführen.",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_config(raw: Any) -> Dict[str, Any]:
|
||||
if raw is None:
|
||||
return {}
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except json.JSONDecodeError as e:
|
||||
raise HTTPException(status_code=400, detail=f"config: ungültiges JSON — {e}") from e
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=400, detail="config muss ein JSON-Objekt sein.")
|
||||
return parsed
|
||||
raise HTTPException(status_code=400, detail="config muss ein Objekt sein.")
|
||||
|
||||
|
||||
class AiRetrievalProfileCreate(BaseModel):
|
||||
name: str = Field(..., min_length=2, max_length=200)
|
||||
description: Optional[str] = Field("", max_length=4000)
|
||||
active: bool = True
|
||||
is_default: bool = False
|
||||
focus_area_id: Optional[int] = Field(None, ge=1)
|
||||
config: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def default_vs_focus(self):
|
||||
if self.is_default and self.focus_area_id is not None:
|
||||
raise ValueError("Standardprofil darf keinen Fokusbereich (focus_area_id) haben.")
|
||||
if not self.is_default and self.focus_area_id is None:
|
||||
raise ValueError("Profil ohne Standard-Flag benötigt eine focus_area_id.")
|
||||
return self
|
||||
|
||||
|
||||
class AiRetrievalProfileUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=2, max_length=200)
|
||||
description: Optional[str] = Field(None, max_length=4000)
|
||||
active: Optional[bool] = None
|
||||
is_default: Optional[bool] = None
|
||||
focus_area_id: Optional[int] = Field(None, ge=1)
|
||||
config: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
def _row_to_out(row: dict) -> dict:
|
||||
cfg = row.get("config")
|
||||
if isinstance(cfg, str):
|
||||
try:
|
||||
cfg = json.loads(cfg)
|
||||
except json.JSONDecodeError:
|
||||
cfg = {}
|
||||
if not isinstance(cfg, dict):
|
||||
cfg = {}
|
||||
out = {
|
||||
"id": row["id"],
|
||||
"focus_area_id": row.get("focus_area_id"),
|
||||
"focus_area_name": row.get("focus_area_name"),
|
||||
"is_default": bool(row.get("is_default")),
|
||||
"name": row.get("name") or "",
|
||||
"description": row.get("description") or "",
|
||||
"active": bool(row.get("active", True)),
|
||||
"config": cfg,
|
||||
"updated_at": row.get("updated_at"),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _active_focus_conflict(cur, focus_area_id: int, exclude_id: Optional[int] = None) -> bool:
|
||||
if exclude_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM ai_skill_retrieval_profiles
|
||||
WHERE active = true AND focus_area_id = %s AND id != %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(focus_area_id, exclude_id),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM ai_skill_retrieval_profiles
|
||||
WHERE active = true AND focus_area_id = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(focus_area_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _focus_area_exists(cur, focus_area_id: int) -> bool:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM focus_areas WHERE id = %s AND (status IS NULL OR status = 'active') LIMIT 1",
|
||||
(focus_area_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
@router.get("/api/admin/ai-skill-retrieval-profiles")
|
||||
def list_ai_skill_retrieval_profiles(session: dict = Depends(require_auth)):
|
||||
_require_superadmin(session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_table(cur)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id, p.focus_area_id, p.is_default, p.name, p.description, p.active, p.config, p.updated_at,
|
||||
fa.name AS focus_area_name
|
||||
FROM ai_skill_retrieval_profiles p
|
||||
LEFT JOIN focus_areas fa ON fa.id = p.focus_area_id
|
||||
ORDER BY p.is_default DESC NULLS LAST, fa.name NULLS LAST, p.name
|
||||
"""
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
return [_row_to_out(r) for r in rows]
|
||||
|
||||
|
||||
@router.get("/api/admin/ai-skill-retrieval-profiles/{profile_id}")
|
||||
def get_ai_skill_retrieval_profile(profile_id: int, session: dict = Depends(require_auth)):
|
||||
_require_superadmin(session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_table(cur)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id, p.focus_area_id, p.is_default, p.name, p.description, p.active, p.config, p.updated_at,
|
||||
fa.name AS focus_area_name
|
||||
FROM ai_skill_retrieval_profiles p
|
||||
LEFT JOIN focus_areas fa ON fa.id = p.focus_area_id
|
||||
WHERE p.id = %s
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
return _row_to_out(r2d(row))
|
||||
|
||||
|
||||
@router.post("/api/admin/ai-skill-retrieval-profiles", status_code=201)
|
||||
def create_ai_skill_retrieval_profile(
|
||||
body: AiRetrievalProfileCreate,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
_require_superadmin(session)
|
||||
cfg = _normalize_config(body.config)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_table(cur)
|
||||
|
||||
if body.is_default:
|
||||
cur.execute(
|
||||
"UPDATE ai_skill_retrieval_profiles SET is_default = false, updated_at = NOW() WHERE is_default = true"
|
||||
)
|
||||
else:
|
||||
if not _focus_area_exists(cur, int(body.focus_area_id)):
|
||||
raise HTTPException(status_code=400, detail="Unbekannter oder inaktiver Fokusbereich.")
|
||||
if body.active and _active_focus_conflict(cur, int(body.focus_area_id)):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Für diesen Fokusbereich existiert bereits ein aktives Profil.",
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO ai_skill_retrieval_profiles
|
||||
(focus_area_id, is_default, name, description, active, config, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, NOW())
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
None if body.is_default else body.focus_area_id,
|
||||
body.is_default,
|
||||
body.name.strip(),
|
||||
(body.description or "").strip(),
|
||||
body.active,
|
||||
Json(cfg),
|
||||
),
|
||||
)
|
||||
new_id_row = cur.fetchone()
|
||||
new_id = int(new_id_row["id"] if isinstance(new_id_row, dict) else new_id_row[0])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id, p.focus_area_id, p.is_default, p.name, p.description, p.active, p.config, p.updated_at,
|
||||
fa.name AS focus_area_name
|
||||
FROM ai_skill_retrieval_profiles p
|
||||
LEFT JOIN focus_areas fa ON fa.id = p.focus_area_id
|
||||
WHERE p.id = %s
|
||||
""",
|
||||
(new_id,),
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
return _row_to_out(row)
|
||||
|
||||
|
||||
@router.put("/api/admin/ai-skill-retrieval-profiles/{profile_id}")
|
||||
def update_ai_skill_retrieval_profile(
|
||||
profile_id: int,
|
||||
body: AiRetrievalProfileUpdate,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
_require_superadmin(session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_table(cur)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, focus_area_id, is_default, name, description, active, config, updated_at
|
||||
FROM ai_skill_retrieval_profiles WHERE id = %s
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
old = cur.fetchone()
|
||||
if not old:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
old_d = dict(old)
|
||||
|
||||
if body.is_default is True and body.focus_area_id is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Standardprofil und Fokusbereich schließen sich aus.",
|
||||
)
|
||||
|
||||
nm = body.name.strip() if body.name is not None else (old_d["name"] or "")
|
||||
nm = nm.strip()
|
||||
desc = (
|
||||
body.description.strip() if body.description is not None else (old_d.get("description") or "")
|
||||
).strip()
|
||||
active = body.active if body.active is not None else bool(old_d.get("active", True))
|
||||
next_is_default = body.is_default if body.is_default is not None else bool(old_d.get("is_default"))
|
||||
next_focus_raw = (
|
||||
body.focus_area_id if body.focus_area_id is not None else old_d.get("focus_area_id")
|
||||
)
|
||||
cfg = (
|
||||
_normalize_config(body.config) if body.config is not None else _normalize_config(old_d.get("config"))
|
||||
)
|
||||
|
||||
if next_is_default:
|
||||
focus_id_sql: Optional[int] = None
|
||||
else:
|
||||
if next_focus_raw is None:
|
||||
raise HTTPException(status_code=400, detail="Nicht-Standard-Profil benötigt focus_area_id.")
|
||||
focus_id_sql = int(next_focus_raw)
|
||||
if not _focus_area_exists(cur, focus_id_sql):
|
||||
raise HTTPException(status_code=400, detail="Unbekannter oder inaktiver Fokusbereich.")
|
||||
if active and _active_focus_conflict(cur, focus_id_sql, exclude_id=profile_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Für diesen Fokusbereich existiert bereits ein anderes aktives Profil.",
|
||||
)
|
||||
|
||||
old_default = bool(old_d.get("is_default"))
|
||||
|
||||
if old_default and not next_is_default:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Das Standardprofil kann hier nicht zum Fokusbereichsprofil geändert werden — zuerst ein anderes Profil als Standard aktivieren.",
|
||||
)
|
||||
|
||||
if old_default and active is False:
|
||||
raise HTTPException(status_code=400, detail="Standardprofil kann nicht deaktiviert werden.")
|
||||
|
||||
if next_is_default:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE ai_skill_retrieval_profiles
|
||||
SET is_default = false, updated_at = NOW()
|
||||
WHERE is_default = true AND id != %s
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE ai_skill_retrieval_profiles
|
||||
SET focus_area_id = %s,
|
||||
is_default = %s,
|
||||
name = %s,
|
||||
description = %s,
|
||||
active = %s,
|
||||
config = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
focus_id_sql,
|
||||
next_is_default,
|
||||
nm,
|
||||
desc,
|
||||
active,
|
||||
Json(cfg),
|
||||
profile_id,
|
||||
),
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id, p.focus_area_id, p.is_default, p.name, p.description, p.active, p.config, p.updated_at,
|
||||
fa.name AS focus_area_name
|
||||
FROM ai_skill_retrieval_profiles p
|
||||
LEFT JOIN focus_areas fa ON fa.id = p.focus_area_id
|
||||
WHERE p.id = %s
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
row = r2d(cur.fetchone())
|
||||
return _row_to_out(row)
|
||||
|
||||
|
||||
@router.delete("/api/admin/ai-skill-retrieval-profiles/{profile_id}")
|
||||
def delete_ai_skill_retrieval_profile(profile_id: int, session: dict = Depends(require_auth)):
|
||||
_require_superadmin(session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_table(cur)
|
||||
cur.execute(
|
||||
"SELECT id, is_default FROM ai_skill_retrieval_profiles WHERE id = %s",
|
||||
(profile_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||
if bool(row.get("is_default") if isinstance(row, dict) else row[1]):
|
||||
raise HTTPException(status_code=400, detail="Standardprofil kann nicht gelöscht werden.")
|
||||
cur.execute("DELETE FROM ai_skill_retrieval_profiles WHERE id = %s", (profile_id,))
|
||||
return {"deleted": True, "id": profile_id}
|
||||
@@ -0,0 +1,448 @@
|
||||
"""
|
||||
Superadmin API: Batch-Anreicherung von Übungen per KI (Skills, Kurzfassung, Anleitung).
|
||||
|
||||
# ACCESS_LAYER exempt: Plattform-weites Superadmin-Werkzeug ohne TenantContext.
|
||||
Siehe ACCESS_LAYER_ENDPOINT_AUDIT.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Dict, List, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db, r2d
|
||||
from exercise_enrichment import (
|
||||
DEFAULT_SET_STATUS,
|
||||
MAX_BATCH_EXERCISES,
|
||||
MAX_PREVIEW_BATCH_EXERCISES,
|
||||
SKILL_MERGE_MODES,
|
||||
SkillMergeMode,
|
||||
apply_exercise_enrichment,
|
||||
estimate_llm_calls,
|
||||
preview_exercise_enrichment,
|
||||
)
|
||||
|
||||
_PREVIEW_MAX_WORKERS = 3
|
||||
|
||||
router = APIRouter(tags=["admin_exercise_enrichment"])
|
||||
|
||||
_VALID_STATUS_FILTER = frozenset({"draft", "in_review", "approved", "archived"})
|
||||
_VALID_VISIBILITY = frozenset({"private", "club", "official", "all"})
|
||||
_MAX_CANDIDATES_LIMIT = 100
|
||||
_MAX_ANALYZE_IDS = 10_000
|
||||
|
||||
|
||||
def _require_superadmin(session: dict) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_id_list(raw: Optional[List[int]], *, max_items: Optional[int] = None) -> List[int]:
|
||||
if not raw:
|
||||
return []
|
||||
seen: set[int] = set()
|
||||
out: List[int] = []
|
||||
for x in raw:
|
||||
try:
|
||||
xi = int(x)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if xi < 1 or xi in seen:
|
||||
continue
|
||||
seen.add(xi)
|
||||
out.append(xi)
|
||||
if max_items is not None and len(out) >= max_items:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _build_candidates_where(
|
||||
*,
|
||||
status: str,
|
||||
visibility: Optional[str],
|
||||
focus_area_id: Optional[int],
|
||||
without_skills: bool,
|
||||
with_ai_suggested_skills: bool,
|
||||
) -> tuple[list[str], list[Any]]:
|
||||
st = (status or "draft").strip().lower()
|
||||
if st not in _VALID_STATUS_FILTER:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger Status-Filter")
|
||||
|
||||
where: List[str] = ["e.status = %s"]
|
||||
params: List[Any] = [st]
|
||||
|
||||
vis_raw = (visibility or "private").strip().lower()
|
||||
if vis_raw and vis_raw != "all":
|
||||
if vis_raw not in _VALID_VISIBILITY - {"all"}:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger Visibility-Filter")
|
||||
where.append("e.visibility = %s")
|
||||
params.append(vis_raw)
|
||||
|
||||
if focus_area_id is not None:
|
||||
where.append(
|
||||
"EXISTS (SELECT 1 FROM exercise_focus_areas efa "
|
||||
"WHERE efa.exercise_id = e.id AND efa.focus_area_id = %s)"
|
||||
)
|
||||
params.append(int(focus_area_id))
|
||||
|
||||
if without_skills:
|
||||
where.append(
|
||||
"NOT EXISTS (SELECT 1 FROM exercise_skills es WHERE es.exercise_id = e.id)"
|
||||
)
|
||||
|
||||
if with_ai_suggested_skills:
|
||||
where.append(
|
||||
"EXISTS (SELECT 1 FROM exercise_skills es "
|
||||
"WHERE es.exercise_id = e.id AND es.ai_suggested = true)"
|
||||
)
|
||||
|
||||
return where, params
|
||||
|
||||
|
||||
class EnrichmentModes(BaseModel):
|
||||
skills: bool = True
|
||||
summary: bool = False
|
||||
instructions: bool = False
|
||||
|
||||
|
||||
class EnrichmentPreviewBody(BaseModel):
|
||||
exercise_ids: List[int] = Field(..., min_length=1, max_length=MAX_PREVIEW_BATCH_EXERCISES)
|
||||
modes: EnrichmentModes = Field(default_factory=EnrichmentModes)
|
||||
merge_mode: SkillMergeMode = "replace_all"
|
||||
|
||||
@field_validator("merge_mode")
|
||||
@classmethod
|
||||
def _merge_mode_ok(cls, v: str) -> str:
|
||||
if v not in SKILL_MERGE_MODES:
|
||||
raise ValueError("merge_mode: additive, replace_ai_only oder replace_all")
|
||||
return v
|
||||
|
||||
|
||||
class EnrichmentAnalyzeBody(BaseModel):
|
||||
exercise_ids: List[int] = Field(..., min_length=1, max_length=_MAX_ANALYZE_IDS)
|
||||
modes: EnrichmentModes = Field(default_factory=EnrichmentModes)
|
||||
|
||||
|
||||
class EnrichmentApplyItem(BaseModel):
|
||||
exercise_id: int = Field(..., ge=1)
|
||||
merged_skills: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
summary: Optional[str] = None
|
||||
instruction_fields: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class EnrichmentApplyBody(BaseModel):
|
||||
items: List[EnrichmentApplyItem] = Field(..., min_length=1, max_length=MAX_BATCH_EXERCISES)
|
||||
modes: EnrichmentModes = Field(default_factory=EnrichmentModes)
|
||||
merge_mode: SkillMergeMode = "replace_all"
|
||||
set_status: Optional[str] = DEFAULT_SET_STATUS
|
||||
|
||||
@field_validator("merge_mode")
|
||||
@classmethod
|
||||
def _merge_mode_ok(cls, v: str) -> str:
|
||||
if v not in SKILL_MERGE_MODES:
|
||||
raise ValueError("merge_mode: additive, replace_ai_only oder replace_all")
|
||||
return v
|
||||
|
||||
@field_validator("set_status")
|
||||
@classmethod
|
||||
def _status_ok(cls, v: Optional[str]) -> Optional[str]:
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip().lower()
|
||||
if s == "approved":
|
||||
raise ValueError("Automatisches Freigeben (approved) ist nicht erlaubt")
|
||||
if s not in _VALID_STATUS_FILTER:
|
||||
raise ValueError("Ungültiger Ziel-Status")
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/api/admin/exercise-enrichment/candidates")
|
||||
def list_enrichment_candidates(
|
||||
session: dict = Depends(require_auth),
|
||||
status: str = Query(default="draft"),
|
||||
visibility: Optional[str] = Query(default="private"),
|
||||
focus_area_id: Optional[int] = Query(default=None, ge=1),
|
||||
without_skills: bool = Query(default=False),
|
||||
with_ai_suggested_skills: bool = Query(default=False),
|
||||
search: Optional[str] = Query(default=None, max_length=200),
|
||||
limit: int = Query(default=25, ge=1, le=_MAX_CANDIDATES_LIMIT),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
):
|
||||
"""Paginierte Kandidatenliste für Superadmin-Anreicherung."""
|
||||
_require_superadmin(session)
|
||||
|
||||
where, params = _build_candidates_where(
|
||||
status=status,
|
||||
visibility=visibility,
|
||||
focus_area_id=focus_area_id,
|
||||
without_skills=without_skills,
|
||||
with_ai_suggested_skills=with_ai_suggested_skills,
|
||||
)
|
||||
|
||||
qtext = (search or "").strip()
|
||||
if qtext:
|
||||
where.append("e.search_vector @@ plainto_tsquery('german', %s)")
|
||||
params.append(qtext)
|
||||
|
||||
where_sql = " AND ".join(where)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"SELECT COUNT(*) AS c FROM exercises e WHERE {where_sql}", tuple(params))
|
||||
count_row = cur.fetchone()
|
||||
total = int(count_row["c"] if isinstance(count_row, dict) else count_row[0])
|
||||
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT e.id, e.title, e.status, e.visibility, e.summary, e.updated_at,
|
||||
(
|
||||
SELECT fa.name FROM exercise_focus_areas efa
|
||||
JOIN focus_areas fa ON fa.id = efa.focus_area_id
|
||||
WHERE efa.exercise_id = e.id
|
||||
ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC
|
||||
LIMIT 1
|
||||
) AS primary_focus_name,
|
||||
(
|
||||
SELECT COUNT(*)::int FROM exercise_skills es WHERE es.exercise_id = e.id
|
||||
) AS skill_count,
|
||||
(
|
||||
SELECT COUNT(*)::int FROM exercise_skills es
|
||||
WHERE es.exercise_id = e.id AND es.ai_suggested = true
|
||||
) AS ai_suggested_skill_count
|
||||
FROM exercises e
|
||||
WHERE {where_sql}
|
||||
ORDER BY e.updated_at DESC, e.id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
""",
|
||||
tuple(params + [limit, offset]),
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
return {
|
||||
"items": rows,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/exercise-enrichment/candidate-ids")
|
||||
def list_enrichment_candidate_ids(
|
||||
session: dict = Depends(require_auth),
|
||||
status: str = Query(default="draft"),
|
||||
visibility: Optional[str] = Query(default="private"),
|
||||
focus_area_id: Optional[int] = Query(default=None, ge=1),
|
||||
without_skills: bool = Query(default=False),
|
||||
with_ai_suggested_skills: bool = Query(default=False),
|
||||
search: Optional[str] = Query(default=None, max_length=200),
|
||||
):
|
||||
"""Alle IDs zum aktuellen Filter (für „Alle auswählen“) — ohne Pagination-Obergrenze."""
|
||||
_require_superadmin(session)
|
||||
|
||||
where, params = _build_candidates_where(
|
||||
status=status,
|
||||
visibility=visibility,
|
||||
focus_area_id=focus_area_id,
|
||||
without_skills=without_skills,
|
||||
with_ai_suggested_skills=with_ai_suggested_skills,
|
||||
)
|
||||
|
||||
qtext = (search or "").strip()
|
||||
if qtext:
|
||||
where.append("e.search_vector @@ plainto_tsquery('german', %s)")
|
||||
params.append(qtext)
|
||||
|
||||
where_sql = " AND ".join(where)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
f"SELECT e.id FROM exercises e WHERE {where_sql} ORDER BY e.updated_at DESC, e.id DESC",
|
||||
tuple(params),
|
||||
)
|
||||
ids = [int(r["id"] if isinstance(r, dict) else r[0]) for r in cur.fetchall()]
|
||||
|
||||
return {"ids": ids, "total": len(ids)}
|
||||
|
||||
|
||||
@router.post("/api/admin/exercise-enrichment/analyze")
|
||||
def analyze_enrichment(body: EnrichmentAnalyzeBody, session: dict = Depends(require_auth)):
|
||||
"""Kosten-/Umfangsanalyse vor dem Batch-Lauf (explizite Nutzerbestätigung)."""
|
||||
_require_superadmin(session)
|
||||
|
||||
ids = _normalize_id_list(body.exercise_ids, max_items=_MAX_ANALYZE_IDS)
|
||||
if not ids:
|
||||
raise HTTPException(status_code=400, detail="Keine gültigen Übungs-IDs")
|
||||
|
||||
if not body.modes.skills and not body.modes.summary and not body.modes.instructions:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Mindestens ein Modus (skills, summary oder instructions) aktivieren",
|
||||
)
|
||||
|
||||
est = estimate_llm_calls(
|
||||
exercise_count=len(ids),
|
||||
want_skills=body.modes.skills,
|
||||
want_summary=body.modes.summary,
|
||||
want_instructions=body.modes.instructions,
|
||||
)
|
||||
|
||||
return {
|
||||
"exercise_count": len(ids),
|
||||
"estimated_llm_calls": est,
|
||||
"modes": body.modes.model_dump(),
|
||||
"warning": (
|
||||
f"Batch mit {len(ids)} Übungen und ca. {est['total']} LLM-Aufrufen — Kosten beachten."
|
||||
if len(ids) >= 25 or est["total"] >= 50
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _preview_one_exercise(
|
||||
ex_id: int,
|
||||
*,
|
||||
want_skills: bool,
|
||||
want_summary: bool,
|
||||
want_instructions: bool,
|
||||
merge_mode: SkillMergeMode,
|
||||
) -> Dict[str, Any]:
|
||||
"""Einzel-Preview mit eigener DB-Connection (Thread-Pool)."""
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
row = preview_exercise_enrichment(
|
||||
cur,
|
||||
ex_id,
|
||||
want_skills=want_skills,
|
||||
want_summary=want_summary,
|
||||
want_instructions=want_instructions,
|
||||
merge_mode=merge_mode,
|
||||
)
|
||||
return row
|
||||
except HTTPException as he:
|
||||
d = he.detail
|
||||
return {"exercise_id": ex_id, "ok": False, "error": d if isinstance(d, str) else str(d)}
|
||||
except Exception as exc: # pragma: no cover
|
||||
return {"exercise_id": ex_id, "ok": False, "error": str(exc)}
|
||||
|
||||
|
||||
@router.post("/api/admin/exercise-enrichment/preview")
|
||||
def preview_enrichment(body: EnrichmentPreviewBody, session: dict = Depends(require_auth)):
|
||||
"""Dry-Run: KI-Vorschläge laden, nichts speichern (max. 3 Übungen/Request, parallel)."""
|
||||
_require_superadmin(session)
|
||||
|
||||
ids = _normalize_id_list(body.exercise_ids, max_items=MAX_PREVIEW_BATCH_EXERCISES)
|
||||
if not ids:
|
||||
raise HTTPException(status_code=400, detail="Keine gültigen Übungs-IDs")
|
||||
|
||||
modes = body.modes
|
||||
if not modes.skills and not modes.summary and not modes.instructions:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Mindestens ein Modus (skills, summary oder instructions) aktivieren",
|
||||
)
|
||||
|
||||
results: List[Dict[str, Any]] = []
|
||||
errors: List[Dict[str, Any]] = []
|
||||
|
||||
workers = min(_PREVIEW_MAX_WORKERS, len(ids))
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [
|
||||
pool.submit(
|
||||
_preview_one_exercise,
|
||||
ex_id,
|
||||
want_skills=modes.skills,
|
||||
want_summary=modes.summary,
|
||||
want_instructions=modes.instructions,
|
||||
merge_mode=body.merge_mode,
|
||||
)
|
||||
for ex_id in ids
|
||||
]
|
||||
for fut in as_completed(futures):
|
||||
row = fut.result()
|
||||
if row.get("ok"):
|
||||
results.append(row)
|
||||
else:
|
||||
errors.append(row)
|
||||
|
||||
results.sort(key=lambda r: int(r.get("exercise_id") or 0))
|
||||
errors.sort(key=lambda r: int(r.get("exercise_id") or 0))
|
||||
|
||||
est = estimate_llm_calls(
|
||||
exercise_count=len(ids),
|
||||
want_skills=modes.skills,
|
||||
want_summary=modes.summary,
|
||||
want_instructions=modes.instructions,
|
||||
)
|
||||
|
||||
return {
|
||||
"results": results,
|
||||
"errors": errors,
|
||||
"processed": len(ids),
|
||||
"ok_count": len(results),
|
||||
"error_count": len(errors),
|
||||
"estimated_llm_calls": est,
|
||||
"merge_mode": body.merge_mode,
|
||||
"modes": modes.model_dump(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/admin/exercise-enrichment/apply")
|
||||
def apply_enrichment(body: EnrichmentApplyBody, session: dict = Depends(require_auth)):
|
||||
"""Vorschläge anwenden und optional Status setzen (Default: in_review)."""
|
||||
_require_superadmin(session)
|
||||
|
||||
if not body.items:
|
||||
raise HTTPException(status_code=400, detail="Keine Items")
|
||||
|
||||
modes = body.modes
|
||||
if not modes.skills and not modes.summary and not modes.instructions:
|
||||
raise HTTPException(status_code=400, detail="Kein Anwendungsmodus aktiv")
|
||||
|
||||
applied: List[Dict[str, Any]] = []
|
||||
failed: List[Dict[str, Any]] = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
for item in body.items:
|
||||
ex_id = int(item.exercise_id)
|
||||
try:
|
||||
row = apply_exercise_enrichment(
|
||||
cur,
|
||||
ex_id,
|
||||
merged_skills=item.merged_skills,
|
||||
merge_mode=body.merge_mode,
|
||||
set_status=body.set_status,
|
||||
apply_skills=modes.skills,
|
||||
summary_text=item.summary,
|
||||
apply_summary=modes.summary,
|
||||
instruction_fields=item.instruction_fields,
|
||||
apply_instructions=modes.instructions,
|
||||
)
|
||||
if row.get("ok"):
|
||||
applied.append(row)
|
||||
else:
|
||||
failed.append(row)
|
||||
except HTTPException as he:
|
||||
d = he.detail
|
||||
failed.append({"exercise_id": ex_id, "ok": False, "error": d if isinstance(d, str) else str(d)})
|
||||
except Exception as exc: # pragma: no cover
|
||||
failed.append({"exercise_id": ex_id, "ok": False, "error": str(exc)})
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
"applied": applied,
|
||||
"failed": failed,
|
||||
"applied_count": len(applied),
|
||||
"failed_count": len(failed),
|
||||
"set_status": body.set_status,
|
||||
"merge_mode": body.merge_mode,
|
||||
"modes": modes.model_dump(),
|
||||
}
|
||||
@@ -35,6 +35,9 @@ from tenant_context import TenantContext, get_tenant_context, get_tenant_context
|
||||
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
|
||||
from media_rights import assert_rights_for_exercise_link, validate_rights_declaration, write_rights_declaration, update_rights_quick_fields
|
||||
from media_legal_hold import assert_not_under_legal_hold
|
||||
from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContext
|
||||
from ai_prompt_job import run_exercise_form_ai_suggestion
|
||||
|
||||
from exercise_rich_text import (
|
||||
RICH_HTML_EXERCISE_FIELDS,
|
||||
assert_no_inline_media_references_on_create,
|
||||
@@ -356,6 +359,66 @@ class ExerciseMediaFromAsset(BaseModel):
|
||||
media_type: Optional[str] = None
|
||||
|
||||
|
||||
class ExerciseAiFocusCtx(ExerciseFormAiFocusRow):
|
||||
"""Alias fuer OpenAPI — identisch zu ExerciseFormAiFocusRow."""
|
||||
|
||||
|
||||
class ExerciseAiSuggestBody(BaseModel):
|
||||
title: Optional[str] = Field(None, max_length=300)
|
||||
goal: Optional[str] = Field(None, max_length=64000)
|
||||
execution: Optional[str] = Field(None, max_length=128000)
|
||||
preparation: Optional[str] = Field(None, max_length=64000)
|
||||
trainer_notes: Optional[str] = Field(None, max_length=64000)
|
||||
focus_area_hint: Optional[str] = Field(None, max_length=1200)
|
||||
focus_areas_context: Optional[list[ExerciseFormAiFocusRow]] = Field(
|
||||
None,
|
||||
description="Optionale Reihenfolge Primär zuerst; steuert Katalogpriorisierung",
|
||||
)
|
||||
include_summary: bool = True
|
||||
include_skills: bool = True
|
||||
include_instructions: bool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_include_any(self):
|
||||
if not self.include_summary and not self.include_skills and not self.include_instructions:
|
||||
raise ValueError(
|
||||
"Mindestens include_summary, include_skills oder include_instructions aktivieren."
|
||||
)
|
||||
return self
|
||||
|
||||
def to_form_context(self) -> ExerciseFormAiPromptContext:
|
||||
return ExerciseFormAiPromptContext.from_api_suggest(
|
||||
title=self.title,
|
||||
goal=self.goal,
|
||||
execution=self.execution,
|
||||
preparation=self.preparation,
|
||||
trainer_notes=self.trainer_notes,
|
||||
focus_area_hint=self.focus_area_hint,
|
||||
focus_areas_context=self.focus_areas_context,
|
||||
)
|
||||
|
||||
|
||||
class ExerciseAiRegenerateBody(BaseModel):
|
||||
"""Welche Artefakte neu angefragt werden sollen."""
|
||||
|
||||
regenerate: list[str] = Field(default_factory=lambda: ["summary", "skills"])
|
||||
|
||||
@model_validator(mode="after")
|
||||
def normalize_regs(self):
|
||||
allowed = {"summary", "skills", "instructions"}
|
||||
raw = [str(x).strip().lower() for x in (self.regenerate or [])]
|
||||
out = []
|
||||
seen = set()
|
||||
for lx in raw:
|
||||
if lx in allowed and lx not in seen:
|
||||
out.append(lx)
|
||||
seen.add(lx)
|
||||
if not out:
|
||||
out = ["summary", "skills"]
|
||||
self.regenerate = out
|
||||
return self
|
||||
|
||||
|
||||
class ExerciseVariantCreate(BaseModel):
|
||||
variant_name: str = Field(..., min_length=3, max_length=200)
|
||||
description: Optional[str] = None
|
||||
@@ -1244,7 +1307,7 @@ def assign_exercise_relations(
|
||||
(
|
||||
exercise_id,
|
||||
skill["skill_id"],
|
||||
False,
|
||||
bool(skill.get("is_primary")),
|
||||
normalize_exercise_skill_intensity(skill.get("intensity")),
|
||||
normalize_exercise_skill_level(skill.get("required_level")),
|
||||
normalize_exercise_skill_level(skill.get("target_level")),
|
||||
@@ -2216,6 +2279,98 @@ def list_exercises_like_get(
|
||||
)
|
||||
|
||||
|
||||
def _focus_areas_ai_ctx_from_detail(exercise: Dict[str, Any]) -> list[tuple[int, bool]]:
|
||||
rows: list[tuple[int, bool]] = []
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
try:
|
||||
fid = int(row.get("focus_area_id"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if fid < 1:
|
||||
continue
|
||||
rows.append((fid, bool(row.get("is_primary"))))
|
||||
rows.sort(key=lambda x: (not x[1], x[0]))
|
||||
return rows
|
||||
|
||||
|
||||
def _focus_area_hint_from_detail(exercise: Dict[str, Any]) -> str:
|
||||
parts: List[str] = []
|
||||
for row in exercise.get("focus_areas") or []:
|
||||
if isinstance(row, dict):
|
||||
nm = (row.get("name") or "").strip()
|
||||
if nm:
|
||||
parts.append(nm)
|
||||
txt = ", ".join(parts).strip()
|
||||
if len(txt) > 900:
|
||||
return txt[:899] + "…"
|
||||
return txt
|
||||
|
||||
|
||||
@router.post("/exercises/ai/suggest")
|
||||
def exercise_ai_suggest_endpoint(
|
||||
body: ExerciseAiSuggestBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
KI-Vorschlaege (Kurzfassung und/oder Skill-Zuordnung) ohne Speichern.
|
||||
OPENROUTER_API_KEY erforderlich.
|
||||
"""
|
||||
_ = tenant.profile_id
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = run_exercise_form_ai_suggestion(
|
||||
cur,
|
||||
body.to_form_context(),
|
||||
want_summary=body.include_summary,
|
||||
want_skills=body.include_skills,
|
||||
want_instructions=body.include_instructions,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@router.post("/exercises/{exercise_id}/ai/regenerate")
|
||||
def exercise_ai_regenerate_endpoint(
|
||||
exercise_id: int,
|
||||
body: ExerciseAiRegenerateBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""Neu-Anfrage KI fuer eine gespeicherte Uebung; schreibendes Ergebnis nur im Frontend (PUT)."""
|
||||
want_summary = "summary" in body.regenerate
|
||||
want_skills = "skills" in body.regenerate
|
||||
want_instructions = "instructions" in body.regenerate
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
if not exercise:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
|
||||
focus = _focus_area_hint_from_detail(exercise)
|
||||
fctx = _focus_areas_ai_ctx_from_detail(exercise)
|
||||
|
||||
ctx = ExerciseFormAiPromptContext.from_focus_tuples(
|
||||
title=str(exercise.get("title") or "").strip(),
|
||||
goal=exercise.get("goal"),
|
||||
execution=exercise.get("execution"),
|
||||
preparation=exercise.get("preparation"),
|
||||
trainer_notes=exercise.get("trainer_notes"),
|
||||
focus_hint=focus or None,
|
||||
focus_tuples=fctx or None,
|
||||
)
|
||||
payload = run_exercise_form_ai_suggestion(
|
||||
cur,
|
||||
ctx,
|
||||
want_summary=want_summary,
|
||||
want_skills=want_skills,
|
||||
want_instructions=want_instructions,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/exercises/{exercise_id}")
|
||||
def get_exercise(
|
||||
exercise_id: int,
|
||||
|
||||
@@ -0,0 +1,727 @@
|
||||
"""
|
||||
Superadmin Export/Import für zentrale Pflege der Fähigkeitsmatrix.
|
||||
|
||||
Fokus: Beschreibungen und Gewichtungen (skills.importance, model_skills.relevance,
|
||||
skill_level_definitions, model_skill_levels) — flaches, bearbeitbares Format.
|
||||
|
||||
Kein Vereinsbezug — require_auth + is_superadmin; kein TenantContext.
|
||||
# ACCESS_LAYER exempt: Plattform-Superadmin-Tool; globale Fähigkeitsmatrix ohne Mandantenkontext
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.responses import JSONResponse, PlainTextResponse
|
||||
|
||||
from auth import require_auth
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin/matrix-editor", tags=["admin_matrix_editor"])
|
||||
|
||||
KIND_V1 = "shinkan.matrix_editor.v1"
|
||||
|
||||
SKILLS_CSV_FIELDS = [
|
||||
"skill_key",
|
||||
"main_category",
|
||||
"subcategory",
|
||||
"skill_name",
|
||||
"description",
|
||||
"importance",
|
||||
"karate_relevance",
|
||||
"relevance_level",
|
||||
"level_1",
|
||||
"level_2",
|
||||
"level_3",
|
||||
"level_4",
|
||||
"level_5",
|
||||
]
|
||||
|
||||
MATRIX_CSV_FIELDS = [
|
||||
"model_key",
|
||||
"model_name",
|
||||
"skill_key",
|
||||
"skill_name",
|
||||
"relevance",
|
||||
"sort_order",
|
||||
"level_number",
|
||||
"level_label",
|
||||
"description",
|
||||
"observable_criteria",
|
||||
]
|
||||
|
||||
|
||||
def _require_superadmin(session: dict) -> dict:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||
return session
|
||||
|
||||
|
||||
def _slugify_label(text: str) -> str:
|
||||
t = (text or "").strip().lower()
|
||||
t = re.sub(r"[^a-z0-9äöüß]+", "_", t, flags=re.IGNORECASE)
|
||||
t = re.sub(r"_+", "_", t).strip("_")
|
||||
return t[:48] or "gruppe"
|
||||
|
||||
|
||||
def _skill_key(main_slug: Optional[str], cat_slug: Optional[str], name: str) -> str:
|
||||
return f"{main_slug or ''}|{cat_slug or ''}|{(name or '').strip()}"
|
||||
|
||||
|
||||
def _model_key(import_id: Optional[str], name: str) -> str:
|
||||
iid = (import_id or "").strip()
|
||||
if iid:
|
||||
return iid
|
||||
return _slugify_label(name)
|
||||
|
||||
|
||||
def _parse_skill_key(raw: str) -> Tuple[str, str, str]:
|
||||
parts = (raw or "").split("|", 2)
|
||||
while len(parts) < 3:
|
||||
parts.append("")
|
||||
return parts[0], parts[1], parts[2]
|
||||
|
||||
|
||||
def _csv_response(text: str, filename: str) -> PlainTextResponse:
|
||||
return PlainTextResponse(
|
||||
content=text,
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
def _rows_to_csv(fieldnames: List[str], rows: List[Dict[str, Any]]) -> str:
|
||||
buf = io.StringIO()
|
||||
writer = csv.DictWriter(buf, fieldnames=fieldnames, extrasaction="ignore", lineterminator="\n")
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow({k: row.get(k, "") for k in fieldnames})
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _load_editor_payload(cur) -> Dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id, s.name, s.description, s.importance, s.karate_relevance, s.relevance_level,
|
||||
mc.slug AS main_category_slug, mc.name AS main_category_name,
|
||||
sc.slug AS category_slug, sc.name AS category_name
|
||||
FROM skills s
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
ORDER BY mc.sort_order NULLS LAST, sc.sort_order NULLS LAST, s.sort_order NULLS LAST, s.name
|
||||
"""
|
||||
)
|
||||
skill_rows = [r2d(r) for r in cur.fetchall()]
|
||||
skill_ids = [int(r["id"]) for r in skill_rows]
|
||||
|
||||
level_defs: Dict[int, Dict[int, str]] = {}
|
||||
if skill_ids:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT skill_id, level, description
|
||||
FROM skill_level_definitions
|
||||
WHERE skill_id = ANY(%s)
|
||||
ORDER BY skill_id, level
|
||||
""",
|
||||
(skill_ids,),
|
||||
)
|
||||
for r in cur.fetchall():
|
||||
sid = int(r["skill_id"])
|
||||
level_defs.setdefault(sid, {})[int(r["level"])] = r.get("description") or ""
|
||||
|
||||
skills_out: List[Dict[str, Any]] = []
|
||||
skills_csv: List[Dict[str, Any]] = []
|
||||
for s in skill_rows:
|
||||
sid = int(s["id"])
|
||||
main_slug = s.get("main_category_slug")
|
||||
cat_slug = s.get("category_slug")
|
||||
name = (s.get("name") or "").strip()
|
||||
key = _skill_key(main_slug, cat_slug, name)
|
||||
defs = level_defs.get(sid, {})
|
||||
level_map = {str(i): defs.get(i, "") for i in range(1, 6)}
|
||||
entry = {
|
||||
"skill_key": key,
|
||||
"main_category": s.get("main_category_name") or "",
|
||||
"subcategory": s.get("category_name") or "",
|
||||
"skill_name": name,
|
||||
"description": s.get("description") or "",
|
||||
"importance": s.get("importance"),
|
||||
"karate_relevance": s.get("karate_relevance"),
|
||||
"relevance_level": s.get("relevance_level"),
|
||||
"level_definitions": level_map,
|
||||
}
|
||||
skills_out.append(entry)
|
||||
csv_row = {
|
||||
"skill_key": key,
|
||||
"main_category": entry["main_category"],
|
||||
"subcategory": entry["subcategory"],
|
||||
"skill_name": name,
|
||||
"description": entry["description"],
|
||||
"importance": entry["importance"] if entry["importance"] is not None else "",
|
||||
"karate_relevance": entry["karate_relevance"] or "",
|
||||
"relevance_level": entry["relevance_level"] if entry["relevance_level"] is not None else "",
|
||||
}
|
||||
for i in range(1, 6):
|
||||
csv_row[f"level_{i}"] = level_map.get(str(i), "")
|
||||
skills_csv.append(csv_row)
|
||||
|
||||
cur.execute("SELECT id, name, import_id, level_count, status FROM maturity_models ORDER BY name")
|
||||
models_raw = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
models_out: List[Dict[str, Any]] = []
|
||||
matrix_csv: List[Dict[str, Any]] = []
|
||||
for m in models_raw:
|
||||
mid = int(m["id"])
|
||||
mkey = _model_key(m.get("import_id"), m.get("name") or "")
|
||||
mname = (m.get("name") or "").strip()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT level_number, name, description
|
||||
FROM model_levels
|
||||
WHERE maturity_model_id = %s
|
||||
ORDER BY sort_order ASC, level_number ASC
|
||||
""",
|
||||
(mid,),
|
||||
)
|
||||
levels = [r2d(r) for r in cur.fetchall()]
|
||||
level_label = {int(lv["level_number"]): lv.get("name") or "" for lv in levels}
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT ms.skill_id, ms.sort_order, ms.relevance, s.name AS skill_name,
|
||||
mc.slug AS main_category_slug, sc.slug AS category_slug
|
||||
FROM model_skills ms
|
||||
JOIN skills s ON s.id = ms.skill_id
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE ms.maturity_model_id = %s
|
||||
ORDER BY ms.sort_order ASC, ms.id ASC
|
||||
""",
|
||||
(mid,),
|
||||
)
|
||||
model_skills = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT msl.skill_id, msl.level_number, msl.description, msl.observable_criteria,
|
||||
s.name AS skill_name, mc.slug AS main_category_slug, sc.slug AS category_slug
|
||||
FROM model_skill_levels msl
|
||||
JOIN skills s ON s.id = msl.skill_id
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE msl.maturity_model_id = %s
|
||||
ORDER BY msl.skill_id, msl.level_number
|
||||
""",
|
||||
(mid,),
|
||||
)
|
||||
skill_levels = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
ms_by_skill: Dict[int, Dict[str, Any]] = {int(ms["skill_id"]): ms for ms in model_skills}
|
||||
cells_by_skill: Dict[int, List[Dict[str, Any]]] = {}
|
||||
for sl in skill_levels:
|
||||
sid = int(sl["skill_id"])
|
||||
cells_by_skill.setdefault(sid, []).append(
|
||||
{
|
||||
"level_number": int(sl["level_number"]),
|
||||
"description": sl.get("description") or "",
|
||||
"observable_criteria": sl.get("observable_criteria"),
|
||||
}
|
||||
)
|
||||
|
||||
matrix_rows: List[Dict[str, Any]] = []
|
||||
seen_skills = set()
|
||||
for ms in model_skills:
|
||||
sid = int(ms["skill_id"])
|
||||
seen_skills.add(sid)
|
||||
skey = _skill_key(ms.get("main_category_slug"), ms.get("category_slug"), ms.get("skill_name") or "")
|
||||
matrix_rows.append(
|
||||
{
|
||||
"skill_key": skey,
|
||||
"skill_name": ms.get("skill_name") or "",
|
||||
"relevance": ms.get("relevance"),
|
||||
"sort_order": int(ms.get("sort_order") or 0),
|
||||
"cells": cells_by_skill.get(sid, []),
|
||||
}
|
||||
)
|
||||
for cell in cells_by_skill.get(sid, []):
|
||||
ln = int(cell["level_number"])
|
||||
matrix_csv.append(
|
||||
{
|
||||
"model_key": mkey,
|
||||
"model_name": mname,
|
||||
"skill_key": skey,
|
||||
"skill_name": ms.get("skill_name") or "",
|
||||
"relevance": ms.get("relevance") or "",
|
||||
"sort_order": int(ms.get("sort_order") or 0),
|
||||
"level_number": ln,
|
||||
"level_label": level_label.get(ln, ""),
|
||||
"description": cell.get("description") or "",
|
||||
"observable_criteria": cell.get("observable_criteria") or "",
|
||||
}
|
||||
)
|
||||
|
||||
for sid, cells in cells_by_skill.items():
|
||||
if sid in seen_skills:
|
||||
continue
|
||||
sample = cells[0] if cells else {}
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.name, mc.slug AS main_category_slug, sc.slug AS category_slug
|
||||
FROM skills s
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE s.id = %s
|
||||
""",
|
||||
(sid,),
|
||||
)
|
||||
sk = r2d(cur.fetchone()) or {}
|
||||
skey = _skill_key(sk.get("main_category_slug"), sk.get("category_slug"), sk.get("name") or "")
|
||||
matrix_rows.append(
|
||||
{
|
||||
"skill_key": skey,
|
||||
"skill_name": sk.get("name") or "",
|
||||
"relevance": None,
|
||||
"sort_order": 0,
|
||||
"cells": cells,
|
||||
}
|
||||
)
|
||||
for cell in cells:
|
||||
ln = int(cell["level_number"])
|
||||
matrix_csv.append(
|
||||
{
|
||||
"model_key": mkey,
|
||||
"model_name": mname,
|
||||
"skill_key": skey,
|
||||
"skill_name": sk.get("name") or "",
|
||||
"relevance": "",
|
||||
"sort_order": 0,
|
||||
"level_number": ln,
|
||||
"level_label": level_label.get(ln, ""),
|
||||
"description": cell.get("description") or "",
|
||||
"observable_criteria": cell.get("observable_criteria") or "",
|
||||
}
|
||||
)
|
||||
|
||||
models_out.append(
|
||||
{
|
||||
"model_key": mkey,
|
||||
"model_name": mname,
|
||||
"level_count": int(m.get("level_count") or 5),
|
||||
"status": m.get("status"),
|
||||
"level_labels": [
|
||||
{
|
||||
"level_number": int(lv["level_number"]),
|
||||
"name": lv.get("name") or "",
|
||||
"description": lv.get("description"),
|
||||
}
|
||||
for lv in levels
|
||||
],
|
||||
"matrix_rows": matrix_rows,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"skills": skills_out,
|
||||
"skills_csv_rows": skills_csv,
|
||||
"maturity_models": models_out,
|
||||
"matrix_csv_rows": matrix_csv,
|
||||
}
|
||||
|
||||
|
||||
def _build_skill_lookup(cur) -> Dict[str, int]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id, s.name, mc.slug AS main_category_slug, sc.slug AS category_slug
|
||||
FROM skills s
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
"""
|
||||
)
|
||||
out: Dict[str, int] = {}
|
||||
for r in cur.fetchall():
|
||||
row = r2d(r)
|
||||
key = _skill_key(row.get("main_category_slug"), row.get("category_slug"), row.get("name") or "")
|
||||
out[key] = int(row["id"])
|
||||
return out
|
||||
|
||||
|
||||
def _build_model_lookup(cur) -> Dict[str, int]:
|
||||
cur.execute("SELECT id, name, import_id FROM maturity_models")
|
||||
out: Dict[str, int] = {}
|
||||
for r in cur.fetchall():
|
||||
row = r2d(r)
|
||||
key = _model_key(row.get("import_id"), row.get("name") or "")
|
||||
out[key] = int(row["id"])
|
||||
return out
|
||||
|
||||
|
||||
def _resolve_skill_id(
|
||||
cur,
|
||||
skill_lookup: Dict[str, int],
|
||||
*,
|
||||
skill_key: str,
|
||||
main_category: str = "",
|
||||
subcategory: str = "",
|
||||
skill_name: str = "",
|
||||
) -> Optional[int]:
|
||||
key = (skill_key or "").strip()
|
||||
if key and key in skill_lookup:
|
||||
return skill_lookup[key]
|
||||
if key:
|
||||
main_slug, cat_slug, name = _parse_skill_key(key)
|
||||
if name and _skill_key(main_slug, cat_slug, name) in skill_lookup:
|
||||
return skill_lookup[_skill_key(main_slug, cat_slug, name)]
|
||||
name = (skill_name or "").strip()
|
||||
if not name:
|
||||
return None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.id
|
||||
FROM skills s
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE s.name = %s
|
||||
AND COALESCE(mc.name, '') = COALESCE(%s, '')
|
||||
AND COALESCE(sc.name, '') = COALESCE(%s, '')
|
||||
LIMIT 1
|
||||
""",
|
||||
(name, (main_category or "").strip() or None, (subcategory or "").strip() or None),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return int(row["id"])
|
||||
cur.execute("SELECT id FROM skills WHERE name = %s LIMIT 1", (name,))
|
||||
row = cur.fetchone()
|
||||
return int(row["id"]) if row else None
|
||||
|
||||
|
||||
def _optional_int(val: Any) -> Optional[int]:
|
||||
if val is None or val == "":
|
||||
return None
|
||||
try:
|
||||
return int(val)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _apply_skills_import(cur, skills: List[Dict[str, Any]], skill_lookup: Dict[str, int], warnings: List[str]) -> int:
|
||||
updated = 0
|
||||
for row in skills:
|
||||
sid = _resolve_skill_id(
|
||||
cur,
|
||||
skill_lookup,
|
||||
skill_key=str(row.get("skill_key") or ""),
|
||||
main_category=str(row.get("main_category") or ""),
|
||||
subcategory=str(row.get("subcategory") or ""),
|
||||
skill_name=str(row.get("skill_name") or ""),
|
||||
)
|
||||
if not sid:
|
||||
warnings.append(f"Skill nicht gefunden: {row.get('skill_key') or row.get('skill_name')}")
|
||||
continue
|
||||
|
||||
importance = row.get("importance")
|
||||
if importance == "":
|
||||
importance = None
|
||||
relevance_level = row.get("relevance_level")
|
||||
if relevance_level == "":
|
||||
relevance_level = None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE skills SET
|
||||
description = COALESCE(%s, description),
|
||||
importance = COALESCE(%s, importance),
|
||||
karate_relevance = COALESCE(%s, karate_relevance),
|
||||
relevance_level = COALESCE(%s, relevance_level),
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
row.get("description"),
|
||||
importance,
|
||||
row.get("karate_relevance") if row.get("karate_relevance") != "" else None,
|
||||
relevance_level,
|
||||
sid,
|
||||
),
|
||||
)
|
||||
updated += 1
|
||||
|
||||
defs = row.get("level_definitions")
|
||||
if isinstance(defs, dict):
|
||||
for lvl_str, desc in defs.items():
|
||||
try:
|
||||
lvl = int(lvl_str)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if lvl < 1 or lvl > 10:
|
||||
continue
|
||||
text = (desc or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO skill_level_definitions (skill_id, level, description)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (skill_id, level) DO UPDATE SET
|
||||
description = EXCLUDED.description,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(sid, lvl, text),
|
||||
)
|
||||
else:
|
||||
for i in range(1, 6):
|
||||
col = row.get(f"level_{i}")
|
||||
if col is None or str(col).strip() == "":
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO skill_level_definitions (skill_id, level, description)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (skill_id, level) DO UPDATE SET
|
||||
description = EXCLUDED.description,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(sid, i, str(col).strip()),
|
||||
)
|
||||
return updated
|
||||
|
||||
|
||||
def _apply_matrix_import(
|
||||
cur,
|
||||
models: List[Dict[str, Any]],
|
||||
model_lookup: Dict[str, int],
|
||||
skill_lookup: Dict[str, int],
|
||||
warnings: List[str],
|
||||
) -> int:
|
||||
cells_updated = 0
|
||||
for model in models:
|
||||
mkey = str(model.get("model_key") or "").strip()
|
||||
mid = model_lookup.get(mkey)
|
||||
if not mid and model.get("model_name"):
|
||||
mid = model_lookup.get(_model_key(None, str(model.get("model_name"))))
|
||||
if not mid:
|
||||
warnings.append(f"Reifegradmodell nicht gefunden: {mkey or model.get('model_name')}")
|
||||
continue
|
||||
|
||||
rows = model.get("matrix_rows") or []
|
||||
if not rows and model.get("cells"):
|
||||
rows = [model]
|
||||
|
||||
for mrow in rows:
|
||||
sid = _resolve_skill_id(
|
||||
cur,
|
||||
skill_lookup,
|
||||
skill_key=str(mrow.get("skill_key") or ""),
|
||||
skill_name=str(mrow.get("skill_name") or ""),
|
||||
)
|
||||
if not sid:
|
||||
warnings.append(f"Matrix-Zeile: Skill nicht gefunden ({mrow.get('skill_key')})")
|
||||
continue
|
||||
|
||||
relevance = mrow.get("relevance")
|
||||
if relevance is not None and str(relevance).strip() != "":
|
||||
sort_order = _optional_int(mrow.get("sort_order")) or 0
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO model_skills (maturity_model_id, skill_id, sort_order, relevance)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (maturity_model_id, skill_id) DO UPDATE SET
|
||||
sort_order = EXCLUDED.sort_order,
|
||||
relevance = EXCLUDED.relevance
|
||||
""",
|
||||
(mid, sid, sort_order, str(relevance).strip()),
|
||||
)
|
||||
|
||||
cells = mrow.get("cells") or []
|
||||
for cell in cells:
|
||||
ln = _optional_int(cell.get("level_number"))
|
||||
if ln is None:
|
||||
continue
|
||||
desc = (cell.get("description") or "").strip()
|
||||
if not desc:
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO model_skill_levels (
|
||||
maturity_model_id, skill_id, level_number,
|
||||
description, observable_criteria
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (maturity_model_id, skill_id, level_number)
|
||||
DO UPDATE SET
|
||||
description = EXCLUDED.description,
|
||||
observable_criteria = COALESCE(EXCLUDED.observable_criteria, model_skill_levels.observable_criteria),
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
mid,
|
||||
sid,
|
||||
ln,
|
||||
desc,
|
||||
cell.get("observable_criteria") if cell.get("observable_criteria") else None,
|
||||
),
|
||||
)
|
||||
cells_updated += 1
|
||||
return cells_updated
|
||||
|
||||
|
||||
def _parse_csv_text(text: str) -> List[Dict[str, str]]:
|
||||
reader = csv.DictReader(io.StringIO(text))
|
||||
return [dict(row) for row in reader]
|
||||
|
||||
|
||||
def _skills_from_csv_rows(rows: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
||||
out: List[Dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if not any(str(v).strip() for v in row.values()):
|
||||
continue
|
||||
entry: Dict[str, Any] = {
|
||||
"skill_key": row.get("skill_key", ""),
|
||||
"main_category": row.get("main_category", ""),
|
||||
"subcategory": row.get("subcategory", ""),
|
||||
"skill_name": row.get("skill_name", ""),
|
||||
"description": row.get("description", ""),
|
||||
"importance": _optional_int(row.get("importance")),
|
||||
"karate_relevance": row.get("karate_relevance", ""),
|
||||
"relevance_level": _optional_int(row.get("relevance_level")),
|
||||
}
|
||||
for i in range(1, 6):
|
||||
entry[f"level_{i}"] = row.get(f"level_{i}", "")
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _matrix_from_csv_rows(rows: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
||||
by_model: Dict[str, Dict[str, Any]] = {}
|
||||
row_index: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
for row in rows:
|
||||
if not any(str(v).strip() for v in row.values()):
|
||||
continue
|
||||
mkey = (row.get("model_key") or "").strip()
|
||||
if not mkey:
|
||||
continue
|
||||
model = by_model.setdefault(
|
||||
mkey,
|
||||
{"model_key": mkey, "model_name": row.get("model_name") or "", "matrix_rows": []},
|
||||
)
|
||||
skey = (row.get("skill_key") or "").strip()
|
||||
row_key = (mkey, skey or (row.get("skill_name") or "").strip())
|
||||
mrow = row_index.get(row_key)
|
||||
if not mrow:
|
||||
mrow = {
|
||||
"skill_key": skey,
|
||||
"skill_name": row.get("skill_name") or "",
|
||||
"relevance": row.get("relevance") or "",
|
||||
"sort_order": _optional_int(row.get("sort_order")) or 0,
|
||||
"cells": [],
|
||||
}
|
||||
row_index[row_key] = mrow
|
||||
model["matrix_rows"].append(mrow)
|
||||
|
||||
ln = _optional_int(row.get("level_number"))
|
||||
if ln is None:
|
||||
continue
|
||||
desc = (row.get("description") or "").strip()
|
||||
if not desc:
|
||||
continue
|
||||
mrow["cells"].append(
|
||||
{
|
||||
"level_number": ln,
|
||||
"description": desc,
|
||||
"observable_criteria": row.get("observable_criteria") or "",
|
||||
}
|
||||
)
|
||||
|
||||
return list(by_model.values())
|
||||
|
||||
|
||||
@router.get("/export")
|
||||
def export_matrix_editor(
|
||||
format: str = Query("json", pattern="^(json|csv_skills|csv_matrix)$"),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
_require_superadmin(session)
|
||||
export_uid = str(uuid.uuid4())
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = _load_editor_payload(cur)
|
||||
|
||||
if format == "csv_skills":
|
||||
csv_text = _rows_to_csv(SKILLS_CSV_FIELDS, payload["skills_csv_rows"])
|
||||
return _csv_response(csv_text, f"faehigkeiten-katalog-{export_uid[:8]}.csv")
|
||||
|
||||
if format == "csv_matrix":
|
||||
csv_text = _rows_to_csv(MATRIX_CSV_FIELDS, payload["matrix_csv_rows"])
|
||||
return _csv_response(csv_text, f"faehigkeitsmatrix-zellen-{export_uid[:8]}.csv")
|
||||
|
||||
bundle = {
|
||||
"kind": KIND_V1,
|
||||
"export_version": 1,
|
||||
"bundle_export_id": export_uid,
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"skills": payload["skills"],
|
||||
"maturity_models": payload["maturity_models"],
|
||||
}
|
||||
return JSONResponse(
|
||||
content=jsonable_encoder(bundle),
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="matrix-editor-{export_uid[:8]}.json"'
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/import")
|
||||
def import_matrix_editor(
|
||||
data: Dict[str, Any] = Body(...),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
_require_superadmin(session)
|
||||
warnings: List[str] = []
|
||||
skills: List[Dict[str, Any]] = []
|
||||
models: List[Dict[str, Any]] = []
|
||||
|
||||
kind = data.get("kind")
|
||||
if kind == KIND_V1:
|
||||
skills = list(data.get("skills") or [])
|
||||
models = list(data.get("maturity_models") or [])
|
||||
elif kind == "shinkan.matrix_editor.csv":
|
||||
part = (data.get("part") or "").strip().lower()
|
||||
csv_text = data.get("csv_text") or ""
|
||||
if not csv_text.strip():
|
||||
raise HTTPException(400, "csv_text fehlt")
|
||||
rows = _parse_csv_text(csv_text)
|
||||
if part == "skills":
|
||||
skills = _skills_from_csv_rows(rows)
|
||||
elif part == "matrix":
|
||||
models = _matrix_from_csv_rows(rows)
|
||||
else:
|
||||
raise HTTPException(400, "part muss skills oder matrix sein")
|
||||
else:
|
||||
raise HTTPException(400, f"Unbekanntes Format (kind={kind!r})")
|
||||
|
||||
if not skills and not models:
|
||||
raise HTTPException(400, "Keine importierbaren Daten")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
skill_lookup = _build_skill_lookup(cur)
|
||||
model_lookup = _build_model_lookup(cur)
|
||||
skills_updated = _apply_skills_import(cur, skills, skill_lookup, warnings) if skills else 0
|
||||
cells_updated = _apply_matrix_import(cur, models, model_lookup, skill_lookup, warnings) if models else 0
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"skills_updated": skills_updated,
|
||||
"matrix_cells_updated": cells_updated,
|
||||
"warnings": warnings,
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
POST /api/planning/exercise-suggest — planungsgebundene Übungssuche (Hybrid + Profil + optional LLM-Rerank).
|
||||
"""
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
from planning_exercise_suggest import PlanningExerciseSuggestRequest, suggest_planning_exercises
|
||||
|
||||
router = APIRouter(prefix="/api/planning", tags=["planning_exercise_suggest"])
|
||||
|
||||
|
||||
@router.post("/exercise-suggest")
|
||||
def post_planning_exercise_suggest(
|
||||
body: PlanningExerciseSuggestRequest,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return suggest_planning_exercises(cur, tenant=tenant, body=body)
|
||||
@@ -23,10 +23,14 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
||||
"admin_users.py",
|
||||
"platform_media_storage.py",
|
||||
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
||||
"ai_skill_retrieval_admin.py", # Superadmin-Plattform-Konfiguration Skill-KI-Retrieval; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"ai_prompts_admin.py", # Superadmin ai_prompts; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"exercise_enrichment_admin.py", # Superadmin Batch-Übungs-Anreicherung KI; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"catalogs.py",
|
||||
"skills.py",
|
||||
"maturity_models.py",
|
||||
"matrix_stack_bundle.py",
|
||||
"matrix_editor.py", # Superadmin Editor-Export/Import Fähigkeitsmatrix; require_auth + is_superadmin — kein Vereinsmandant
|
||||
"import_wiki.py",
|
||||
"import_wiki_admin.py",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Superadmin Übungs-Anreicherung — Auth, Merge-Logik, Status, Analyze."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from exercise_enrichment import (
|
||||
apply_exercise_enrichment,
|
||||
compute_skill_diff,
|
||||
estimate_llm_calls,
|
||||
merge_skills,
|
||||
persist_merged_skills,
|
||||
validate_exercise_for_enrichment,
|
||||
)
|
||||
from main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
|
||||
|
||||
def test_candidates_requires_superadmin(client: TestClient) -> None:
|
||||
def _admin():
|
||||
return {"profile_id": 1, "role": "admin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _admin
|
||||
r = client.get("/api/admin/exercise-enrichment/candidates", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_preview_requires_superadmin(client: TestClient) -> None:
|
||||
def _trainer():
|
||||
return {"profile_id": 1, "role": "trainer"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _trainer
|
||||
r = client.post(
|
||||
"/api/admin/exercise-enrichment/preview",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={"exercise_ids": [1], "modes": {"skills": True}},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
@patch("routers.exercise_enrichment_admin.get_db")
|
||||
def test_candidates_ok_for_superadmin(mock_get_db, client: TestClient) -> None:
|
||||
def _super():
|
||||
return {"profile_id": 1, "role": "superadmin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _super
|
||||
|
||||
mock_cm = MagicMock()
|
||||
mock_conn = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.side_effect = [{"c": 2}, None]
|
||||
mock_cur.fetchall.return_value = [
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Kata Basics",
|
||||
"status": "draft",
|
||||
"visibility": "private",
|
||||
"summary": "",
|
||||
"updated_at": "2026-05-23T10:00:00",
|
||||
"primary_focus_name": "Karate",
|
||||
"skill_count": 0,
|
||||
"ai_suggested_skill_count": 0,
|
||||
}
|
||||
]
|
||||
mock_get_db.return_value = mock_cm
|
||||
|
||||
with patch("routers.exercise_enrichment_admin.get_cursor", return_value=mock_cur):
|
||||
r = client.get(
|
||||
"/api/admin/exercise-enrichment/candidates?status=draft&without_skills=true",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["total"] == 2
|
||||
assert len(body["items"]) == 1
|
||||
assert body["items"][0]["id"] == 10
|
||||
|
||||
|
||||
def test_analyze_returns_llm_estimate(client: TestClient) -> None:
|
||||
def _super():
|
||||
return {"profile_id": 1, "role": "superadmin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _super
|
||||
r = client.post(
|
||||
"/api/admin/exercise-enrichment/analyze",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={
|
||||
"exercise_ids": [1, 2, 3],
|
||||
"modes": {"skills": True, "summary": True, "instructions": False},
|
||||
},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["exercise_count"] == 3
|
||||
est = body["estimated_llm_calls"]
|
||||
assert est["total"] == 6
|
||||
assert est["skills"] == 3
|
||||
assert est["summary"] == 3
|
||||
|
||||
|
||||
def test_validate_exercise_requires_title_and_content() -> None:
|
||||
assert (
|
||||
validate_exercise_for_enrichment({"title": "", "goal": "<p>x</p>"}, want_skills=True)
|
||||
== "Titel fehlt"
|
||||
)
|
||||
assert (
|
||||
validate_exercise_for_enrichment({"title": "Foo", "goal": "", "execution": ""}, want_skills=True)
|
||||
== "Mindestens Ziel oder Durchführung muss Inhalt liefern (für Skills/Kurzfassung)"
|
||||
)
|
||||
assert validate_exercise_for_enrichment({"title": "Foo", "goal": "<p>Ziel</p>"}, want_skills=True) is None
|
||||
|
||||
|
||||
def test_merge_skills_additive_keeps_manual() -> None:
|
||||
existing = [
|
||||
{
|
||||
"skill_id": 1,
|
||||
"skill_name": "Manual",
|
||||
"intensity": "hoch",
|
||||
"required_level": "aufbau",
|
||||
"target_level": "fortgeschritten",
|
||||
"is_primary": True,
|
||||
"ai_suggested": False,
|
||||
}
|
||||
]
|
||||
suggested = [
|
||||
{
|
||||
"skill_id": 1,
|
||||
"skill_name": "Manual AI",
|
||||
"intensity": "niedrig",
|
||||
"required_level": "basis",
|
||||
"target_level": "grundlagen",
|
||||
"is_primary": False,
|
||||
},
|
||||
{
|
||||
"skill_id": 2,
|
||||
"skill_name": "New AI",
|
||||
"intensity": "mittel",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"is_primary": False,
|
||||
},
|
||||
]
|
||||
merged = merge_skills(existing, suggested, "additive")
|
||||
assert len(merged) == 2
|
||||
manual = next(s for s in merged if s["skill_id"] == 1)
|
||||
assert manual["intensity"] == "hoch"
|
||||
assert manual["ai_suggested"] is False
|
||||
ai_new = next(s for s in merged if s["skill_id"] == 2)
|
||||
assert ai_new["ai_suggested"] is True
|
||||
assert ai_new["intensity"] == "mittel"
|
||||
|
||||
|
||||
def test_merge_skills_replace_all_marks_ai() -> None:
|
||||
existing = [
|
||||
{"skill_id": 1, "skill_name": "M", "intensity": "hoch", "ai_suggested": False},
|
||||
]
|
||||
suggested = [
|
||||
{"skill_id": 3, "skill_name": "New AI", "intensity": "niedrig", "required_level": "basis", "target_level": "aufbau"},
|
||||
]
|
||||
merged = merge_skills(existing, suggested, "replace_all")
|
||||
assert len(merged) == 1
|
||||
assert merged[0]["skill_id"] == 3
|
||||
assert merged[0]["ai_suggested"] is True
|
||||
assert merged[0]["intensity"] == "niedrig"
|
||||
|
||||
|
||||
def test_compute_skill_diff_added_and_removed() -> None:
|
||||
before = [{"skill_id": 1, "skill_name": "A", "intensity": "mittel", "ai_suggested": False}]
|
||||
after = [
|
||||
{"skill_id": 1, "skill_name": "A", "intensity": "mittel", "ai_suggested": False},
|
||||
{"skill_id": 2, "skill_name": "B", "intensity": "hoch", "ai_suggested": True},
|
||||
]
|
||||
diff = compute_skill_diff(before, after)
|
||||
assert len(diff["added"]) == 1
|
||||
assert diff["added"][0]["skill_id"] == 2
|
||||
|
||||
|
||||
@patch("exercise_enrichment.enrich_exercise_detail")
|
||||
def test_apply_sets_in_review(mock_enrich) -> None:
|
||||
mock_enrich.return_value = {
|
||||
"id": 5,
|
||||
"title": "Test",
|
||||
"goal": "<p>G</p>",
|
||||
"execution": "",
|
||||
"status": "draft",
|
||||
"skills": [],
|
||||
}
|
||||
mock_cur = MagicMock()
|
||||
row = apply_exercise_enrichment(
|
||||
mock_cur,
|
||||
5,
|
||||
merged_skills=[
|
||||
{
|
||||
"skill_id": 9,
|
||||
"skill_name": "Kick",
|
||||
"intensity": "mittel",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"is_primary": True,
|
||||
"ai_suggested": True,
|
||||
}
|
||||
],
|
||||
merge_mode="replace_all",
|
||||
set_status="in_review",
|
||||
apply_skills=True,
|
||||
)
|
||||
assert row["ok"] is True
|
||||
assert row["status"] == "in_review"
|
||||
assert mock_cur.execute.call_count >= 2
|
||||
|
||||
|
||||
def test_apply_rejects_approved_status() -> None:
|
||||
mock_cur = MagicMock()
|
||||
with patch(
|
||||
"exercise_enrichment.enrich_exercise_detail",
|
||||
return_value={
|
||||
"title": "T",
|
||||
"goal": "<p>G</p>",
|
||||
"status": "draft",
|
||||
"skills": [],
|
||||
},
|
||||
):
|
||||
row = apply_exercise_enrichment(
|
||||
mock_cur,
|
||||
1,
|
||||
merged_skills=[{"skill_id": 1, "intensity": "mittel", "ai_suggested": True}],
|
||||
set_status="approved",
|
||||
apply_skills=True,
|
||||
)
|
||||
assert row["ok"] is False
|
||||
assert "approved" in row["error"]
|
||||
|
||||
|
||||
def test_persist_merged_skills_uses_upsert() -> None:
|
||||
mock_cur = MagicMock()
|
||||
persist_merged_skills(
|
||||
mock_cur,
|
||||
7,
|
||||
[
|
||||
{
|
||||
"skill_id": 3,
|
||||
"intensity": "mittel",
|
||||
"required_level": "grundlagen",
|
||||
"target_level": "aufbau",
|
||||
"is_primary": False,
|
||||
"ai_suggested": True,
|
||||
}
|
||||
],
|
||||
"replace_all",
|
||||
)
|
||||
sql = mock_cur.execute.call_args_list[-1][0][0]
|
||||
assert "INSERT INTO exercise_skills" in sql
|
||||
|
||||
|
||||
def test_estimate_llm_calls_breakdown() -> None:
|
||||
est = estimate_llm_calls(
|
||||
exercise_count=100,
|
||||
want_skills=True,
|
||||
want_summary=False,
|
||||
want_instructions=True,
|
||||
)
|
||||
assert est["total"] == 200
|
||||
assert est["per_exercise"] == 2
|
||||
@@ -0,0 +1,146 @@
|
||||
"""GET/POST /api/admin/matrix-editor — Superadmin Export/Import."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_overrides():
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
|
||||
|
||||
def test_matrix_editor_export_requires_superadmin(client: TestClient) -> None:
|
||||
def _admin():
|
||||
return {"profile_id": 1, "role": "admin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _admin
|
||||
r = client.get("/api/admin/matrix-editor/export", headers={"X-Auth-Token": "t"})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
@patch("routers.matrix_editor._load_editor_payload")
|
||||
def test_matrix_editor_export_json_ok(mock_load, client: TestClient) -> None:
|
||||
def _superadmin():
|
||||
return {"profile_id": 1, "role": "superadmin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
mock_load.return_value = {
|
||||
"skills": [{"skill_key": "a|b|Test", "skill_name": "Test", "description": "x", "level_definitions": {}}],
|
||||
"skills_csv_rows": [],
|
||||
"maturity_models": [],
|
||||
"matrix_csv_rows": [],
|
||||
}
|
||||
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
|
||||
with patch("routers.matrix_editor.get_db", return_value=mock_cm), patch(
|
||||
"routers.matrix_editor.get_cursor", return_value=MagicMock()
|
||||
):
|
||||
r = client.get("/api/admin/matrix-editor/export", headers={"X-Auth-Token": "t"})
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["kind"] == "shinkan.matrix_editor.v1"
|
||||
assert len(body["skills"]) == 1
|
||||
|
||||
|
||||
@patch("routers.matrix_editor._load_editor_payload")
|
||||
def test_matrix_editor_export_csv_skills(mock_load, client: TestClient) -> None:
|
||||
def _superadmin():
|
||||
return {"profile_id": 1, "role": "superadmin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
mock_load.return_value = {
|
||||
"skills": [],
|
||||
"skills_csv_rows": [
|
||||
{
|
||||
"skill_key": "main|sub|Skill A",
|
||||
"main_category": "Main",
|
||||
"subcategory": "Sub",
|
||||
"skill_name": "Skill A",
|
||||
"description": "Desc",
|
||||
"importance": 3,
|
||||
"karate_relevance": "",
|
||||
"relevance_level": "",
|
||||
"level_1": "L1",
|
||||
"level_2": "",
|
||||
"level_3": "",
|
||||
"level_4": "",
|
||||
"level_5": "",
|
||||
}
|
||||
],
|
||||
"maturity_models": [],
|
||||
"matrix_csv_rows": [],
|
||||
}
|
||||
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
|
||||
with patch("routers.matrix_editor.get_db", return_value=mock_cm), patch(
|
||||
"routers.matrix_editor.get_cursor", return_value=MagicMock()
|
||||
):
|
||||
r = client.get(
|
||||
"/api/admin/matrix-editor/export?format=csv_skills",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
assert "skill_key" in r.text
|
||||
assert "Skill A" in r.text
|
||||
|
||||
|
||||
@patch("routers.matrix_editor._apply_matrix_import", return_value=0)
|
||||
@patch("routers.matrix_editor._apply_skills_import", return_value=1)
|
||||
@patch("routers.matrix_editor._build_model_lookup", return_value={})
|
||||
@patch("routers.matrix_editor._build_skill_lookup", return_value={"main|sub|Skill A": 42})
|
||||
def test_matrix_editor_import_json_ok(
|
||||
mock_skill_lookup,
|
||||
mock_model_lookup,
|
||||
mock_apply_skills,
|
||||
mock_apply_matrix,
|
||||
client: TestClient,
|
||||
) -> None:
|
||||
def _superadmin():
|
||||
return {"profile_id": 1, "role": "superadmin"}
|
||||
|
||||
app.dependency_overrides[require_auth] = _superadmin
|
||||
|
||||
mock_cm = MagicMock()
|
||||
mock_conn = MagicMock()
|
||||
mock_cm.__enter__.return_value = mock_conn
|
||||
mock_cm.__exit__.return_value = False
|
||||
|
||||
with patch("routers.matrix_editor.get_db", return_value=mock_cm), patch(
|
||||
"routers.matrix_editor.get_cursor", return_value=MagicMock()
|
||||
):
|
||||
r = client.post(
|
||||
"/api/admin/matrix-editor/import",
|
||||
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||
json={
|
||||
"kind": "shinkan.matrix_editor.v1",
|
||||
"skills": [{"skill_key": "main|sub|Skill A", "description": "Neu"}],
|
||||
},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["ok"] is True
|
||||
assert body["skills_updated"] == 1
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Tests Progressionsgraph-Auflösung für Planungs-KI (Phase C1)."""
|
||||
from planning_exercise_progression import (
|
||||
edge_matches_anchor_from,
|
||||
filter_outgoing_progression_edges,
|
||||
parse_successors_from_edges,
|
||||
rank_progression_graph_rows,
|
||||
)
|
||||
|
||||
|
||||
def test_edge_matches_anchor_from_generic_edge():
|
||||
assert edge_matches_anchor_from({"from_exercise_variant_id": None}, None)
|
||||
assert edge_matches_anchor_from({"from_exercise_variant_id": None}, 5)
|
||||
|
||||
|
||||
def test_edge_matches_anchor_from_variant_specific():
|
||||
assert edge_matches_anchor_from({"from_exercise_variant_id": 3}, 3)
|
||||
assert not edge_matches_anchor_from({"from_exercise_variant_id": 3}, None)
|
||||
assert not edge_matches_anchor_from({"from_exercise_variant_id": 3}, 4)
|
||||
|
||||
|
||||
def test_filter_outgoing_progression_edges():
|
||||
edges = [
|
||||
{"from_exercise_variant_id": None, "to_exercise_id": 10},
|
||||
{"from_exercise_variant_id": 2, "to_exercise_id": 11},
|
||||
]
|
||||
filtered = filter_outgoing_progression_edges(edges, from_variant_id=2)
|
||||
assert len(filtered) == 2
|
||||
only_generic = filter_outgoing_progression_edges(edges, from_variant_id=None)
|
||||
assert len(only_generic) == 1
|
||||
assert only_generic[0]["to_exercise_id"] == 10
|
||||
|
||||
|
||||
def test_parse_successors_from_edges():
|
||||
ids, notes, variants = parse_successors_from_edges(
|
||||
[
|
||||
{
|
||||
"to_exercise_id": 20,
|
||||
"to_exercise_variant_id": 7,
|
||||
"notes": " leicht ",
|
||||
},
|
||||
{"to_exercise_id": 21, "to_exercise_variant_id": None, "notes": ""},
|
||||
]
|
||||
)
|
||||
assert ids == {20, 21}
|
||||
assert notes[20] == "leicht"
|
||||
assert variants[20] == 7
|
||||
assert variants[21] is None
|
||||
|
||||
|
||||
def test_rank_progression_graph_rows_prefers_variant_match():
|
||||
rows = [
|
||||
{"id": 1, "variant_match_count": 0, "outgoing_count": 5},
|
||||
{"id": 2, "variant_match_count": 2, "outgoing_count": 1},
|
||||
]
|
||||
best = rank_progression_graph_rows(rows)
|
||||
assert best["id"] == 2
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Tests Planungs-Retrieval Phase A (Voll-Library-Ranking)."""
|
||||
from planning_exercise_profiles import ExerciseMatchProfile, PlanningTargetProfile
|
||||
from planning_exercise_retrieval import (
|
||||
fetch_all_visible_exercise_rows,
|
||||
rank_visible_library_hits,
|
||||
)
|
||||
|
||||
|
||||
def test_fetch_all_visible_has_no_profile_or_pool_filter():
|
||||
captured = {}
|
||||
|
||||
class _Cur:
|
||||
def execute(self, sql, params):
|
||||
captured["sql"] = sql
|
||||
captured["params"] = list(params)
|
||||
|
||||
def fetchall(self):
|
||||
return []
|
||||
|
||||
fetch_all_visible_exercise_rows(
|
||||
_Cur(),
|
||||
vis_sql="(e.visibility = 'official' OR (e.visibility = 'private' AND e.created_by = %s))",
|
||||
vis_params=[42],
|
||||
query="Kime Partner",
|
||||
exercise_kind_any=["simple"],
|
||||
)
|
||||
|
||||
sql = captured["sql"].lower()
|
||||
assert "exercise_skills" not in sql
|
||||
assert "@@ plainto_tsquery" not in sql
|
||||
assert " exists " not in sql.replace("primary_focus_name", "")
|
||||
params = captured["params"]
|
||||
assert params[0] == "Kime Partner"
|
||||
assert params[1] == 42
|
||||
assert params[2] == "archived"
|
||||
assert params[3] == "simple"
|
||||
assert params[-1] == 8000
|
||||
|
||||
|
||||
def test_rank_visible_library_prefers_profile_over_untagged_pool_miss():
|
||||
"""Übung ohne Pool-Tags, aber hoher Profil-Match, muss vor schwachem Treffer ranken."""
|
||||
|
||||
target = PlanningTargetProfile(
|
||||
focus_area_ids={10: 1.0},
|
||||
skill_weights={5: 1.0},
|
||||
sources=["framework_catalog"],
|
||||
)
|
||||
rows = [
|
||||
{"id": 1, "title": "Schwach", "summary": "", "primary_focus_name": "X", "ft_rank": 0.9},
|
||||
{"id": 2, "title": "Stark", "summary": "", "primary_focus_name": "Karate", "ft_rank": 0.0},
|
||||
]
|
||||
|
||||
profiles = {
|
||||
1: ExerciseMatchProfile(exercise_id=1, focus_area_ids={99: 1.0}),
|
||||
2: ExerciseMatchProfile(exercise_id=2, focus_area_ids={10: 1.0}, skill_weights={5: 1.0}),
|
||||
}
|
||||
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
return None
|
||||
|
||||
def fetchall(self):
|
||||
return []
|
||||
|
||||
def _fake_load(cur, exercise_ids, *, batch=400):
|
||||
_ = (cur, batch)
|
||||
return {eid: profiles[eid] for eid in exercise_ids if eid in profiles}
|
||||
|
||||
def _fake_skills(cur, exercise_ids, *, batch=400):
|
||||
_ = (cur, batch)
|
||||
return {1: {99}, 2: {5, 10}}
|
||||
|
||||
import planning_exercise_retrieval as mod
|
||||
|
||||
orig_profiles = mod._load_match_profiles_chunked
|
||||
orig_skills = mod._load_skill_sets_chunked
|
||||
try:
|
||||
mod._load_match_profiles_chunked = _fake_load
|
||||
mod._load_skill_sets_chunked = _fake_skills
|
||||
hits, _ = rank_visible_library_hits(
|
||||
_Cur(),
|
||||
rows,
|
||||
query="",
|
||||
intent="suggest_next",
|
||||
intent_weights={
|
||||
"fulltext": 0.08,
|
||||
"progression": 0.28,
|
||||
"skill": 0.12,
|
||||
"plan": 0.10,
|
||||
"profile": 0.25,
|
||||
"repeat_unit": -0.30,
|
||||
"repeat_group": -0.15,
|
||||
},
|
||||
target=target,
|
||||
pack={
|
||||
"planned_exercise_ids": [],
|
||||
"group_recent_exercise_ids": [],
|
||||
"progression_successor_ids": [],
|
||||
"anchor_skill_ids": [],
|
||||
"anchor_exercise_id": None,
|
||||
"progression_edge_notes": {},
|
||||
},
|
||||
)
|
||||
finally:
|
||||
mod._load_match_profiles_chunked = orig_profiles
|
||||
mod._load_skill_sets_chunked = orig_skills
|
||||
|
||||
assert hits[0]["id"] == 2
|
||||
assert hits[0]["score"] > hits[1]["score"]
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Tests Partner-Filter im Planungs-Retrieval."""
|
||||
from planning_exercise_retrieval import _exercise_looks_partner_related
|
||||
|
||||
|
||||
def test_exercise_partner_heuristic():
|
||||
assert _exercise_looks_partner_related({"title": "Partner-Fangspiel", "summary": ""})
|
||||
assert not _exercise_looks_partner_related({"title": "Kihon Solo", "summary": "Allein"})
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Tests Planungs-Übungssuche: Intent, Szenario-Pipeline, LLM-Parser."""
|
||||
from planning_exercise_suggest import resolve_planning_exercise_intent
|
||||
from planning_exercise_intent import parse_planning_query_intent_response
|
||||
from planning_exercise_llm_rank import parse_planning_exercise_rank_response
|
||||
from planning_exercise_target_pipeline import (
|
||||
SCENARIO_ADDITIVE,
|
||||
SCENARIO_PRESET_NEXT,
|
||||
classify_planning_scenario,
|
||||
compose_retrieval_phase,
|
||||
is_simple_preset_query,
|
||||
should_run_llm_intent_pipeline,
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_planning_exercise_intent_defaults():
|
||||
assert resolve_planning_exercise_intent("", None) == "suggest_next"
|
||||
assert resolve_planning_exercise_intent(" ", "suggest_next") == "suggest_next"
|
||||
|
||||
|
||||
def test_resolve_planning_exercise_intent_keywords():
|
||||
assert resolve_planning_exercise_intent("Vertiefung Partner", None) == "deepen_exercise"
|
||||
assert resolve_planning_exercise_intent("nächste übung", None) == "suggest_next"
|
||||
assert resolve_planning_exercise_intent("progression graph", None) == "progression_next"
|
||||
|
||||
|
||||
def test_classify_planning_scenario_preset():
|
||||
assert is_simple_preset_query("Schlage mir die nächste Übung vor")
|
||||
assert is_simple_preset_query("nächste Übung planen")
|
||||
assert classify_planning_scenario("", "suggest_next") == SCENARIO_PRESET_NEXT
|
||||
assert classify_planning_scenario("nächste übung", "suggest_next") == SCENARIO_PRESET_NEXT
|
||||
assert classify_planning_scenario("nächste Übung planen", "suggest_next") == SCENARIO_PRESET_NEXT
|
||||
|
||||
|
||||
def test_classify_planning_scenario_additive():
|
||||
q = "Baut auf der Planung auf und trainiert zusätzlich Schnellkraft"
|
||||
assert classify_planning_scenario(q, "continue_plan_goal") == SCENARIO_ADDITIVE
|
||||
assert should_run_llm_intent_pipeline(q, SCENARIO_ADDITIVE, include_llm_intent=True)
|
||||
|
||||
|
||||
def test_should_skip_llm_for_preset():
|
||||
assert not should_run_llm_intent_pipeline("", SCENARIO_PRESET_NEXT, include_llm_intent=True)
|
||||
assert not should_run_llm_intent_pipeline(
|
||||
"nächste übung",
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_intent=True,
|
||||
)
|
||||
|
||||
|
||||
def test_should_skip_llm_intent_short_free_search():
|
||||
from planning_exercise_target_pipeline import SCENARIO_FREE_SEARCH, should_run_llm_intent_pipeline
|
||||
|
||||
assert not should_run_llm_intent_pipeline(
|
||||
"Partnerübung",
|
||||
SCENARIO_FREE_SEARCH,
|
||||
include_llm_intent=True,
|
||||
)
|
||||
|
||||
|
||||
def test_should_run_llm_rank_when_intent_applied_and_ambiguous():
|
||||
from planning_exercise_target_pipeline import SCENARIO_ADDITIVE, should_run_llm_rank_pipeline
|
||||
|
||||
hits = [{"score": 0.5}, {"score": 0.48}, {"score": 0.47}, {"score": 0.46}]
|
||||
assert should_run_llm_rank_pipeline(
|
||||
"Baut auf dem Plan auf und trainiert zusätzlich Schnellkraft mit Partner",
|
||||
SCENARIO_ADDITIVE,
|
||||
include_llm_rank=True,
|
||||
query_intent_applied=True,
|
||||
hits=hits,
|
||||
)
|
||||
|
||||
|
||||
def test_should_skip_llm_rank_when_ranking_confident():
|
||||
from planning_exercise_target_pipeline import SCENARIO_PRESET_NEXT, should_run_llm_rank_pipeline
|
||||
|
||||
hits = [{"score": 0.9}, {"score": 0.5}, {"score": 0.4}, {"score": 0.3}]
|
||||
assert not should_run_llm_rank_pipeline(
|
||||
"",
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_rank=True,
|
||||
query_intent_applied=False,
|
||||
llm_expectation_applied=True,
|
||||
has_planning_reference=True,
|
||||
hits=hits,
|
||||
)
|
||||
|
||||
|
||||
def test_should_run_llm_rank_for_preset_when_ambiguous():
|
||||
from planning_exercise_target_pipeline import SCENARIO_PRESET_NEXT, should_run_llm_rank_pipeline
|
||||
|
||||
hits = [{"score": 0.42}, {"score": 0.41}, {"score": 0.4}, {"score": 0.39}]
|
||||
assert should_run_llm_rank_pipeline(
|
||||
"",
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_rank=True,
|
||||
query_intent_applied=False,
|
||||
llm_expectation_applied=True,
|
||||
has_planning_reference=True,
|
||||
hits=hits,
|
||||
)
|
||||
|
||||
|
||||
def test_compose_retrieval_phase():
|
||||
assert compose_retrieval_phase(query_intent=False, llm_rank=False) == "profile_v1"
|
||||
assert compose_retrieval_phase(query_intent=True, llm_rank=True) == "profile_v1+query_intent+llm_rank"
|
||||
|
||||
assert (
|
||||
compose_retrieval_phase(full_library=True, query_intent=True, llm_rank=False)
|
||||
== "profile_v1+full_library+query_intent"
|
||||
)
|
||||
|
||||
|
||||
def test_should_run_llm_expectation_for_preset_with_planning_ref():
|
||||
from planning_exercise_target_pipeline import should_run_llm_expectation_pipeline
|
||||
|
||||
assert should_run_llm_expectation_pipeline(
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_intent=True,
|
||||
has_planning_reference=True,
|
||||
)
|
||||
assert not should_run_llm_expectation_pipeline(
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_intent=False,
|
||||
has_planning_reference=True,
|
||||
)
|
||||
assert not should_run_llm_expectation_pipeline(
|
||||
SCENARIO_ADDITIVE,
|
||||
include_llm_intent=True,
|
||||
has_planning_reference=True,
|
||||
)
|
||||
|
||||
|
||||
def test_should_skip_llm_rank_when_expectation_applied_but_confident():
|
||||
from planning_exercise_target_pipeline import SCENARIO_PRESET_NEXT, should_run_llm_rank_pipeline
|
||||
|
||||
hits = [{"score": 0.85}, {"score": 0.4}, {"score": 0.35}, {"score": 0.3}]
|
||||
assert not should_run_llm_rank_pipeline(
|
||||
"",
|
||||
SCENARIO_PRESET_NEXT,
|
||||
include_llm_rank=True,
|
||||
query_intent_applied=False,
|
||||
llm_expectation_applied=True,
|
||||
hits=hits,
|
||||
)
|
||||
|
||||
|
||||
def test_compose_retrieval_phase_llm_expectation():
|
||||
assert (
|
||||
compose_retrieval_phase(llm_expectation=True)
|
||||
== "profile_v1+llm_expectation"
|
||||
)
|
||||
assert (
|
||||
compose_retrieval_phase(full_library=True, llm_expectation=True)
|
||||
== "profile_v1+full_library+llm_expectation"
|
||||
)
|
||||
|
||||
|
||||
def test_query_only_expectation_without_planning_reference():
|
||||
from planning_exercise_profiles import PlanningTargetProfile
|
||||
from planning_exercise_target_pipeline import build_planning_target_with_query_pipeline
|
||||
|
||||
class _Cur:
|
||||
pass
|
||||
|
||||
target, intent, scenario, summary = build_planning_target_with_query_pipeline(
|
||||
_Cur(),
|
||||
unit={"id": None, "framework_slot_id": None, "origin_framework_slot_id": None},
|
||||
planned_exercise_ids=[],
|
||||
section_planned_exercise_ids=[],
|
||||
anchor_exercise_id=None,
|
||||
query="Partnerübung Reaktion",
|
||||
heuristic_intent="free_search",
|
||||
include_llm_intent=False,
|
||||
context_summary={"expectation_mode": "query_only"},
|
||||
has_planning_reference=False,
|
||||
)
|
||||
assert intent == "free_search"
|
||||
assert summary.get("expectation_mode") == "query_only"
|
||||
assert target.sources == ["query_only"] or "query_only" in target.sources
|
||||
|
||||
|
||||
def test_parse_planning_query_intent_response():
|
||||
parsed = parse_planning_query_intent_response(
|
||||
'{"intent":"continue_plan_goal","scenario":"additive_constraint",'
|
||||
'"skill_hints":[{"name":"Schnellkraft","weight":1}],"emphasis":"additive",'
|
||||
'"rationale":"Zusatz Schnellkraft"}'
|
||||
)
|
||||
assert parsed.intent == "continue_plan_goal"
|
||||
assert parsed.scenario == "additive_constraint"
|
||||
assert parsed.skill_hints[0].name == "Schnellkraft"
|
||||
|
||||
|
||||
def test_parse_planning_exercise_rank_response_filters_ids():
|
||||
allowed = {10, 20, 30}
|
||||
ranked, reasons = parse_planning_exercise_rank_response(
|
||||
'{"ranked_ids":[20,999,20,10],"reasons":{"20":"Passt gut","999":"ignore"}}',
|
||||
allowed,
|
||||
)
|
||||
assert ranked == [20, 10]
|
||||
assert reasons[20] == "Passt gut"
|
||||
assert 999 not in reasons
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Tests Phase C2: Varianten-Metadaten in Planungs-Treffern."""
|
||||
from planning_exercise_suggest import _enrich_planning_hits_with_variant_meta
|
||||
|
||||
|
||||
class _Cur:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
self.last_query = ''
|
||||
|
||||
def execute(self, query, params=None):
|
||||
self.last_query = query
|
||||
self._params = params
|
||||
|
||||
def fetchall(self):
|
||||
q = self.last_query
|
||||
if 'FROM exercise_variants WHERE id IN' in q:
|
||||
return [
|
||||
{'id': 7, 'variant_name': 'Leicht'},
|
||||
]
|
||||
if 'FROM exercise_variants' in q and 'exercise_id IN' in q:
|
||||
return [
|
||||
{
|
||||
'exercise_id': 10,
|
||||
'id': 7,
|
||||
'variant_name': 'Leicht',
|
||||
'sequence_order': 1,
|
||||
},
|
||||
{
|
||||
'exercise_id': 10,
|
||||
'id': 8,
|
||||
'variant_name': 'Schwer',
|
||||
'sequence_order': 2,
|
||||
},
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def test_enrich_planning_hits_with_variant_meta():
|
||||
hits = [{'id': 10, 'title': 'Test', 'suggested_variant_id': 7}]
|
||||
out = _enrich_planning_hits_with_variant_meta(_Cur([]), hits)
|
||||
assert out[0]['suggested_variant_name'] == 'Leicht'
|
||||
assert len(out[0]['variants']) == 2
|
||||
assert out[0]['variants'][0]['id'] == 7
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Tests Phase B: Text-Signale für PlanningTargetProfile."""
|
||||
from planning_exercise_text_signals import resolve_planning_text_to_catalog_weights
|
||||
|
||||
|
||||
def test_resolve_planning_text_matches_skill_and_partner_hint():
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
self._sql = sql
|
||||
|
||||
def fetchall(self):
|
||||
sql = getattr(self, "_sql", "")
|
||||
if "FROM skills" in sql:
|
||||
return [
|
||||
{"id": 5, "name": "Kime"},
|
||||
{"id": 8, "name": "Schnellkraft"},
|
||||
{"id": 2, "name": "Ab"},
|
||||
]
|
||||
if "FROM focus_areas" in sql:
|
||||
return [{"id": 10, "name": "Karate Technik"}]
|
||||
if "FROM style_directions" in sql:
|
||||
return []
|
||||
if "FROM training_types" in sql:
|
||||
return []
|
||||
if "FROM target_groups" in sql:
|
||||
return [{"id": 3, "name": "Partnerübung"}]
|
||||
return []
|
||||
|
||||
focus, style, tt, tg, skills = resolve_planning_text_to_catalog_weights(
|
||||
_Cur(),
|
||||
"Abschnitt: Kime vertiefen mit Partnerübung",
|
||||
)
|
||||
assert skills.get(5, 0) > 0
|
||||
assert 8 not in skills
|
||||
assert tg.get(3, 0) > 0
|
||||
assert not style and not tt
|
||||
|
||||
|
||||
def test_resolve_planning_text_empty():
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
pass
|
||||
|
||||
def fetchall(self):
|
||||
return []
|
||||
|
||||
focus, style, tt, tg, skills = resolve_planning_text_to_catalog_weights(_Cur(), " ")
|
||||
assert not focus and not skills
|
||||
+277
-4
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.151"
|
||||
BUILD_DATE = "2026-05-20"
|
||||
DB_SCHEMA_VERSION = "20260520066"
|
||||
APP_VERSION = "0.8.184"
|
||||
BUILD_DATE = "2026-05-23"
|
||||
DB_SCHEMA_VERSION = "20260531074"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -18,11 +18,18 @@ MODULE_VERSIONS = {
|
||||
"media_assets": "1.18.1", # P-13: open_report_count in Listendaten (fuer Admins)
|
||||
"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
|
||||
"admin_ai_skill_retrieval": "1.0.0", # Superadmin CRUD /api/admin/ai-skill-retrieval-profiles (Migration 068)
|
||||
"exercise_enrichment_admin": "1.1.1", # Preview max 3/Request + parallel LLM (Gateway-504 vermeiden)
|
||||
"admin_ai_prompts": "1.0.3", # Migration 070: openrouter_model; PUT/Liste/Detail
|
||||
"ai_prompt_job": "0.2.1", # want_instructions; run_exercise_form_ai_suggestion
|
||||
"ai_prompt_context": "0.2.0", # preparation/trainer_notes; has_instruction_source_text
|
||||
"ai_prompt_runtime": "0.2.2", # Slug planning_exercise_expectation_profile
|
||||
"groups": "0.1.0",
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
|
||||
"exercises": "2.37.0", # Planungs-KI P1: Szenario-Pipeline + Query-Intent-Overlay
|
||||
"planning_exercise_suggest": "0.12.0", # Phase C2: Varianten in Treffern + Übernahme
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
|
||||
@@ -37,6 +44,272 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.184",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Planungs-KI Phase C2: Treffer mit Variantenliste + suggested_variant_name; Picker wählt Graph-Variante vor Übernahme.",
|
||||
"hydrateExercisePlanningRow übernimmt exercise_variant_id / suggested_variant_id in die Planungszeile.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.183",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Planungs-KI Phase C1: Progressionsgraph auto-match vom Anker; variantenbewusste Nachfolger-Kanten (034).",
|
||||
"Request/Response: anchor_exercise_variant_id, progression_graph_name, suggested_variant_id in Treffern.",
|
||||
"Frontend Übungsliste: Planungs-KI-Suche im KI-Assistent-Modus; Neuanlage im Dialog statt „+ Neu“.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.182",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Planungs-KI Phase B2: LLM-Rerank bei engem Top-Feld — auch nach Erwartungs-/Intent-LLM (max. 2 Calls).",
|
||||
"Preset „Nächste aus Kontext“: Rerank wenn Ranking unklar; Frontend sendet include_llm_rank immer.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.181",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Planungs-KI Phase B: guidance_notes + Rahmen-Ziele/Notizen → Text-Signale im Erwartungsprofil (planning_text_signals).",
|
||||
"requires_partner aus Intent filtert Übungen; retrieval_phase +text_signals; Grund „Passt zu Abschnitts-/Rahmen-Zieltext“.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.180",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Fix: Übungs-Anreicherung Vorschau — max. 3 Übungen/Request, parallel LLM; Frontend-Pakete + Retry bei 504.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.179",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Übungs-Anreicherung: Dialog mit Merge-Modus, Skills/Summary/Anleitung, Kosten-Analyse + Bestätigung.",
|
||||
"Alle aus Filter auswählen (300+), chunked Preview/Apply; Default Sichtbarkeit privat, replace_all empfohlen.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.178",
|
||||
"date": "2026-05-23",
|
||||
"changes": [
|
||||
"Superadmin-Werkzeug Übungs-Anreicherung (KI): Kandidaten filtern, Vorschau, Batch-Apply Skills + Status in_review.",
|
||||
"API /api/admin/exercise-enrichment/* — wiederverwendet exercise_ai / run_exercise_form_ai_suggestion.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.177",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-Übungssuche Phase A: gesamte sichtbare Bibliothek deterministisch gegen Erwartungsprofil gerankt.",
|
||||
"Kein OR-Profil-Pool mehr; Volltext nur noch als Score-Signal; retrieval_phase full_library.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.176",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Fix: Planungs-Übungssuche mit Suchtext — SQL-Parameter für ts_rank/plainto_tsquery korrekt gebunden (500).",
|
||||
"Preset-Erkennung: „nächste Übung planen“.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.175",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI: „Nächste aus Kontext“ — LLM leitet Erwartungsprofil aus Planungskontext ab (Prompt 074).",
|
||||
"API: llm_expectation_applied, profile_llm_applied; Retrieval-Phase llm_expectation; max. 1 LLM-Call.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.174",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI: Abschnitts-Kontext (guidance_notes, Übungszahl, letzte Übung), Fähigkeitenprofil Einheit/Abschnitt an LLM.",
|
||||
"Erwartungsprofil hybrid (Planungsbezug) vs. query_only (nur Suchtext); current_section_plan im Target-Profil.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.173",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI: mehrstufiges Profil-Retrieval (Pool → Profil-Vorselektion → Hybrid); LLM max. 1 Call pro Suche.",
|
||||
"LLM-Gates: kein Intent bei Kurz-Stichwort/preset; kein Rerank wenn Intent-LLM lief oder Ranking klar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.172",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI UI: Menüpunkt „Planungs-KI: Übung vorschlagen“ im +-Dialog; Freitext-Suche ohne gespeicherte unit_id (client_free).",
|
||||
"API exercise-suggest: unit_id optional, group_id für Client-Kontext.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.171",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI P1: Szenario-Pipeline (preset/progression/additive/…) + LLM Intent planning_exercise_search_intent → Erwartungsprofil-Overlay.",
|
||||
"API: scenario_kind, query_intent_summary, include_llm_intent; Migration 073.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.170",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI P2: optionaler LLM-Rerank (planning_exercise_search_rank) mit Titel/summary/goal; include_llm_rank.",
|
||||
"Client planned_exercise_ids für ungespeicherten Plan; Migration 072 Prompt.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.169",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Fix: planning_exercise_suggest Import library_content_visibility_sql aus tenant_context (Backend-Start/502).",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.168",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI P0.1: ExerciseMatchProfile + PlanningTargetProfile — Profil-Score (Fokus, Stil, Skills, Gap) im Hybrid-Retrieval.",
|
||||
"API exercise-suggest: retrieval_phase profile_v1, target_profile_summary; Doku §12–§14.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.167",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Planungs-KI P0: POST /api/planning/exercise-suggest — Kontext-Pack (Einheit, Plan, Anker, Graph) + Hybrid-Score.",
|
||||
"ExercisePickerModal: Planungskontext aus TrainingUnitEditPage; Treffer mit Begründungen; Doku PLANNING_EXERCISE_SUGGEST_CONTEXT.md.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.166",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"KI Schnellanlage: Suche und Anlage kombiniert (Picker + Übungsliste); Suchstring → Titel/Skizze; Rich-Text-Entwurf bearbeitbar vor Speichern.",
|
||||
"Übungsliste: Schalter „KI-Anlage“ für direkten Einstieg ohne leere Trefferliste.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.165",
|
||||
"date": "2026-05-31",
|
||||
"changes": [
|
||||
"Übungspicker Schnellanlage: KI-Vorschau-Dialog vor Speichern; Live-Bibliothekssuche (Titel+Skizze) mit Übernahme bestehender Übung.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.164",
|
||||
"date": "2026-05-31",
|
||||
"changes": [
|
||||
"Planung/Übungspicker: Schnellanlage nutzt suggestExerciseAi (Anleitung, Kurzbeschreibung, Fähigkeiten); Fokusbereich Pflichtfeld.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.163",
|
||||
"date": "2026-05-31",
|
||||
"changes": [
|
||||
"KI Anleitung: Migration 071 Prompt exercise_instruction_rewrite (JSON: goal, execution, preparation, trainer_notes);",
|
||||
"POST /exercises/ai/suggest include_instructions; Sanitize/Plaintext-Limits; Medien-Verweise bleiben erhalten;",
|
||||
"Ueungsformular Tab Anleitung: Button „KI: Anleitung ueberarbeiten“ mit Vorschau-Dialog pro Feld.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.162",
|
||||
"date": "2026-05-31",
|
||||
"changes": [
|
||||
"KI Prompt P1 abgeschlossen: ai_prompt_context (Formular-Kontext), run_exercise_form_ai_suggestion als gemeinsamer Einstieg;",
|
||||
"POST /exercises/ai/suggest und regenerate bauen ExerciseFormAiPromptContext; Admin-Vorschau nutzt dasselbe Modell.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.161",
|
||||
"date": "2026-05-31",
|
||||
"changes": [
|
||||
"Migration 070: ai_prompts.openrouter_model (optional je Prompt; Fallback OPENROUTER_MODEL).",
|
||||
"exercise_ai: effektives OpenRouter-Modell pro Slug; API-Response models_by_slug + model (Skills bevorzugt).",
|
||||
"Superadmin „KI Prompts“: OpenRouter-Modell speicherbar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.160",
|
||||
"date": "2026-05-30",
|
||||
"changes": [
|
||||
"KI Prompt P1: ai_prompt_runtime load_and_render_ai_prompt + render_ai_prompt_template_for_row; AiPromptUnavailableError;",
|
||||
"Neu ai_prompt_job: ExerciseFormAiPromptContext (Pydantic), resolve_exercise_form_variables; Admin-Prompt-Vorschau nutzt gleichen Pfad wie exercise_ai-Logik;",
|
||||
"Zielarchitektur-Doku: Phasendiagramm P0/P1 angepasst.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.159",
|
||||
"date": "2026-05-30",
|
||||
"changes": [
|
||||
"Doku: AI_PROMPT_TARGET_ARCHITECTURE.md (Zielbild Kontext-Arten, Composition, Planung/Rahmen, Phasenplan); HANDOVER & docs/architecture/README verlinkt;",
|
||||
"Backend ai_prompt_runtime: AiPromptContextKind, load_ai_prompt_row — exercise_ai ohne duplizierte Prompt-SQL;",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.158",
|
||||
"date": "2026-05-30",
|
||||
"changes": [
|
||||
"KI-Prompts: Backend prompt_resolver ({{platzhalter}} robust), Admin-API /api/admin/ai-prompts* (Liste, Detail, PUT, Preview, Reset), Migration 069 default_template;",
|
||||
"Superadmin-Web: Admin KI Prompts (/admin/ai-prompts) mit Platzhalter-Katalog und Vorschau ohne OpenRouter.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.157",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"Übungsformular-KI: Buttons nur noch bei Busy deaktiviert; Vorschau wird vor neuem Aufruf geschlossen (kein Permanent-Grauschalter durch Modal-Zustand)",
|
||||
"OpenRouter: verschachtelte Textbloecke/Content-Huellen fuer Anthropic; refusal optional mitgenommen",
|
||||
"exercise_ai: SHINKAN_AI_DEBUG=1 — detaillierte WARN-Logs (Prompt-Laengen, parse-Fehler, Sanitize-Anzahl)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.156",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"OpenRouter Client: Assistant-Content als Liste/Bloecke (Claude über Bedrock/OpenRouter)",
|
||||
"exercise_ai: leere Modelantwort als 502; Skill-JSON aus Fließtext per balanciertem Array-Zuschnitt robuster parsen",
|
||||
"Admin Retrieval-Profil: Gewichte/Unterkategorien per Formular ohne JSON-Editor",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.155",
|
||||
"date": "2026-05-29",
|
||||
"changes": [
|
||||
"exercise_ai: Fix haengender KI-Endpunkt bei sehr langen Skill-Arrays vom Modell (Cap + frueher Abbruch nach 5 gueltigen Zeilen)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.154",
|
||||
"date": "2026-05-29",
|
||||
"changes": [
|
||||
"Superadmin-Web: KI Skill-Retrieval-Profile unter /admin/ai-skill-retrieval (Liste, JSON config, CRUD gegen /api/admin/ai-skill-retrieval-profiles*)",
|
||||
"Backend: Router ai_skill_retrieval_admin registriert; ACCESS_HINTS EXEMPT dokumentiert",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.153",
|
||||
"date": "2026-05-29",
|
||||
"changes": [
|
||||
"Migration 068: ai_skill_retrieval_profiles — konfigurierbare Gewichte/Quotes fuer Skill-Katalog in exercise_ai",
|
||||
"POST /api/exercises/ai/suggest: optionales Body-Feld focus_areas_context; regenerate nutzt gespeicherte Fokusbereiche",
|
||||
"exercise_ai: kontextbezogene Skill-Auswahl (Score, Kategorie-Caps), Keyword-Patches wie Rollenspiel vs. Haltegriff/Befreiung",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.152",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"KI bei Uebungen: Migration 067 ai_prompts + summary_ai_generated; OpenRouter-Hilfsmodul; POST /api/exercises/ai/suggest und POST /api/exercises/{id}/ai/regenerate",
|
||||
"Uebungsformular: Buttons KI Kurzfassung / Fähigkeiten; exercise_skills is_primary wird aus Payload gespeichert",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.151",
|
||||
"date": "2026-05-20",
|
||||
|
||||
@@ -29,6 +29,7 @@ services:
|
||||
DB_PASSWORD: "${DB_PASSWORD:-dev_password}"
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL}
|
||||
SHINKAN_AI_DEBUG: "${SHINKAN_AI_DEBUG:-}"
|
||||
SMTP_HOST: ${SMTP_HOST}
|
||||
SMTP_PORT: ${SMTP_PORT}
|
||||
SMTP_USER: ${SMTP_USER}
|
||||
|
||||
@@ -28,6 +28,7 @@ services:
|
||||
DB_PASSWORD: ${DB_PASSWORD}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY}
|
||||
OPENROUTER_MODEL: ${OPENROUTER_MODEL}
|
||||
SHINKAN_AI_DEBUG: "${SHINKAN_AI_DEBUG:-}"
|
||||
SMTP_HOST: ${SMTP_HOST}
|
||||
SMTP_PORT: ${SMTP_PORT}
|
||||
SMTP_USER: ${SMTP_USER}
|
||||
|
||||
@@ -52,9 +52,10 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
||||
|
||||
### 4.1 Übungen (Kernobjekt)
|
||||
|
||||
- **Anlegen, Bearbeiten, Archivieren/Löschen** je nach Rolle und Sichtbarkeit.
|
||||
- **Mehrdimensionale Einordnung:** Fokusbereiche, Stilrichtungen, Trainingsstile, Zielgruppen, **Fähigkeiten mit Stufen**; Suche und Filter über diese Dimensionen.
|
||||
- **Übungsvarianten:** mehrere Ausprägungen einer Übung (z. B. Aufbau, Schwierigkeit, Material), mit Reihenfolge und optionaler **Voraussetzungsvariante**.
|
||||
- **Anlegen, Bearbeiten, Archivieren/Löschen** je nach Rolle und Freigabelevel (siehe §4.7).
|
||||
- **Bearbeitungsformular (Registerkarten):** Stammdaten · Anleitung · Einordnung · (Kombination) · Varianten · Medien & Mehr — reduziert Scroll-Tiefe; farbige Panel-Trenner; Varianten und Medien erst nach erstem Speichern.
|
||||
- **Mehrdimensionale Einordnung:** Fokusbereiche, Stilrichtungen, Trainingsstile, Zielgruppen, **Fähigkeiten mit Stufen und Intensität** (`niedrig`/`mittel`/`hoch`); Suche und Filter über diese Dimensionen.
|
||||
- **Übungsvarianten:** mehrere Ausprägungen einer Übung (z. B. Aufbau, Schwierigkeit, Material), mit Reihenfolge und optionaler **Voraussetzungsvariante**; Bearbeitung im Tab **Varianten**; Änderungen werden mit **Speichern** in der Aktionsleiste mitgesichert (oder „Variante anlegen“ für sofortiges Anlegen).
|
||||
- **Progressionsgraph:** gerichtete Beziehungen **von Übung zu Übung** (und Variantenbezug), Pflege in der Übungswelt; unterstützt didaktische „weiter“-Ketten.
|
||||
- **Medien an der Übung:** Upload, Einbettung, Verknüpfung aus dem **Archiv**; Darstellung in Detail- und Bearbeitungsansicht.
|
||||
- **Rich-Text-Felder** (Ablauf, Ziele, Hinweise): **Inline-Verweise auf verknüpfte Medien** über eine einheitliche Platzhalter-/Renderlogik (konsistent mit Archiv-Governance).
|
||||
@@ -100,8 +101,12 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
|
||||
|
||||
### 4.7 Governance von Übungsinhalten
|
||||
|
||||
- **Freigabelevel** (`visibility` in der API): steuert, wer eine Übung **lesen** darf — Werte u. a. **privat**, **Verein** (`club`), **offiziell** (`official`). In der Oberfläche heißt das Feld durchgängig **Freigabelevel** (nicht „Sichtbarkeit“).
|
||||
- **Status:** Entwurf, in Prüfung, freigegeben, archiviert — konkrete Werte siehe Datenmodell.
|
||||
- **Owner:** Der anlegende Nutzer (`created_by`). Varianten haben keinen eigenen Owner; Rechte folgen der Eltern-Übung.
|
||||
- **Bearbeiten** (Stammdaten, Varianten, Medien): Ersteller; Plattform-Admin; bei Vereins-Übungen zusätzlich Planungs-/Inhaltsrollen im Objekt-Verein (Trainer, Content-Editor, Spartenleitung, Vereins-Admin).
|
||||
- **Löschen:** privat — Ersteller (Vereins-Admin im gemeinsamen Verein mit Ersteller); Verein — nur Vereins-Admin; offiziell — nur Plattform-Admin.
|
||||
- **Änderungsanfragen** (Content Change Requests) für vorgeschlagene Änderungen an Inhalten – Einreichung und Bearbeitung über Posteingang/Admin-Prozesse (Detailtiefe siehe Fachdoku).
|
||||
- **Sichtbarkeits- und Statusmodelle** für Übungen (Entwurf, veröffentlicht, archiviert – konkrete Werte siehe Datenmodell).
|
||||
|
||||
### 4.8 Inhaltsmeldungen (P-13, vertrauens- und compliance-orientiert)
|
||||
|
||||
|
||||
+72
-15
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo – Entwicklungsstand & Handover
|
||||
|
||||
**Stand:** 2026-05-20
|
||||
**App-Version / DB-Schema:** App **`0.8.149`** (Einheiten-Editor Vollseite), DB-Schema **`20260515063`** — maßgeblich **`backend/version.py`**: `APP_VERSION`, `DB_SCHEMA_VERSION`
|
||||
**Stand:** 2026-05-23
|
||||
**App-Version / DB-Schema:** App **`0.8.184`** (Planungs-KI Phase C2); DB **`20260531074`** — maßgeblich **`backend/version.py`**.
|
||||
|
||||
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**.
|
||||
|
||||
@@ -29,6 +29,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Media / Upload-Limits / Embed | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
|
||||
| MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
|
||||
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
|
||||
| KI-Prompt-System — Zielarchitektur (Roadmap) | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
|
||||
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
|
||||
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
|
||||
| **Trainingsmodule & Kombinationsübungen (Fachspez, Drift-Schutz)** | `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (§ 10.2.1 Archetyp-IDs, § 10.4 Coaching-Stufen, **Anhang A** Code-Abgleich) |
|
||||
@@ -36,7 +37,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
|
||||
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
|
||||
| **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
|
||||
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
|
||||
| **Lieferliste inkl. Medien & Formular-UX** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §6, §16 |
|
||||
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
|
||||
|
||||
---
|
||||
@@ -79,6 +80,53 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
- **Frontend:** KPI-Kacheln + Filter-Modal (UX wie Übungsliste) auf **`/planning/framework-programs`** und **`/planning/training-modules`**; Panels in Editoren; Discovery auf Fähigkeiten-Seite; `SkillTreeMultiSelect` mit Portal-Dropdown in Modals
|
||||
- **Offen (Backlog):** Corpus-Caching bei großen Bibliotheken; Tests für Typ-Trennung; Filter-Persistenz; Skill-Filter im Dialog „Rahmen übernehmen“; API-Umbenennung `club_*` → Peer-Namen
|
||||
|
||||
### 2.7 Übungsformular UX, Freigabelevel & Varianten-Speichern (Stand 2026-05-20)
|
||||
|
||||
- **Code:** `frontend/src/components/exercises/ExerciseFormPageRoot.jsx`, `ExerciseFormLayout.jsx`, `ExerciseCatalogAssocEditor.jsx`, `ExerciseSkillsEditor.jsx`, `frontend/src/constants/exerciseGovernanceLabels.js`, `exerciseSkillIntensity.js`
|
||||
- **Tab-Navigation:** Stammdaten | Anleitung | Einordnung | (Kombination) | Varianten | Medien & Mehr — `PageSectionNav` mit farbigen Panels (`.exercise-form-edit` in `app.css`); Varianten/Medien erst nach erstem Speichern aktiv; Kombi-Übungen ohne Varianten-Tab
|
||||
- **Freigabelevel:** UI-Label für `exercises.visibility` in Formular, Liste, Filter, Bulk, Picker — API-Feldname unverändert
|
||||
- **Fähigkeiten:** Intensität `niedrig`/`mittel`/`hoch` (Default `mittel`); kein Primär-Flag in UI; Backend setzt `exercise_skills.is_primary` immer `false`
|
||||
- **Varianten:** Speichern in der **Aktionsleiste** persistiert zuerst geänderte Varianten (`persistPendingVariantChanges`), dann Übungs-Stammdaten; „Variante anlegen“ als `type="button"` ohne verschachteltes Formular (`createVariantFromDraft`)
|
||||
- **Governance (Übungen):** Owner = `created_by`; Bearbeiten = Ersteller, Plattform-Admin oder `can_plan_in_club` bei `visibility=club`; Löschen `club` = nur `club_admin`; Details **`FEATURES_DELIVERED_2026-Q2.md`** §16, **`EXERCISES_API_SPEC.md`** Permissions
|
||||
|
||||
### 2.8 KI Assistenz Übungen & Planungs-KI Übungssuche (Stand **0.8.183**)
|
||||
|
||||
**Spec / Pipeline:** `.claude/docs/working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md`
|
||||
|
||||
| Phase | Inhalt | Status |
|
||||
|-------|--------|--------|
|
||||
| **P0** | Kontext-Pack, Hybrid-Score, Planungs-Picker | ✅ |
|
||||
| **P0.1** | `ExerciseMatchProfile` / `PlanningTargetProfile`, `profile_v1` | ✅ |
|
||||
| **P1** | Szenario-Pipeline + LLM Intent (`073`) + Erwartungsprofil (`074`) | ✅ |
|
||||
| **P2 / B2** | LLM-Rerank (`072`) bei engem Top-Feld, max. 2 LLM-Calls | ✅ **0.8.182** |
|
||||
| **A** | Voll-Library deterministisch ranken (kein OR-Profil-Pool) | ✅ **0.8.177** |
|
||||
| **B** | Text-Signale aus guidance/Rahmen-Zielen (`planning_text_signals`) | ✅ **0.8.181** |
|
||||
| **C1** | Progressionsgraph auto-match + variantenbewusste Nachfolger | ✅ **0.8.183** |
|
||||
| **C2** | Varianten in Trefferliste / Picker-Auswahl | ✅ **0.8.184** |
|
||||
| **C3** | Graph-Builder: Ziel → Pfad vorschlagen → in Graph speichern | 🔲 |
|
||||
| **D** | `planning_context` an `suggestExerciseAi` (Neu-Anlage) | 🔲 |
|
||||
|
||||
**Backend:** `planning_exercise_suggest.py`, `planning_exercise_retrieval.py`, `planning_exercise_profiles.py`, `planning_exercise_target_pipeline.py`, `planning_exercise_progression.py` · Router `POST /api/planning/exercise-suggest`
|
||||
|
||||
**Frontend:** `ExercisePickerModal` (Planung) · **`ExercisesListPageRoot`** — Schalter „Neu mit KI-Assistent“: Planungs-KI-Suche + Neuanlage-Modal (statt „+ Neu“) · `TrainingUnitEditPage` — `planningContext`
|
||||
|
||||
**Superadmin:** Übungs-Anreicherung (Skills) — `exercise_enrichment_admin` (**0.8.178+**), separater Admin-Flow
|
||||
|
||||
**Offen (Qualität):** Bibliothek durchgängig mit Skills (Enrichment-Datenarbeit); manuelle Graph-Auswahl in UI; Progressionsgraph-Builder; Skill-Discovery/Framework-Pfade im Pack (P3)
|
||||
|
||||
#### Übungs-KI Formular / Schnellanlage (Stand **0.8.171**)
|
||||
|
||||
- **Planungs-Übungssuche:** siehe Tabelle oben — getrennt von Formular-KI.
|
||||
- **Doku:** Umsetzung `.claude/docs/working/AI_EXERCISE_IMPLEMENTATION_PLAN.md`; Profil-/JSON-Konzept `.claude/docs/working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`; Ist-Prompt/UI **`AI_PROMPT_SYSTEM_SPEC.md`**; API-Felder **`KI_FEATURES_SPEC.md`** §5.2
|
||||
- **Kontext / Job:** **`ai_prompt_context`** (Titel, Ziel, Durchführung, Vorbereitung, Trainer-Hinweise, Fokus); **`ai_prompt_job`** — **`run_exercise_form_ai_suggestion`**; **`ai_prompt_runtime`**; **`exercise_ai`** — OpenRouter
|
||||
- **DB:** **`067`** ai_prompts · **`069`** default_template · **`068`** ai_skill_retrieval_profiles · **`070`** openrouter_model · **`071`** **`exercise_instruction_rewrite`**
|
||||
- **Prompt-Slugs:** `exercise_summary`, `exercise_skill_suggestions`, **`exercise_instruction_rewrite`** (Anleitung JSON, prägnant, HTML p/ul/ol/li)
|
||||
- **API:** `POST /api/exercises/ai/suggest` — **`include_instructions`**, Body **`preparation`**, **`trainer_notes`**; Response **`instructions.fields`**; **`POST …/ai/regenerate`** mit **`instructions`** in `regenerate`
|
||||
- **Pflege:** Superadmin **`/admin/ai-prompts`**, **`/admin/ai-skill-retrieval`**
|
||||
- **Diagnose:** **`SHINKAN_AI_DEBUG=1`** — Logs `shinkan.exercise_ai`, `shinkan.openrouter`
|
||||
- **Frontend Formular:** Tab **Anleitung** — **„KI: Anleitung überarbeiten“**; Vorschau-Dialog pro Feld (**`ExerciseFormPageRoot.jsx`**)
|
||||
- **Frontend Schnellanlage:** **`ExercisePickerModal`** (Planung/Rahmen) — Volltext vs. Planungs-KI; KI-Neuanlage im Picker. **`ExercisesListPageRoot`** — Schalter **„Neu mit KI-Assistent“**: Planungs-KI-Suche (`usePlanningExerciseSuggestSearch`) + **`ExerciseAiQuickCreateModal`**; normales **„+ Neu“** ausgeblendet solange aktiv.
|
||||
|
||||
---
|
||||
|
||||
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
|
||||
@@ -197,18 +245,27 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
|
||||
|
||||
## 7. Nächste Session — sinnvolle Arbeitspakete
|
||||
|
||||
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
|
||||
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
|
||||
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||
### Planungs-KI (priorisiert)
|
||||
|
||||
1. **C3 — Graph-Builder:** Modus „Pfad zum Ziel“ → sequenzielle Vorschläge → `POST …/edges/sequence` nach Review.
|
||||
2. **Graph-Auswahl UI:** Dropdown neben Auto-Match; Rahmen-Slot mit Default-Graph verknüpfen.
|
||||
3. **Enrichment:** Skills für Kern-Übungen nachziehen (sonst schwaches Profil-Ranking).
|
||||
4. **D — Neu-Anlage:** `planning_context_json` an `POST /api/exercises/ai/suggest`.
|
||||
|
||||
### Allgemein
|
||||
|
||||
6. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
|
||||
7. **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).
|
||||
8. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
|
||||
9. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
|
||||
10. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
|
||||
11. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
|
||||
12. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
|
||||
13. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
|
||||
14. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
|
||||
15. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
|
||||
16. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
|
||||
17. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ Dieses Bündel ist die **Leitlinie für die große Refaktorierung** nach dem MVP
|
||||
| [`frontend/src/api/exercises.js`](../../frontend/src/api/exercises.js) | Phase 4: Übungen, Medien/Archiv, Progressionsgraphen, KI-Hilfen |
|
||||
| [`frontend/src/api/planning.js`](../../frontend/src/api/planning.js) | Phase 4: Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, KPIs) |
|
||||
| [BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md) | Phase 0: Bundle-, API- und Last-Baseline (Messvorlagen, Vergleich nach Phase 2) |
|
||||
| [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) | **Verbindliche** Shinkan-spezifische Regeln (Ergänzung zu den globalen Rules) |
|
||||
| [KI-Prompt-Zielarchitektur](../../.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md) | Roadmap: Kontext-Arten, Composition, Planung/Rahmen, Phasenplan (verbindliche Zielrichtung) |
|
||||
|
||||
## Tests (E2E / Refaktor-Budget)
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ const AdminUsersPage = lazy(() => import('./pages/AdminUsersPage'))
|
||||
const MediaLibraryPage = lazy(() => import('./pages/MediaLibraryPage'))
|
||||
const LegalPage = lazy(() => import('./pages/LegalPage'))
|
||||
const AdminLegalDocumentsPage = lazy(() => import('./pages/AdminLegalDocumentsPage'))
|
||||
const AdminAiSkillRetrievalPage = lazy(() => import('./pages/AdminAiSkillRetrievalPage'))
|
||||
const AdminAiPromptsPage = lazy(() => import('./pages/AdminAiPromptsPage'))
|
||||
const AdminExerciseEnrichmentPage = lazy(() => import('./pages/AdminExerciseEnrichmentPage'))
|
||||
const SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
|
||||
|
||||
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
|
||||
@@ -300,6 +303,30 @@ const appRouter = createBrowserRouter([
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/ai-skill-retrieval',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminAiSkillRetrievalPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/ai-prompts',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminAiPromptsPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/exercise-enrichment',
|
||||
element: (
|
||||
<PlatformAdminRoute>
|
||||
<AdminExerciseEnrichmentPage />
|
||||
</PlatformAdminRoute>
|
||||
),
|
||||
},
|
||||
{ path: 'trainer-contexts', element: <TrainerContextsPage /> },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -13,13 +13,10 @@ export function mergeActiveClubHeader(headers = {}) {
|
||||
if (cid && /^\d+$/.test(String(cid).trim())) {
|
||||
return { ...headers, 'X-Active-Club-Id': String(cid).trim() }
|
||||
}
|
||||
return { ...headers }
|
||||
return headers
|
||||
}
|
||||
|
||||
/**
|
||||
* Generischer API-Aufruf inkl. X-Auth-Token und X-Active-Club-Id.
|
||||
*/
|
||||
export async function request(endpoint, options = {}) {
|
||||
async function _fetchWithAuth(endpoint, options = {}) {
|
||||
const token = localStorage.getItem('authToken')
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
|
||||
@@ -65,7 +62,7 @@ export async function request(endpoint, options = {}) {
|
||||
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
return response
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError && (e.message === 'Failed to fetch' || e.message.includes('fetch'))) {
|
||||
const hint =
|
||||
@@ -77,3 +74,22 @@ export async function request(endpoint, options = {}) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generischer API-Aufruf inkl. X-Auth-Token und X-Active-Club-Id.
|
||||
*/
|
||||
export async function request(endpoint, options = {}) {
|
||||
const response = await _fetchWithAuth(endpoint, options)
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/** Text-Download (z. B. CSV-Export) mit gleicher Auth wie request(). */
|
||||
export async function requestText(endpoint, options = {}) {
|
||||
const response = await _fetchWithAuth(endpoint, options)
|
||||
const disposition = response.headers.get('Content-Disposition') || ''
|
||||
const match = disposition.match(/filename="([^"]+)"/)
|
||||
return {
|
||||
text: await response.text(),
|
||||
filename: match ? match[1] : null,
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,11 @@ export function buildExerciseApiPayload(formData, extras = {}) {
|
||||
age_groups: [],
|
||||
skills: (formData.skills || []).map((s) => ({
|
||||
skill_id: s.skill_id,
|
||||
is_primary: !!s.is_primary,
|
||||
intensity: normalizeExerciseSkillIntensity(s.intensity),
|
||||
required_level: s.required_level || null,
|
||||
target_level: s.target_level || null,
|
||||
ai_suggested: !!s.ai_suggested,
|
||||
})),
|
||||
visibility: visibilityNorm,
|
||||
status: formData.status || 'draft',
|
||||
@@ -577,17 +579,24 @@ export async function deleteExerciseProgressionEdgesBatch(graphId, edgeIds) {
|
||||
})
|
||||
}
|
||||
|
||||
/** KI-Ausbaustufe (EXERCISES_API_SPEC): benötigt Backend + z. B. OPENROUTER_API_KEY. */
|
||||
export async function suggestExerciseAi(payload) {
|
||||
/** KI (OpenRouter): Nur Vorschlaege; Speichern ueber normales exercise PUT/POST. */
|
||||
export async function suggestExerciseAi(payload = {}) {
|
||||
return request('/api/exercises/ai/suggest', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify({
|
||||
include_summary: true,
|
||||
include_skills: true,
|
||||
...payload,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function regenerateExerciseAi(exerciseId, payload) {
|
||||
export async function regenerateExerciseAi(exerciseId, payload = {}) {
|
||||
return request(`/api/exercises/${exerciseId}/ai/regenerate`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify({
|
||||
regenerate: ['summary', 'skills'],
|
||||
...payload,
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -76,6 +76,14 @@ export async function quickCreateTrainingUnit(data) {
|
||||
})
|
||||
}
|
||||
|
||||
/** Planungs-KI: kontextgebundene Übungssuche (Hybrid + Profil + optional LLM-Rerank). */
|
||||
export async function suggestPlanningExercises(body = {}) {
|
||||
return request('/api/planning/exercise-suggest', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
/** Rahmen-Slot → geplante Einheit (tiefe Kopie, origin_framework_slot_id). */
|
||||
export async function createTrainingUnitFromFrameworkSlot(data) {
|
||||
return request('/api/training-units/from-framework-slot', {
|
||||
|
||||
@@ -3733,6 +3733,68 @@ html.modal-scroll-locked .app-main {
|
||||
.exercises-page__title {
|
||||
margin: 0;
|
||||
}
|
||||
.exercises-page__header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.exercises-ai-assistant-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
font-size: 14px;
|
||||
color: var(--text2);
|
||||
padding: 6px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface2);
|
||||
}
|
||||
.exercises-ai-assistant-toggle:hover {
|
||||
border-color: var(--accent-dark, rgba(29, 158, 117, 0.45));
|
||||
}
|
||||
.exercises-ai-assistant-toggle:has(input:checked) {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-light, rgba(29, 158, 117, 0.12));
|
||||
color: var(--accent-dark);
|
||||
font-weight: 600;
|
||||
}
|
||||
.exercises-ai-assistant-toggle input {
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.exercises-ai-assistant-toggle__track {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 40px;
|
||||
height: 22px;
|
||||
border-radius: 999px;
|
||||
background: var(--border);
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
.exercises-ai-assistant-toggle__track::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
.exercises-ai-assistant-toggle:has(input:checked) .exercises-ai-assistant-toggle__track {
|
||||
background: var(--accent);
|
||||
}
|
||||
.exercises-ai-assistant-toggle:has(input:checked) .exercises-ai-assistant-toggle__track::after {
|
||||
transform: translateX(18px);
|
||||
}
|
||||
.exercises-page-toolbar-tabs {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale } from 'lucide-react'
|
||||
import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Brain, Sparkles, Wand2 } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
|
||||
@@ -12,6 +12,8 @@ export default function AdminPageNav() {
|
||||
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
|
||||
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
|
||||
{ to: '/admin/legal-documents', label: 'Rechtstexte', icon: Scale },
|
||||
{ to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles },
|
||||
{ to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import React from 'react'
|
||||
|
||||
/**
|
||||
* Inline-Angebot: aus Suchstring neue Übung per KI anlegen (Fokusbereich + optional Titel/Skizze).
|
||||
*/
|
||||
/** Kompakter Einstieg unter Trefferliste — expandiert zum vollen Formular. */
|
||||
export function ExerciseAiQuickCreateTeaser({ onExpand, disabled = false }) {
|
||||
return (
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
padding: '12px 16px',
|
||||
marginTop: 16,
|
||||
borderColor: 'var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '10px 12px',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: '0.92rem', lineHeight: 1.45 }}>
|
||||
<strong>Nichts Richtiges dabei?</strong>{' '}
|
||||
<span style={{ color: 'var(--text2)' }}>Neue Übung mit KI anlegen und direkt übernehmen.</span>
|
||||
</span>
|
||||
<button type="button" className="btn btn-secondary" disabled={disabled} onClick={() => onExpand?.()}>
|
||||
Neue Übung anlegen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ExerciseAiQuickCreateOffer({
|
||||
searchLabel,
|
||||
title,
|
||||
onTitleChange,
|
||||
sketch,
|
||||
onSketchChange,
|
||||
focusAreaId,
|
||||
onFocusAreaChange,
|
||||
focusAreas = [],
|
||||
catalogsReady = true,
|
||||
busy = false,
|
||||
error = '',
|
||||
onRunAi,
|
||||
showSketchField = true,
|
||||
sketchOptional = true,
|
||||
hint,
|
||||
headline,
|
||||
}) {
|
||||
const canRun =
|
||||
!busy &&
|
||||
(title || '').trim().length >= 3 &&
|
||||
focusAreaId &&
|
||||
(sketchOptional || (sketch || '').trim().length > 0)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
padding: '14px 16px',
|
||||
marginBottom: '12px',
|
||||
borderColor: 'var(--accent-dark, rgba(29,158,117,0.35))',
|
||||
background: 'var(--surface2)',
|
||||
}}
|
||||
>
|
||||
<strong style={{ display: 'block', marginBottom: '6px', fontSize: '0.95rem' }}>
|
||||
{headline || 'Keine passende Übung gefunden'}
|
||||
</strong>
|
||||
<p style={{ margin: '0 0 12px', fontSize: '13px', color: 'var(--text2)', lineHeight: 1.45 }}>
|
||||
{hint ||
|
||||
(searchLabel
|
||||
? `Für „${searchLabel}“ lässt sich eine neue Übung mit KI vorschlagen — Texte danach bearbeiten und speichern.`
|
||||
: 'Neue Übung mit KI vorschlagen — Texte danach bearbeiten und speichern.')}
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'grid', gap: '10px' }}>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="ex-ai-quick-title">
|
||||
Titel *
|
||||
</label>
|
||||
<input
|
||||
id="ex-ai-quick-title"
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={title}
|
||||
onChange={(e) => onTitleChange(e.target.value)}
|
||||
autoComplete="off"
|
||||
maxLength={300}
|
||||
placeholder="Titel der neuen Übung"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="form-label" htmlFor="ex-ai-quick-focus">
|
||||
Fokusbereich *
|
||||
</label>
|
||||
<select
|
||||
id="ex-ai-quick-focus"
|
||||
className="form-input"
|
||||
value={focusAreaId}
|
||||
onChange={(e) => onFocusAreaChange(e.target.value)}
|
||||
disabled={!catalogsReady}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{(focusAreas || []).map((fa) => (
|
||||
<option key={fa.id} value={String(fa.id)}>
|
||||
{`${fa.icon ? `${fa.icon} ` : ''}${fa.name || `#${fa.id}`}`.trim()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{showSketchField ? (
|
||||
<div>
|
||||
<label className="form-label" htmlFor="ex-ai-quick-sketch">
|
||||
Kurzbeschreibung / Idee{sketchOptional ? ' (optional)' : ' *'}
|
||||
</label>
|
||||
<textarea
|
||||
id="ex-ai-quick-sketch"
|
||||
className="form-input"
|
||||
rows={4}
|
||||
value={sketch}
|
||||
onChange={(e) => onSketchChange(e.target.value)}
|
||||
placeholder={
|
||||
sketchOptional
|
||||
? 'Leer lassen: KI schlägt Inhalt frei vor (Titel + Fokus). Oder kurz beschreiben, was die Übung tun soll …'
|
||||
: 'Kurze Beschreibung für die KI …'
|
||||
}
|
||||
/>
|
||||
{searchLabel && !(sketch || '').trim() ? (
|
||||
<p style={{ margin: '6px 0 0', fontSize: '12px', color: 'var(--text3)' }}>
|
||||
Suchbegriff: „{searchLabel}“ — wird als Titel übernommen.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<p style={{ margin: 0, fontSize: '13px', color: 'var(--danger)' }}>{error}</p>
|
||||
) : null}
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<button type="button" className="btn btn-primary" disabled={!canRun} onClick={() => onRunAi()}>
|
||||
{busy ? 'KI erzeugt Vorschlag…' : 'Mit KI anlegen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import React, { useEffect } from 'react'
|
||||
import RichTextEditor from './RichTextEditor'
|
||||
import {
|
||||
INSTRUCTION_AI_FIELD_DEFS,
|
||||
describeAiSkillRowForPreview,
|
||||
} from '../utils/exerciseAiQuickCreate'
|
||||
import { stripHtmlToText } from '../utils/htmlUtils'
|
||||
|
||||
/**
|
||||
* Modal: KI-Entwurf bearbeiten (Rich-Text) und speichern.
|
||||
*/
|
||||
export default function ExerciseAiSuggestPreviewModal({
|
||||
draft,
|
||||
onDraftChange,
|
||||
onDiscard,
|
||||
onApply,
|
||||
focusAreas = [],
|
||||
skillsCatalog = [],
|
||||
dialogTitle = 'Neue Übung — KI-Entwurf bearbeiten',
|
||||
hint = 'Texte formatiert anzeigen und bei Bedarf anpassen, dann speichern.',
|
||||
applyLabel = 'Übung anlegen',
|
||||
applyDisabled = false,
|
||||
zIndex = 2000,
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!draft) return undefined
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onDiscard()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [draft, onDiscard])
|
||||
|
||||
if (!draft) return null
|
||||
|
||||
const fields = draft.instructionFields || {}
|
||||
const canApply =
|
||||
!applyDisabled &&
|
||||
(draft.title || '').trim().length >= 3 &&
|
||||
draft.focusAreaId &&
|
||||
(stripHtmlToText(fields.goal).trim() || stripHtmlToText(fields.execution).trim())
|
||||
|
||||
const patchDraft = (patch) => onDraftChange((prev) => (prev ? { ...prev, ...patch } : prev))
|
||||
|
||||
const patchInstructionField = (key, html) => {
|
||||
onDraftChange((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
instructionFields: { ...(prev.instructionFields || {}), [key]: html },
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={dialogTitle}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.55)',
|
||||
zIndex,
|
||||
overflow: 'auto',
|
||||
padding: '16px',
|
||||
}}
|
||||
onClick={() => onDiscard()}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
maxWidth: 820,
|
||||
margin: '2vh auto',
|
||||
maxHeight: '94vh',
|
||||
overflow: 'auto',
|
||||
position: 'relative',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h3 style={{ marginTop: 0, fontSize: '1.1rem', marginBottom: '6px' }}>{dialogTitle}</h3>
|
||||
<p style={{ fontSize: '13px', color: 'var(--text3)', marginTop: 0, marginBottom: '16px' }}>{hint}</p>
|
||||
|
||||
<div style={{ display: 'grid', gap: '12px', marginBottom: '18px' }}>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="ai-draft-title">
|
||||
Titel *
|
||||
</label>
|
||||
<input
|
||||
id="ai-draft-title"
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={draft.title || ''}
|
||||
onChange={(e) => patchDraft({ title: e.target.value })}
|
||||
maxLength={300}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="ai-draft-focus">
|
||||
Fokusbereich *
|
||||
</label>
|
||||
<select
|
||||
id="ai-draft-focus"
|
||||
className="form-input"
|
||||
value={draft.focusAreaId || ''}
|
||||
onChange={(e) => patchDraft({ focusAreaId: e.target.value })}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{(focusAreas || []).map((fa) => (
|
||||
<option key={fa.id} value={String(fa.id)}>
|
||||
{`${fa.icon ? `${fa.icon} ` : ''}${fa.name || `#${fa.id}`}`.trim()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section style={{ marginBottom: '18px' }} aria-labelledby="ai-draft-summary-heading">
|
||||
<div id="ai-draft-summary-heading" style={{ fontWeight: 600, fontSize: '0.95rem', marginBottom: '8px' }}>
|
||||
Kurzfassung
|
||||
</div>
|
||||
<RichTextEditor
|
||||
value={draft.summaryHtml || ''}
|
||||
onChange={(html) => patchDraft({ summaryHtml: html })}
|
||||
placeholder="Kurzbeschreibung …"
|
||||
minHeight="88px"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section style={{ marginBottom: '18px' }} aria-labelledby="ai-draft-instructions-heading">
|
||||
<div
|
||||
id="ai-draft-instructions-heading"
|
||||
style={{ fontWeight: 600, fontSize: '0.95rem', marginBottom: '10px' }}
|
||||
>
|
||||
Anleitung
|
||||
</div>
|
||||
{INSTRUCTION_AI_FIELD_DEFS.map((def) => (
|
||||
<div key={def.key} style={{ marginBottom: '14px' }}>
|
||||
<label className="form-label">{def.label}</label>
|
||||
<RichTextEditor
|
||||
value={fields[def.key] || ''}
|
||||
onChange={(html) => patchInstructionField(def.key, html)}
|
||||
placeholder={`${def.label} …`}
|
||||
minHeight={def.key === 'execution' ? '140px' : '100px'}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
|
||||
{(draft.skillChoices || []).length > 0 ? (
|
||||
<section aria-labelledby="ai-draft-skills-heading">
|
||||
<div id="ai-draft-skills-heading" style={{ fontWeight: 600, fontSize: '0.95rem', marginBottom: '10px' }}>
|
||||
Fähigkeiten ({draft.skillChoices.length})
|
||||
</div>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{draft.skillChoices.map((c) => (
|
||||
<li
|
||||
key={c.key}
|
||||
style={{
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
padding: '10px 12px',
|
||||
marginBottom: '10px',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: '8px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!c.include}
|
||||
style={{ marginTop: 3 }}
|
||||
onChange={(e) =>
|
||||
onDraftChange((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
skillChoices: prev.skillChoices.map((x) =>
|
||||
x.key === c.key ? { ...x, include: e.target.checked } : x,
|
||||
),
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{describeAiSkillRowForPreview(c.after, skillsCatalog)}</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
style={{
|
||||
marginTop: '20px',
|
||||
paddingTop: '14px',
|
||||
borderTop: '1px solid var(--border)',
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
flexWrap: 'wrap',
|
||||
gap: '10px',
|
||||
}}
|
||||
>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => onDiscard()}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={!canApply} onClick={() => onApply()}>
|
||||
{applyLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -500,13 +500,17 @@ export default function ExerciseProgressionGraphPanel({
|
||||
|
||||
const applyPickedExercise = async (ex) => {
|
||||
const title = ex.title || `Übung #${ex.id}`
|
||||
const variants = await loadVariantsForExercise(ex.id)
|
||||
const variants = Array.isArray(ex.variants) && ex.variants.length
|
||||
? ex.variants
|
||||
: await loadVariantsForExercise(ex.id)
|
||||
const variantId =
|
||||
ex.exercise_variant_id ?? ex.suggested_variant_id ?? null
|
||||
|
||||
if (pickContext?.kind === 'sequence') {
|
||||
patchSeqStep(pickContext.index, {
|
||||
exerciseId: ex.id,
|
||||
exerciseTitle: title,
|
||||
variantId: null,
|
||||
variantId: variantId != null ? Number(variantId) : null,
|
||||
variants,
|
||||
})
|
||||
setPickContext(null)
|
||||
@@ -516,7 +520,7 @@ export default function ExerciseProgressionGraphPanel({
|
||||
const patch = {
|
||||
exerciseId: ex.id,
|
||||
exerciseTitle: title,
|
||||
variantId: null,
|
||||
variantId: variantId != null ? Number(variantId) : null,
|
||||
variants,
|
||||
}
|
||||
if (pickContext.slot === 'first') setFirstEp(patch)
|
||||
|
||||
@@ -253,6 +253,7 @@ export default function TrainingUnitSectionsEditor({
|
||||
sections,
|
||||
onSectionsChange,
|
||||
onRequestExercisePick,
|
||||
onRequestPlanningExercisePick,
|
||||
onRequestTrainingModulePick,
|
||||
onPeekExercise,
|
||||
showExecutionExtras = false,
|
||||
@@ -2591,12 +2592,23 @@ export default function TrainingUnitSectionsEditor({
|
||||
</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
|
||||
{onRequestPlanningExercisePick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary framework-ctrl framework-ctrl--xs"
|
||||
onClick={() =>
|
||||
onRequestPlanningExercisePick?.({ sectionIndex: sIdx })
|
||||
}
|
||||
>
|
||||
+ Planungs-KI
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary framework-ctrl framework-ctrl--xs"
|
||||
onClick={() => onRequestExercisePick?.({ sectionIndex: sIdx })}
|
||||
>
|
||||
+ Übung
|
||||
+ Übung (Bibliothek)
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -2807,9 +2819,25 @@ export default function TrainingUnitSectionsEditor({
|
||||
ändern.
|
||||
</p>
|
||||
<div className="tu-insert-chooser-actions">
|
||||
{onRequestPlanningExercisePick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary tu-insert-chooser-actions__full"
|
||||
onClick={() => {
|
||||
const { sIdx, beforeIx } = insertChooser
|
||||
closeInsertChooser()
|
||||
onRequestPlanningExercisePick?.({
|
||||
sectionIndex: sIdx,
|
||||
insertBeforeIndex: beforeIx,
|
||||
})
|
||||
}}
|
||||
>
|
||||
Planungs-KI: Übung vorschlagen …
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary tu-insert-chooser-actions__full"
|
||||
className={`btn ${onRequestPlanningExercisePick ? 'btn-secondary' : 'btn-primary'} tu-insert-chooser-actions__full`}
|
||||
onClick={() => {
|
||||
const { sIdx, beforeIx } = insertChooser
|
||||
closeInsertChooser()
|
||||
@@ -2819,7 +2847,7 @@ export default function TrainingUnitSectionsEditor({
|
||||
})
|
||||
}}
|
||||
>
|
||||
Übung auswählen …
|
||||
{onRequestPlanningExercisePick ? 'Übung aus Bibliothek …' : 'Übung auswählen …'}
|
||||
</button>
|
||||
{onRequestTrainingModulePick ? (
|
||||
<button
|
||||
|
||||
@@ -13,6 +13,16 @@ function downloadJson(obj, filename) {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function downloadText(text, filename, mime = 'text/csv;charset=utf-8') {
|
||||
const blob = new Blob([text], { type: mime })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function groupModelSkills(model) {
|
||||
if (!model?.model_skills?.length) return []
|
||||
const groups = new Map()
|
||||
@@ -56,6 +66,8 @@ export default function MaturityMatrixToolsAdmin() {
|
||||
const [stackConfirmText, setStackConfirmText] = useState('')
|
||||
const [stackLoading, setStackLoading] = useState(false)
|
||||
const [stackImportLoading, setStackImportLoading] = useState(false)
|
||||
const [editorLoading, setEditorLoading] = useState(false)
|
||||
const [editorImportLoading, setEditorImportLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -144,6 +156,94 @@ export default function MaturityMatrixToolsAdmin() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExportEditorJson() {
|
||||
setError('')
|
||||
setMessage('')
|
||||
setEditorLoading(true)
|
||||
try {
|
||||
const bundle = await api.exportMatrixEditorBundle()
|
||||
const name = `matrix-editor-${(bundle.bundle_export_id || 'export').slice(0, 8)}.json`
|
||||
downloadJson(bundle, name)
|
||||
setMessage('Editor-Export (JSON) heruntergeladen.')
|
||||
} catch (err) {
|
||||
setError(err.message || String(err))
|
||||
} finally {
|
||||
setEditorLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExportEditorCsv(part) {
|
||||
setError('')
|
||||
setMessage('')
|
||||
setEditorLoading(true)
|
||||
try {
|
||||
const { text, filename } = await api.exportMatrixEditorCsv(part)
|
||||
downloadText(
|
||||
text,
|
||||
filename || (part === 'skills' ? 'faehigkeiten-katalog.csv' : 'faehigkeitsmatrix-zellen.csv')
|
||||
)
|
||||
setMessage(part === 'skills' ? 'Katalog-CSV heruntergeladen.' : 'Matrix-CSV heruntergeladen.')
|
||||
} catch (err) {
|
||||
setError(err.message || String(err))
|
||||
} finally {
|
||||
setEditorLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImportEditorJson(e) {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
setError('')
|
||||
setMessage('')
|
||||
setEditorImportLoading(true)
|
||||
try {
|
||||
const data = JSON.parse(await file.text())
|
||||
if (data.kind !== 'shinkan.matrix_editor.v1') {
|
||||
setError('Erwartet wird kind: shinkan.matrix_editor.v1')
|
||||
return
|
||||
}
|
||||
const res = await api.importMatrixEditorBundle(data)
|
||||
const w = res.warnings || []
|
||||
setMessage(
|
||||
`Import OK: ${res.skills_updated || 0} Fähigkeit(en), ${res.matrix_cells_updated || 0} Matrix-Zelle(n) aktualisiert.` +
|
||||
(w.length ? ` ${w.length} Hinweis(e) in der Konsole.` : '')
|
||||
)
|
||||
if (w.length) console.warn('matrix_editor import warnings', w)
|
||||
} catch (err) {
|
||||
setError(err.message || String(err))
|
||||
} finally {
|
||||
setEditorImportLoading(false)
|
||||
e.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImportEditorCsv(e, part) {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
setError('')
|
||||
setMessage('')
|
||||
setEditorImportLoading(true)
|
||||
try {
|
||||
const csv_text = await file.text()
|
||||
const res = await api.importMatrixEditorBundle({
|
||||
kind: 'shinkan.matrix_editor.csv',
|
||||
part,
|
||||
csv_text
|
||||
})
|
||||
const w = res.warnings || []
|
||||
setMessage(
|
||||
`CSV-Import (${part}) OK: ${res.skills_updated || 0} Fähigkeit(en), ${res.matrix_cells_updated || 0} Matrix-Zelle(n) aktualisiert.` +
|
||||
(w.length ? ` ${w.length} Hinweis(e) in der Konsole.` : '')
|
||||
)
|
||||
if (w.length) console.warn('matrix_editor csv import warnings', w)
|
||||
} catch (err) {
|
||||
setError(err.message || String(err))
|
||||
} finally {
|
||||
setEditorImportLoading(false)
|
||||
e.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExportStack() {
|
||||
setError('')
|
||||
setMessage('')
|
||||
@@ -234,9 +334,8 @@ export default function MaturityMatrixToolsAdmin() {
|
||||
return (
|
||||
<div className="admin-matrix-tools">
|
||||
<p className="admin-matrix-tools__intro muted">
|
||||
Matrix nach Kontext auflösen, hierarchisch nach Hauptkategorie und Kategorie darstellen, sowie JSON
|
||||
exportieren oder importieren (gespeichertes Modell inkl. optional Kontext-Bindings, aufgelöste Matrix, oder{' '}
|
||||
<strong>Komplett-Stack</strong> mit Fähigkeitskatalog und allen Reifegradmodellen für Test → Prod).
|
||||
Zentral Beschreibungen und Gewichtungen pflegen (Superadmin), Matrix nach Kontext anzeigen, sowie
|
||||
vollständige JSON-Stacks für Test → Prod.
|
||||
</p>
|
||||
|
||||
{error ? (
|
||||
@@ -246,6 +345,76 @@ export default function MaturityMatrixToolsAdmin() {
|
||||
) : null}
|
||||
{message ? <p className="muted admin-matrix-tools__msg">{message}</p> : null}
|
||||
|
||||
<section className="card admin-matrix-tools__section">
|
||||
<h2 className="admin-matrix-tools__h2">Zentral bearbeiten (Export / Import)</h2>
|
||||
<p className="muted admin-matrix-tools__hint">
|
||||
Flaches Format für Excel oder JSON-Editor: Fähigkeits-Beschreibungen,{' '}
|
||||
<code className="admin-bindings__code">importance</code> (Gewichtung 1–5), globale Stufen-Texte (
|
||||
<code className="admin-bindings__code">level_1</code> … <code className="admin-bindings__code">level_5</code>
|
||||
), Matrix-Zelltexte und Zeilen-Relevanz pro Reifegradmodell. Import aktualisiert bestehende Einträge —
|
||||
es werden keine neuen Fähigkeiten oder Modelle angelegt.
|
||||
</p>
|
||||
<div className="admin-matrix-tools__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={editorLoading || editorImportLoading}
|
||||
onClick={handleExportEditorJson}
|
||||
>
|
||||
{editorLoading ? 'Export…' : 'JSON exportieren'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={editorLoading || editorImportLoading}
|
||||
onClick={() => handleExportEditorCsv('skills')}
|
||||
>
|
||||
Katalog als CSV
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={editorLoading || editorImportLoading}
|
||||
onClick={() => handleExportEditorCsv('matrix')}
|
||||
>
|
||||
Matrix-Zellen als CSV
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-matrix-tools__io-grid admin-matrix-tools__io-grid--editor">
|
||||
<div>
|
||||
<h3 className="admin-matrix-tools__h3">JSON importieren</h3>
|
||||
<label className="form-label">Datei (<code className="admin-bindings__code">shinkan.matrix_editor.v1</code>)</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
disabled={editorImportLoading}
|
||||
onChange={handleImportEditorJson}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="admin-matrix-tools__h3">CSV importieren</h3>
|
||||
<p className="muted admin-matrix-tools__hint">
|
||||
Nur geänderte Datei hochladen — Katalog-CSV oder Matrix-CSV getrennt.
|
||||
</p>
|
||||
<label className="form-label">Katalog-CSV</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="text/csv,.csv"
|
||||
disabled={editorImportLoading}
|
||||
onChange={(e) => handleImportEditorCsv(e, 'skills')}
|
||||
/>
|
||||
<label className="form-label admin-matrix-tools__btn-mt">Matrix-CSV</label>
|
||||
<input
|
||||
type="file"
|
||||
accept="text/csv,.csv"
|
||||
disabled={editorImportLoading}
|
||||
onChange={(e) => handleImportEditorCsv(e, 'matrix')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{editorImportLoading ? <p className="muted admin-matrix-tools__msg">Import läuft…</p> : null}
|
||||
</section>
|
||||
|
||||
<section className="card admin-matrix-tools__section">
|
||||
<h2 className="admin-matrix-tools__h2">Kontext und Anzeige</h2>
|
||||
<div className="admin-matrix-tools__filters">
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import React, { useEffect } from 'react'
|
||||
import ExerciseAiQuickCreateOffer from '../ExerciseAiQuickCreateOffer'
|
||||
|
||||
/**
|
||||
* KI-gestützte Neuanlage in einem Dialog — statt normalem „+ Neu“-Formular.
|
||||
*/
|
||||
export default function ExerciseAiQuickCreateModal({
|
||||
open,
|
||||
onClose,
|
||||
searchLabel,
|
||||
title,
|
||||
onTitleChange,
|
||||
sketch,
|
||||
onSketchChange,
|
||||
focusAreaId,
|
||||
onFocusAreaChange,
|
||||
focusAreas = [],
|
||||
catalogsReady = true,
|
||||
busy = false,
|
||||
error = '',
|
||||
onRunAi,
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!open) return undefined
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape' && !busy) {
|
||||
e.preventDefault()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, busy, onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget && !busy) onClose()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-sheet exercise-ai-quick-create-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="exercise-ai-quick-create-title"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{ maxWidth: '640px' }}
|
||||
>
|
||||
<div className="admin-modal-sheet__header">
|
||||
<h3 id="exercise-ai-quick-create-title" className="admin-modal-sheet__title">
|
||||
Neue Übung mit KI
|
||||
</h3>
|
||||
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-modal-sheet__body">
|
||||
<p className="muted" style={{ marginTop: 0, marginBottom: '12px', lineHeight: 1.45 }}>
|
||||
Die KI schlägt Titel, Ziel, Anleitung und Fähigkeiten vor — danach bearbeiten und als Entwurf speichern.
|
||||
Für die normale manuelle Anlage den KI-Assistenten ausschalten.
|
||||
</p>
|
||||
<ExerciseAiQuickCreateOffer
|
||||
searchLabel={searchLabel}
|
||||
title={title}
|
||||
onTitleChange={onTitleChange}
|
||||
sketch={sketch}
|
||||
onSketchChange={onSketchChange}
|
||||
focusAreaId={focusAreaId}
|
||||
onFocusAreaChange={onFocusAreaChange}
|
||||
focusAreas={focusAreas}
|
||||
catalogsReady={catalogsReady}
|
||||
busy={busy}
|
||||
error={error}
|
||||
onRunAi={onRunAi}
|
||||
headline="Übung vorschlagen lassen"
|
||||
hint={
|
||||
searchLabel
|
||||
? `Optional aus Suchanfrage „${searchLabel}“ — Titel mindestens 3 Zeichen, Fokusbereich Pflicht.`
|
||||
: 'Titel mindestens 3 Zeichen, Fokusbereich Pflicht; Kurzbeschreibung optional.'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
buildExerciseMediaDragPayload,
|
||||
} from '../../utils/exerciseInlineMediaRefs'
|
||||
import { autoScrollForDragNearEdges } from '../../utils/dragAutoScroll'
|
||||
import { normalizeSkillLevelSlug } from '../../constants/skillLevels'
|
||||
import { normalizeSkillLevelSlug, formatSkillLevelSlug } from '../../constants/skillLevels'
|
||||
import { stripHtmlToText } from '../../utils/htmlUtils'
|
||||
import ExerciseCatalogAssocEditor from './ExerciseCatalogAssocEditor'
|
||||
import ExerciseSkillsEditor from './ExerciseSkillsEditor'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
@@ -43,6 +44,7 @@ import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../../hooks/useUn
|
||||
import {
|
||||
EXERCISE_SKILL_INTENSITY_DEFAULT,
|
||||
normalizeExerciseSkillIntensity,
|
||||
formatExerciseSkillIntensityLabel,
|
||||
} from '../../constants/exerciseSkillIntensity'
|
||||
import {
|
||||
EXERCISE_VISIBILITY_CLUB_FIELD_LABEL,
|
||||
@@ -71,6 +73,140 @@ const comboTinyNumberInputSx = {
|
||||
textAlign: 'center',
|
||||
}
|
||||
|
||||
function escapeHtmlText(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/** Plaintext fuer RichTextEditor: ein bis mehrere Absaetze, ohne bestehendes HTML zu zerstoeren. */
|
||||
function aiPlainSummaryToMinimalHtml(text) {
|
||||
const raw = String(text || '').trim()
|
||||
if (!raw) return ''
|
||||
const parts = raw.split(/\n+/).map((p) => p.trim()).filter(Boolean)
|
||||
const paras = parts.length ? parts : [raw]
|
||||
return paras.map((p) => `<p>${escapeHtmlText(p)}</p>`).join('')
|
||||
}
|
||||
|
||||
const INSTRUCTION_AI_FIELD_DEFS = [
|
||||
{ key: 'goal', label: 'Ziel' },
|
||||
{ key: 'execution', label: 'Durchführung' },
|
||||
{ key: 'preparation', label: 'Vorbereitung / Aufbau' },
|
||||
{ key: 'trainer_notes', label: 'Hinweise für Trainer' },
|
||||
]
|
||||
|
||||
function cloneExerciseSkillRows(rows) {
|
||||
return Array.isArray(rows) ? rows.map((s) => ({ ...s })) : []
|
||||
}
|
||||
|
||||
function buildNormalizedAiSkillRowFromApi(sug) {
|
||||
const sid = Number(sug.skill_id)
|
||||
if (!Number.isFinite(sid)) return null
|
||||
return {
|
||||
skill_id: sid,
|
||||
intensity: normalizeExerciseSkillIntensity(sug.intensity),
|
||||
required_level: normalizeSkillLevelSlug(sug.required_level) || 'grundlagen',
|
||||
target_level:
|
||||
normalizeSkillLevelSlug(sug.target_level) ||
|
||||
normalizeSkillLevelSlug(sug.required_level) ||
|
||||
'grundlagen',
|
||||
is_primary: !!sug.is_primary,
|
||||
ai_suggested: true,
|
||||
}
|
||||
}
|
||||
|
||||
function buildExerciseAiSuggestionPreview({
|
||||
mode,
|
||||
snapshotSummaryHtml,
|
||||
snapshotSkills,
|
||||
snapshotInstructions,
|
||||
apiRes,
|
||||
}) {
|
||||
const summaryRequested = mode !== 'skills' && mode !== 'instructions'
|
||||
const skillsRequested = mode !== 'summary' && mode !== 'instructions'
|
||||
const instructionsRequested = mode === 'instructions'
|
||||
|
||||
let summaryAfterHtml = null
|
||||
let summaryAfterPlain = ''
|
||||
if (summaryRequested && apiRes.summary?.text) {
|
||||
summaryAfterPlain = String(apiRes.summary.text).trim()
|
||||
if (summaryAfterPlain) {
|
||||
summaryAfterHtml = aiPlainSummaryToMinimalHtml(apiRes.summary.text)
|
||||
}
|
||||
}
|
||||
|
||||
const skillChoices = []
|
||||
if (skillsRequested && Array.isArray(apiRes.skills)) {
|
||||
for (const sug of apiRes.skills) {
|
||||
const after = buildNormalizedAiSkillRowFromApi(sug)
|
||||
if (!after) continue
|
||||
const ix = snapshotSkills.findIndex((s) => Number(s.skill_id) === after.skill_id)
|
||||
const before = ix >= 0 ? { ...snapshotSkills[ix] } : null
|
||||
skillChoices.push({
|
||||
key: String(after.skill_id),
|
||||
skill_id: after.skill_id,
|
||||
kind: before ? 'update' : 'add',
|
||||
before,
|
||||
after,
|
||||
include: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const instructionChoices = []
|
||||
if (instructionsRequested && apiRes.instructions?.fields) {
|
||||
const fields = apiRes.instructions.fields
|
||||
const snap = snapshotInstructions || {}
|
||||
for (const def of INSTRUCTION_AI_FIELD_DEFS) {
|
||||
const afterHtml = fields[def.key]
|
||||
if (!afterHtml || !String(afterHtml).trim()) continue
|
||||
const beforeHtml = snap[def.key] || ''
|
||||
instructionChoices.push({
|
||||
key: def.key,
|
||||
field: def.key,
|
||||
label: def.label,
|
||||
beforePlain: stripHtmlToText(beforeHtml).trim(),
|
||||
afterHtml: String(afterHtml),
|
||||
afterPlain: stripHtmlToText(afterHtml).trim(),
|
||||
include: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const hasSummaryProposal = !!(summaryRequested && summaryAfterHtml)
|
||||
const hasSkillChoices = skillChoices.length > 0
|
||||
const hasInstructionChoices = instructionChoices.length > 0
|
||||
|
||||
return {
|
||||
mode,
|
||||
applySummary: hasSummaryProposal,
|
||||
summaryBeforePlain: stripHtmlToText(snapshotSummaryHtml || '').trim(),
|
||||
summaryAfterPlain,
|
||||
summaryAfterHtml,
|
||||
skillChoices,
|
||||
instructionChoices,
|
||||
hasSummaryProposal,
|
||||
hasSkillChoices,
|
||||
hasInstructionChoices,
|
||||
summaryRequested,
|
||||
skillsRequested,
|
||||
instructionsRequested,
|
||||
}
|
||||
}
|
||||
|
||||
function describeExerciseSkillRowForPreview(row, skillsCatalog) {
|
||||
if (!row) return ''
|
||||
const sk = skillsCatalog.find((x) => Number(x.id) === Number(row.skill_id))
|
||||
const name = sk?.name || `Fähigkeit #${row.skill_id}`
|
||||
const int = formatExerciseSkillIntensityLabel(row.intensity)
|
||||
const from = formatSkillLevelSlug(row.required_level) || '—'
|
||||
const to = formatSkillLevelSlug(row.target_level) || '—'
|
||||
const prim = row.is_primary ? ' · Primär' : ''
|
||||
return `${name}: Intensität ${int}, Niveau ${from} → ${to}${prim}`
|
||||
}
|
||||
|
||||
function emptyComboSlotRow() {
|
||||
return {
|
||||
title: '',
|
||||
@@ -417,6 +553,8 @@ function detailToForm(exercise) {
|
||||
intensity: normalizeExerciseSkillIntensity(s.intensity),
|
||||
required_level: normalizeSkillLevelSlug(s.required_level),
|
||||
target_level: normalizeSkillLevelSlug(s.target_level),
|
||||
is_primary: !!s.is_primary,
|
||||
ai_suggested: !!s.ai_suggested,
|
||||
})) || [],
|
||||
exercise_kind:
|
||||
String(exercise.exercise_kind || 'simple').toLowerCase() === 'combination'
|
||||
@@ -503,6 +641,8 @@ function ExerciseFormPageRoot() {
|
||||
const [variantDraft, setVariantDraft] = useState(() => emptyVariantDraft())
|
||||
const [variantSavingId, setVariantSavingId] = useState(null)
|
||||
const [variantBusy, setVariantBusy] = useState(false)
|
||||
const [aiSuggestBusy, setAiSuggestBusy] = useState(false)
|
||||
const [aiSuggestionPreview, setAiSuggestionPreview] = useState(null)
|
||||
const [variantEditSelection, setVariantEditSelection] = useState(null)
|
||||
const [activeFormTab, setActiveFormTab] = useState('stammdaten')
|
||||
const variantsSavedSnapshotRef = useRef({})
|
||||
@@ -855,6 +995,198 @@ function ExerciseFormPageRoot() {
|
||||
)
|
||||
}
|
||||
|
||||
const runExerciseAiSuggestion = async (mode) => {
|
||||
const gPlain = stripHtmlToText(formData.goal || '').trim()
|
||||
const ePlain = stripHtmlToText(formData.execution || '').trim()
|
||||
if (!gPlain && !ePlain) {
|
||||
toast.error('Ziel oder Durchführung ausfüllen — die KI benötigt Kontext.')
|
||||
return
|
||||
}
|
||||
|
||||
const summaryOn = mode !== 'skills'
|
||||
const skillsOn = mode !== 'summary'
|
||||
|
||||
const focusHint = (formData.focus_areas_multi || [])
|
||||
.map((row) => {
|
||||
const id = row?.focus_area_id
|
||||
const fa = focusAreas.find((x) => Number(x.id) === Number(id))
|
||||
return (fa?.name || '').trim()
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
|
||||
const snapshotSummaryHtml = formData.summary || ''
|
||||
const snapshotSkills = cloneExerciseSkillRows(formData.skills)
|
||||
|
||||
const focusAreasContext = [...(formData.focus_areas_multi || [])]
|
||||
.map((row) => ({
|
||||
focus_area_id: Number(row?.focus_area_id),
|
||||
is_primary: !!row?.is_primary,
|
||||
}))
|
||||
.filter((x) => Number.isFinite(x.focus_area_id) && x.focus_area_id >= 1)
|
||||
.sort((a, b) => {
|
||||
const p = Number(!!b.is_primary) - Number(!!a.is_primary)
|
||||
if (p !== 0) return p
|
||||
return a.focus_area_id - b.focus_area_id
|
||||
})
|
||||
|
||||
/* Vor jedem neuen Aufruf: Vorschau schließen; sonst bleiben die KI-Buttons wegen Modal-Zustand dauerhaft deaktiviert. */
|
||||
setAiSuggestionPreview(null)
|
||||
setAiSuggestBusy(true)
|
||||
try {
|
||||
const res = await api.suggestExerciseAi({
|
||||
title: (formData.title || '').trim(),
|
||||
goal: formData.goal || '',
|
||||
execution: formData.execution || '',
|
||||
focus_area_hint: focusHint || undefined,
|
||||
focus_areas_context: focusAreasContext.length ? focusAreasContext : undefined,
|
||||
include_summary: summaryOn,
|
||||
include_skills: skillsOn,
|
||||
})
|
||||
|
||||
const preview = buildExerciseAiSuggestionPreview({
|
||||
mode,
|
||||
snapshotSummaryHtml,
|
||||
snapshotSkills,
|
||||
apiRes: res,
|
||||
})
|
||||
|
||||
const hasSomething = preview.hasSummaryProposal || preview.hasSkillChoices
|
||||
if (!hasSomething) {
|
||||
toast.info('Die KI lieferte keinen verwertbaren Vorschlag für die gewählten Bereiche.')
|
||||
return
|
||||
}
|
||||
|
||||
setAiSuggestionPreview(preview)
|
||||
} catch (err) {
|
||||
toast.error(err?.message || String(err))
|
||||
} finally {
|
||||
setAiSuggestBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const runExerciseAiInstructionRewrite = async () => {
|
||||
const title = (formData.title || '').trim()
|
||||
const snapshotInstructions = {
|
||||
goal: formData.goal || '',
|
||||
execution: formData.execution || '',
|
||||
preparation: formData.preparation || '',
|
||||
trainer_notes: formData.trainer_notes || '',
|
||||
}
|
||||
const hasSource =
|
||||
!!title ||
|
||||
Object.values(snapshotInstructions).some((html) => stripHtmlToText(html || '').trim())
|
||||
if (!hasSource) {
|
||||
toast.error('Titel oder mindestens ein Anleitungsfeld ausfüllen.')
|
||||
return
|
||||
}
|
||||
|
||||
const focusHint = (formData.focus_areas_multi || [])
|
||||
.map((row) => {
|
||||
const id = row?.focus_area_id
|
||||
const fa = focusAreas.find((x) => Number(x.id) === Number(id))
|
||||
return (fa?.name || '').trim()
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
|
||||
const focusAreasContext = [...(formData.focus_areas_multi || [])]
|
||||
.map((row) => ({
|
||||
focus_area_id: Number(row?.focus_area_id),
|
||||
is_primary: !!row?.is_primary,
|
||||
}))
|
||||
.filter((x) => Number.isFinite(x.focus_area_id) && x.focus_area_id >= 1)
|
||||
.sort((a, b) => {
|
||||
const p = Number(!!b.is_primary) - Number(!!a.is_primary)
|
||||
if (p !== 0) return p
|
||||
return a.focus_area_id - b.focus_area_id
|
||||
})
|
||||
|
||||
setAiSuggestionPreview(null)
|
||||
setAiSuggestBusy(true)
|
||||
try {
|
||||
const res = await api.suggestExerciseAi({
|
||||
title,
|
||||
goal: snapshotInstructions.goal,
|
||||
execution: snapshotInstructions.execution,
|
||||
preparation: snapshotInstructions.preparation,
|
||||
trainer_notes: snapshotInstructions.trainer_notes,
|
||||
focus_area_hint: focusHint || undefined,
|
||||
focus_areas_context: focusAreasContext.length ? focusAreasContext : undefined,
|
||||
include_summary: false,
|
||||
include_skills: false,
|
||||
include_instructions: true,
|
||||
})
|
||||
|
||||
const preview = buildExerciseAiSuggestionPreview({
|
||||
mode: 'instructions',
|
||||
snapshotInstructions,
|
||||
apiRes: res,
|
||||
})
|
||||
|
||||
if (!preview.hasInstructionChoices) {
|
||||
toast.info('Die KI lieferte keinen verwertbaren Anleitungs-Vorschlag.')
|
||||
return
|
||||
}
|
||||
|
||||
setAiSuggestionPreview(preview)
|
||||
} catch (err) {
|
||||
toast.error(err?.message || String(err))
|
||||
} finally {
|
||||
setAiSuggestBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const applyExerciseAiSuggestionPreview = () => {
|
||||
const p = aiSuggestionPreview
|
||||
if (!p) return
|
||||
const takeSummary = !!(p.applySummary && p.summaryAfterHtml)
|
||||
const skillsToMerge = p.skillChoices.filter((c) => c.include).map((c) => c.after)
|
||||
const instrToApply = (p.instructionChoices || []).filter((c) => c.include && c.afterHtml)
|
||||
|
||||
if (!takeSummary && skillsToMerge.length === 0 && instrToApply.length === 0) {
|
||||
toast.error('Bitte mindestens einen Vorschlag zur Übernahme auswählen.')
|
||||
return
|
||||
}
|
||||
|
||||
if (takeSummary) {
|
||||
updateFormField('summary', p.summaryAfterHtml)
|
||||
}
|
||||
for (const c of instrToApply) {
|
||||
updateFormField(c.field, c.afterHtml)
|
||||
}
|
||||
if (skillsToMerge.length > 0) {
|
||||
setFormDirty(true)
|
||||
setFormData((prev) => {
|
||||
const next = [...(prev.skills || [])]
|
||||
for (const row of skillsToMerge) {
|
||||
const sid = Number(row.skill_id)
|
||||
const ix = next.findIndex((s) => Number(s.skill_id) === sid)
|
||||
if (ix >= 0) next[ix] = { ...next[ix], ...row }
|
||||
else next.push(row)
|
||||
}
|
||||
return { ...prev, skills: next }
|
||||
})
|
||||
}
|
||||
|
||||
toast.success('Ausgewählte KI-Vorschläge übernommen — bitte prüfen und speichern.')
|
||||
setAiSuggestionPreview(null)
|
||||
}
|
||||
|
||||
const discardExerciseAiSuggestionPreview = () => setAiSuggestionPreview(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!aiSuggestionPreview) return undefined
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
setAiSuggestionPreview(null)
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [aiSuggestionPreview])
|
||||
|
||||
const refreshVariants = useCallback(async () => {
|
||||
if (!exerciseId) return
|
||||
const ex = await api.getExercise(exerciseId)
|
||||
@@ -1309,7 +1641,28 @@ function ExerciseFormPageRoot() {
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label">Kurzbeschreibung</label>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '8px',
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<label className="form-label" style={{ marginBottom: 0 }}>
|
||||
Kurzbeschreibung
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '12px' }}
|
||||
disabled={aiSuggestBusy}
|
||||
onClick={() => runExerciseAiSuggestion('summary')}
|
||||
>
|
||||
KI: Kurzfassung
|
||||
</button>
|
||||
</div>
|
||||
<RichTextEditor
|
||||
value={formData.summary}
|
||||
onChange={(html) => updateFormField('summary', html)}
|
||||
@@ -1906,6 +2259,29 @@ function ExerciseFormPageRoot() {
|
||||
title="Anleitung"
|
||||
hint="Ziel, Ablauf und Hinweise — Medien kannst du in die Texte einbetten (Symbolleiste)."
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '8px',
|
||||
marginBottom: '12px',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '12px' }}
|
||||
disabled={aiSuggestBusy}
|
||||
onClick={() => runExerciseAiInstructionRewrite()}
|
||||
>
|
||||
KI: Anleitung überarbeiten
|
||||
</button>
|
||||
<span style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
Überarbeitet Ziel, Durchführung, Vorbereitung und Trainer-Hinweise — prägnant und strukturiert. Vorschau
|
||||
im Dialog; nichts wird automatisch gespeichert.
|
||||
</span>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Ziel *</label>
|
||||
<RichTextEditor
|
||||
@@ -1966,6 +2342,42 @@ function ExerciseFormPageRoot() {
|
||||
title="Einordnung"
|
||||
hint="Fokus, Stile, Zielgruppen und Fähigkeiten für Suche, Filter und Skill-Profil."
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '8px',
|
||||
marginBottom: '12px',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '12px' }}
|
||||
disabled={aiSuggestBusy}
|
||||
onClick={() => runExerciseAiSuggestion('skills')}
|
||||
>
|
||||
KI: Fähigkeiten
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '12px' }}
|
||||
disabled={aiSuggestBusy}
|
||||
onClick={() => runExerciseAiSuggestion('both')}
|
||||
>
|
||||
KI: Kurzfassung und Fähigkeiten
|
||||
</button>
|
||||
<span style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
Benötigt Ziel oder Durchführung sowie optional{' '}
|
||||
<button type="button" className="exercise-form-inline-tab-link" onClick={() => setActiveFormTab('anleitung')}>
|
||||
Anleitung
|
||||
</button>
|
||||
· Es öffnet ein Dialogfeld mit Vorschau; Übernahme wählweise pro Teil. Speichern nur über die Aktionsleiste.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<section className="exercise-form-meta-panel" aria-label="Klassifikation">
|
||||
<div className="exercise-form-meta-panel__grid">
|
||||
<ExerciseCatalogAssocEditor
|
||||
@@ -2490,6 +2902,348 @@ function ExerciseFormPageRoot() {
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{aiSuggestionPreview &&
|
||||
(() => {
|
||||
const p = aiSuggestionPreview
|
||||
const summaryBoxSx = {
|
||||
padding: '10px 12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface2)',
|
||||
fontSize: '13px',
|
||||
lineHeight: 1.45,
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
minHeight: '72px',
|
||||
}
|
||||
const canApplySomething =
|
||||
(p.applySummary && p.summaryAfterHtml) ||
|
||||
p.skillChoices.some((c) => c.include) ||
|
||||
(p.instructionChoices || []).some((c) => c.include && c.afterHtml)
|
||||
const dialogTitle =
|
||||
p.instructionsRequested
|
||||
? 'KI: Anleitung überarbeiten'
|
||||
: 'KI-Vorschlag übernehmen'
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="KI-Vorschlag prüfen"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
zIndex: 1001,
|
||||
overflow: 'auto',
|
||||
padding: '16px',
|
||||
}}
|
||||
onClick={() => discardExerciseAiSuggestionPreview()}
|
||||
onKeyDown={(e) => e.key === 'Escape' && discardExerciseAiSuggestionPreview()}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
maxWidth: 760,
|
||||
margin: '3vh auto',
|
||||
maxHeight: '92vh',
|
||||
overflow: 'auto',
|
||||
position: 'relative',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h3 style={{ marginTop: 0, fontSize: '1.1rem', marginBottom: '6px' }}>{dialogTitle}</h3>
|
||||
<p style={{ fontSize: '13px', color: 'var(--text3)', marginTop: 0, marginBottom: '16px' }}>
|
||||
{p.instructionsRequested
|
||||
? 'Vergleichen und nur die gewünschten Felder übernehmen. Eingebettete Medien bleiben erhalten, wenn die KI sie nicht erwähnt.'
|
||||
: 'Vergleichen und nur die gewünschten Teile übernehmen. Es werden keine Daten automatisch gespeichert.'}
|
||||
</p>
|
||||
|
||||
{p.hasInstructionChoices ? (
|
||||
<section style={{ marginBottom: '20px' }} aria-labelledby="ai-preview-instructions-heading">
|
||||
<div
|
||||
id="ai-preview-instructions-heading"
|
||||
style={{ fontWeight: 600, fontSize: '0.95rem', marginBottom: '10px' }}
|
||||
>
|
||||
Anleitung ({p.instructionChoices.length}{' '}
|
||||
{p.instructionChoices.length === 1 ? 'Feld' : 'Felder'})
|
||||
</div>
|
||||
{p.instructionChoices.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
style={{
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
padding: '12px',
|
||||
marginBottom: '12px',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
marginBottom: '10px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={c.include}
|
||||
onChange={(e) =>
|
||||
setAiSuggestionPreview((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
instructionChoices: prev.instructionChoices.map((x) =>
|
||||
x.key === c.key ? { ...x, include: e.target.checked } : x,
|
||||
),
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{c.label} übernehmen
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)',
|
||||
gap: '12px',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)', marginBottom: '4px' }}>
|
||||
Aktuell (Plaintext)
|
||||
</div>
|
||||
<div style={summaryBoxSx}>{c.beforePlain || '(leer)'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)', marginBottom: '4px' }}>
|
||||
KI-Vorschlag
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
...summaryBoxSx,
|
||||
borderColor: 'var(--accent-dark, rgba(29,158,117,0.45))',
|
||||
}}
|
||||
>
|
||||
{c.afterPlain || '(leer)'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{p.hasSummaryProposal ? (
|
||||
<section style={{ marginBottom: '20px' }} aria-labelledby="ai-preview-summary-heading">
|
||||
<div
|
||||
id="ai-preview-summary-heading"
|
||||
style={{ fontWeight: 600, fontSize: '0.95rem', marginBottom: '10px' }}
|
||||
>
|
||||
Kurzfassung
|
||||
</div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
marginBottom: '10px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={p.applySummary}
|
||||
onChange={(e) =>
|
||||
setAiSuggestionPreview((prev) =>
|
||||
prev ? { ...prev, applySummary: e.target.checked } : prev,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Kurzfassung durch Vorschlag ersetzen (bestehende Kurzbeschreibung wird überschrieben)
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)',
|
||||
gap: '12px',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)', marginBottom: '4px' }}>
|
||||
Aktuell (ohne Formatierung)
|
||||
</div>
|
||||
<div style={summaryBoxSx}>{p.summaryBeforePlain || '(leer)'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)', marginBottom: '4px' }}>KI-Vorschlag</div>
|
||||
<div style={{ ...summaryBoxSx, borderColor: 'var(--accent-dark, rgba(29,158,117,0.45))' }}>
|
||||
{p.summaryAfterPlain || '(leer)'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{p.skillsRequested ? (
|
||||
<section aria-labelledby="ai-preview-skills-heading">
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '8px',
|
||||
marginBottom: '10px',
|
||||
}}
|
||||
>
|
||||
<div id="ai-preview-skills-heading" style={{ fontWeight: 600, fontSize: '0.95rem' }}>
|
||||
Fähigkeiten ({p.skillChoices.length}
|
||||
{p.skillChoices.length === 1 ? ' Vorschlag' : ' Vorschläge'})
|
||||
</div>
|
||||
{p.skillChoices.length > 0 ? (
|
||||
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '4px 8px' }}
|
||||
onClick={() =>
|
||||
setAiSuggestionPreview((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
skillChoices: prev.skillChoices.map((x) => ({ ...x, include: true })),
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
>
|
||||
Alle auswählen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: '11px', padding: '4px 8px' }}
|
||||
onClick={() =>
|
||||
setAiSuggestionPreview((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
skillChoices: prev.skillChoices.map((x) => ({ ...x, include: false })),
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
>
|
||||
Alle abwählen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{p.skillChoices.length === 0 ? (
|
||||
<p style={{ fontSize: '13px', color: 'var(--text3)', margin: 0 }}>
|
||||
Keine passenden Fähigkeiten — der Katalog-Vorschlag war leer oder enthielt nur ungültige IDs.
|
||||
</p>
|
||||
) : (
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{p.skillChoices.map((c) => (
|
||||
<li
|
||||
key={c.key}
|
||||
style={{
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
padding: '10px 12px',
|
||||
marginBottom: '10px',
|
||||
background: 'var(--surface)',
|
||||
}}
|
||||
>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
alignItems: 'flex-start',
|
||||
cursor: 'pointer',
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={c.include}
|
||||
onChange={() =>
|
||||
setAiSuggestionPreview((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
skillChoices: prev.skillChoices.map((x) =>
|
||||
x.skill_id === c.skill_id ? { ...x, include: !x.include } : x,
|
||||
),
|
||||
}
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
style={{ marginTop: '4px' }}
|
||||
/>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: '13px', marginBottom: '6px' }}>
|
||||
{c.kind === 'add' ? 'Neu hinzufügen' : 'Bestehende Zeile aktualisieren'}
|
||||
</div>
|
||||
{c.kind === 'update' && c.before ? (
|
||||
<div style={{ fontSize: '12px', lineHeight: 1.5 }}>
|
||||
<div style={{ color: 'var(--text3)', marginBottom: '2px' }}>Bisher</div>
|
||||
<div style={{ marginBottom: '8px' }}>
|
||||
{describeExerciseSkillRowForPreview(c.before, skillsCatalog)}
|
||||
</div>
|
||||
<div style={{ color: 'var(--text3)', marginBottom: '2px' }}>Nach KI-Vorschlag</div>
|
||||
<div>{describeExerciseSkillRowForPreview(c.after, skillsCatalog)}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ fontSize: '13px', lineHeight: 1.5 }}>
|
||||
{describeExerciseSkillRowForPreview(c.after, skillsCatalog)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
style={{
|
||||
marginTop: '20px',
|
||||
paddingTop: '14px',
|
||||
borderTop: '1px solid var(--border)',
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
flexWrap: 'wrap',
|
||||
gap: '10px',
|
||||
}}
|
||||
>
|
||||
<button type="button" className="btn btn-secondary" onClick={discardExerciseAiSuggestionPreview}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={!canApplySomething}
|
||||
onClick={() => applyExerciseAiSuggestionPreview()}
|
||||
>
|
||||
Ausgewähltes übernehmen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
<ExercisePickerModal
|
||||
open={comboStationPickerIx !== null}
|
||||
onClose={() => setComboStationPickerIx(null)}
|
||||
@@ -2504,11 +3258,9 @@ function ExerciseFormPageRoot() {
|
||||
/>
|
||||
|
||||
<p style={{ fontSize: '12px', color: 'var(--text3)', marginTop: '16px' }}>
|
||||
<strong>KI-Ausbaustufe:</strong> Backend laut Spec{' '}
|
||||
<code style={{ fontSize: '11px' }}>POST /api/exercises/ai/suggest</code> und{' '}
|
||||
<code style={{ fontSize: '11px' }}>POST /api/exercises/{'{id}'}/ai/regenerate</code> — z. B.{' '}
|
||||
<code>OPENROUTER_API_KEY</code>, Vorschläge nur nach Trainer-Bestätigung übernehmen (siehe{' '}
|
||||
<code>api.suggestExerciseAi</code>).
|
||||
<strong>KI-Unterstützung:</strong> OpenRouter-Vorschläge für Kurzfassung, Fähigkeiten und Anleitung
|
||||
(<code>suggestExerciseAi</code> / <code>regenerateExerciseAi</code>). Übernahme im Dialog ins Formular; Speichern
|
||||
wie gewohnt.
|
||||
</p>
|
||||
<UnsavedChangesPrompt
|
||||
blocker={blocker}
|
||||
|
||||
@@ -241,6 +241,22 @@ export default function ExerciseListCard({
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{Array.isArray(exercise._planningReasons) && exercise._planningReasons.length > 0 ? (
|
||||
<ul
|
||||
className="exercise-card__planning-reasons"
|
||||
style={{
|
||||
margin: '8px 0 0',
|
||||
paddingLeft: '18px',
|
||||
fontSize: '12px',
|
||||
color: 'var(--accent-dark)',
|
||||
lineHeight: 1.4,
|
||||
}}
|
||||
>
|
||||
{exercise._planningReasons.slice(0, 3).map((r) => (
|
||||
<li key={r}>{r}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="exercise-card__footer">
|
||||
|
||||
@@ -14,7 +14,110 @@ export default function ExerciseListSearchBar({
|
||||
exerciseCount,
|
||||
allOnPageSelected,
|
||||
onToggleSelectAllPage,
|
||||
kiSearchMode = false,
|
||||
planningSearchInput = '',
|
||||
onPlanningSearchInputChange,
|
||||
onSubmitPlanningSearch,
|
||||
planningSearchLoading = false,
|
||||
planningHasSearched = false,
|
||||
planningRetrievalPhase = '',
|
||||
planningContextSummary = null,
|
||||
planningTargetProfileSummary = null,
|
||||
planningSearchError = '',
|
||||
}) {
|
||||
if (kiSearchMode) {
|
||||
return (
|
||||
<div className="card exercise-search-bar exercise-search-bar--ki">
|
||||
<label className="form-label">Planungs-Anfrage (KI)</label>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'stretch' }}>
|
||||
<input
|
||||
type="search"
|
||||
className="form-input exercise-search-bar__primary"
|
||||
placeholder="z. B. Partnerübung Reaktion, Vertiefung Schnellkraft …"
|
||||
value={planningSearchInput}
|
||||
onChange={(e) => onPlanningSearchInputChange?.(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
onSubmitPlanningSearch?.()
|
||||
}
|
||||
}}
|
||||
autoComplete="off"
|
||||
enterKeyHint="search"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={planningSearchLoading}
|
||||
onClick={() => onSubmitPlanningSearch?.()}
|
||||
>
|
||||
{planningSearchLoading ? 'Suche …' : 'Vorschläge laden'}
|
||||
</button>
|
||||
</div>
|
||||
<p className="exercise-search-hint" style={{ marginTop: '10px' }}>
|
||||
<strong>Planungs-KI</strong> durchsucht die sichtbare Bibliothek mit Profil-Score und optional LLM — nicht
|
||||
die einfache Volltextsuche. Filter und „Meine Übungen“ gelten hier nicht; KI-Assistent ausschalten für
|
||||
klassische Liste.
|
||||
{planningRetrievalPhase ? (
|
||||
<>
|
||||
{' '}
|
||||
· Phase: <code>{planningRetrievalPhase}</code>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
{planningSearchError ? (
|
||||
<p className="form-error" style={{ marginTop: '8px' }}>
|
||||
{planningSearchError}
|
||||
</p>
|
||||
) : null}
|
||||
{planningHasSearched && planningContextSummary ? (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '10px',
|
||||
padding: '8px 10px',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface2)',
|
||||
border: '1px solid var(--border)',
|
||||
fontSize: '12px',
|
||||
color: 'var(--text2)',
|
||||
lineHeight: 1.45,
|
||||
}}
|
||||
>
|
||||
<strong style={{ color: 'var(--text1)', fontSize: '13px' }}>KI-Kontext</strong>
|
||||
<div style={{ marginTop: '4px', display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
|
||||
{planningContextSummary.expectation_mode ? (
|
||||
<span className="exercise-tag">
|
||||
{planningContextSummary.expectation_mode === 'query_only' ? 'Freitext-Profil' : 'Hybrid-Profil'}
|
||||
</span>
|
||||
) : null}
|
||||
{Array.isArray(planningTargetProfileSummary?.focus_areas) &&
|
||||
planningTargetProfileSummary.focus_areas.length > 0
|
||||
? planningTargetProfileSummary.focus_areas.slice(0, 2).map((fa) => (
|
||||
<span key={fa} className="exercise-tag">
|
||||
Fokus: {fa}
|
||||
</span>
|
||||
))
|
||||
: null}
|
||||
{Array.isArray(planningTargetProfileSummary?.top_skills) &&
|
||||
planningTargetProfileSummary.top_skills.length > 0
|
||||
? planningTargetProfileSummary.top_skills.slice(0, 2).map((sk) => (
|
||||
<span key={sk.skill_id} className="exercise-tag">
|
||||
{sk.name}
|
||||
</span>
|
||||
))
|
||||
: null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{!planningHasSearched ? (
|
||||
<p className="muted" style={{ marginTop: '10px', marginBottom: 0, fontSize: '13px' }}>
|
||||
Anfrage formulieren und „Vorschläge laden“ klicken.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card exercise-search-bar">
|
||||
<label className="form-label">Volltextsuche (Titel, Ziel, …)</label>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback, useRef, lazy, Suspense } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import api from '../../utils/api'
|
||||
import { useAuth } from '../../context/AuthContext'
|
||||
import { activeClubMemberships, getTenantClubDependencyKey } from '../../utils/activeClub'
|
||||
@@ -11,6 +12,15 @@ import ExerciseListBulkToolbar from './ExerciseListBulkToolbar'
|
||||
import SaveSelectedExercisesAsModuleModal from './SaveSelectedExercisesAsModuleModal'
|
||||
import ExercisePeekModal from '../ExercisePeekModal'
|
||||
import NavStateLink from '../NavStateLink'
|
||||
import { ExerciseAiQuickCreateTeaser } from '../ExerciseAiQuickCreateOffer'
|
||||
import ExerciseAiQuickCreateModal from './ExerciseAiQuickCreateModal'
|
||||
import ExerciseAiSuggestPreviewModal from '../ExerciseAiSuggestPreviewModal'
|
||||
import {
|
||||
buildQuickCreateAiPreview,
|
||||
buildQuickCreateExercisePayloadFromDraft,
|
||||
aiPreviewToQuickCreateDraft,
|
||||
} from '../../utils/exerciseAiQuickCreate'
|
||||
import { useExerciseAiQuickCreateFields } from '../../hooks/useExerciseAiQuickCreateFields'
|
||||
import { buildExercisesListReturnContext } from '../../utils/navReturnContext'
|
||||
import { buildExerciseListFilterChips } from '../../utils/exerciseListFilterChips'
|
||||
import { skillCatalogPathLabel } from '../../utils/skillCatalogTree'
|
||||
@@ -22,6 +32,7 @@ import {
|
||||
snapshotExerciseForSelection,
|
||||
} from '../../utils/exerciseListSelection'
|
||||
import { useExerciseListCatalogsAndQuery } from '../../hooks/useExerciseListCatalogsAndQuery'
|
||||
import { usePlanningExerciseSuggestSearch } from '../../hooks/usePlanningExerciseSuggestSearch'
|
||||
import {
|
||||
INITIAL_EXERCISE_LIST_FILTERS,
|
||||
mergeExerciseListPrefsFromApi,
|
||||
@@ -37,6 +48,7 @@ const EXERCISES_PAGE_TABS = [
|
||||
]
|
||||
|
||||
function ExercisesListPageRoot() {
|
||||
const navigate = useNavigate()
|
||||
const { user, checkAuth } = useAuth()
|
||||
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
@@ -78,6 +90,31 @@ function ExercisesListPageRoot() {
|
||||
const [bulkTargetGroupIds, setBulkTargetGroupIds] = useState([])
|
||||
const [peekExercise, setPeekExercise] = useState(null)
|
||||
const [saveModuleModalOpen, setSaveModuleModalOpen] = useState(false)
|
||||
const [aiQuickCreateEnabled, setAiQuickCreateEnabled] = useState(false)
|
||||
const [aiQuickCreateModalOpen, setAiQuickCreateModalOpen] = useState(false)
|
||||
const [quickSaving, setQuickSaving] = useState(false)
|
||||
const [quickAiError, setQuickAiError] = useState('')
|
||||
const [quickCreateDraft, setQuickCreateDraft] = useState(null)
|
||||
|
||||
const planningKi = usePlanningExerciseSuggestSearch({
|
||||
enabled: pageTab === 'list' && aiQuickCreateEnabled,
|
||||
})
|
||||
|
||||
const {
|
||||
title: quickTitle,
|
||||
sketch: quickSketch,
|
||||
focusAreaId: quickFocusAreaId,
|
||||
setTitle: setQuickTitle,
|
||||
setSketch: setQuickSketch,
|
||||
setFocusAreaId: setQuickFocusAreaId,
|
||||
} = useExerciseAiQuickCreateFields(
|
||||
aiQuickCreateModalOpen
|
||||
? planningKi.submittedQuery || planningKi.searchInput || debouncedSearch
|
||||
: debouncedSearch,
|
||||
{
|
||||
enabled: pageTab === 'list' && aiQuickCreateModalOpen,
|
||||
},
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!user?.id) return
|
||||
@@ -149,7 +186,18 @@ function ExercisesListPageRoot() {
|
||||
loadingMore,
|
||||
hasMore,
|
||||
loadMore,
|
||||
} = useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey })
|
||||
} = useExerciseListCatalogsAndQuery({
|
||||
queryBase,
|
||||
pageTab,
|
||||
tenantClubDepKey,
|
||||
skipListFetch: aiQuickCreateEnabled,
|
||||
})
|
||||
|
||||
const listExercises = exercises
|
||||
const listFetchingResolved = listFetching
|
||||
const exercisesForDisplay = aiQuickCreateEnabled ? planningKi.rows : listExercises
|
||||
const listFetchingDisplay = aiQuickCreateEnabled ? planningKi.loading : listFetchingResolved
|
||||
const hasMoreDisplay = aiQuickCreateEnabled ? false : hasMore
|
||||
|
||||
const selectedIds = useMemo(
|
||||
() => new Set(selectedEntries.map((e) => Number(e.id)).filter((id) => Number.isFinite(id) && id > 0)),
|
||||
@@ -157,15 +205,22 @@ function ExercisesListPageRoot() {
|
||||
)
|
||||
|
||||
const selectedExercisesDisplay = useMemo(
|
||||
() => mergeSelectedWithListEntries(selectedEntries, exercises),
|
||||
[selectedEntries, exercises]
|
||||
() => mergeSelectedWithListEntries(selectedEntries, exercisesForDisplay),
|
||||
[selectedEntries, exercisesForDisplay],
|
||||
)
|
||||
|
||||
const filterResultExercises = useMemo(
|
||||
() => exercises.filter((e) => !selectedIds.has(Number(e.id))),
|
||||
[exercises, selectedIds]
|
||||
() => exercisesForDisplay.filter((e) => !selectedIds.has(Number(e.id))),
|
||||
[exercisesForDisplay, selectedIds],
|
||||
)
|
||||
|
||||
const showKiCreateTeaser =
|
||||
aiQuickCreateEnabled &&
|
||||
planningKi.hasSearched &&
|
||||
!planningKi.loading &&
|
||||
catalogsReady &&
|
||||
filterResultExercises.length > 0
|
||||
|
||||
const focusOptions = useMemo(
|
||||
() =>
|
||||
catalogs.focusAreas.map((fa) => ({
|
||||
@@ -242,9 +297,9 @@ function ExercisesListPageRoot() {
|
||||
|
||||
/** Für Browser-/datalist-Vorschläge (aktuelle Treffer-Titel, begrenzt) */
|
||||
const searchTitleSuggestions = useMemo(() => {
|
||||
const titles = exercises.map((e) => (e.title || '').trim()).filter(Boolean)
|
||||
const titles = listExercises.map((e) => (e.title || '').trim()).filter(Boolean)
|
||||
return [...new Set(titles)].slice(0, 80)
|
||||
}, [exercises])
|
||||
}, [listExercises])
|
||||
|
||||
const clubNameById = useMemo(() => {
|
||||
const m = {}
|
||||
@@ -304,6 +359,83 @@ function ExercisesListPageRoot() {
|
||||
|
||||
const exercisesModuleReturnContext = useMemo(() => buildExercisesListReturnContext(), [])
|
||||
|
||||
const runQuickCreateAiSuggest = useCallback(async () => {
|
||||
const title = (quickTitle || '').trim()
|
||||
if (title.length < 3) {
|
||||
alert('Titel: mindestens 3 Zeichen.')
|
||||
return
|
||||
}
|
||||
const sketch = (quickSketch || '').trim()
|
||||
|
||||
const focusId = parseInt(String(quickFocusAreaId).trim(), 10)
|
||||
if (!Number.isFinite(focusId) || focusId < 1) {
|
||||
alert('Bitte einen Fokusbereich wählen.')
|
||||
return
|
||||
}
|
||||
|
||||
const focusRow = (catalogs.focusAreas || []).find((x) => Number(x.id) === focusId)
|
||||
const focusHint = (focusRow?.name || '').trim()
|
||||
|
||||
setQuickAiError('')
|
||||
setQuickCreateDraft(null)
|
||||
setQuickSaving(true)
|
||||
try {
|
||||
const aiRes = await api.suggestExerciseAi({
|
||||
title,
|
||||
goal: sketch || undefined,
|
||||
execution: '',
|
||||
preparation: '',
|
||||
trainer_notes: '',
|
||||
focus_area_hint: focusHint || undefined,
|
||||
focus_areas_context: [{ focus_area_id: focusId, is_primary: true }],
|
||||
include_summary: true,
|
||||
include_skills: true,
|
||||
include_instructions: true,
|
||||
})
|
||||
|
||||
const preview = buildQuickCreateAiPreview(aiRes, { sketchPlain: sketch })
|
||||
if (!preview.hasSummaryProposal && !preview.hasInstructionChoices && !preview.hasSkillChoices) {
|
||||
throw new Error('Die KI lieferte keinen verwertbaren Vorschlag.')
|
||||
}
|
||||
setQuickCreateDraft(
|
||||
aiPreviewToQuickCreateDraft(preview, { title, focusAreaId: focusId, sketchPlain: sketch }),
|
||||
)
|
||||
setAiQuickCreateModalOpen(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
const msg = e?.message || String(e)
|
||||
setQuickAiError(msg)
|
||||
alert(msg || 'KI-Vorschlag fehlgeschlagen')
|
||||
} finally {
|
||||
setQuickSaving(false)
|
||||
}
|
||||
}, [quickTitle, quickSketch, quickFocusAreaId, catalogs.focusAreas])
|
||||
|
||||
const applyQuickCreateDraft = useCallback(async () => {
|
||||
if (!quickCreateDraft) return
|
||||
|
||||
setQuickSaving(true)
|
||||
setQuickAiError('')
|
||||
try {
|
||||
const payload = buildQuickCreateExercisePayloadFromDraft(quickCreateDraft)
|
||||
const created = await api.createExercise(payload)
|
||||
if (!created?.id) throw new Error('Anlegen fehlgeschlagen')
|
||||
setQuickCreateDraft(null)
|
||||
setAiQuickCreateEnabled(false)
|
||||
setExercises((prev) => [created, ...prev])
|
||||
navigate(`/exercises/${created.id}/edit`, {
|
||||
state: { returnContext: exercisesModuleReturnContext },
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
const msg = e?.message || String(e)
|
||||
setQuickAiError(msg)
|
||||
alert(msg || 'Übung konnte nicht angelegt werden')
|
||||
} finally {
|
||||
setQuickSaving(false)
|
||||
}
|
||||
}, [quickCreateDraft, setExercises, navigate, exercisesModuleReturnContext])
|
||||
|
||||
const bulkVisibilityOptions = useMemo(() => {
|
||||
const base = [
|
||||
{ id: '', label: '— nicht ändern —' },
|
||||
@@ -486,13 +618,40 @@ function ExercisesListPageRoot() {
|
||||
<div className="exercises-page__header">
|
||||
<h1 className="page-title exercises-page__title">Übungen</h1>
|
||||
{pageTab === 'list' ? (
|
||||
<NavStateLink
|
||||
to="/exercises/new"
|
||||
returnContext={exercisesModuleReturnContext}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
+ Neu
|
||||
</NavStateLink>
|
||||
<div className="exercises-page__header-actions">
|
||||
<label
|
||||
className="exercises-ai-assistant-toggle"
|
||||
title="Planungs-KI-Suche in der Bibliothek und Neuanlage per KI-Dialog (ohne normales Formular „+ Neu“)"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={aiQuickCreateEnabled}
|
||||
onChange={(e) => {
|
||||
setAiQuickCreateEnabled(e.target.checked)
|
||||
if (!e.target.checked) setAiQuickCreateModalOpen(false)
|
||||
}}
|
||||
/>
|
||||
<span className="exercises-ai-assistant-toggle__track" aria-hidden="true" />
|
||||
<span>Neu mit KI-Assistent</span>
|
||||
</label>
|
||||
{aiQuickCreateEnabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => setAiQuickCreateModalOpen(true)}
|
||||
>
|
||||
+ Neue Übung mit KI
|
||||
</button>
|
||||
) : (
|
||||
<NavStateLink
|
||||
to="/exercises/new"
|
||||
returnContext={exercisesModuleReturnContext}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
+ Neu
|
||||
</NavStateLink>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span aria-hidden="true" />
|
||||
)}
|
||||
@@ -522,6 +681,16 @@ function ExercisesListPageRoot() {
|
||||
) : (
|
||||
<>
|
||||
<ExerciseListSearchBar
|
||||
kiSearchMode={aiQuickCreateEnabled}
|
||||
planningSearchInput={planningKi.searchInput}
|
||||
onPlanningSearchInputChange={planningKi.setSearchInput}
|
||||
onSubmitPlanningSearch={() => planningKi.submitSearch()}
|
||||
planningSearchLoading={planningKi.loading}
|
||||
planningHasSearched={planningKi.hasSearched}
|
||||
planningRetrievalPhase={planningKi.retrievalPhase}
|
||||
planningContextSummary={planningKi.contextSummary}
|
||||
planningTargetProfileSummary={planningKi.targetProfileSummary}
|
||||
planningSearchError={planningKi.error}
|
||||
searchTitleSuggestions={searchTitleSuggestions}
|
||||
searchInput={searchInput}
|
||||
onSearchInputChange={setSearchInput}
|
||||
@@ -532,11 +701,18 @@ function ExercisesListPageRoot() {
|
||||
onOpenFilter={() => setFilterModalOpen(true)}
|
||||
filterChips={filterChips}
|
||||
onResetAllFilters={resetAllFilters}
|
||||
exerciseCount={exercises.length}
|
||||
exerciseCount={exercisesForDisplay.length}
|
||||
allOnPageSelected={allOnPageSelected}
|
||||
onToggleSelectAllPage={toggleSelectAllPage}
|
||||
/>
|
||||
|
||||
{showKiCreateTeaser ? (
|
||||
<ExerciseAiQuickCreateTeaser
|
||||
onExpand={() => setAiQuickCreateModalOpen(true)}
|
||||
disabled={quickSaving}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ExerciseListBulkToolbar
|
||||
selectedCount={selectedIds.size}
|
||||
bulkMaxIds={BULK_MAX_IDS}
|
||||
@@ -618,16 +794,34 @@ function ExercisesListPageRoot() {
|
||||
onClose={() => setPeekExercise(null)}
|
||||
/>
|
||||
|
||||
{listFetching && exercises.length === 0 && selectedEntries.length === 0 ? (
|
||||
{listFetchingDisplay && exercisesForDisplay.length === 0 && selectedEntries.length === 0 ? (
|
||||
<div className="card empty-state" style={{ padding: '2rem 1rem' }}>
|
||||
<div className="spinner" />
|
||||
<p className="muted" style={{ marginTop: '12px' }}>
|
||||
Lade Übungen…
|
||||
{aiQuickCreateEnabled ? 'Planungs-KI lädt Vorschläge…' : 'Lade Übungen…'}
|
||||
</p>
|
||||
</div>
|
||||
) : exercises.length === 0 && selectedEntries.length === 0 ? (
|
||||
) : exercisesForDisplay.length === 0 && selectedEntries.length === 0 ? (
|
||||
<div className="card">
|
||||
<p className="exercises-empty-text">Keine Übungen gefunden.</p>
|
||||
<p className="exercises-empty-text">
|
||||
{aiQuickCreateEnabled
|
||||
? planningKi.hasSearched
|
||||
? 'Keine passenden Übungen — neue Übung mit KI anlegen?'
|
||||
: 'Planungs-Anfrage formulieren und „Vorschläge laden“ klicken — oder „Neue Übung mit KI“ oben.'
|
||||
: debouncedSearch.length >= 3
|
||||
? 'Keine Übungen gefunden.'
|
||||
: 'Keine Übungen gefunden — Suchbegriff eingeben oder Filter anpassen.'}
|
||||
</p>
|
||||
{aiQuickCreateEnabled && planningKi.hasSearched ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ marginTop: '12px' }}
|
||||
onClick={() => setAiQuickCreateModalOpen(true)}
|
||||
>
|
||||
Neue Übung mit KI …
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
@@ -664,13 +858,14 @@ function ExercisesListPageRoot() {
|
||||
) : null
|
||||
) : (
|
||||
<>
|
||||
{listFetching ? (
|
||||
{listFetchingDisplay ? (
|
||||
<p className="exercises-meta-line exercises-meta-line--muted">Aktualisiere Treffer…</p>
|
||||
) : null}
|
||||
<p className="exercises-meta-line">
|
||||
{filterResultExercises.length} Treffer
|
||||
{aiQuickCreateEnabled ? ' (Planungs-KI)' : ''}
|
||||
{selectedEntries.length > 0 ? ' (ohne bereits Ausgewählte)' : ''}
|
||||
{hasMore ? ' · es gibt weitere Einträge' : ''}
|
||||
{hasMoreDisplay ? ' · es gibt weitere Einträge' : ''}
|
||||
</p>
|
||||
<div className="exercises-list-grid" data-testid="exercises-list-grid">
|
||||
{filterResultExercises.map((exercise) => (
|
||||
@@ -685,7 +880,7 @@ function ExercisesListPageRoot() {
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{hasMore && (
|
||||
{hasMoreDisplay && (
|
||||
<div className="exercises-load-more">
|
||||
<button type="button" className="btn btn-secondary" disabled={loadingMore} onClick={loadMore}>
|
||||
{loadingMore ? 'Laden…' : 'Mehr laden'}
|
||||
@@ -696,6 +891,40 @@ function ExercisesListPageRoot() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ExerciseAiQuickCreateModal
|
||||
open={aiQuickCreateModalOpen}
|
||||
onClose={() => {
|
||||
if (!quickSaving) setAiQuickCreateModalOpen(false)
|
||||
}}
|
||||
searchLabel={
|
||||
planningKi.submittedQuery || planningKi.searchInput || debouncedSearch || undefined
|
||||
}
|
||||
title={quickTitle}
|
||||
onTitleChange={setQuickTitle}
|
||||
sketch={quickSketch}
|
||||
onSketchChange={setQuickSketch}
|
||||
focusAreaId={quickFocusAreaId}
|
||||
onFocusAreaChange={setQuickFocusAreaId}
|
||||
focusAreas={catalogs.focusAreas}
|
||||
catalogsReady={catalogsReady}
|
||||
busy={quickSaving}
|
||||
error={quickAiError}
|
||||
onRunAi={runQuickCreateAiSuggest}
|
||||
/>
|
||||
|
||||
<ExerciseAiSuggestPreviewModal
|
||||
draft={quickCreateDraft}
|
||||
onDraftChange={setQuickCreateDraft}
|
||||
onDiscard={() => setQuickCreateDraft(null)}
|
||||
onApply={applyQuickCreateDraft}
|
||||
focusAreas={catalogs.focusAreas}
|
||||
skillsCatalog={catalogs.skills}
|
||||
dialogTitle="Neue Übung — KI-Entwurf bearbeiten"
|
||||
hint="Texte sind formatiert — passe sie an und lege die Übung als Entwurf an."
|
||||
applyLabel={quickSaving ? 'Wird angelegt…' : 'Übung anlegen'}
|
||||
applyDisabled={quickSaving}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -37,6 +37,7 @@ export default function TrainingUnitFormShell({
|
||||
onRequestSaveAsModule,
|
||||
onRequestTrainingModulePick,
|
||||
onRequestExercisePick,
|
||||
onRequestPlanningExercisePick,
|
||||
onPeekExercise,
|
||||
formId = 'planning-unit-form',
|
||||
}) {
|
||||
@@ -427,6 +428,7 @@ export default function TrainingUnitFormShell({
|
||||
}
|
||||
onRequestTrainingModulePick={onRequestTrainingModulePick}
|
||||
onRequestExercisePick={onRequestExercisePick}
|
||||
onRequestPlanningExercisePick={onRequestPlanningExercisePick}
|
||||
onPeekExercise={onPeekExercise}
|
||||
showExecutionExtras={Boolean(editingUnit) && sectionsEditMode === 'debrief'}
|
||||
enableParallelPhaseControls
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Backend POST /api/planning/exercise-suggest erlaubt max. 50 */
|
||||
export const PLANNING_SUGGEST_LIMIT = 50
|
||||
|
||||
/** Client-Hinweis — Backend entscheidet final über LLM-Gates. */
|
||||
export const PLANNING_LLM_INTENT_MIN_CHARS = 10
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
|
||||
import { parseSearchQueryForQuickCreate } from '../utils/exerciseAiQuickCreate'
|
||||
|
||||
/**
|
||||
* Titel aus Suche vorbelegen; Kurzbeschreibung optional und manuell editierbar.
|
||||
* Suchwechsel setzt „touched“ zurück und befüllt neu — solange der Nutzer nicht editiert hat.
|
||||
*/
|
||||
export function useExerciseAiQuickCreateFields(debouncedSearch, { enabled = true } = {}) {
|
||||
const [title, setTitleState] = useState('')
|
||||
const [sketch, setSketchState] = useState('')
|
||||
const [focusAreaId, setFocusAreaId] = useState('')
|
||||
const titleTouchedRef = useRef(false)
|
||||
const sketchTouchedRef = useRef(false)
|
||||
const lastSearchRef = useRef('')
|
||||
|
||||
const parsed = useMemo(() => parseSearchQueryForQuickCreate(debouncedSearch), [debouncedSearch])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
if (debouncedSearch !== lastSearchRef.current) {
|
||||
lastSearchRef.current = debouncedSearch
|
||||
titleTouchedRef.current = false
|
||||
sketchTouchedRef.current = false
|
||||
}
|
||||
if (!debouncedSearch) return
|
||||
if (!titleTouchedRef.current) {
|
||||
setTitleState(parsed.title)
|
||||
}
|
||||
if (!sketchTouchedRef.current) {
|
||||
setSketchState('')
|
||||
}
|
||||
}, [enabled, debouncedSearch, parsed.title])
|
||||
|
||||
const setTitle = useCallback((v) => {
|
||||
titleTouchedRef.current = true
|
||||
setTitleState(v)
|
||||
}, [])
|
||||
|
||||
const setSketch = useCallback((v) => {
|
||||
sketchTouchedRef.current = true
|
||||
setSketchState(v)
|
||||
}, [])
|
||||
|
||||
const resetQuickCreateFields = useCallback(() => {
|
||||
setTitleState('')
|
||||
setSketchState('')
|
||||
setFocusAreaId('')
|
||||
titleTouchedRef.current = false
|
||||
sketchTouchedRef.current = false
|
||||
lastSearchRef.current = ''
|
||||
}, [])
|
||||
|
||||
return {
|
||||
title,
|
||||
sketch,
|
||||
focusAreaId,
|
||||
setTitle,
|
||||
setSketch,
|
||||
setFocusAreaId,
|
||||
resetQuickCreateFields,
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export const EXERCISE_LIST_PAGE_SIZE = 100
|
||||
/**
|
||||
* Lädt Kataloge für Filter/Bulk einmalig und hält die Übungsliste (Offset + Keyset „Mehr laden“) synchron zu queryBase.
|
||||
*/
|
||||
export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey }) {
|
||||
export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey, skipListFetch = false }) {
|
||||
const [catalogs, setCatalogs] = useState({
|
||||
focusAreas: [],
|
||||
styleDirections: [],
|
||||
@@ -55,7 +55,14 @@ export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClub
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!catalogsReady || pageTab !== 'list') return
|
||||
if (!catalogsReady || pageTab !== 'list' || skipListFetch) {
|
||||
if (skipListFetch) {
|
||||
setExercises([])
|
||||
setHasMore(false)
|
||||
setListFetching(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
const run = async () => {
|
||||
setListFetching(true)
|
||||
@@ -81,7 +88,7 @@ export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClub
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [queryBase, catalogsReady, pageTab, tenantClubDepKey])
|
||||
}, [queryBase, catalogsReady, pageTab, tenantClubDepKey, skipListFetch])
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
if (loadingMore || !hasMore) return
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import api from '../utils/api'
|
||||
import { PLANNING_LLM_INTENT_MIN_CHARS, PLANNING_SUGGEST_LIMIT } from '../constants/planningExerciseSuggest'
|
||||
|
||||
export function mapPlanningHitsToListRows(hits) {
|
||||
return (Array.isArray(hits) ? hits : []).map((h) => ({
|
||||
id: h.id,
|
||||
title: h.title,
|
||||
summary: h.summary,
|
||||
focus_area: h.focus_area,
|
||||
focus_area_names: h.focus_area ? [h.focus_area] : [],
|
||||
variants: Array.isArray(h.variants) ? h.variants : [],
|
||||
suggested_variant_id: h.suggested_variant_id ?? null,
|
||||
suggested_variant_name: h.suggested_variant_name ?? null,
|
||||
updated_at: new Date().toISOString(),
|
||||
_planningScore: h.score,
|
||||
_planningReasons: Array.isArray(h.reasons) ? h.reasons : [],
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Freie Planungs-KI-Suche (ohne unit_id) — z. B. Übungsliste im KI-Assistent-Modus.
|
||||
*/
|
||||
export function usePlanningExerciseSuggestSearch({ enabled, groupId = null } = {}) {
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [submittedQuery, setSubmittedQuery] = useState('')
|
||||
const [searchTick, setSearchTick] = useState(0)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [hasSearched, setHasSearched] = useState(false)
|
||||
const [rows, setRows] = useState([])
|
||||
const [contextSummary, setContextSummary] = useState(null)
|
||||
const [targetProfileSummary, setTargetProfileSummary] = useState(null)
|
||||
const [retrievalPhase, setRetrievalPhase] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSearchInput('')
|
||||
setSubmittedQuery('')
|
||||
setSearchTick(0)
|
||||
setHasSearched(false)
|
||||
setRows([])
|
||||
setContextSummary(null)
|
||||
setTargetProfileSummary(null)
|
||||
setRetrievalPhase('')
|
||||
setError('')
|
||||
}, [])
|
||||
|
||||
const submitSearch = useCallback(
|
||||
(queryOverride) => {
|
||||
const q =
|
||||
queryOverride !== undefined && queryOverride !== null
|
||||
? String(queryOverride).trim()
|
||||
: searchInput.trim()
|
||||
setSubmittedQuery(q)
|
||||
setHasSearched(true)
|
||||
setSearchTick((t) => t + 1)
|
||||
},
|
||||
[searchInput],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
reset()
|
||||
}
|
||||
}, [enabled, reset])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || searchTick === 0) return undefined
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const query = submittedQuery
|
||||
const body = {
|
||||
query,
|
||||
include_llm_intent: query.length >= PLANNING_LLM_INTENT_MIN_CHARS || !query,
|
||||
include_llm_rank: true,
|
||||
intent_hint: query ? 'free_search' : 'suggest_next',
|
||||
limit: PLANNING_SUGGEST_LIMIT,
|
||||
}
|
||||
const gid = Number(groupId)
|
||||
if (Number.isFinite(gid) && gid > 0) body.group_id = gid
|
||||
const res = await api.suggestPlanningExercises(body)
|
||||
if (cancelled) return
|
||||
setContextSummary(res?.context_summary || null)
|
||||
setTargetProfileSummary(res?.target_profile_summary || null)
|
||||
setRetrievalPhase(res?.retrieval_phase || '')
|
||||
setRows(mapPlanningHitsToListRows(res?.hits))
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
console.error(e)
|
||||
setError(e.message || 'Planungs-KI-Suche fehlgeschlagen')
|
||||
setRows([])
|
||||
setContextSummary(null)
|
||||
setTargetProfileSummary(null)
|
||||
setRetrievalPhase('')
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [enabled, searchTick, submittedQuery, groupId])
|
||||
|
||||
return {
|
||||
searchInput,
|
||||
setSearchInput,
|
||||
submittedQuery,
|
||||
submitSearch,
|
||||
loading,
|
||||
hasSearched,
|
||||
rows,
|
||||
contextSummary,
|
||||
targetProfileSummary,
|
||||
retrievalPhase,
|
||||
error,
|
||||
reset,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
|
||||
/**
|
||||
* Pflege von ai_prompts (OpenRouter-Vorlagen) — nur Superadmin.
|
||||
*/
|
||||
export default function AdminAiPromptsPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [prompts, setPrompts] = useState([])
|
||||
const [catalog, setCatalog] = useState(null)
|
||||
const [selectedId, setSelectedId] = useState(null)
|
||||
const [detail, setDetail] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const [draftName, setDraftName] = useState('')
|
||||
const [draftDesc, setDraftDesc] = useState('')
|
||||
const [draftTemplate, setDraftTemplate] = useState('')
|
||||
const [draftOpenrouterModel, setDraftOpenrouterModel] = useState('')
|
||||
const [draftActive, setDraftActive] = useState(true)
|
||||
|
||||
const [pvTitle, setPvTitle] = useState('Testübung')
|
||||
const [pvGoal, setPvGoal] = useState('<p>Ziel hier</p>')
|
||||
const [pvExec, setPvExec] = useState('<p>Ablauf hier</p>')
|
||||
const [pvHint, setPvHint] = useState('')
|
||||
const [pvFocusId, setPvFocusId] = useState('')
|
||||
const [pvPreview, setPvPreview] = useState(null)
|
||||
|
||||
const loadList = useCallback(async () => {
|
||||
const [pList, cat] = await Promise.all([
|
||||
api.listAdminAiPrompts(),
|
||||
api.getAdminAiPromptPlaceholdersCatalog(),
|
||||
])
|
||||
setPrompts(Array.isArray(pList) ? pList : [])
|
||||
setCatalog(cat || null)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
await loadList()
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin, loadList])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin || !selectedId) {
|
||||
setDetail(null)
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const d = await api.getAdminAiPrompt(selectedId)
|
||||
if (!cancelled) {
|
||||
setDetail(d)
|
||||
setDraftName(d.display_name || '')
|
||||
setDraftDesc(d.description || '')
|
||||
setDraftTemplate(d.template || '')
|
||||
setDraftOpenrouterModel(
|
||||
typeof d.openrouter_model === 'string' ? d.openrouter_model : ''
|
||||
)
|
||||
setDraftActive(!!d.active)
|
||||
setPvPreview(null)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin, selectedId])
|
||||
|
||||
const save = async () => {
|
||||
if (!detail?.id) return
|
||||
setSaving(true)
|
||||
setError('')
|
||||
try {
|
||||
await api.updateAdminAiPrompt(detail.id, {
|
||||
template: draftTemplate,
|
||||
display_name: draftName,
|
||||
description: draftDesc,
|
||||
active: draftActive,
|
||||
openrouter_model: draftOpenrouterModel.trim(),
|
||||
})
|
||||
await loadList()
|
||||
const nd = await api.getAdminAiPrompt(detail.id)
|
||||
setDetail(nd)
|
||||
setPvPreview(null)
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const resetTemplate = async () => {
|
||||
if (!detail?.id || !detail.has_reference_template) return
|
||||
if (!confirm('Template auf gespeicherten Referenztext zurücksetzen?')) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const nd = await api.resetAdminAiPromptTemplate(detail.id)
|
||||
setDetail(nd)
|
||||
setDraftTemplate(nd.template || '')
|
||||
await loadList()
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const runPreview = async () => {
|
||||
if (!detail?.id) return
|
||||
setError('')
|
||||
try {
|
||||
const body = {
|
||||
title: pvTitle,
|
||||
goal: pvGoal,
|
||||
execution: pvExec,
|
||||
focus_hint: pvHint || undefined,
|
||||
}
|
||||
const fid = parseInt(String(pvFocusId).trim(), 10)
|
||||
if (Number.isFinite(fid) && fid >= 1) {
|
||||
body.focus_areas_context = [{ focus_area_id: fid, is_primary: true }]
|
||||
}
|
||||
const r = await api.previewAdminAiPrompt(detail.id, body)
|
||||
setPvPreview(r)
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSuperadmin) return <Navigate to="/" replace />
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 16 }}>
|
||||
<AdminPageNav />
|
||||
<div className="card" style={{ marginTop: 16, padding: 24, textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 1100, margin: '0 auto', padding: '16px', paddingBottom: 96 }}>
|
||||
<AdminPageNav />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
|
||||
<Sparkles size={22} />
|
||||
<h1 style={{ margin: 0, fontSize: '1.25rem' }}>KI Prompts</h1>
|
||||
</div>
|
||||
<p style={{ fontSize: '13px', color: 'var(--text3)', marginTop: 0 }}>
|
||||
Datenbankvorlagen (<code>ai_prompts</code>) für Übungs-KI. Platzhalter im Mustache-Stil werden serverseitig
|
||||
aufgelöst — die Vorschau unten ruft kein externes Modell auf.
|
||||
</p>
|
||||
{error ? <p style={{ color: 'var(--danger)' }}>{error}</p> : null}
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '260px minmax(0,1fr)', gap: 16 }}>
|
||||
<div className="card" style={{ padding: 12 }}>
|
||||
<strong style={{ fontSize: '13px' }}>Prompts</strong>
|
||||
<ul style={{ listStyle: 'none', padding: 0, margin: '12px 0 0 0', maxHeight: '70vh', overflow: 'auto' }}>
|
||||
{(prompts || []).map((p) => (
|
||||
<li key={p.id} style={{ marginBottom: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${selectedId === p.id ? 'btn-primary' : 'btn-secondary'}`}
|
||||
style={{
|
||||
width: '100%',
|
||||
justifyContent: 'flex-start',
|
||||
fontSize: 12,
|
||||
padding: '8px 10px',
|
||||
alignItems: 'flex-start',
|
||||
flexDirection: 'column',
|
||||
textAlign: 'left',
|
||||
}}
|
||||
onClick={() => {
|
||||
setSelectedId(p.id)
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 600 }}>{p.display_name}</span>
|
||||
<span style={{ opacity: 0.85, marginTop: 2 }}>{p.slug}</span>
|
||||
{!p.active ? (
|
||||
<span style={{ color: 'var(--danger)', fontSize: 11 }}>
|
||||
inaktiv
|
||||
</span>
|
||||
) : null}
|
||||
{p.openrouter_model ? (
|
||||
<span style={{ fontSize: 11, color: 'var(--text3)' }} title="OpenRouter-Modell für diesen Prompt">
|
||||
Model: <code>{p.openrouter_model}</code>
|
||||
</span>
|
||||
) : null}
|
||||
{p.is_modified ? <span style={{ fontSize: 11 }}>(von Referenz abweichend)</span> : null}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{!selectedId ? (
|
||||
<p style={{ color: 'var(--text3)' }}>Prompt links wählen.</p>
|
||||
) : (
|
||||
<div className="card" style={{ padding: 16 }}>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
slug: <code>{detail?.slug}</code> · Ausgabe:{' '}
|
||||
<code>{detail?.output_format}</code> · Kategorie: <code>{detail?.category}</code>
|
||||
</div>
|
||||
<div className="form-row" style={{ marginTop: 10 }}>
|
||||
<label className="form-label">Name</label>
|
||||
<input className="form-input" value={draftName} onChange={(e) => setDraftName(e.target.value)} />
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Beschreibung</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
rows={3}
|
||||
value={draftDesc}
|
||||
onChange={(e) => setDraftDesc(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">OpenRouter-Modell (optional)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="Leer = Server-OPENROUTER_MODEL · z.B. anthropic/claude-3.5-haiku"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={draftOpenrouterModel}
|
||||
onChange={(e) => setDraftOpenrouterModel(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<input type="checkbox" checked={draftActive} onChange={(e) => setDraftActive(e.target.checked)} />
|
||||
Aktiv
|
||||
</label>
|
||||
<label className="form-label">Template (Mustache-Zeilen mit {'{{'}}name{'}'}})</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
style={{ fontFamily: 'ui-monospace, monospace', fontSize: 12 }}
|
||||
rows={22}
|
||||
value={draftTemplate}
|
||||
onChange={(e) => setDraftTemplate(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
<button type="button" className="btn btn-primary" disabled={saving} onClick={() => save()}>
|
||||
Speichern
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={saving || !detail?.has_reference_template}
|
||||
title={!detail?.has_reference_template ? 'Nach Migration 069 bzw. manuell default_template gesetzt' : ''}
|
||||
onClick={() => resetTemplate()}
|
||||
>
|
||||
Auf Referenz zurücksetzen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<details style={{ marginTop: 20 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 600 }}>Platzhalter-Katalog (Übung)</summary>
|
||||
{catalog?.placeholders ? (
|
||||
<ul style={{ paddingLeft: 18, marginTop: 8 }}>
|
||||
{catalog.placeholders.map((ph) => (
|
||||
<li key={ph.key} style={{ marginBottom: 10, fontSize: 13 }}>
|
||||
<code>{ph.placeholder}</code> — {ph.description}{' '}
|
||||
<span style={{ color: 'var(--text3)' }}>
|
||||
[{Array.isArray(ph.used_by_slugs) ? ph.used_by_slugs.join(', ') : ''}]
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Wird geladen …</p>
|
||||
)}
|
||||
</details>
|
||||
|
||||
<section style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
|
||||
<h4 style={{ margin: '0 0 12px', fontSize: '15px' }}>Vorschau (ohne OpenRouter)</h4>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Titel</label>
|
||||
<input className="form-input" value={pvTitle} onChange={(e) => setPvTitle(e.target.value)} />
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Fokus-ID (optional, Retrieval‑Raster)</label>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="numerisch"
|
||||
value={pvFocusId}
|
||||
onChange={(e) => setPvFocusId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Fokus-Hinweistext</label>
|
||||
<input className="form-input" value={pvHint} onChange={(e) => setPvHint(e.target.value)} />
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Ziel (HTML möglich)</label>
|
||||
<textarea className="form-input" rows={4} value={pvGoal} onChange={(e) => setPvGoal(e.target.value)} />
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Durchführung (HTML möglich)</label>
|
||||
<textarea className="form-input" rows={4} value={pvExec} onChange={(e) => setPvExec(e.target.value)} />
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => runPreview()}>
|
||||
Platzhalter auflösen
|
||||
</button>
|
||||
{pvPreview?.warning ? (
|
||||
<p style={{ marginTop: 10, color: 'var(--text3)', fontSize: 13 }}>{pvPreview.warning}</p>
|
||||
) : null}
|
||||
{pvPreview?.placeholders_remaining?.length ? (
|
||||
<p style={{ color: 'var(--danger)', fontSize: 13 }}>
|
||||
Unbekannte Platzhalter im Ergebnis:{' '}
|
||||
{pvPreview.placeholders_remaining.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
{pvPreview?.resolved_template != null ? (
|
||||
<pre
|
||||
style={{
|
||||
marginTop: 12,
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
maxHeight: 360,
|
||||
overflow: 'auto',
|
||||
}}
|
||||
>
|
||||
{pvPreview.resolved_template}
|
||||
</pre>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,704 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
|
||||
function formatDt(iso) {
|
||||
if (!iso) return ''
|
||||
try {
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return String(iso)
|
||||
return d.toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })
|
||||
} catch {
|
||||
return String(iso)
|
||||
}
|
||||
}
|
||||
|
||||
/** Bestehende Zusatzfelder aus der DB übernehmen (keine eigene Pflegeoberfläche). */
|
||||
function configExtrasFromRow(cfg) {
|
||||
const c = cfg && typeof cfg === 'object' ? cfg : {}
|
||||
return {
|
||||
keyword_overrides: Array.isArray(c.keyword_overrides) ? c.keyword_overrides : [],
|
||||
main_min_share: c.main_min_share && typeof c.main_min_share === 'object' ? { ...c.main_min_share } : {},
|
||||
}
|
||||
}
|
||||
|
||||
function buildRetrievalDraft(cfg, mainList, subList) {
|
||||
const c = cfg && typeof cfg === 'object' ? cfg : {}
|
||||
const mainW = c.main_slug_weights || {}
|
||||
const catW = c.category_slug_weights || {}
|
||||
const catCap = c.category_max_share || {}
|
||||
|
||||
let mains = (mainList || [])
|
||||
.map((m) => {
|
||||
const slug = String(m.slug || '').trim()
|
||||
if (!slug) return null
|
||||
const w = mainW[slug]
|
||||
return {
|
||||
slug,
|
||||
name: String(m.name || '').trim() || slug,
|
||||
weight: w != null && w !== '' ? String(w) : '1',
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
|
||||
if (mains.length === 0) {
|
||||
mains = ['karate', 'allgemeine'].map((slug) => ({
|
||||
slug,
|
||||
name: slug,
|
||||
weight: mainW[slug] != null && mainW[slug] !== '' ? String(mainW[slug]) : '1',
|
||||
}))
|
||||
}
|
||||
|
||||
const categories = (subList || [])
|
||||
.map((sc) => {
|
||||
const slug = String(sc.slug || '').trim()
|
||||
if (!slug) return null
|
||||
const capNum = catCap[slug]
|
||||
let maxSharePct = ''
|
||||
if (capNum != null && capNum !== '') {
|
||||
const v = Number(capNum)
|
||||
if (Number.isFinite(v) && v > 0 && v <= 1) {
|
||||
maxSharePct = String(Math.round(v * 1000) / 10)
|
||||
} else if (Number.isFinite(v) && v > 1 && v <= 100) {
|
||||
maxSharePct = String(v)
|
||||
}
|
||||
}
|
||||
const w = catW[slug]
|
||||
return {
|
||||
slug,
|
||||
label: [sc.main_category_name, sc.name].filter(Boolean).join(' · ') || sc.name || slug,
|
||||
weight: w != null && w !== '' ? String(w) : '',
|
||||
maxSharePct,
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => a.label.localeCompare(b.label, 'de'))
|
||||
|
||||
return {
|
||||
importanceMultiplier: c.importance_multiplier != null ? String(c.importance_multiplier) : '1',
|
||||
textOverlapBonus: c.text_overlap_bonus != null ? String(c.text_overlap_bonus) : '2',
|
||||
descMaxLen: c.description_plain_max_len != null ? String(c.description_plain_max_len) : '160',
|
||||
karateRelMaxLen: c.karate_relevance_max_len != null ? String(c.karate_relevance_max_len) : '72',
|
||||
mains,
|
||||
categories,
|
||||
}
|
||||
}
|
||||
|
||||
function buildConfigPayload(extras, draft) {
|
||||
const next = {
|
||||
version: 1,
|
||||
importance_multiplier: parseFloat(String(draft.importanceMultiplier).replace(',', '.')) || 1,
|
||||
text_overlap_bonus: parseFloat(String(draft.textOverlapBonus).replace(',', '.')) || 2,
|
||||
description_plain_max_len: Math.max(
|
||||
40,
|
||||
Math.min(400, parseInt(String(draft.descMaxLen), 10) || 160),
|
||||
),
|
||||
karate_relevance_max_len: Math.max(
|
||||
0,
|
||||
Math.min(280, parseInt(String(draft.karateRelMaxLen), 10) || 0),
|
||||
),
|
||||
main_slug_weights: {},
|
||||
category_slug_weights: {},
|
||||
category_max_share: {},
|
||||
keyword_overrides: Array.isArray(extras.keyword_overrides) ? extras.keyword_overrides : [],
|
||||
main_min_share:
|
||||
extras.main_min_share && typeof extras.main_min_share === 'object' ? { ...extras.main_min_share } : {},
|
||||
}
|
||||
|
||||
for (const m of draft.mains || []) {
|
||||
if (!m.slug) continue
|
||||
const w = parseFloat(String(m.weight).replace(',', '.'))
|
||||
if (Number.isFinite(w) && w > 0) next.main_slug_weights[m.slug] = w
|
||||
}
|
||||
for (const slug of ['karate', 'allgemeine']) {
|
||||
if (next.main_slug_weights[slug] == null) next.main_slug_weights[slug] = 1
|
||||
}
|
||||
|
||||
for (const row of draft.categories || []) {
|
||||
if (!row.slug) continue
|
||||
const w = parseFloat(String(row.weight).replace(',', '.'))
|
||||
if (Number.isFinite(w) && w > 0 && w !== 1) next.category_slug_weights[row.slug] = w
|
||||
|
||||
const capRaw = String(row.maxSharePct || '').trim().replace(',', '.')
|
||||
if (capRaw) {
|
||||
const v = parseFloat(capRaw)
|
||||
if (Number.isFinite(v) && v > 0) {
|
||||
const frac = v > 1 ? v / 100 : v
|
||||
if (frac > 0 && frac <= 1) next.category_max_share[row.slug] = frac
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* Pflege von ai_skill_retrieval_profiles — Gewichte pro Haupt- und Unterkategorie ohne JSON-Bearbeitung.
|
||||
* Nur Superadmin (PlatformAdminRoute).
|
||||
*/
|
||||
export default function AdminAiSkillRetrievalPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [profiles, setProfiles] = useState([])
|
||||
const [focusAreas, setFocusAreas] = useState([])
|
||||
const [skillMainCatalog, setSkillMainCatalog] = useState([])
|
||||
const [skillSubCatalog, setSkillSubCatalog] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const [editor, setEditor] = useState(null)
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
const [p, faRaw, mc, sc] = await Promise.all([
|
||||
api.listAiSkillRetrievalProfiles(),
|
||||
api.listFocusAreas(),
|
||||
api.listSkillMainCategories(),
|
||||
api.listSkillCategories({ status: 'active' }),
|
||||
])
|
||||
setProfiles(Array.isArray(p) ? p : [])
|
||||
const fa = Array.isArray(faRaw) ? faRaw : []
|
||||
setFocusAreas(fa.filter((a) => !a.status || String(a.status).toLowerCase() === 'active'))
|
||||
setSkillMainCatalog(Array.isArray(mc) ? mc : [])
|
||||
setSkillSubCatalog(Array.isArray(sc) ? sc : [])
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
await loadAll()
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin, loadAll])
|
||||
|
||||
const openNew = () => {
|
||||
setEditor({
|
||||
mode: 'new',
|
||||
isDefault: false,
|
||||
focusAreaId: '',
|
||||
name: '',
|
||||
description: '',
|
||||
active: true,
|
||||
configExtras: { keyword_overrides: [], main_min_share: {} },
|
||||
retrieval: buildRetrievalDraft({}, skillMainCatalog, skillSubCatalog),
|
||||
})
|
||||
}
|
||||
|
||||
const openEdit = (row) => {
|
||||
const cfg = row.config && typeof row.config === 'object' ? row.config : {}
|
||||
setEditor({
|
||||
mode: 'edit',
|
||||
id: row.id,
|
||||
originalIsDefault: !!row.is_default,
|
||||
isDefault: !!row.is_default,
|
||||
promoteToDefault: false,
|
||||
focusAreaId: row.focus_area_id != null ? String(row.focus_area_id) : '',
|
||||
name: row.name || '',
|
||||
description: row.description || '',
|
||||
active: !!row.active,
|
||||
configExtras: configExtrasFromRow(cfg),
|
||||
retrieval: buildRetrievalDraft(cfg, skillMainCatalog, skillSubCatalog),
|
||||
})
|
||||
}
|
||||
|
||||
const closeEditor = () => setEditor(null)
|
||||
|
||||
const save = async () => {
|
||||
if (!editor) return
|
||||
const cfg = buildConfigPayload(editor.configExtras, editor.retrieval)
|
||||
|
||||
const name = editor.name.trim()
|
||||
if (name.length < 2) {
|
||||
alert('Name mindestens 2 Zeichen.')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (editor.mode === 'new') {
|
||||
const body = {
|
||||
name,
|
||||
description: (editor.description || '').trim(),
|
||||
active: editor.active,
|
||||
is_default: editor.isDefault,
|
||||
config: cfg,
|
||||
}
|
||||
if (!editor.isDefault) {
|
||||
const fid = parseInt(editor.focusAreaId, 10)
|
||||
if (!fid) {
|
||||
alert('Fokusbereich wählen (oder „Standardprofil“ aktivieren).')
|
||||
return
|
||||
}
|
||||
body.focus_area_id = fid
|
||||
}
|
||||
await api.createAiSkillRetrievalProfile(body)
|
||||
} else {
|
||||
const body = {
|
||||
name,
|
||||
description: (editor.description || '').trim(),
|
||||
active: editor.active,
|
||||
config: cfg,
|
||||
}
|
||||
if (editor.originalIsDefault) {
|
||||
await api.updateAiSkillRetrievalProfile(editor.id, body)
|
||||
} else {
|
||||
if (editor.promoteToDefault) {
|
||||
body.is_default = true
|
||||
} else {
|
||||
const fid = parseInt(editor.focusAreaId, 10)
|
||||
if (!fid) {
|
||||
alert('Fokusbereich wählen oder „Als Standardprofil setzen“ aktivieren.')
|
||||
return
|
||||
}
|
||||
body.focus_area_id = fid
|
||||
}
|
||||
await api.updateAiSkillRetrievalProfile(editor.id, body)
|
||||
}
|
||||
}
|
||||
closeEditor()
|
||||
await loadAll()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async (row) => {
|
||||
if (row.is_default) return
|
||||
if (!confirm(`Profil „${row.name}“ wirklich löschen?`)) return
|
||||
try {
|
||||
await api.deleteAiSkillRetrievalProfile(row.id)
|
||||
await loadAll()
|
||||
} catch (e) {
|
||||
alert(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSuperadmin) return <Navigate to="/" replace />
|
||||
|
||||
const retrieval = editor?.retrieval
|
||||
|
||||
return (
|
||||
<div className="app-page">
|
||||
<AdminPageNav />
|
||||
|
||||
<h1 style={{ marginTop: 0 }}>KI Skill-Retrieval-Profile</h1>
|
||||
<p style={{ color: 'var(--text2)', maxWidth: '52rem', lineHeight: 1.55, marginBottom: '1rem' }}>
|
||||
Gewichtungen für den Skill-Katalog bei der <strong>Übungs-KI</strong> (OpenRouter).{' '}
|
||||
<strong>Unterkategorien</strong> (z. B. Kondition, Selbstverteidigung): Multiplikatoren optional;{' '}
|
||||
<strong>max. Anteil</strong> begrenzt den Listenanteil dieser Kategorie (1–100 %). Hauptgruppen
|
||||
(Karate / Allgemein) separat einstellbar — siehe auch{' '}
|
||||
<span style={{ fontSize: '0.88em' }}>.claude/docs/working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md</span>.
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginBottom: '1rem' }}>
|
||||
<button type="button" className="btn btn-primary" onClick={openNew}>
|
||||
Neues Profil
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => loadAll().catch((e) => setError(e.message))}>
|
||||
Aktualisieren
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="card" style={{ padding: '12px 16px', marginBottom: '1rem', borderColor: 'var(--danger)' }}>
|
||||
<strong style={{ color: 'var(--danger)' }}>Fehler</strong>
|
||||
<div style={{ marginTop: '0.35rem', whiteSpace: 'pre-wrap' }}>{error}</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="spinner" style={{ margin: '2rem auto' }} />
|
||||
) : (
|
||||
<div className="card" style={{ padding: 0, overflow: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.92rem' }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
|
||||
<th style={{ padding: '10px 12px' }}>Name</th>
|
||||
<th style={{ padding: '10px 12px' }}>Typ</th>
|
||||
<th style={{ padding: '10px 12px' }}>Fokusbereich</th>
|
||||
<th style={{ padding: '10px 12px' }}>Aktiv</th>
|
||||
<th style={{ padding: '10px 12px' }}>Geändert</th>
|
||||
<th style={{ padding: '10px 12px', width: '1%' }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{profiles.map((row) => (
|
||||
<tr key={row.id} style={{ borderBottom: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '10px 12px', fontWeight: 600 }}>{row.name}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.is_default ? 'Standard' : 'Fokus'}</td>
|
||||
<td style={{ padding: '10px 12px', color: 'var(--text2)' }}>
|
||||
{row.is_default ? '—' : row.focus_area_name || `(ID ${row.focus_area_id})`}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.active ? 'ja' : 'nein'}</td>
|
||||
<td style={{ padding: '10px 12px', color: 'var(--text3)' }}>{formatDt(row.updated_at)}</td>
|
||||
<td style={{ padding: '10px 12px', whiteSpace: 'nowrap' }}>
|
||||
<button type="button" className="btn btn-secondary" style={{ marginRight: 6 }} onClick={() => openEdit(row)}>
|
||||
Bearbeiten
|
||||
</button>
|
||||
{!row.is_default ? (
|
||||
<button type="button" className="btn btn-secondary" onClick={() => remove(row)}>
|
||||
Löschen
|
||||
</button>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{profiles.length === 0 ? (
|
||||
<div style={{ padding: '1.25rem', color: 'var(--text3)' }}>Keine Einträge (oder Tabelle/Migration 068 fehlt).</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editor && retrieval && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1200,
|
||||
padding: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="card"
|
||||
style={{
|
||||
maxWidth: '920px',
|
||||
width: '100%',
|
||||
maxHeight: '92vh',
|
||||
overflow: 'auto',
|
||||
padding: '1.25rem 1.5rem',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ marginTop: 0 }}>{editor.mode === 'new' ? 'Neues Profil' : 'Profil bearbeiten'}</h2>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="arp-name">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
id="arp-name"
|
||||
className="form-input"
|
||||
value={editor.name}
|
||||
onChange={(e) => setEditor((ed) => (ed ? { ...ed, name: e.target.value } : ed))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="arp-desc">
|
||||
Beschreibung
|
||||
</label>
|
||||
<textarea
|
||||
id="arp-desc"
|
||||
className="form-input"
|
||||
rows={3}
|
||||
value={editor.description}
|
||||
onChange={(e) => setEditor((ed) => (ed ? { ...ed, description: e.target.value } : ed))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{editor.mode === 'new' ? (
|
||||
<div className="form-row">
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editor.isDefault}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed ? { ...ed, isDefault: e.target.checked, focusAreaId: e.target.checked ? '' : ed.focusAreaId } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
Standardprofil (ohne Fokusbereich)
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{editor.mode === 'edit' && editor.originalIsDefault ? (
|
||||
<p style={{ color: 'var(--text2)', fontSize: '0.9rem' }}>
|
||||
Standardprofil: Fokusbereich ist immer leer; Deaktivieren ist nicht erlaubt.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{editor.mode === 'edit' && !editor.originalIsDefault ? (
|
||||
<div className="form-row">
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!editor.promoteToDefault}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed ? { ...ed, promoteToDefault: e.target.checked, focusAreaId: e.target.checked ? '' : ed.focusAreaId } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
Als Standardprofil setzen (andere Standard-Markierung wird entfernt)
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!editor.isDefault && editor.mode === 'new' ? (
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="arp-focus">
|
||||
Fokusbereich
|
||||
</label>
|
||||
<select
|
||||
id="arp-focus"
|
||||
className="form-input"
|
||||
value={editor.focusAreaId}
|
||||
onChange={(e) => setEditor((ed) => (ed ? { ...ed, focusAreaId: e.target.value } : ed))}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{focusAreas.map((fa) => (
|
||||
<option key={fa.id} value={String(fa.id)}>
|
||||
{fa.name || `Fokus ${fa.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{editor.mode === 'edit' && !editor.originalIsDefault && !editor.promoteToDefault ? (
|
||||
<div className="form-row">
|
||||
<label className="form-label" htmlFor="arp-focus-e">
|
||||
Fokusbereich
|
||||
</label>
|
||||
<select
|
||||
id="arp-focus-e"
|
||||
className="form-input"
|
||||
value={editor.focusAreaId}
|
||||
onChange={(e) => setEditor((ed) => (ed ? { ...ed, focusAreaId: e.target.value } : ed))}
|
||||
>
|
||||
<option value="">— wählen —</option>
|
||||
{focusAreas.map((fa) => (
|
||||
<option key={fa.id} value={String(fa.id)}>
|
||||
{fa.name || `Fokus ${fa.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="form-row">
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editor.active}
|
||||
disabled={editor.mode === 'edit' && editor.originalIsDefault}
|
||||
onChange={(e) => setEditor((ed) => (ed ? { ...ed, active: e.target.checked } : ed))}
|
||||
/>
|
||||
Aktiv
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '1.25rem 0' }} />
|
||||
|
||||
<h3 style={{ margin: '0 0 0.75rem', fontSize: '1rem' }}>Globale Ranking-Parameter</h3>
|
||||
<div className="form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="arp-imp">
|
||||
importance_multiplier
|
||||
</label>
|
||||
<input
|
||||
id="arp-imp"
|
||||
className="form-input"
|
||||
inputMode="decimal"
|
||||
value={retrieval.importanceMultiplier}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed?.retrieval ? { ...ed, retrieval: { ...ed.retrieval, importanceMultiplier: e.target.value } } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="arp-tob">
|
||||
text_overlap_bonus
|
||||
</label>
|
||||
<input
|
||||
id="arp-tob"
|
||||
className="form-input"
|
||||
inputMode="decimal"
|
||||
value={retrieval.textOverlapBonus}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed?.retrieval ? { ...ed, retrieval: { ...ed.retrieval, textOverlapBonus: e.target.value } } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="arp-dmax">
|
||||
Beschreibung max. Zeichen (je Zeile im Katalog)
|
||||
</label>
|
||||
<input
|
||||
id="arp-dmax"
|
||||
className="form-input"
|
||||
inputMode="numeric"
|
||||
value={retrieval.descMaxLen}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed?.retrieval ? { ...ed, retrieval: { ...ed.retrieval, descMaxLen: e.target.value } } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label" htmlFor="arp-krm">
|
||||
Karate-Relevanz max. Zeichen (0 = weglassen)
|
||||
</label>
|
||||
<input
|
||||
id="arp-krm"
|
||||
className="form-input"
|
||||
inputMode="numeric"
|
||||
value={retrieval.karateRelMaxLen}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) =>
|
||||
ed?.retrieval ? { ...ed, retrieval: { ...ed.retrieval, karateRelMaxLen: e.target.value } } : ed
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 style={{ margin: '1.25rem 0 0.5rem', fontSize: '1rem' }}>Hauptkategorien (Multiplikatoren)</h3>
|
||||
<div className="card" style={{ padding: 0, overflow: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem' }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
|
||||
<th style={{ padding: '8px 10px' }}>Bezeichnung</th>
|
||||
<th style={{ padding: '8px 10px', width: '30%' }}>Multiplikator</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{retrieval.mains.map((m) => (
|
||||
<tr key={m.slug} style={{ borderBottom: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '8px 10px' }}>
|
||||
<div style={{ fontWeight: 600 }}>{m.name}</div>
|
||||
<div style={{ color: 'var(--text3)', fontSize: '0.8rem' }}>{m.slug}</div>
|
||||
</td>
|
||||
<td style={{ padding: '8px 10px' }}>
|
||||
<input
|
||||
className="form-input"
|
||||
inputMode="decimal"
|
||||
value={m.weight}
|
||||
aria-label={`Gewicht ${m.slug}`}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) => {
|
||||
if (!ed?.retrieval) return ed
|
||||
const nm = ed.retrieval.mains.map((row) =>
|
||||
row.slug === m.slug ? { ...row, weight: e.target.value } : row
|
||||
)
|
||||
return { ...ed, retrieval: { ...ed.retrieval, mains: nm } }
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3 style={{ margin: '1.25rem 0 0.5rem', fontSize: '1rem' }}>
|
||||
Unterkategorien (optional: Gewicht · max. Listenanteil)
|
||||
</h3>
|
||||
<p style={{ margin: '0 0 0.5rem', fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.45 }}>
|
||||
Gewicht leer oder 1 = neutral. „Max. Anteil“ in Prozent der Katalogzeilen für diese Unterkategorie
|
||||
(z. B. 25 für 25 %).
|
||||
</p>
|
||||
<div style={{ maxHeight: '280px', overflow: 'auto', border: '1px solid var(--border)', borderRadius: '8px' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}>
|
||||
<thead style={{ position: 'sticky', top: 0, background: 'var(--surface2)', zIndex: 1 }}>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
|
||||
<th style={{ padding: '8px 10px' }}>Unterkategorie</th>
|
||||
<th style={{ padding: '8px 10px', width: '110px' }}>Gewicht</th>
|
||||
<th style={{ padding: '8px 10px', width: '120px' }}>Max. %</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{retrieval.categories.map((c) => (
|
||||
<tr key={c.slug} style={{ borderBottom: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '6px 10px', verticalAlign: 'middle' }}>
|
||||
<span title={c.slug}>{c.label}</span>
|
||||
</td>
|
||||
<td style={{ padding: '6px 8px', verticalAlign: 'middle' }}>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="1"
|
||||
inputMode="decimal"
|
||||
value={c.weight}
|
||||
aria-label={`Gewicht ${c.slug}`}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) => {
|
||||
if (!ed?.retrieval) return ed
|
||||
const nc = ed.retrieval.categories.map((row) =>
|
||||
row.slug === c.slug ? { ...row, weight: e.target.value } : row
|
||||
)
|
||||
return { ...ed, retrieval: { ...ed.retrieval, categories: nc } }
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td style={{ padding: '6px 8px', verticalAlign: 'middle' }}>
|
||||
<input
|
||||
className="form-input"
|
||||
placeholder="—"
|
||||
inputMode="decimal"
|
||||
value={c.maxSharePct}
|
||||
aria-label={`Max. Anteil ${c.slug}`}
|
||||
onChange={(e) =>
|
||||
setEditor((ed) => {
|
||||
if (!ed?.retrieval) return ed
|
||||
const nc = ed.retrieval.categories.map((row) =>
|
||||
row.slug === c.slug ? { ...row, maxSharePct: e.target.value } : row
|
||||
)
|
||||
return { ...ed, retrieval: { ...ed.retrieval, categories: nc } }
|
||||
})
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p style={{ margin: '1rem 0 0', fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.45 }}>
|
||||
Hinweis: <strong>Keyword-Overrides</strong> und etwaige <strong>main_min_share</strong>-Felder aus der Datenbank werden
|
||||
beim Speichern mitgeschrieben ({editor.configExtras?.keyword_overrides?.length || 0} Overrides). Es gibt dafür
|
||||
keine separate Maske.
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1.25rem', flexWrap: 'wrap' }}>
|
||||
<button type="button" className="btn btn-primary" style={{ flex: '1 1 120px' }} onClick={save}>
|
||||
Speichern
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" onClick={closeEditor}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,910 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import api from '../utils/api'
|
||||
import AdminPageNav from '../components/AdminPageNav'
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'draft', label: 'Entwurf' },
|
||||
{ value: 'in_review', label: 'In Prüfung' },
|
||||
{ value: 'approved', label: 'Freigegeben' },
|
||||
{ value: 'archived', label: 'Archiviert' },
|
||||
]
|
||||
|
||||
const VISIBILITY_OPTIONS = [
|
||||
{ value: 'private', label: 'Privat (Standard)' },
|
||||
{ value: 'all', label: 'Alle Sichtbarkeiten' },
|
||||
{ value: 'official', label: 'Offiziell' },
|
||||
{ value: 'club', label: 'Verein' },
|
||||
]
|
||||
|
||||
const MERGE_OPTIONS = [
|
||||
{
|
||||
value: 'replace_all',
|
||||
label: 'Alle Skills ersetzen (empfohlen)',
|
||||
hint: 'Bestehende Zuordnungen werden entfernt. Alle neuen Skills erhalten ai_suggested=true — klar als KI erkennbar.',
|
||||
},
|
||||
{
|
||||
value: 'replace_ai_only',
|
||||
label: 'Nur bisherige KI-Skills ersetzen',
|
||||
hint: 'Manuelle Skills bleiben; nur ai_suggested=true wird neu gesetzt.',
|
||||
},
|
||||
{
|
||||
value: 'additive',
|
||||
label: 'Ergänzen (manuell behalten)',
|
||||
hint: 'Manuelle Skills bleiben unverändert; KI ergänzt neue. Intensität/Level nur bei KI-Skills.',
|
||||
},
|
||||
]
|
||||
|
||||
const INSTRUCTION_LABELS = {
|
||||
goal: 'Ziel',
|
||||
execution: 'Durchführung',
|
||||
preparation: 'Vorbereitung',
|
||||
trainer_notes: 'Trainer-Hinweise',
|
||||
}
|
||||
|
||||
/** Preview: kleine Pakete — Gateway (Fritz!Box o.ä.) timeout oft ~60s bei LLM-Ketten. */
|
||||
const PREVIEW_CHUNK_SIZE = 3
|
||||
const APPLY_CHUNK_SIZE = 25
|
||||
|
||||
function skillLabel(sk) {
|
||||
if (!sk) return '—'
|
||||
const name = sk.skill_name || `Skill #${sk.skill_id}`
|
||||
const inten = sk.intensity ? ` · Int. ${sk.intensity}` : ''
|
||||
const from = sk.required_level || '?'
|
||||
const to = sk.target_level || from
|
||||
const lvl = ` · ${from}→${to}`
|
||||
const ai = sk.ai_suggested ? ' · KI' : ' · manuell'
|
||||
return `${name}${inten}${lvl}${ai}`
|
||||
}
|
||||
|
||||
function buildFilterParams(filters) {
|
||||
const params = { status: filters.status, visibility: filters.visibility || 'private' }
|
||||
if (filters.focusAreaId) params.focus_area_id = Number(filters.focusAreaId)
|
||||
if (filters.withoutSkills) params.without_skills = true
|
||||
if (filters.withAiSuggested) params.with_ai_suggested_skills = true
|
||||
if (filters.search.trim()) params.search = filters.search.trim()
|
||||
return params
|
||||
}
|
||||
|
||||
function DiffBlock({ diff }) {
|
||||
if (!diff) return null
|
||||
const hasAny =
|
||||
(diff.added?.length || 0) + (diff.changed?.length || 0) + (diff.removed?.length || 0) > 0
|
||||
if (!hasAny) {
|
||||
return (
|
||||
<p className="text-muted" style={{ margin: '8px 0 0', fontSize: '0.9rem' }}>
|
||||
Keine Skill-Änderungen.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div style={{ fontSize: '0.88rem', marginTop: 8 }}>
|
||||
{diff.added?.length > 0 && (
|
||||
<div>
|
||||
<strong style={{ color: 'var(--accent)' }}>Neu:</strong>{' '}
|
||||
{diff.added.map((s) => skillLabel(s)).join('; ')}
|
||||
</div>
|
||||
)}
|
||||
{diff.changed?.length > 0 && (
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<strong>Geändert:</strong>{' '}
|
||||
{diff.changed.map((c) => (
|
||||
<span key={c.skill_id}>
|
||||
{c.skill_name}: {skillLabel(c.before)} → {skillLabel(c.after)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{diff.removed?.length > 0 && (
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<strong style={{ color: 'var(--danger)' }}>Entfernt:</strong>{' '}
|
||||
{diff.removed.map((s) => skillLabel(s)).join('; ')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RunDialog({
|
||||
open,
|
||||
onClose,
|
||||
exerciseCount,
|
||||
analysis,
|
||||
modes,
|
||||
setModes,
|
||||
mergeMode,
|
||||
setMergeMode,
|
||||
setStatusAfterApply,
|
||||
statusAfterApply,
|
||||
costConfirmed,
|
||||
setCostConfirmed,
|
||||
onStartPreview,
|
||||
jobRunning,
|
||||
}) {
|
||||
if (!open) return null
|
||||
|
||||
const est = analysis?.estimated_llm_calls
|
||||
const totalCalls = est?.total ?? 0
|
||||
const mergeHint = MERGE_OPTIONS.find((o) => o.value === mergeMode)?.hint || ''
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal-overlay"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="enrichment-run-title"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget && !jobRunning) onClose()
|
||||
}}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
background: 'rgba(0,0,0,0.45)',
|
||||
zIndex: 1000,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
padding: 16,
|
||||
}}
|
||||
>
|
||||
<div className="card" style={{ maxWidth: 520, width: '100%', padding: 20, maxHeight: '90vh', overflow: 'auto' }}>
|
||||
<h2 id="enrichment-run-title" style={{ margin: '0 0 12px', fontSize: '1.15rem' }}>
|
||||
Batch-Anreicherung konfigurieren
|
||||
</h2>
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
fontSize: '0.92rem',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>{exerciseCount}</strong> Übung(en) ausgewählt
|
||||
</div>
|
||||
{est && (
|
||||
<div style={{ marginTop: 8, color: 'var(--text2)' }}>
|
||||
Geschätzte LLM-Aufrufe: <strong>{totalCalls}</strong>
|
||||
{modes.skills && est.skills > 0 && (
|
||||
<span> · Skills: {est.skills}</span>
|
||||
)}
|
||||
{modes.summary && est.summary > 0 && (
|
||||
<span> · Kurzfassung: {est.summary}</span>
|
||||
)}
|
||||
{modes.instructions && est.instructions > 0 && (
|
||||
<span> · Anleitung: {est.instructions}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{exerciseCount >= 10 && (
|
||||
<p style={{ margin: '10px 0 0', color: 'var(--text2)', fontSize: '0.88rem' }}>
|
||||
Die Vorschau läuft in Paketen à 3 Übungen (Gateway-Timeout vermeiden). Fenster offen lassen —
|
||||
bei {exerciseCount} Übungen ca. {Math.ceil(exerciseCount / 3)} Pakete.
|
||||
</p>
|
||||
)}
|
||||
{exerciseCount >= 25 && (
|
||||
<p style={{ margin: '6px 0 0', color: 'var(--danger)', fontSize: '0.88rem' }}>
|
||||
Großer Batch — OpenRouter-Kosten und Gesamtlaufzeit (mehrere Minuten) beachten.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<fieldset style={{ border: 'none', padding: 0, margin: '0 0 16px' }}>
|
||||
<legend style={{ fontWeight: 600, marginBottom: 8 }}>Inhalte per KI</legend>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<label style={{ display: 'flex', gap: 8, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={modes.skills}
|
||||
onChange={(e) => setModes((m) => ({ ...m, skills: e.target.checked }))}
|
||||
/>
|
||||
Fähigkeiten (inkl. Intensität & Levelbereich)
|
||||
</label>
|
||||
<label style={{ display: 'flex', gap: 8, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={modes.summary}
|
||||
onChange={(e) => setModes((m) => ({ ...m, summary: e.target.checked }))}
|
||||
/>
|
||||
Kurzfassung (Summary)
|
||||
</label>
|
||||
<label style={{ display: 'flex', gap: 8, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={modes.instructions}
|
||||
onChange={(e) => setModes((m) => ({ ...m, instructions: e.target.checked }))}
|
||||
/>
|
||||
Anleitung (Ziel, Durchführung, Vorbereitung, Trainer-Hinweise)
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{modes.skills && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label className="form-label">
|
||||
Skill-Merge-Modus
|
||||
<select className="form-input" value={mergeMode} onChange={(e) => setMergeMode(e.target.value)}>
|
||||
{MERGE_OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{mergeHint && (
|
||||
<p style={{ margin: '6px 0 0', fontSize: '0.85rem', color: 'var(--text2)' }}>{mergeHint}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<label className="form-label" style={{ marginBottom: 16 }}>
|
||||
Nach erfolgreichem Apply Status
|
||||
<select
|
||||
className="form-input"
|
||||
value={statusAfterApply}
|
||||
onChange={(e) => setStatusAfterApply(e.target.value)}
|
||||
>
|
||||
<option value="in_review">In Prüfung</option>
|
||||
<option value="draft">Entwurf (unverändert)</option>
|
||||
<option value="">Status nicht ändern</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: 16,
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={costConfirmed}
|
||||
onChange={(e) => setCostConfirmed(e.target.checked)}
|
||||
style={{ marginTop: 3 }}
|
||||
/>
|
||||
<span>
|
||||
Ich bestätige <strong>{exerciseCount}</strong> Übung(en) und ca.{' '}
|
||||
<strong>{totalCalls}</strong> LLM-Aufruf(e) — mir sind die Kosten bewusst.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={jobRunning} onClick={onClose}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={
|
||||
jobRunning ||
|
||||
!costConfirmed ||
|
||||
exerciseCount === 0 ||
|
||||
(!modes.skills && !modes.summary && !modes.instructions)
|
||||
}
|
||||
onClick={onStartPreview}
|
||||
>
|
||||
Vorschau starten
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Superadmin: Batch-Anreicherung von Übungen per KI.
|
||||
*/
|
||||
export default function AdminExerciseEnrichmentPage() {
|
||||
const { user } = useAuth()
|
||||
const isSuperadmin = user?.role === 'superadmin'
|
||||
|
||||
const [filters, setFilters] = useState({
|
||||
status: 'draft',
|
||||
visibility: 'private',
|
||||
focusAreaId: '',
|
||||
withoutSkills: true,
|
||||
withAiSuggested: false,
|
||||
search: '',
|
||||
})
|
||||
const [focusAreas, setFocusAreas] = useState([])
|
||||
const [items, setItems] = useState([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const limit = 25
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [selected, setSelected] = useState(() => new Set())
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [analysis, setAnalysis] = useState(null)
|
||||
const [modes, setModes] = useState({ skills: true, summary: false, instructions: false })
|
||||
const [mergeMode, setMergeMode] = useState('replace_all')
|
||||
const [setStatusAfterApply, setSetStatusAfterApply] = useState('in_review')
|
||||
const [costConfirmed, setCostConfirmed] = useState(false)
|
||||
|
||||
const [previewRows, setPreviewRows] = useState([])
|
||||
const [previewErrors, setPreviewErrors] = useState([])
|
||||
const [previewMeta, setPreviewMeta] = useState(null)
|
||||
const [showPreview, setShowPreview] = useState(false)
|
||||
|
||||
const [jobRunning, setJobRunning] = useState(false)
|
||||
const [jobProgress, setJobProgress] = useState({ done: 0, total: 0, phase: '' })
|
||||
const abortRef = useRef(false)
|
||||
|
||||
const selectedIds = useMemo(() => Array.from(selected), [selected])
|
||||
const filterParams = useMemo(() => buildFilterParams(filters), [filters])
|
||||
|
||||
const loadCandidates = useCallback(async () => {
|
||||
const data = await api.listExerciseEnrichmentCandidates({ ...filterParams, limit, offset })
|
||||
setItems(Array.isArray(data.items) ? data.items : [])
|
||||
setTotal(Number(data.total) || 0)
|
||||
}, [filterParams, offset])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuperadmin) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const faRaw = await api.listFocusAreas()
|
||||
if (!cancelled) {
|
||||
const fa = Array.isArray(faRaw) ? faRaw : []
|
||||
setFocusAreas(fa.filter((a) => !a.status || String(a.status).toLowerCase() === 'active'))
|
||||
}
|
||||
await loadCandidates()
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isSuperadmin, loadCandidates])
|
||||
|
||||
useEffect(() => {
|
||||
if (!dialogOpen || selectedIds.length === 0) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const data = await api.analyzeExerciseEnrichment({
|
||||
exercise_ids: selectedIds,
|
||||
modes,
|
||||
})
|
||||
if (!cancelled) {
|
||||
setAnalysis(data)
|
||||
setCostConfirmed(false)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(e.message || String(e))
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [dialogOpen, modes, selectedIds])
|
||||
|
||||
if (!isSuperadmin) return <Navigate to="/" replace />
|
||||
|
||||
const pageIds = items.map((r) => r.id)
|
||||
const allPageSelected = pageIds.length > 0 && pageIds.every((id) => selected.has(id))
|
||||
|
||||
function toggleRow(id) {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function togglePageAll() {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (allPageSelected) pageIds.forEach((id) => next.delete(id))
|
||||
else pageIds.forEach((id) => next.add(id))
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
async function selectAllMatchingFilter() {
|
||||
setError('')
|
||||
try {
|
||||
const data = await api.listExerciseEnrichmentCandidateIds(filterParams)
|
||||
const ids = Array.isArray(data.ids) ? data.ids : []
|
||||
setSelected(new Set(ids))
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function openRunDialog() {
|
||||
if (selectedIds.length === 0) {
|
||||
setError('Bitte mindestens eine Übung auswählen.')
|
||||
return
|
||||
}
|
||||
setError('')
|
||||
setCostConfirmed(false)
|
||||
setModes({ skills: true, summary: false, instructions: false })
|
||||
setMergeMode('replace_all')
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
async function previewChunkWithRetry(chunk, attempt = 0) {
|
||||
try {
|
||||
return await api.previewExerciseEnrichment({
|
||||
exercise_ids: chunk,
|
||||
modes,
|
||||
merge_mode: mergeMode,
|
||||
})
|
||||
} catch (e) {
|
||||
const msg = e.message || String(e)
|
||||
const isTimeout = /504|502|timeout/i.test(msg)
|
||||
if (isTimeout && attempt < 2) {
|
||||
await new Promise((r) => setTimeout(r, 2500))
|
||||
return previewChunkWithRetry(chunk, attempt + 1)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
async function runPreviewFromDialog() {
|
||||
setDialogOpen(false)
|
||||
setError('')
|
||||
setJobRunning(true)
|
||||
abortRef.current = false
|
||||
const allResults = []
|
||||
const allErrors = []
|
||||
let estTotal = 0
|
||||
const totalChunks = Math.ceil(selectedIds.length / PREVIEW_CHUNK_SIZE)
|
||||
|
||||
setJobProgress({ done: 0, total: selectedIds.length, phase: 'Vorschau' })
|
||||
|
||||
try {
|
||||
for (let i = 0; i < selectedIds.length; i += PREVIEW_CHUNK_SIZE) {
|
||||
if (abortRef.current) break
|
||||
const chunk = selectedIds.slice(i, i + PREVIEW_CHUNK_SIZE)
|
||||
const chunkNo = Math.floor(i / PREVIEW_CHUNK_SIZE) + 1
|
||||
setJobProgress({
|
||||
done: i,
|
||||
total: selectedIds.length,
|
||||
phase: `Vorschau Paket ${chunkNo}/${totalChunks}`,
|
||||
})
|
||||
const resp = await previewChunkWithRetry(chunk)
|
||||
allResults.push(...(resp.results || []))
|
||||
allErrors.push(...(resp.errors || []))
|
||||
const est = resp.estimated_llm_calls
|
||||
estTotal += typeof est === 'object' ? est.total || 0 : est || 0
|
||||
setJobProgress({
|
||||
done: Math.min(i + chunk.length, selectedIds.length),
|
||||
total: selectedIds.length,
|
||||
phase: `Vorschau Paket ${chunkNo}/${totalChunks}`,
|
||||
})
|
||||
}
|
||||
setPreviewRows(allResults)
|
||||
setPreviewErrors(allErrors)
|
||||
setPreviewMeta({
|
||||
estimated_llm_calls: estTotal,
|
||||
merge_mode: mergeMode,
|
||||
modes: { ...modes },
|
||||
})
|
||||
setShowPreview(true)
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setJobRunning(false)
|
||||
setJobProgress({ done: 0, total: 0, phase: '' })
|
||||
}
|
||||
}
|
||||
|
||||
function cancelJob() {
|
||||
abortRef.current = true
|
||||
}
|
||||
|
||||
async function runApply() {
|
||||
const applyItems = previewRows
|
||||
.filter((r) => r.ok)
|
||||
.map((r) => ({
|
||||
exercise_id: r.exercise_id,
|
||||
merged_skills: r.merged_skills || [],
|
||||
summary: r.suggested_summary || null,
|
||||
instruction_fields: r.suggested_instructions || null,
|
||||
}))
|
||||
if (applyItems.length === 0) {
|
||||
setError('Keine anwendbaren Vorschau-Ergebnisse.')
|
||||
return
|
||||
}
|
||||
|
||||
const statusLabel =
|
||||
setStatusAfterApply === 'in_review'
|
||||
? 'In Prüfung'
|
||||
: setStatusAfterApply || 'unverändert'
|
||||
if (
|
||||
!window.confirm(
|
||||
`${applyItems.length} Übung(en) speichern und Status „${statusLabel}“ setzen?`,
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
setError('')
|
||||
setJobRunning(true)
|
||||
abortRef.current = false
|
||||
const appliedAll = []
|
||||
const failedAll = []
|
||||
|
||||
setJobProgress({ done: 0, total: applyItems.length, phase: 'Anwenden' })
|
||||
|
||||
try {
|
||||
for (let i = 0; i < applyItems.length; i += APPLY_CHUNK_SIZE) {
|
||||
if (abortRef.current) break
|
||||
const chunk = applyItems.slice(i, i + APPLY_CHUNK_SIZE)
|
||||
const resp = await api.applyExerciseEnrichment({
|
||||
items: chunk,
|
||||
modes: previewMeta?.modes || modes,
|
||||
merge_mode: mergeMode,
|
||||
set_status: setStatusAfterApply || null,
|
||||
})
|
||||
appliedAll.push(...(resp.applied || []))
|
||||
failedAll.push(...(resp.failed || []))
|
||||
setJobProgress({
|
||||
done: Math.min(i + chunk.length, applyItems.length),
|
||||
total: applyItems.length,
|
||||
phase: 'Anwenden',
|
||||
})
|
||||
}
|
||||
setPreviewRows([])
|
||||
setShowPreview(false)
|
||||
setSelected(new Set())
|
||||
await loadCandidates()
|
||||
const msg = `${appliedAll.length} OK, ${failedAll.length} Fehler`
|
||||
if (failedAll.length) setError(msg)
|
||||
else setError('')
|
||||
window.alert(msg)
|
||||
} catch (e) {
|
||||
setError(e.message || String(e))
|
||||
} finally {
|
||||
setJobRunning(false)
|
||||
setJobProgress({ done: 0, total: 0, phase: '' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page" style={{ paddingBottom: 80 }}>
|
||||
<AdminPageNav />
|
||||
<header style={{ marginBottom: 16 }}>
|
||||
<h1 style={{ margin: '0 0 4px', fontSize: '1.35rem' }}>Übungs-Anreicherung (KI)</h1>
|
||||
<p style={{ margin: 0, color: 'var(--text2)', fontSize: '0.95rem' }}>
|
||||
Batchweise Anreicherung nach Status — Vorschau ohne Speichern, danach kontrolliert in Prüfung
|
||||
überführen. Für große Bestände (300+) alle passenden Übungen auswählen und Kosten bestätigen.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{error && (
|
||||
<div className="card" style={{ borderColor: 'var(--danger)', marginBottom: 12, padding: 12 }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card" style={{ marginBottom: 16, padding: 16 }}>
|
||||
<div className="form-row" style={{ flexWrap: 'wrap', gap: 12 }}>
|
||||
<label className="form-label" style={{ minWidth: 120 }}>
|
||||
Status
|
||||
<select
|
||||
className="form-input"
|
||||
value={filters.status}
|
||||
onChange={(e) => {
|
||||
setOffset(0)
|
||||
setFilters((f) => ({ ...f, status: e.target.value }))
|
||||
}}
|
||||
>
|
||||
{STATUS_OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="form-label" style={{ minWidth: 160 }}>
|
||||
Sichtbarkeit
|
||||
<select
|
||||
className="form-input"
|
||||
value={filters.visibility}
|
||||
onChange={(e) => {
|
||||
setOffset(0)
|
||||
setFilters((f) => ({ ...f, visibility: e.target.value }))
|
||||
}}
|
||||
>
|
||||
{VISIBILITY_OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="form-label" style={{ minWidth: 140 }}>
|
||||
Fokusbereich
|
||||
<select
|
||||
className="form-input"
|
||||
value={filters.focusAreaId}
|
||||
onChange={(e) => {
|
||||
setOffset(0)
|
||||
setFilters((f) => ({ ...f, focusAreaId: e.target.value }))
|
||||
}}
|
||||
>
|
||||
<option value="">—</option>
|
||||
{focusAreas.map((fa) => (
|
||||
<option key={fa.id} value={fa.id}>
|
||||
{fa.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="form-label" style={{ flex: '1 1 180px' }}>
|
||||
Suche
|
||||
<input
|
||||
className="form-input"
|
||||
value={filters.search}
|
||||
placeholder="Titel, Stichworte…"
|
||||
onChange={(e) => setFilters((f) => ({ ...f, search: e.target.value }))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
setOffset(0)
|
||||
loadCandidates().catch((err) => setError(err.message))
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, marginTop: 12, alignItems: 'center' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filters.withoutSkills}
|
||||
onChange={(e) => {
|
||||
setOffset(0)
|
||||
setFilters((f) => ({ ...f, withoutSkills: e.target.checked }))
|
||||
}}
|
||||
/>
|
||||
Ohne Skills
|
||||
</label>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filters.withAiSuggested}
|
||||
onChange={(e) => {
|
||||
setOffset(0)
|
||||
setFilters((f) => ({ ...f, withAiSuggested: e.target.checked }))
|
||||
}}
|
||||
/>
|
||||
Mit KI-Skills
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => {
|
||||
setOffset(0)
|
||||
loadCandidates().catch((err) => setError(err.message))
|
||||
}}
|
||||
>
|
||||
Filtern
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ marginBottom: 16, padding: 16 }}>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={jobRunning || total === 0}
|
||||
onClick={selectAllMatchingFilter}
|
||||
>
|
||||
Alle {total} aus Filter auswählen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={jobRunning || selectedIds.length === 0}
|
||||
onClick={openRunDialog}
|
||||
>
|
||||
Anreicherung konfigurieren ({selectedIds.length})
|
||||
</button>
|
||||
{showPreview && previewRows.length > 0 && (
|
||||
<button type="button" className="btn btn-primary" disabled={jobRunning} onClick={runApply}>
|
||||
Anwenden & Status setzen
|
||||
</button>
|
||||
)}
|
||||
{jobRunning && (
|
||||
<button type="button" className="btn btn-secondary" onClick={cancelJob}>
|
||||
Abbrechen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{jobRunning && jobProgress.total > 0 && (
|
||||
<p style={{ margin: '10px 0 0', fontSize: '0.9rem' }}>
|
||||
{jobProgress.phase}: {jobProgress.done}/{jobProgress.total}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RunDialog
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
exerciseCount={selectedIds.length}
|
||||
analysis={analysis}
|
||||
modes={modes}
|
||||
setModes={setModes}
|
||||
mergeMode={mergeMode}
|
||||
setMergeMode={setMergeMode}
|
||||
setStatusAfterApply={setStatusAfterApply}
|
||||
statusAfterApply={setStatusAfterApply}
|
||||
costConfirmed={costConfirmed}
|
||||
setCostConfirmed={setCostConfirmed}
|
||||
onStartPreview={runPreviewFromDialog}
|
||||
jobRunning={jobRunning}
|
||||
/>
|
||||
|
||||
{showPreview && (
|
||||
<div className="card" style={{ marginBottom: 16, padding: 16 }}>
|
||||
<h2 style={{ margin: '0 0 12px', fontSize: '1.1rem' }}>Vorschau</h2>
|
||||
{previewMeta && (
|
||||
<p style={{ margin: '0 0 12px', color: 'var(--text2)', fontSize: '0.9rem' }}>
|
||||
{previewRows.length} OK · {previewErrors.length} Fehler/übersprungen · ca.{' '}
|
||||
{previewMeta.estimated_llm_calls} LLM-Call(s)
|
||||
</p>
|
||||
)}
|
||||
{previewRows.map((row) => (
|
||||
<div
|
||||
key={row.exercise_id}
|
||||
style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 12 }}
|
||||
>
|
||||
<strong>{row.title || `#${row.exercise_id}`}</strong>
|
||||
<span style={{ color: 'var(--text2)', marginLeft: 8, fontSize: '0.85rem' }}>
|
||||
{row.status} · {row.visibility} · {row.primary_focus_name || '—'}
|
||||
</span>
|
||||
{(previewMeta?.modes?.skills || modes.skills) && (
|
||||
<div style={{ marginTop: 6, fontSize: '0.88rem' }}>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Vorhanden:</span>{' '}
|
||||
{(row.existing_skills || []).map((s) => skillLabel(s)).join('; ') || '—'}
|
||||
</div>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<span style={{ color: 'var(--text2)' }}>Vorgeschlagen:</span>{' '}
|
||||
{(row.suggested_skills || []).map((s) => skillLabel(s)).join('; ') || '—'}
|
||||
</div>
|
||||
<DiffBlock diff={row.diff} />
|
||||
</div>
|
||||
)}
|
||||
{(previewMeta?.modes?.summary || modes.summary) && row.suggested_summary && (
|
||||
<div style={{ marginTop: 8, fontSize: '0.88rem' }}>
|
||||
<span style={{ color: 'var(--text2)' }}>Kurzfassung:</span>{' '}
|
||||
{row.existing_summary ? `"${row.existing_summary}" → ` : ''}
|
||||
"{row.suggested_summary}"
|
||||
</div>
|
||||
)}
|
||||
{(previewMeta?.modes?.instructions || modes.instructions) &&
|
||||
row.suggested_instructions &&
|
||||
Object.keys(row.suggested_instructions).length > 0 && (
|
||||
<div style={{ marginTop: 8, fontSize: '0.88rem' }}>
|
||||
<span style={{ color: 'var(--text2)' }}>Anleitung geändert:</span>{' '}
|
||||
{Object.keys(row.suggested_instructions)
|
||||
.map((k) => INSTRUCTION_LABELS[k] || k)
|
||||
.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{previewErrors.map((err) => (
|
||||
<div
|
||||
key={`err-${err.exercise_id}`}
|
||||
style={{ color: 'var(--danger)', marginTop: 8, fontSize: '0.88rem' }}
|
||||
>
|
||||
#{err.exercise_id}: {err.error || 'Fehler'}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card" style={{ padding: 0, overflow: 'hidden' }}>
|
||||
{loading ? (
|
||||
<p style={{ padding: 16 }}>Lade…</p>
|
||||
) : (
|
||||
<>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.92rem' }}>
|
||||
<thead>
|
||||
<tr style={{ background: 'var(--surface2)', textAlign: 'left' }}>
|
||||
<th style={{ padding: '10px 12px', width: 40 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allPageSelected}
|
||||
onChange={togglePageAll}
|
||||
aria-label="Alle auf Seite"
|
||||
/>
|
||||
</th>
|
||||
<th style={{ padding: '10px 12px' }}>Titel</th>
|
||||
<th style={{ padding: '10px 12px' }}>Status</th>
|
||||
<th style={{ padding: '10px 12px' }}>Sichtbarkeit</th>
|
||||
<th style={{ padding: '10px 12px' }}>Fokus</th>
|
||||
<th style={{ padding: '10px 12px' }}>Skills</th>
|
||||
<th style={{ padding: '10px 12px' }}>KI-Skills</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} style={{ padding: 16, color: 'var(--text2)' }}>
|
||||
Keine Kandidaten für die Filter.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
items.map((row) => (
|
||||
<tr key={row.id} style={{ borderTop: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.has(row.id)}
|
||||
onChange={() => toggleRow(row.id)}
|
||||
aria-label={`Auswahl ${row.title}`}
|
||||
/>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.title}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.status}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.visibility}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.primary_focus_name || '—'}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.skill_count ?? 0}</td>
|
||||
<td style={{ padding: '10px 12px' }}>{row.ai_suggested_skill_count ?? 0}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: '12px 16px',
|
||||
borderTop: '1px solid var(--border)',
|
||||
}}
|
||||
>
|
||||
<span style={{ color: 'var(--text2)', fontSize: '0.88rem' }}>
|
||||
{total} gesamt · {selectedIds.length} ausgewählt
|
||||
</span>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={offset <= 0}
|
||||
onClick={() => setOffset((o) => Math.max(0, o - limit))}
|
||||
>
|
||||
Zurück
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={offset + limit >= total}
|
||||
onClick={() => setOffset((o) => o + limit)}
|
||||
>
|
||||
Weiter
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -238,6 +238,101 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
const [targetGroupsCatalog, setTargetGroupsCatalog] = useState([])
|
||||
const [sectionPickerCtx, setSectionPickerCtx] = useState(null)
|
||||
const [peekCtx, setPeekCtx] = useState(null)
|
||||
|
||||
const frameworkPlanningContext = useMemo(() => {
|
||||
if (!sectionPickerCtx) return null
|
||||
const { slotIdx, sectionIndex: sIdx, itemIndex: iIdx, insertBeforeIndex: beforeIx } = sectionPickerCtx
|
||||
const slot = form.slots?.[slotIdx]
|
||||
const secs = slot?.sections?.length ? slot.sections : [defaultSection('Ablauf')]
|
||||
const sec = secs[sIdx]
|
||||
let anchorExerciseId = null
|
||||
if (sec?.items?.length) {
|
||||
if (typeof iIdx === 'number') {
|
||||
const item = sec.items[iIdx]
|
||||
if (item?.exercise_id) {
|
||||
anchorExerciseId = Number(item.exercise_id)
|
||||
} else {
|
||||
for (let i = iIdx - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
anchorExerciseId = Number(sec.items[i].exercise_id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (typeof beforeIx === 'number') {
|
||||
for (let i = beforeIx - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
anchorExerciseId = Number(sec.items[i].exercise_id)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (let i = sec.items.length - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
anchorExerciseId = Number(sec.items[i].exercise_id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const plannedExerciseIds = []
|
||||
const seenPlan = new Set()
|
||||
for (const s of secs) {
|
||||
for (const it of s?.items || []) {
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
const eid = Number(it?.exercise_id)
|
||||
if (!Number.isFinite(eid) || eid < 1 || seenPlan.has(eid)) continue
|
||||
seenPlan.add(eid)
|
||||
plannedExerciseIds.push(eid)
|
||||
}
|
||||
}
|
||||
const sectionPlannedExerciseIds = []
|
||||
const seenSec = new Set()
|
||||
for (const it of sec?.items || []) {
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
const eid = Number(it?.exercise_id)
|
||||
if (!Number.isFinite(eid) || eid < 1 || seenSec.has(eid)) continue
|
||||
seenSec.add(eid)
|
||||
sectionPlannedExerciseIds.push(eid)
|
||||
}
|
||||
let lastExerciseTitle = null
|
||||
if (sec?.items?.length) {
|
||||
for (let i = sec.items.length - 1; i >= 0; i -= 1) {
|
||||
const it = sec.items[i]
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
if (it?.exercise_id) {
|
||||
lastExerciseTitle = (it.exercise_title || '').trim() || null
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
unitId: null,
|
||||
groupId: null,
|
||||
sectionOrderIndex: sIdx,
|
||||
sectionTitle: (sec?.title || '').trim() || null,
|
||||
sectionGuidanceNotes: (sec?.guidance_notes || '').trim() || null,
|
||||
sectionPlannedExerciseIds,
|
||||
sectionExerciseCount: sectionPlannedExerciseIds.length,
|
||||
lastExerciseTitle,
|
||||
anchorExerciseId: Number.isFinite(anchorExerciseId) && anchorExerciseId > 0 ? anchorExerciseId : null,
|
||||
progressionGraphId: null,
|
||||
plannedExerciseIds,
|
||||
}
|
||||
}, [sectionPickerCtx, form.slots])
|
||||
|
||||
const openFrameworkExercisePicker = useCallback((slotIdx, ctx, pickerMode = 'library') => {
|
||||
setSectionPickerCtx({
|
||||
slotIdx,
|
||||
sectionIndex: ctx.sectionIndex,
|
||||
itemIndex: typeof ctx.itemIndex === 'number' ? ctx.itemIndex : undefined,
|
||||
insertBeforeIndex:
|
||||
typeof ctx.insertBeforeIndex === 'number' && Number.isFinite(ctx.insertBeforeIndex)
|
||||
? ctx.insertBeforeIndex
|
||||
: undefined,
|
||||
pickerMode,
|
||||
})
|
||||
}, [])
|
||||
const [editingGoalIdx, setEditingGoalIdx] = useState(null)
|
||||
const [goalMenuGi, setGoalMenuGi] = useState(null)
|
||||
/** Nur schmal: Stammdaten | Plan (Ziele übereinander, darunter Slots) — Desktop: alles sichtbar */
|
||||
@@ -911,17 +1006,8 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
),
|
||||
}))
|
||||
}}
|
||||
onRequestExercisePick={({ sectionIndex, itemIndex, insertBeforeIndex }) =>
|
||||
setSectionPickerCtx({
|
||||
slotIdx: si,
|
||||
sectionIndex,
|
||||
itemIndex: typeof itemIndex === 'number' ? itemIndex : undefined,
|
||||
insertBeforeIndex:
|
||||
typeof insertBeforeIndex === 'number' && Number.isFinite(insertBeforeIndex)
|
||||
? insertBeforeIndex
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
onRequestExercisePick={(ctx) => openFrameworkExercisePicker(si, ctx, 'library')}
|
||||
onRequestPlanningExercisePick={(ctx) => openFrameworkExercisePicker(si, ctx, 'planning')}
|
||||
onPeekExercise={(id, variantId) =>
|
||||
setPeekCtx({ exerciseId: id, variantId: variantId ?? null })
|
||||
}
|
||||
@@ -1366,6 +1452,9 @@ export default function TrainingFrameworkProgramEditPage() {
|
||||
open={sectionPickerCtx != null}
|
||||
multiSelect
|
||||
enableQuickCreateDraft
|
||||
pickerMode={sectionPickerCtx?.pickerMode === 'planning' ? 'planning' : 'library'}
|
||||
enableFreePlanningSearch
|
||||
planningContext={frameworkPlanningContext}
|
||||
onClose={() => setSectionPickerCtx(null)}
|
||||
onSelectExercises={async (picked) => {
|
||||
if (!sectionPickerCtx || !picked?.length) return
|
||||
|
||||
@@ -123,6 +123,115 @@ export default function TrainingUnitEditPage() {
|
||||
const [publishFrameworkOpen, setPublishFrameworkOpen] = useState(false)
|
||||
const [saveModuleOpen, setSaveModuleOpen] = useState(false)
|
||||
|
||||
const exercisePickerPlanningContext = useMemo(() => {
|
||||
if (!exercisePickerTarget) return null
|
||||
const resolvedUnitId =
|
||||
editingUnit?.id ?? (Number.isFinite(unitId) && unitId > 0 ? unitId : null)
|
||||
const target = exercisePickerTarget
|
||||
const secs = formData.sections || []
|
||||
const sIdx = target?.sIdx ?? 0
|
||||
const sec = secs[sIdx]
|
||||
let anchorExerciseId = null
|
||||
let anchorExerciseVariantId = null
|
||||
const pickAnchorFromItem = (item) => {
|
||||
if (!item?.exercise_id) return
|
||||
anchorExerciseId = Number(item.exercise_id)
|
||||
const rawVar = item.exercise_variant_id
|
||||
const vid = Number(rawVar)
|
||||
anchorExerciseVariantId =
|
||||
rawVar != null && Number.isFinite(vid) && vid > 0 ? vid : null
|
||||
}
|
||||
if (sec?.items?.length) {
|
||||
if (typeof target?.iIdx === 'number') {
|
||||
const item = sec.items[target.iIdx]
|
||||
if (item?.exercise_id) {
|
||||
pickAnchorFromItem(item)
|
||||
} else {
|
||||
for (let i = target.iIdx - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
pickAnchorFromItem(sec.items[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (typeof target?.insertBeforeIndex === 'number') {
|
||||
const beforeIx = target.insertBeforeIndex
|
||||
for (let i = beforeIx - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
pickAnchorFromItem(sec.items[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (let i = sec.items.length - 1; i >= 0; i -= 1) {
|
||||
if (sec.items[i]?.exercise_id) {
|
||||
pickAnchorFromItem(sec.items[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const plannedExerciseIds = []
|
||||
const seenPlan = new Set()
|
||||
for (const sec of secs) {
|
||||
for (const it of sec?.items || []) {
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
const eid = Number(it?.exercise_id)
|
||||
if (!Number.isFinite(eid) || eid < 1 || seenPlan.has(eid)) continue
|
||||
seenPlan.add(eid)
|
||||
plannedExerciseIds.push(eid)
|
||||
}
|
||||
}
|
||||
const sectionPlannedExerciseIds = []
|
||||
const seenSec = new Set()
|
||||
for (const it of sec?.items || []) {
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
const eid = Number(it?.exercise_id)
|
||||
if (!Number.isFinite(eid) || eid < 1 || seenSec.has(eid)) continue
|
||||
seenSec.add(eid)
|
||||
sectionPlannedExerciseIds.push(eid)
|
||||
}
|
||||
let lastExerciseTitle = null
|
||||
if (sec?.items?.length) {
|
||||
for (let i = sec.items.length - 1; i >= 0; i -= 1) {
|
||||
const it = sec.items[i]
|
||||
if (String(it?.item_type || '').toLowerCase() === 'note') continue
|
||||
if (it?.exercise_id) {
|
||||
lastExerciseTitle = (it.exercise_title || '').trim() || null
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
const groupIdRaw = Number(formData.group_id)
|
||||
return {
|
||||
unitId: resolvedUnitId ? Number(resolvedUnitId) : null,
|
||||
groupId: Number.isFinite(groupIdRaw) && groupIdRaw > 0 ? groupIdRaw : null,
|
||||
sectionOrderIndex: sIdx,
|
||||
sectionTitle: (sec?.title || '').trim() || null,
|
||||
sectionGuidanceNotes: (sec?.guidance_notes || '').trim() || null,
|
||||
sectionPlannedExerciseIds,
|
||||
sectionExerciseCount: sectionPlannedExerciseIds.length,
|
||||
lastExerciseTitle,
|
||||
anchorExerciseId: Number.isFinite(anchorExerciseId) && anchorExerciseId > 0 ? anchorExerciseId : null,
|
||||
anchorExerciseVariantId,
|
||||
progressionGraphId: null,
|
||||
plannedExerciseIds,
|
||||
}
|
||||
}, [editingUnit?.id, unitId, exercisePickerTarget, formData.sections, formData.group_id])
|
||||
|
||||
const openExercisePicker = useCallback(({ sectionIndex, itemIndex, insertBeforeIndex, pickerMode = 'library' }) => {
|
||||
setExercisePickerTarget({
|
||||
sIdx: sectionIndex,
|
||||
iIdx: typeof itemIndex === 'number' ? itemIndex : undefined,
|
||||
insertBeforeIndex:
|
||||
typeof insertBeforeIndex === 'number' && Number.isFinite(insertBeforeIndex)
|
||||
? insertBeforeIndex
|
||||
: undefined,
|
||||
pickerMode,
|
||||
})
|
||||
setExercisePickerOpen(true)
|
||||
}, [])
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
goNavReturn(navigate, location, {
|
||||
path: PLANNING_HUB_PATH,
|
||||
@@ -688,17 +797,8 @@ export default function TrainingUnitEditPage() {
|
||||
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)
|
||||
}}
|
||||
onRequestExercisePick={(ctx) => openExercisePicker({ ...ctx, pickerMode: 'library' })}
|
||||
onRequestPlanningExercisePick={(ctx) => openExercisePicker({ ...ctx, pickerMode: 'planning' })}
|
||||
onPeekExercise={(id, variantId, peekExtras) =>
|
||||
setPlanningPeekCtx({ exerciseId: id, variantId: variantId ?? null, peekExtras: peekExtras ?? null })
|
||||
}
|
||||
@@ -752,6 +852,14 @@ export default function TrainingUnitEditPage() {
|
||||
open={exercisePickerOpen}
|
||||
multiSelect
|
||||
enableQuickCreateDraft
|
||||
expectPlanningSearch
|
||||
pickerMode={exercisePickerTarget?.pickerMode === 'planning' ? 'planning' : 'library'}
|
||||
enableFreePlanningSearch
|
||||
planningUnitId={
|
||||
editingUnit?.id ??
|
||||
(Number.isFinite(unitId) && unitId > 0 ? unitId : null)
|
||||
}
|
||||
planningContext={exercisePickerPlanningContext}
|
||||
onClose={() => {
|
||||
setExercisePickerOpen(false)
|
||||
setExercisePickerTarget(null)
|
||||
|
||||
+139
-1
@@ -4,7 +4,7 @@
|
||||
* Zentrale API-Kommunikation mit automatischer Token-Injektion
|
||||
*/
|
||||
|
||||
import { request, ACTIVE_CLUB_STORAGE_KEY } from '../api/client.js'
|
||||
import { request, ACTIVE_CLUB_STORAGE_KEY, requestText } from '../api/client.js'
|
||||
import * as exercises from '../api/exercises.js'
|
||||
import * as planning from '../api/planning.js'
|
||||
import * as skillProfiles from '../api/skillProfiles.js'
|
||||
@@ -361,6 +361,108 @@ export async function getAdminHierarchy() {
|
||||
return request('/api/admin/hierarchy')
|
||||
}
|
||||
|
||||
// Superadmin: KI Skill-Retrieval-Profile (Migration 068, exercise_ai)
|
||||
export async function listAiSkillRetrievalProfiles() {
|
||||
return request('/api/admin/ai-skill-retrieval-profiles')
|
||||
}
|
||||
|
||||
export async function getAiSkillRetrievalProfile(profileId) {
|
||||
return request(`/api/admin/ai-skill-retrieval-profiles/${profileId}`)
|
||||
}
|
||||
|
||||
export async function createAiSkillRetrievalProfile(data) {
|
||||
return request('/api/admin/ai-skill-retrieval-profiles', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateAiSkillRetrievalProfile(profileId, data) {
|
||||
return request(`/api/admin/ai-skill-retrieval-profiles/${profileId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteAiSkillRetrievalProfile(profileId) {
|
||||
return request(`/api/admin/ai-skill-retrieval-profiles/${profileId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
/** Superadmin: Übungs-Anreicherung per KI (Batch Skills) */
|
||||
export async function listExerciseEnrichmentCandidates(params = {}) {
|
||||
const q = new URLSearchParams()
|
||||
Object.entries(params).forEach(([k, v]) => {
|
||||
if (v === undefined || v === null || v === '') return
|
||||
if (typeof v === 'boolean') q.set(k, v ? 'true' : 'false')
|
||||
else q.set(k, String(v))
|
||||
})
|
||||
const qs = q.toString()
|
||||
return request(`/api/admin/exercise-enrichment/candidates${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function previewExerciseEnrichment(body) {
|
||||
return request('/api/admin/exercise-enrichment/preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function applyExerciseEnrichment(body) {
|
||||
return request('/api/admin/exercise-enrichment/apply', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listExerciseEnrichmentCandidateIds(params = {}) {
|
||||
const q = new URLSearchParams()
|
||||
Object.entries(params).forEach(([k, v]) => {
|
||||
if (v === undefined || v === null || v === '') return
|
||||
if (typeof v === 'boolean') q.set(k, v ? 'true' : 'false')
|
||||
else q.set(k, String(v))
|
||||
})
|
||||
const qs = q.toString()
|
||||
return request(`/api/admin/exercise-enrichment/candidate-ids${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function analyzeExerciseEnrichment(body) {
|
||||
return request('/api/admin/exercise-enrichment/analyze', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
/** Superadmin: KI Prompt-Templates (ai_prompts) */
|
||||
export async function listAdminAiPrompts() {
|
||||
return request('/api/admin/ai-prompts')
|
||||
}
|
||||
|
||||
export async function getAdminAiPrompt(promptId) {
|
||||
return request(`/api/admin/ai-prompts/${promptId}`)
|
||||
}
|
||||
|
||||
export async function updateAdminAiPrompt(promptId, data) {
|
||||
return request(`/api/admin/ai-prompts/${promptId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function previewAdminAiPrompt(promptId, data) {
|
||||
return request(`/api/admin/ai-prompts/${promptId}/preview`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data || {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function resetAdminAiPromptTemplate(promptId) {
|
||||
return request(`/api/admin/ai-prompts/${promptId}/reset-template`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getAdminAiPromptPlaceholdersCatalog() {
|
||||
return request('/api/admin/ai-prompts/catalog/placeholders')
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Reifegradmodelle / Fähigkeitsmatrix
|
||||
// ============================================================================
|
||||
@@ -465,6 +567,23 @@ export async function importMatrixStackBundle(payload) {
|
||||
})
|
||||
}
|
||||
|
||||
/** Superadmin: flacher Export für zentrale Pflege (Beschreibungen, Gewichtungen) */
|
||||
export async function exportMatrixEditorBundle() {
|
||||
return request('/api/admin/matrix-editor/export')
|
||||
}
|
||||
|
||||
export async function exportMatrixEditorCsv(part) {
|
||||
const format = part === 'skills' ? 'csv_skills' : 'csv_matrix'
|
||||
return requestText(`/api/admin/matrix-editor/export?format=${format}`)
|
||||
}
|
||||
|
||||
export async function importMatrixEditorBundle(payload) {
|
||||
return request('/api/admin/matrix-editor/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
// Style Directions (formerly Training Styles)
|
||||
export async function listStyleDirections(filters = {}) {
|
||||
const query = new URLSearchParams(filters).toString()
|
||||
@@ -764,6 +883,22 @@ export const api = {
|
||||
updateFocusArea,
|
||||
deleteFocusArea,
|
||||
getAdminHierarchy,
|
||||
listAiSkillRetrievalProfiles,
|
||||
getAiSkillRetrievalProfile,
|
||||
createAiSkillRetrievalProfile,
|
||||
updateAiSkillRetrievalProfile,
|
||||
deleteAiSkillRetrievalProfile,
|
||||
listExerciseEnrichmentCandidates,
|
||||
previewExerciseEnrichment,
|
||||
applyExerciseEnrichment,
|
||||
listExerciseEnrichmentCandidateIds,
|
||||
analyzeExerciseEnrichment,
|
||||
listAdminAiPrompts,
|
||||
getAdminAiPrompt,
|
||||
updateAdminAiPrompt,
|
||||
previewAdminAiPrompt,
|
||||
resetAdminAiPromptTemplate,
|
||||
getAdminAiPromptPlaceholdersCatalog,
|
||||
listStyleDirections,
|
||||
listTrainingStyles,
|
||||
createStyleDirection,
|
||||
@@ -805,6 +940,9 @@ export const api = {
|
||||
exportResolvedMaturityBundle,
|
||||
exportMatrixStackBundle,
|
||||
importMatrixStackBundle,
|
||||
exportMatrixEditorBundle,
|
||||
exportMatrixEditorCsv,
|
||||
importMatrixEditorBundle,
|
||||
resolveMaturityModel,
|
||||
getMaturityModel,
|
||||
createMaturityModel,
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* KI-gestützte Schnellanlage / Vorschau (Planung / ExercisePickerModal).
|
||||
*/
|
||||
import { stripHtmlToText } from './htmlUtils'
|
||||
import { normalizeSkillLevelSlug, formatSkillLevelSlug } from '../constants/skillLevels'
|
||||
import {
|
||||
EXERCISE_SKILL_INTENSITY_DEFAULT,
|
||||
normalizeExerciseSkillIntensity,
|
||||
formatExerciseSkillIntensityLabel,
|
||||
} from '../constants/exerciseSkillIntensity'
|
||||
|
||||
export const INSTRUCTION_AI_FIELD_DEFS = [
|
||||
{ key: 'goal', label: 'Ziel' },
|
||||
{ key: 'execution', label: 'Durchführung' },
|
||||
{ key: 'preparation', label: 'Vorbereitung / Aufbau' },
|
||||
{ key: 'trainer_notes', label: 'Hinweise für Trainer' },
|
||||
]
|
||||
|
||||
function escapeHtmlText(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/** Suchstring → Titel + Skizze für Schnellanlage (erste Zeile / Satz als Titel). */
|
||||
export function parseSearchQueryForQuickCreate(searchText) {
|
||||
const raw = String(searchText || '').trim()
|
||||
if (!raw) return { title: '', sketch: '' }
|
||||
|
||||
const lines = raw.split(/\n/).map((l) => l.trim()).filter(Boolean)
|
||||
if (lines.length >= 2) {
|
||||
return {
|
||||
title: lines[0].slice(0, 300),
|
||||
sketch: lines.slice(1).join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
const single = lines[0] || raw
|
||||
if (single.length <= 80) {
|
||||
return { title: single.slice(0, 300), sketch: single }
|
||||
}
|
||||
|
||||
const sentenceMatch = single.match(/^(.{10,120}?[.!?;:])\s+(.+)$/s)
|
||||
if (sentenceMatch) {
|
||||
return {
|
||||
title: sentenceMatch[1].trim().slice(0, 300),
|
||||
sketch: single,
|
||||
}
|
||||
}
|
||||
|
||||
const words = single.split(/\s+/).filter(Boolean)
|
||||
const titleWordCount = Math.min(8, Math.max(3, Math.ceil(words.length / 3)))
|
||||
const title = words.slice(0, titleWordCount).join(' ').slice(0, 120)
|
||||
return { title, sketch: single }
|
||||
}
|
||||
|
||||
/** Plaintext → Absätze für RichTextEditor / API. */
|
||||
export function aiPlainTextToMinimalHtml(text) {
|
||||
const raw = String(text || '').trim()
|
||||
if (!raw) return ''
|
||||
const parts = raw.split(/\n+/).map((p) => p.trim()).filter(Boolean)
|
||||
const paras = parts.length ? parts : [raw]
|
||||
return paras.map((p) => `<p>${escapeHtmlText(p)}</p>`).join('')
|
||||
}
|
||||
|
||||
export function normalizeAiSkillRowFromApi(sug) {
|
||||
const sid = Number(sug?.skill_id)
|
||||
if (!Number.isFinite(sid) || sid < 1) return null
|
||||
return {
|
||||
skill_id: sid,
|
||||
intensity: normalizeExerciseSkillIntensity(sug.intensity) || EXERCISE_SKILL_INTENSITY_DEFAULT,
|
||||
required_level: normalizeSkillLevelSlug(sug.required_level) || 'grundlagen',
|
||||
target_level:
|
||||
normalizeSkillLevelSlug(sug.target_level) ||
|
||||
normalizeSkillLevelSlug(sug.required_level) ||
|
||||
'grundlagen',
|
||||
is_primary: !!sug.is_primary,
|
||||
ai_suggested: true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Vorschau für Schnellanlage: Kurzfassung + Anleitung + Fähigkeiten. */
|
||||
export function buildQuickCreateAiPreview(apiRes, { sketchPlain = '' } = {}) {
|
||||
const sketchHtml = aiPlainTextToMinimalHtml(sketchPlain)
|
||||
const snapshotInstructions = {
|
||||
goal: sketchHtml,
|
||||
execution: '',
|
||||
preparation: '',
|
||||
trainer_notes: '',
|
||||
}
|
||||
|
||||
let summaryAfterHtml = null
|
||||
let summaryAfterPlain = ''
|
||||
if (apiRes?.summary?.text) {
|
||||
summaryAfterPlain = String(apiRes.summary.text).trim()
|
||||
if (summaryAfterPlain) {
|
||||
summaryAfterHtml = aiPlainTextToMinimalHtml(apiRes.summary.text)
|
||||
}
|
||||
}
|
||||
|
||||
const skillChoices = []
|
||||
if (Array.isArray(apiRes?.skills)) {
|
||||
for (const sug of apiRes.skills) {
|
||||
const after = normalizeAiSkillRowFromApi(sug)
|
||||
if (!after) continue
|
||||
skillChoices.push({
|
||||
key: String(after.skill_id),
|
||||
skill_id: after.skill_id,
|
||||
kind: 'add',
|
||||
before: null,
|
||||
after,
|
||||
include: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const instructionChoices = []
|
||||
const fields = apiRes?.instructions?.fields || {}
|
||||
for (const def of INSTRUCTION_AI_FIELD_DEFS) {
|
||||
const afterHtml = fields[def.key]
|
||||
if (!afterHtml || !String(afterHtml).trim()) continue
|
||||
const beforeHtml = snapshotInstructions[def.key] || ''
|
||||
instructionChoices.push({
|
||||
key: def.key,
|
||||
field: def.key,
|
||||
label: def.label,
|
||||
beforePlain: stripHtmlToText(beforeHtml).trim(),
|
||||
afterHtml: String(afterHtml),
|
||||
afterPlain: stripHtmlToText(afterHtml).trim(),
|
||||
include: true,
|
||||
})
|
||||
}
|
||||
|
||||
const hasSummaryProposal = !!summaryAfterHtml
|
||||
const hasSkillChoices = skillChoices.length > 0
|
||||
const hasInstructionChoices = instructionChoices.length > 0
|
||||
|
||||
return {
|
||||
mode: 'quick_create',
|
||||
applySummary: hasSummaryProposal,
|
||||
summaryBeforePlain: stripHtmlToText(sketchPlain).trim(),
|
||||
summaryAfterPlain,
|
||||
summaryAfterHtml,
|
||||
skillChoices,
|
||||
instructionChoices,
|
||||
hasSummaryProposal,
|
||||
hasSkillChoices,
|
||||
hasInstructionChoices,
|
||||
summaryRequested: true,
|
||||
skillsRequested: true,
|
||||
instructionsRequested: true,
|
||||
}
|
||||
}
|
||||
|
||||
export function describeAiSkillRowForPreview(row, skillsCatalog) {
|
||||
if (!row) return ''
|
||||
const sk = (skillsCatalog || []).find((x) => Number(x.id) === Number(row.skill_id))
|
||||
const name = sk?.name || `Fähigkeit #${row.skill_id}`
|
||||
const int = formatExerciseSkillIntensityLabel(row.intensity)
|
||||
const from = formatSkillLevelSlug(row.required_level) || '—'
|
||||
const to = formatSkillLevelSlug(row.target_level) || '—'
|
||||
const prim = row.is_primary ? ' · Primär' : ''
|
||||
return `${name}: Intensität ${int}, Niveau ${from} → ${to}${prim}`
|
||||
}
|
||||
|
||||
/** KI-Vorschau → bearbeitbarer Entwurf (Rich-Text-Felder). */
|
||||
export function aiPreviewToQuickCreateDraft(preview, { title, focusAreaId, sketchPlain }) {
|
||||
const sketchHtml = aiPlainTextToMinimalHtml(sketchPlain)
|
||||
const instructionFields = {
|
||||
goal: sketchHtml,
|
||||
execution: '',
|
||||
preparation: '',
|
||||
trainer_notes: '',
|
||||
}
|
||||
for (const c of preview?.instructionChoices || []) {
|
||||
if (c.field && c.include !== false && c.afterHtml) {
|
||||
instructionFields[c.field] = String(c.afterHtml)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: (title || '').trim(),
|
||||
focusAreaId: focusAreaId != null && focusAreaId !== '' ? String(focusAreaId) : '',
|
||||
summaryHtml:
|
||||
preview?.applySummary !== false && preview?.summaryAfterHtml ? String(preview.summaryAfterHtml) : '',
|
||||
instructionFields,
|
||||
skillChoices: (preview?.skillChoices || []).map((c) => ({ ...c })),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* createExercise-Payload aus bearbeitetem Entwurf.
|
||||
* @throws {Error}
|
||||
*/
|
||||
export function buildQuickCreateExercisePayloadFromDraft(draft) {
|
||||
const title = (draft?.title || '').trim()
|
||||
if (title.length < 3) {
|
||||
throw new Error('Titel: mindestens 3 Zeichen.')
|
||||
}
|
||||
|
||||
const fid = Number(draft?.focusAreaId)
|
||||
if (!Number.isFinite(fid) || fid < 1) {
|
||||
throw new Error('Fokusbereich ist erforderlich.')
|
||||
}
|
||||
|
||||
const fields = draft?.instructionFields || {}
|
||||
let goal = (fields.goal || '').trim()
|
||||
let execution = (fields.execution || '').trim()
|
||||
const prep = (fields.preparation || '').trim() || null
|
||||
const trainerNotes = (fields.trainer_notes || '').trim() || null
|
||||
|
||||
if (!stripHtmlToText(goal).trim() && !stripHtmlToText(execution).trim()) {
|
||||
throw new Error('Mindestens Ziel oder Durchführung ausfüllen.')
|
||||
}
|
||||
if (!stripHtmlToText(goal).trim()) goal = execution
|
||||
if (!stripHtmlToText(execution).trim()) execution = goal
|
||||
|
||||
let summary = (draft?.summaryHtml || '').trim() || null
|
||||
if (summary && !stripHtmlToText(summary).trim()) summary = null
|
||||
|
||||
const skills = (draft?.skillChoices || []).filter((c) => c.include).map((c) => c.after)
|
||||
|
||||
return {
|
||||
title,
|
||||
summary,
|
||||
goal,
|
||||
execution,
|
||||
preparation: prep,
|
||||
trainer_notes: trainerNotes,
|
||||
visibility: 'private',
|
||||
status: 'draft',
|
||||
equipment: [],
|
||||
focus_areas_multi: [{ focus_area_id: fid, is_primary: true }],
|
||||
training_styles_multi: [],
|
||||
training_types_multi: [],
|
||||
target_groups_multi: [],
|
||||
age_groups: [],
|
||||
skills,
|
||||
club_id: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* createExercise-Payload aus bestätigter Vorschau (Checkbox-Modus).
|
||||
* @throws {Error}
|
||||
*/
|
||||
export function buildQuickCreateExercisePayloadFromPreview(preview, { title, focusAreaId, sketchPlain }) {
|
||||
const sketchHtml = aiPlainTextToMinimalHtml(sketchPlain)
|
||||
const fieldMap = {}
|
||||
for (const c of preview?.instructionChoices || []) {
|
||||
if (c.include && c.afterHtml) fieldMap[c.field] = c.afterHtml
|
||||
}
|
||||
|
||||
let goal = (fieldMap.goal || '').trim() || sketchHtml
|
||||
let execution = (fieldMap.execution || '').trim()
|
||||
const prep = (fieldMap.preparation || '').trim() || null
|
||||
const trainerNotes = (fieldMap.trainer_notes || '').trim() || null
|
||||
|
||||
if (!stripHtmlToText(goal).trim() && !stripHtmlToText(execution).trim()) {
|
||||
throw new Error('Mindestens Ziel oder Durchführung muss übernommen werden.')
|
||||
}
|
||||
if (!stripHtmlToText(goal).trim()) goal = execution
|
||||
if (!stripHtmlToText(execution).trim()) execution = goal
|
||||
|
||||
let summary = null
|
||||
if (preview?.applySummary && preview?.summaryAfterHtml) {
|
||||
summary = preview.summaryAfterHtml
|
||||
}
|
||||
|
||||
const skills = (preview?.skillChoices || []).filter((c) => c.include).map((c) => c.after)
|
||||
|
||||
const fid = Number(focusAreaId)
|
||||
if (!Number.isFinite(fid) || fid < 1) {
|
||||
throw new Error('Fokusbereich ist erforderlich.')
|
||||
}
|
||||
|
||||
return {
|
||||
title: (title || '').trim(),
|
||||
summary,
|
||||
goal,
|
||||
execution,
|
||||
preparation: prep,
|
||||
trainer_notes: trainerNotes,
|
||||
visibility: 'private',
|
||||
status: 'draft',
|
||||
equipment: [],
|
||||
focus_areas_multi: [{ focus_area_id: fid, is_primary: true }],
|
||||
training_styles_multi: [],
|
||||
training_types_multi: [],
|
||||
target_groups_multi: [],
|
||||
age_groups: [],
|
||||
skills,
|
||||
club_id: null,
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated Direkt aus API — nutze Preview + buildQuickCreateExercisePayloadFromPreview */
|
||||
export function buildQuickCreateExercisePayload({ title, focusAreaId, sketchPlain, apiRes }) {
|
||||
const preview = buildQuickCreateAiPreview(apiRes, { sketchPlain })
|
||||
return buildQuickCreateExercisePayloadFromPreview(preview, { title, focusAreaId, sketchPlain })
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Varianten-Auswahl beim Übernehmen aus Planungs-KI-Treffern. */
|
||||
export function resolveExercisePickVariantId(exercise, overrideVariantId) {
|
||||
if (exercise == null) return null
|
||||
const raw =
|
||||
overrideVariantId !== undefined && overrideVariantId !== null && overrideVariantId !== ''
|
||||
? overrideVariantId
|
||||
: exercise.exercise_variant_id ?? exercise.suggested_variant_id
|
||||
if (raw == null || raw === '') return null
|
||||
const vid = Number(raw)
|
||||
return Number.isFinite(vid) && vid > 0 ? vid : null
|
||||
}
|
||||
|
||||
export function variantLabelForPick(variants, variantId) {
|
||||
if (variantId == null) return null
|
||||
const list = Array.isArray(variants) ? variants : []
|
||||
const row = list.find((v) => Number(v.id) === Number(variantId))
|
||||
return (row?.variant_name || '').trim() || null
|
||||
}
|
||||
@@ -325,6 +325,18 @@ export async function hydrateExercisePlanningRow(exercise) {
|
||||
row.exercise_variant_id = ''
|
||||
} else {
|
||||
row.variants = variants
|
||||
const pickVidRaw =
|
||||
exercise?.exercise_variant_id ?? exercise?.suggested_variant_id ?? null
|
||||
const pickVid =
|
||||
pickVidRaw != null && pickVidRaw !== '' ? Number(pickVidRaw) : NaN
|
||||
if (Number.isFinite(pickVid) && pickVid > 0) {
|
||||
const known = variants.some((v) => Number(v.id) === pickVid)
|
||||
if (known || !variants.length) row.exercise_variant_id = pickVid
|
||||
}
|
||||
if (row.exercise_variant_id !== '' && variants.length > 0) {
|
||||
const ok = variants.some((v) => Number(v.id) === Number(row.exercise_variant_id))
|
||||
if (!ok) row.exercise_variant_id = ''
|
||||
}
|
||||
}
|
||||
Object.assign(row, meta)
|
||||
if (row.exercise_kind === 'combination') {
|
||||
|
||||
Reference in new issue
Block a user