26 Commits
Author SHA1 Message Date
Lars fc5748bef1 Merge pull request 'KI Übungen - MVP 0.8' (#48) from develop into main
Deploy Production / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Reviewed-on: #48
2026-05-22 19:51:54 +02:00
Lars 9d880e2346 Enhance Exercise List Page with AI Assistant Toggle and UI Improvements
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (pull_request) Successful in 37s
Test Suite / lint-backend (pull_request) Successful in 1s
Test Suite / build-frontend (pull_request) Successful in 12s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m17s
- Introduced a new AI assistant toggle in the Exercise List Page header, allowing users to enable quick exercise creation via AI suggestions.
- Updated the ExerciseListSearchBar component to remove deprecated AI quick create functionality, streamlining the interface.
- Enhanced CSS styles for the AI assistant toggle, improving visual feedback and user interaction.
- Improved overall layout and spacing in the exercises page for better usability.
2026-05-22 19:44:15 +02:00
Lars c816e50c68 Refactor Exercise Creation Components to Utilize Custom Hook for Quick Create Fields
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m20s
- Updated ExerciseAiQuickCreateOffer to set showSketchField to true by default and introduced sketchOptional prop for improved flexibility in exercise creation.
- Refactored ExercisePickerModal and ExercisesListPageRoot to leverage useExerciseAiQuickCreateFields hook, simplifying state management for quick create fields.
- Removed deprecated parsing logic and streamlined error handling for sketch input, enhancing user experience during exercise creation.
- Improved placeholder text and labels for clarity, ensuring better guidance for users when providing input for AI-generated exercises.
2026-05-22 19:36:22 +02:00
Lars 294740b780 Increment application version to 0.8.166 and update changelog for new features in AI exercise creation
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m15s
- Updated APP_VERSION to 0.8.166 and modified BUILD_DATE to reflect recent changes.
- Enhanced AI exercise creation process with a new quick create feature, allowing users to generate exercises based on search input.
- Introduced a rich text editor for editing AI-generated drafts, improving user experience in exercise creation.
- Updated ExercisePickerModal and related components to support the new quick create functionality, including error handling and input validation.
- Added new utility functions for parsing search queries and building exercise payloads from drafts.
2026-05-22 19:24:36 +02:00
Lars 675cfa85f0 Enhance AI Quick Create Functionality in ExercisePickerModal
Deploy Development / deploy (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m20s
- Updated the quick create process to include a preview feature for AI-generated exercises, allowing users to review goals, execution, preparation, and trainer notes.
- Introduced new constants for instruction fields and refactored the payload building function to utilize the preview data.
- Improved error handling to ensure at least one of the goal or execution fields is populated.
- Deprecated the previous payload building function in favor of the new preview-based approach, streamlining the exercise creation workflow.
2026-05-22 19:10:16 +02:00
Lars 4725eaa90b Increment application version to 0.8.164 and update changelog for new features in ExercisePickerModal
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m15s
- Updated APP_VERSION to 0.8.164 and added changelog entry for the new version.
- Enhanced ExercisePickerModal to support quick exercise creation using AI, including fields for sketch and focus area.
- Implemented error handling for AI suggestions and improved user prompts for input validation.
- Updated UI elements to reflect changes in exercise creation workflow.
2026-05-22 19:01:01 +02:00
Lars 9f4678f418 Implement exercise_instruction_rewrite for AI Prompt System
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m16s
- Added `exercise_instruction_rewrite` functionality to enhance AI-generated instructions, incorporating fields for goal, execution, preparation, and trainer notes.
- Updated `ExerciseFormAiPromptContext` to include new fields and methods for instruction handling.
- Enhanced the `run_exercise_form_ai_suggestion` function to support instruction rewriting and validation.
- Modified API endpoints and frontend components to integrate instruction features, including a new button for AI instruction revision.
- Incremented application version to 0.8.163 and updated changelog to reflect these changes, including migration details and new functionality.
2026-05-22 18:53:36 +02:00
Lars 5331eab39c Implement ExerciseFormAiPromptContext and Refactor AI Prompt Job Functionality
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m23s
- Introduced `ExerciseFormAiPromptContext` for unified handling of prompt-related data, enhancing the admin preview and exercise API.
- Added `run_exercise_form_ai_suggestion` function to streamline AI suggestion processing, integrating with the OpenRouter.
- Updated various modules to utilize the new context model, improving code clarity and reducing redundancy.
- Incremented application version to 0.8.162 and updated changelog to reflect these changes, including migration details and new functionality.
2026-05-22 18:47:09 +02:00
Lars 93b8d09d05 Implement OpenRouter Model Support in AI Prompt System
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
- Added `openrouter_model` field to the `ai_prompts` table, allowing for optional model overrides per prompt.
- Updated the `exercise_ai` module to utilize the effective OpenRouter model based on prompt-specific settings, enhancing flexibility in AI interactions.
- Enhanced the admin interface to support OpenRouter model configuration for prompts, improving usability for Superadmins.
- Incremented application version to 0.8.161 and updated changelog to reflect these changes, including migration details and new functionality.
2026-05-22 12:37:43 +02:00
Lars 0551bb3d80 Refactor AI Prompt System and Enhance Functionality
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
- Introduced `load_and_render_ai_prompt` and `render_ai_prompt_template_for_row` in `ai_prompt_runtime` to streamline prompt loading and rendering processes.
- Added `AiPromptUnavailableError` for better error handling when prompts are inactive or missing.
- Created `ai_prompt_job` module with `ExerciseFormAiPromptContext` and `resolve_exercise_form_variables` to support admin preview functionality.
- Updated documentation and target architecture to reflect changes in the AI prompt system.
- Incremented application version to 0.8.160 and updated changelog accordingly.
2026-05-22 12:19:52 +02:00
Lars 3bf012a8f4 Merge pull request 'export der Fähigkeiten, KI- Admin' (#47) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
Reviewed-on: #47
2026-05-22 11:56:54 +02:00
Lars e22266a18c Update ACCESS_LAYER_ENDPOINT_AUDIT and Matrix Editor Documentation
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m13s
- Added the `matrix_editor` endpoint to the ACCESS_LAYER_ENDPOINT_AUDIT.md, specifying its access requirements and exempt status for superadmins.
- Updated comments in the `matrix_editor.py` file to clarify its role as a superadmin tool and its access restrictions.
- Included the `matrix_editor.py` in the EXEMPT_ROUTERS list in the access layer hints script, ensuring proper access control documentation.
2026-05-22 11:54:59 +02:00
Lars d58db3d5dd Enhance Maturity Matrix Tools and API Integration
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m19s
- Added new functionality for exporting and importing matrix editor data in JSON and CSV formats within the MaturityMatrixToolsAdmin component.
- Updated the API utility functions to support matrix editor exports and imports, enhancing the backend communication for Superadmin tasks.
- Refactored the client API to streamline request handling and improve code clarity.
- Included new UI elements for file upload and download actions, improving user experience in managing matrix data.
2026-05-22 11:12:50 +02:00
Lars cdeddc7cec Update AI Prompt System and Documentation
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
- Added a new target architecture document for the AI Prompt System, detailing context types, composition, and planning phases.
- Refactored the backend to utilize a shared function for loading AI prompt rows, reducing SQL duplication in the `exercise_ai` module.
- Incremented the application version to 0.8.159 and updated the changelog to reflect these changes, including enhancements to the AI prompt management and documentation links.
2026-05-22 11:05:35 +02:00
Lars 2148d0aa7f Update AI Prompt System and Admin API
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m16s
- Incremented version to 1.1 and updated the status to reflect the implementation of core features including `ai_prompts`, `prompt_resolver`, and the Superadmin HTTP API.
- Documented the current API endpoints for managing AI prompts, including CRUD operations and preview functionality.
- Introduced a new placeholder catalog and preview capabilities for the Superadmin interface.
- Enhanced the backend with new functions for handling AI prompt templates and integrated them into the API.
- Updated frontend components to include navigation and routing for the new Admin AI Prompts page.
- Incremented application version to 0.8.158 and updated changelog to reflect these changes.
2026-05-22 11:02:02 +02:00
Lars 69f238d9b8 Merge pull request 'KI Implementierung (MVP) auf Übungen' (#46) from develop into main
Deploy Production / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
Reviewed-on: #46
2026-05-22 10:38:39 +02:00
Lars f9e295bce0 Remove AI suggestion preview dialog from ExerciseFormPageRoot component to streamline user interface and improve performance. This change eliminates unnecessary complexity in the component's rendering logic.
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m30s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m31s
2026-05-22 10:29:49 +02:00
Lars 888d0bd009 Update environment configuration for AI debugging support
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m16s
- Added `SHINKAN_AI_DEBUG` environment variable to `.env.example`, enabling detailed logging for AI operations in Docker containers.
- Integrated `SHINKAN_AI_DEBUG` into both `docker-compose.dev-env.yml` and `docker-compose.yml` to facilitate debugging during development and production environments.
2026-05-22 10:20:16 +02:00
Lars 1942585546 Enhance exercise_ai and openrouter_chat modules with AI debugging and improved content handling
Test Suite / lint-backend (push) Waiting to run
Test Suite / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Has been cancelled
- Introduced detailed logging for AI operations in the `exercise_ai` and `openrouter_chat` modules, activated by the `SHINKAN_AI_DEBUG` environment variable, to aid in debugging and performance monitoring.
- Updated the `run_exercise_ai_suggestion` function to log prompt lengths, response sizes, and JSON parsing errors, enhancing transparency in AI interactions.
- Improved the `_flatten_message_content` function to handle nested content structures more effectively, ensuring compatibility with various AI response formats.
- Incremented the application version to 0.8.157 and updated the changelog to reflect these enhancements, including new logging features and content handling improvements.
2026-05-22 10:19:31 +02:00
Lars a28a9d399a Enhance exercise_ai and openrouter_chat modules with improved JSON handling and error management
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
- Added a new function `_first_balanced_json_array` to extract the first complete top-level JSON array from arbitrary text, enhancing robustness in parsing.
- Updated the `run_exercise_ai_suggestion` function to raise clear HTTP exceptions for empty responses from the OpenRouter, ensuring better error handling.
- Introduced `_flatten_message_content` in the `openrouter_chat` module to handle structured message content from OpenAI, improving compatibility with various content formats.
- Incremented the application version to 0.8.156 and updated the changelog to reflect these enhancements, including improved error messages and JSON parsing capabilities.
2026-05-22 10:09:07 +02:00
Lars 9be69ace5c Enhance exercise_ai module with skill input sanitization and version update
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m16s
- Introduced a new constant `_MAX_SANITIZE_SKILL_INPUT_ROWS` to limit the number of skill entries processed, improving performance and preventing issues with excessively long skill arrays.
- Updated the `_extract_json_array` and `_sanitize_skill_entries` functions to enforce this limit, ensuring that only a maximum of 250 skill entries are handled and that processing stops after 5 valid entries.
- Incremented the application version to 0.8.155 and updated the changelog to reflect these changes, including a note on the improvements made to the AI endpoint for skill arrays.
2026-05-22 09:59:56 +02:00
Lars 286c36e9d7 Document Superadmin API for AI Skill Retrieval Profiles and Update Access Layer
Deploy Development / deploy (push) Successful in 38s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
- Added documentation for the new Superadmin CRUD endpoints for managing AI Skill Retrieval Profiles (`/api/admin/ai-skill-retrieval-profiles*`).
- Updated the ACCESS_LAYER_ENDPOINT_AUDIT.md to include the new Superadmin API and its exempt status.
- Registered the ai_skill_retrieval_admin router in the backend and updated versioning to reflect the changes.
- Enhanced the frontend with a new Admin page for AI Skill Retrieval, including navigation and API integration for profile management.
2026-05-22 09:57:39 +02:00
Lars 294b09a5d9 Implement AI Skill Retrieval Profiles and Enhance Exercise AI Functionality
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
- Introduced migration 068 for `ai_skill_retrieval_profiles`, enabling configurable weights and quotes for skill catalog prioritization in exercise AI suggestions.
- Updated the `POST /api/exercises/ai/suggest` endpoint to include an optional `focus_areas_context` field, allowing for enhanced context in AI-generated suggestions.
- Enhanced the `exercise_ai` module to utilize context-based skill selection, incorporating scoring, category caps, and keyword patches for improved AI responses.
- Updated the ExerciseFormPageRoot component to pass focus area context to the AI suggestion API, streamlining user interaction with AI-generated content.
- Incremented version numbers in `backend/version.py` to reflect the latest changes and ensure accurate tracking in the changelog.
2026-05-22 09:49:08 +02:00
Lars e5291256d0 Enhance AI Exercise Suggestion Functionality and UX
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m21s
- Updated the AI Exercise Implementation Plan to include a detailed description of the new suggestion dialog for AI proposals, allowing users to preview and selectively adopt AI-generated summaries and skills.
- Implemented a new preview feature in the ExerciseFormPageRoot component, enabling users to review AI suggestions before applying them to the form.
- Enhanced the skill management process by normalizing AI-suggested skills and integrating them into the exercise form, improving user interaction and data handling.
2026-05-22 09:21:44 +02:00
Lars 4d36bbf634 Update AI Training Planning Document and Versioning
Deploy Development / deploy (push) Successful in 38s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
- Incremented the version number from 0.2 to 0.3 in the AI Training Planning document to reflect the latest changes.
- Added a new reference to the `working/AI_PLANNING_KI_MULTISTAGE_FORECAST.md` document, outlining the architecture preview for the planning AI.
- Updated the changelog in `backend/version.py` to include the latest version entry, ensuring accurate tracking of changes.
2026-05-22 07:56:56 +02:00
Lars e4451e1362 Enhance Exercise Management and AI Integration
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Has been cancelled
- Updated the exercise form to include a tabbed navigation structure, improving user experience with sections for Stammdaten, Anleitung, Einordnung, Varianten, and Medien & Mehr.
- Introduced the concept of **Freigabelevel** (visibility level) in the UI, replacing previous terminology for clarity and consistency across components.
- Implemented new AI endpoints for exercise suggestions and regeneration, allowing for dynamic content generation without direct database writes.
- Removed the legacy `is_primary` flag from exercise skills in the UI, ensuring that intensity levels (`niedrig`, `mittel`, `hoch`) are the primary focus for skill management.
- Enhanced the variant management process with improved saving mechanisms and UI updates to reflect changes more intuitively.
2026-05-22 07:52:31 +02:00
61 changed files with 7983 additions and 218 deletions

No files matched your search

+3 -1
View File
@@ -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.
+1 -1
View File
@@ -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.
---
+45 -13
View File
@@ -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)
+38 -6
View File
@@ -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,25 @@ 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 |
**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-30 — Superadmin `/api/admin/ai-prompts*` (Prompt-Pflege, Vorschau ohne OpenRouter); weiterhin suggest + Retrieval-Profile.
---
### Changelog (Fortführung)
- **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.
+6
View File
@@ -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
+1
View File
@@ -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
+105
View File
@@ -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",
]
+58
View File
@@ -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",
]
+114
View File
@@ -0,0 +1,114 @@
"""
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
_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.
"""
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 _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
View File
@@ -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
+4 -1
View File
@@ -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, 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
app.include_router(auth.router)
app.include_router(profiles.router)
@@ -216,10 +216,13 @@ 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)
# 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) = '');
+224
View File
@@ -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()
+140
View File
@@ -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
View File
@@ -1,3 +1,4 @@
httpx==0.27.2
fastapi==0.111.0
uvicorn[standard]==0.29.0
anthropic==0.26.0
+241
View File
@@ -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,
}
+370
View File
@@ -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}
+156 -1
View File
@@ -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,
+727
View File
@@ -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,
}
@@ -23,10 +23,13 @@ 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
"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",
}
+146
View File
@@ -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
+132 -4
View File
@@ -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.166"
BUILD_DATE = "2026-05-22"
DB_SCHEMA_VERSION = "20260531071"
MODULE_VERSIONS = {
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
@@ -18,11 +18,16 @@ 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)
"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.0", # load_and_render_ai_prompt, AiPromptUnavailableError, render_ai_prompt_template_for_row
"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.33.0", # KI Schnellanlage: Suche+Anlage kombiniert; Rich-Text-Editor; Übungsliste KI-Schalter
"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 +42,129 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
{
"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",
+1
View File
@@ -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}
+1
View File
@@ -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}
+9 -4
View File
@@ -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)
+26 -3
View File
@@ -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-31
**App-Version / DB-Schema:** App **`0.8.166`** (KI Schnellanlage Suche+Anlage); DB **`20260531071`** — 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,28 @@ 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 & Skill-Katalog-Retrieval (Stand **0.8.166**)
- **Zielarchitektur (Pflicht fuer Erweiterungen):** `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` — Kontext-Arten, Composition, Einbindung Planung/Rahmen; Phasenplan P0–P4.
- **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) — Volltextsuche; bei keinem Treffer **„Mit KI anlegen“** (Suchstring → Titel/Skizze); Entwurf im **Rich-Text-Dialog** bearbeiten, dann speichern & übernehmen. **`ExercisesListPageRoot`** — gleiches Muster + Schalter **„KI-Anlage“** in der Suchleiste.
---
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
+1 -1
View File
@@ -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)
+18
View File
@@ -54,6 +54,8 @@ 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 SettingsLegalPage = lazy(() => import('./pages/SettingsLegalPage'))
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
@@ -300,6 +302,22 @@ const appRouter = createBrowserRouter([
</PlatformAdminRoute>
),
},
{
path: 'admin/ai-skill-retrieval',
element: (
<PlatformAdminRoute>
<AdminAiSkillRetrievalPage />
</PlatformAdminRoute>
),
},
{
path: 'admin/ai-prompts',
element: (
<PlatformAdminRoute>
<AdminAiPromptsPage />
</PlatformAdminRoute>
),
},
{ path: 'trainer-contexts', element: <TrainerContextsPage /> },
],
},
+22 -6
View File
@@ -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,
}
}
+14 -5
View File
@@ -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,
}),
})
}
+62
View File
@@ -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;
}
+2 -1
View File
@@ -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 } from 'lucide-react'
/**
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
@@ -12,6 +12,7 @@ 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 },
]
return (
@@ -0,0 +1,123 @@
import React from 'react'
/**
* Inline-Angebot: aus Suchstring neue Übung per KI anlegen (Fokusbereich + optional Titel/Skizze).
*/
export default function ExerciseAiQuickCreateOffer({
searchLabel,
title,
onTitleChange,
sketch,
onSketchChange,
focusAreaId,
onFocusAreaChange,
focusAreas = [],
catalogsReady = true,
busy = false,
error = '',
onRunAi,
showSketchField = true,
sketchOptional = true,
hint,
}) {
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' }}>
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>
)
}
+131 -105
View File
@@ -17,16 +17,20 @@ import {
import SkillTreeMultiSelect from './SkillTreeMultiSelect'
import ExerciseFocusRulePicker from './ExerciseFocusRulePicker'
import CatalogRulePicker from './CatalogRulePicker'
import ExerciseAiSuggestPreviewModal from './ExerciseAiSuggestPreviewModal'
import ExerciseAiQuickCreateOffer from './ExerciseAiQuickCreateOffer'
import { useExerciseAiQuickCreateFields } from '../hooks/useExerciseAiQuickCreateFields'
import {
buildQuickCreateAiPreview,
buildQuickCreateExercisePayloadFromDraft,
aiPreviewToQuickCreateDraft,
} from '../utils/exerciseAiQuickCreate'
const PAGE_SIZE = 100
const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)
const INITIAL_FILTERS = { ...INITIAL_EXERCISE_LIST_FILTERS }
/** Stub-Ziel für API-Validator (mind. Ziel oder Durchführung); Nutzer ergänzt Details in der Übungsbearbeitung. */
const QUICK_CREATE_GOAL_PLACEHOLDER =
'Aus der Trainingsplanung angelegt — bitte Ziel und Durchführung in der Übungsbearbeitung ergänzen.'
export default function ExercisePickerModal({
open,
onClose,
@@ -57,12 +61,21 @@ export default function ExercisePickerModal({
const [loadingMore, setLoadingMore] = useState(false)
const [hasMore, setHasMore] = useState(false)
const [multiPicked, setMultiPicked] = useState([])
const [quickOpen, setQuickOpen] = useState(false)
const [quickTitle, setQuickTitle] = useState('')
const [quickSummary, setQuickSummary] = useState('')
const [quickSaving, setQuickSaving] = useState(false)
const [quickAiError, setQuickAiError] = useState('')
const [quickCreateDraft, setQuickCreateDraft] = useState(null)
const pickerScrollRef = useRef(null)
const {
title: quickTitle,
sketch: quickSketch,
focusAreaId: quickFocusAreaId,
setTitle: setQuickTitle,
setSketch: setQuickSketch,
setFocusAreaId: setQuickFocusAreaId,
resetQuickCreateFields,
} = useExerciseAiQuickCreateFields(debouncedSearch, { enabled: open && enableQuickCreateDraft })
const toggleMultiPick = (ex) => {
setMultiPicked((prev) =>
prev.some((p) => p.id === ex.id) ? prev.filter((p) => p.id !== ex.id) : [...prev, ex]
@@ -79,6 +92,13 @@ export default function ExercisePickerModal({
return () => clearTimeout(t)
}, [aiSearchInput])
const showQuickCreateOffer =
enableQuickCreateDraft &&
catalogsReady &&
!loading &&
debouncedSearch.length >= 3 &&
list.length === 0
useEffect(() => {
if (!open) return
let cancelled = false
@@ -122,10 +142,10 @@ export default function ExercisePickerModal({
setList([])
setHasMore(false)
setMultiPicked([])
setQuickOpen(false)
setQuickTitle('')
setQuickSummary('')
resetQuickCreateFields()
setQuickSaving(false)
setQuickAiError('')
setQuickCreateDraft(null)
return
}
setFilters(mergeExerciseListPrefsFromApi(user?.exercise_list_prefs))
@@ -285,43 +305,83 @@ export default function ExercisePickerModal({
const resetFilters = () => setFilters({ ...INITIAL_FILTERS })
const submitQuickCreate = async () => {
const adoptExistingExercise = async (ex) => {
if (!ex?.id) return
if (multiSelect && typeof onSelectExercises === 'function') {
await Promise.resolve(onSelectExercises([ex]))
} else if (typeof onSelectExercise === 'function') {
await Promise.resolve(onSelectExercise(ex))
}
onClose()
}
const runQuickCreateAiSuggest = async () => {
const title = (quickTitle || '').trim()
if (title.length < 3) {
alert('Titel: mindestens 3 Zeichen.')
return
}
const summaryRaw = (quickSummary || '').trim()
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 created = await api.createExercise({
const aiRes = await api.suggestExerciseAi({
title,
summary: summaryRaw || null,
goal: QUICK_CREATE_GOAL_PLACEHOLDER,
execution: null,
visibility: 'private',
status: 'draft',
equipment: [],
focus_areas_multi: [],
training_styles_multi: [],
training_types_multi: [],
target_groups_multi: [],
age_groups: [],
skills: [],
club_id: null,
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,
})
if (!created?.id) {
throw new Error('Anlegen fehlgeschlagen')
const preview = buildQuickCreateAiPreview(aiRes, { sketchPlain: sketch })
if (!preview.hasSummaryProposal && !preview.hasInstructionChoices && !preview.hasSkillChoices) {
throw new Error('Die KI lieferte keinen verwertbaren Vorschlag.')
}
if (multiSelect && typeof onSelectExercises === 'function') {
await Promise.resolve(onSelectExercises([created]))
} else if (typeof onSelectExercise === 'function') {
await Promise.resolve(onSelectExercise(created))
}
onClose()
setQuickCreateDraft(
aiPreviewToQuickCreateDraft(preview, { title, focusAreaId: focusId, sketchPlain: sketch }),
)
} catch (e) {
console.error(e)
alert(e.message || 'Übung konnte nicht angelegt werden')
const msg = e?.message || String(e)
setQuickAiError(msg)
alert(msg || 'KI-Vorschlag fehlgeschlagen')
} finally {
setQuickSaving(false)
}
}
const applyQuickCreateDraft = 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)
await adoptExistingExercise(created)
} catch (e) {
console.error(e)
const msg = e?.message || String(e)
setQuickAiError(msg)
alert(msg || 'Übung konnte nicht angelegt werden')
} finally {
setQuickSaving(false)
}
@@ -353,75 +413,6 @@ export default function ExercisePickerModal({
</button>
</div>
{enableQuickCreateDraft ? (
<div
style={{
padding: '10px 1rem 12px',
borderBottom: '1px solid var(--border)',
flexShrink: 0,
background: 'var(--surface2)',
}}
>
<button
type="button"
className="btn btn-secondary"
style={{ width: '100%' }}
onClick={() => setQuickOpen((v) => !v)}
aria-expanded={quickOpen}
>
{quickOpen ? 'Neue Übung ausblenden' : 'Neue Übung anlegen (Entwurf, privat)'}
</button>
{quickOpen ? (
<div style={{ marginTop: '12px', display: 'grid', gap: '10px' }}>
<p style={{ margin: 0, fontSize: '13px', color: 'var(--text2)', lineHeight: 1.45 }}>
Wird mit Freigabelevel <strong>privat</strong> und Status <strong>Entwurf</strong> gespeichert und
erscheint auf dem Dashboard zum Weiterbearbeiten. Nach dem Speichern wird die Übung direkt in den
Ablauf übernommen.
</p>
<div>
<label className="form-label" htmlFor="ex-picker-quick-title">
Titel
</label>
<input
id="ex-picker-quick-title"
type="text"
className="form-input"
value={quickTitle}
onChange={(e) => setQuickTitle(e.target.value)}
autoComplete="off"
minLength={3}
maxLength={300}
placeholder="z. B. Partnerübung Abwehr"
/>
</div>
<div>
<label className="form-label" htmlFor="ex-picker-quick-summary">
Kurzbeschreibung
</label>
<textarea
id="ex-picker-quick-summary"
className="form-input"
rows={3}
value={quickSummary}
onChange={(e) => setQuickSummary(e.target.value)}
placeholder="Optional: grobe Idee, Kontext aus der Planung …"
/>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', justifyContent: 'flex-end' }}>
<button
type="button"
className="btn btn-primary"
disabled={quickSaving || (quickTitle || '').trim().length < 3}
onClick={submitQuickCreate}
>
{quickSaving ? 'Wird angelegt…' : 'Entwurf anlegen und übernehmen'}
</button>
</div>
</div>
) : null}
</div>
) : null}
<div style={{ padding: '0 1rem 0.75rem', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
<div style={{ display: 'grid', gap: '0.65rem' }}>
<div>
@@ -602,7 +593,28 @@ export default function ExercisePickerModal({
<div className="spinner" />
</div>
) : list.length === 0 ? (
<p style={{ color: 'var(--text2)', textAlign: 'center' }}>Keine Treffer.</p>
showQuickCreateOffer ? (
<ExerciseAiQuickCreateOffer
searchLabel={debouncedSearch}
title={quickTitle}
onTitleChange={setQuickTitle}
sketch={quickSketch}
onSketchChange={setQuickSketch}
focusAreaId={quickFocusAreaId}
onFocusAreaChange={setQuickFocusAreaId}
focusAreas={catalogs.focusAreas}
catalogsReady={catalogsReady}
busy={quickSaving}
error={quickAiError}
onRunAi={runQuickCreateAiSuggest}
/>
) : (
<p style={{ color: 'var(--text2)', textAlign: 'center' }}>
{debouncedSearch.length >= 3
? 'Keine Treffer.'
: 'Suchbegriff eingeben (mind. 3 Zeichen) …'}
</p>
)
) : (
<>
<p style={{ fontSize: '13px', color: 'var(--text2)', marginBottom: 10 }}>
@@ -770,6 +782,20 @@ export default function ExercisePickerModal({
)}
</div>
</div>
<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 Titel, Kurzfassung, Anleitung und Fähigkeiten an, dann speichern und übernehmen."
applyLabel={quickSaving ? 'Wird angelegt…' : 'Anlegen und übernehmen'}
applyDisabled={quickSaving}
zIndex={2100}
/>
</div>
)
}
@@ -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">
@@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
/** 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}
@@ -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,14 @@ import ExerciseListBulkToolbar from './ExerciseListBulkToolbar'
import SaveSelectedExercisesAsModuleModal from './SaveSelectedExercisesAsModuleModal'
import ExercisePeekModal from '../ExercisePeekModal'
import NavStateLink from '../NavStateLink'
import ExerciseAiQuickCreateOffer from '../ExerciseAiQuickCreateOffer'
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'
@@ -37,6 +46,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 +88,21 @@ function ExercisesListPageRoot() {
const [bulkTargetGroupIds, setBulkTargetGroupIds] = useState([])
const [peekExercise, setPeekExercise] = useState(null)
const [saveModuleModalOpen, setSaveModuleModalOpen] = useState(false)
const [aiQuickCreateEnabled, setAiQuickCreateEnabled] = useState(false)
const [quickSaving, setQuickSaving] = useState(false)
const [quickAiError, setQuickAiError] = useState('')
const [quickCreateDraft, setQuickCreateDraft] = useState(null)
const {
title: quickTitle,
sketch: quickSketch,
focusAreaId: quickFocusAreaId,
setTitle: setQuickTitle,
setSketch: setQuickSketch,
setFocusAreaId: setQuickFocusAreaId,
} = useExerciseAiQuickCreateFields(debouncedSearch, {
enabled: pageTab === 'list' && (aiQuickCreateEnabled || debouncedSearch.length >= 3),
})
useEffect(() => {
if (!user?.id) return
@@ -151,6 +176,13 @@ function ExercisesListPageRoot() {
loadMore,
} = useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey })
const showQuickCreateOffer =
pageTab === 'list' &&
catalogsReady &&
!listFetching &&
(aiQuickCreateEnabled ||
(exercises.length === 0 && selectedEntries.length === 0 && debouncedSearch.length >= 3))
const selectedIds = useMemo(
() => new Set(selectedEntries.map((e) => Number(e.id)).filter((id) => Number.isFinite(id) && id > 0)),
[selectedEntries]
@@ -304,6 +336,82 @@ 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 }),
)
} 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 +594,27 @@ 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="Neue Übung per KI vorschlagen — Titel, optional Kurzbeschreibung, Fokusbereich"
>
<input
type="checkbox"
checked={aiQuickCreateEnabled}
onChange={(e) => setAiQuickCreateEnabled(e.target.checked)}
/>
<span className="exercises-ai-assistant-toggle__track" aria-hidden="true" />
<span>Neu mit KI-Assistent</span>
</label>
<NavStateLink
to="/exercises/new"
returnContext={exercisesModuleReturnContext}
className="btn btn-primary"
>
+ Neu
</NavStateLink>
</div>
) : (
<span aria-hidden="true" />
)}
@@ -537,6 +659,28 @@ function ExercisesListPageRoot() {
onToggleSelectAllPage={toggleSelectAllPage}
/>
{showQuickCreateOffer ? (
<ExerciseAiQuickCreateOffer
searchLabel={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}
hint={
aiQuickCreateEnabled
? 'Titel aus Suche oder manuell; Kurzbeschreibung optional — leer für freien KI-Vorschlag, ausgefüllt als deine Ausgangsidee.'
: undefined
}
/>
) : null}
<ExerciseListBulkToolbar
selectedCount={selectedIds.size}
bulkMaxIds={BULK_MAX_IDS}
@@ -625,11 +769,15 @@ function ExercisesListPageRoot() {
Lade Übungen…
</p>
</div>
) : exercises.length === 0 && selectedEntries.length === 0 ? (
) : exercises.length === 0 && selectedEntries.length === 0 && !showQuickCreateOffer ? (
<div className="card">
<p className="exercises-empty-text">Keine Übungen gefunden.</p>
<p className="exercises-empty-text">
{debouncedSearch.length >= 3
? 'Keine Übungen gefunden.'
: 'Keine Übungen gefunden — Suchbegriff eingeben oder Filter anpassen.'}
</p>
</div>
) : (
) : exercises.length === 0 && selectedEntries.length === 0 && showQuickCreateOffer ? null : (
<>
{selectedEntries.length > 0 ? (
<section className="exercises-selection-section" data-testid="exercises-selection-section">
@@ -696,6 +844,19 @@ function ExercisesListPageRoot() {
)}
</>
)}
<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>
@@ -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,
}
}
+367
View File
@@ -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&nbsp;%). 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&nbsp;%).
</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>
)
}
+90 -1
View File
@@ -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,64 @@ 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: 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 +523,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 +839,17 @@ export const api = {
updateFocusArea,
deleteFocusArea,
getAdminHierarchy,
listAiSkillRetrievalProfiles,
getAiSkillRetrievalProfile,
createAiSkillRetrievalProfile,
updateAiSkillRetrievalProfile,
deleteAiSkillRetrievalProfile,
listAdminAiPrompts,
getAdminAiPrompt,
updateAdminAiPrompt,
previewAdminAiPrompt,
resetAdminAiPromptTemplate,
getAdminAiPromptPlaceholdersCatalog,
listStyleDirections,
listTrainingStyles,
createStyleDirection,
@@ -805,6 +891,9 @@ export const api = {
exportResolvedMaturityBundle,
exportMatrixStackBundle,
importMatrixStackBundle,
exportMatrixEditorBundle,
exportMatrixEditorCsv,
importMatrixEditorBundle,
resolveMaturityModel,
getMaturityModel,
createMaturityModel,
+303
View File
@@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
/** 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 })
}