160 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 / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #48
2026-05-22 19:51:54 +02:00
Lars 9d880e2346 Enhance Exercise List Page with AI Assistant Toggle and UI Improvements
Test Suite / build-frontend (push) Successful in 16s
Test Suite / pytest-backend (pull_request) Successful in 37s
Test Suite / lint-backend (pull_request) Successful in 1s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
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
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 41s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
- 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
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 36s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m23s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 46s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 44s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #47
2026-05-22 11:56:54 +02:00
Lars e22266a18c Update ACCESS_LAYER_ENDPOINT_AUDIT and Matrix Editor Documentation
Test Suite / build-frontend (push) Successful in 12s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / playwright-tests (pull_request) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m19s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 42s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
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.
Test Suite / build-frontend (push) Successful in 13s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 38s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m30s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / playwright-tests (pull_request) Successful in 1m31s
Test Suite / lint-backend (push) Successful in 0s
2026-05-22 10:29:49 +02:00
Lars 888d0bd009 Update environment configuration for AI debugging support
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 38s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 43s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 41s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 1s
- 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
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 38s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 1s
- 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 / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Has been cancelled
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Failing after 1s
Test Suite / lint-backend (push) Successful in 0s
- 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
Lars a1b85cd865 Merge pull request 'Bug_fixes' (#45) from develop into main
Deploy Production / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #45
2026-05-22 07:16:32 +02:00
Lars 7245bbb1da bug_fix Variantenerzeugung
Test Suite / build-frontend (push) Successful in 12s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / build-frontend (pull_request) Successful in 13s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m35s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m22s
2026-05-22 07:14:03 +02:00
Lars 5f67c01cef Refactor Exercise Visibility Labels for Consistency Across Components
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m17s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / lint-backend (push) Successful in 0s
- Replaced hardcoded visibility labels with the new constant EXERCISE_VISIBILITY_FIELD_LABEL in multiple components, ensuring consistent terminology throughout the application.
- Updated UI text to reflect the change from "Sichtbarkeit" to "Freigabelevel" in various contexts, enhancing clarity for users.
- Improved accessibility by standardizing the visibility-related labels in the ExercisePickerModal, ExerciseProgressionGraphPanel, and other related components.
2026-05-21 15:08:35 +02:00
Lars 4720d70af0 Merge pull request 'Verbesserung UX für Übungen' (#44) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
Reviewed-on: #44
2026-05-21 15:02:15 +02:00
Lars 13a1d3a060 Enhance Exercise Form UI and Functionality with New Tab Structure
Test Suite / build-frontend (push) Successful in 12s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Deploy Development / deploy (push) Successful in 38s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / build-frontend (pull_request) Successful in 15s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m15s
- Introduced a tabbed interface for the exercise form, allowing users to navigate between different sections (Stammdaten, Anleitung, Einordnung, etc.) more intuitively.
- Added new CSS styles for the exercise form, including improved layout and visual differentiation for various sections.
- Implemented dynamic tab management based on exercise type and edit state, enhancing user experience during form interactions.
- Refactored existing components to integrate the new tab structure, ensuring a cohesive design and functionality across the exercise form.
2026-05-21 14:58:14 +02:00
Lars 7f62b6ceee Enhance Exercise Form Functionality with Variant Management Improvements
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / lint-backend (push) Successful in 0s
- Introduced snapshot and dirty check functions for variant payloads, enabling better tracking of unsaved changes.
- Implemented synchronization of saved variant snapshots to improve data integrity during edits.
- Enhanced the variant saving process with validation for variant names and automatic saving of changes.
- Updated the UI to reflect changes in variant management, ensuring a smoother user experience when editing exercise variants.
2026-05-21 14:54:32 +02:00
Lars 9b3f594007 Implement Exercise Form Enhancements with New Meta Panel
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 0s
- Added a new meta panel for exercise classification and target groups, improving the organization of exercise attributes.
- Introduced ExerciseCatalogAssocEditor component to manage focus areas, training styles, and target groups, enhancing user interaction.
- Refactored CSS styles for the new meta panel and associated components, ensuring a cohesive design and improved responsiveness.
- Removed the MultiAssocBlock component to streamline the code and improve maintainability.
2026-05-21 14:40:50 +02:00
Lars 5d308b20ba Add VARIANT_DIFFICULTY constant to ExerciseFormPageRoot component
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new constant, VARIANT_DIFFICULTY, to define difficulty options for exercises.
- Improved code organization by separating the import statements for better readability.
2026-05-21 12:58:18 +02:00
Lars 1d698e4b0a Implement Phase 3 Enhancements for Skill Scoring and Profiles
Test Suite / build-frontend (push) Failing after 3s
Deploy Development / deploy (push) Failing after 22s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added capabilities for weighted skill profiles, allowing trainers to compare training modules, frameworks, and regression paths based on skill contributions.
- Updated the skill scoring specification to include peer context separation and list filtering, ensuring accurate comparisons among visible artifacts of the same type.
- Enhanced the API to support batch summaries for skill profiles and discovery suggestions, improving data retrieval efficiency.
- Refactored frontend components to display skill metrics, including scores and peer percentages, with improved filtering options for better user experience.
- Updated documentation to reflect the latest changes and enhancements in the skill scoring system.
2026-05-21 12:35:45 +02:00
Lars 57c464c9f6 Merge pull request 'KPI-Scroing, Filter, etc,' (#43) from develop into main
Deploy Production / deploy (push) Successful in 1m2s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #43
2026-05-21 10:36:49 +02:00
Lars a7a428745f Enhance SkillTreeMultiSelect Component and CSS Styles
Test Suite / build-frontend (push) Successful in 13s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 48s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m28s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m16s
- Updated the SkillTreeMultiSelect component to support dynamic positioning and improved accessibility through the use of portals.
- Refactored the dropdown panel rendering logic to enhance user experience when selecting skills.
- Added CSS styles for the exercise filter modal to improve layout and responsiveness.
- Introduced new styles for the skill tree multiselect panel, ensuring better visual integration and usability.
2026-05-21 10:31:21 +02:00
Lars 2d187447bb Enhance Framework Programs Filtering and UI Components
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Updated the FrameworkProgramsFilterBlock to include a search input and filter modal, improving user interaction and accessibility.
- Refactored CSS styles for filter components to ensure consistent layout and spacing.
- Removed deprecated panel open state management, streamlining the component logic.
- Integrated new filtering capabilities in the TrainingPlanningFrameworkImportModal and TrainingModulesListPage, enhancing the overall filtering experience.
- Improved the display of active filters and results count, providing clearer feedback to users.
2026-05-21 10:23:05 +02:00
Lars 2de4c0b7c9 Refactor Skill Scoring Functions and Enhance Corpus Handling
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 40s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m17s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 1s
- Introduced new helper functions for managing artifact type corpus, improving code organization and readability.
- Updated the `compute_club_corpus_reference` function to utilize the new corpus handling methods, enhancing clarity and maintainability.
- Refactored skill profile functions to leverage the new corpus structure, ensuring consistent data retrieval across different artifact types.
- Improved the handling of visibility clauses for library content, streamlining database queries for skill profiles.
- Enhanced the batch skill profile summary function to aggregate reference data by artifact type, improving performance and accuracy.
2026-05-21 10:17:22 +02:00
Lars 34966b9e84 Update Skill Profile Summary and Frontend Components
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Modified the `compact_profile_summary` function to allow for dynamic skill and category limits, enhancing flexibility in profile data retrieval.
- Updated frontend components to display skill weights and scores more effectively, improving user interaction with skill metrics.
- Adjusted CSS styles for skill KPI tiles to better differentiate between score and percentage displays, ensuring a clearer visual representation.
- Refactored utility functions to streamline skill summary handling, enhancing overall code maintainability and performance.
2026-05-21 09:42:13 +02:00
Lars 9a0cf7f823 Enhance Skill Scoring and Profile Functionality
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function to calculate club-specific skill percentages, ensuring values are capped at 100%.
- Updated skill profile calculations to include indicators for the best club performance per skill.
- Enhanced frontend components to display club best indicators and improved layout for skill profiles.
- Refactored CSS styles for skill profile components, ensuring a more cohesive and user-friendly interface.
- Updated tests to validate new functionality and ensure accurate representation of skill metrics.
2026-05-21 09:33:20 +02:00
Lars 78c6c51520 Enhance Skill Scoring and Profile Features
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / lint-backend (push) Successful in 0s
- Updated the skill scoring specification to include club-specific metrics and improved aggregation methods for skill profiles.
- Introduced new API endpoints for batch skill profile summaries, allowing for efficient retrieval of compact skill data.
- Enhanced frontend components to display skill profiles with club comparisons, improving user interaction and visibility of skill strengths.
- Added filtering options for skills in the framework programs, enabling users to refine selections based on training weight relative to club maximums.
- Improved CSS styles for skill profile displays, ensuring a cohesive and user-friendly interface across the application.
2026-05-21 09:05:13 +02:00
Lars 5200895a73 Update Skill Scoring Specification and Implementation to v1.2
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m27s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 1s
- Enhanced the skill scoring system with category grouping and a universal scale for improved comparability across programs.
- Introduced new calculations for artifact share percentage and universal percent, allowing for a more nuanced understanding of skill contributions.
- Updated the API to reflect changes in the skill profile structure, including main category and top skill details.
- Improved frontend components to display skills by main category, enhancing user experience in skill discovery and profile visualization.
- Adjusted tests to validate the new scoring logic and ensure accurate representation of skills and their weights.
2026-05-21 08:37:58 +02:00
Lars 8f8bdf6d8b Update Skill Scoring Specification and Implementation to v1.1
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced the skill scoring formula to incorporate intensity and level range factors, improving the accuracy of skill contributions.
- Removed the use of `is_primary` and `development_contribution` from calculations, streamlining the scoring process.
- Updated documentation to reflect changes in the scoring logic and versioning.
- Adjusted frontend components to align with the new scoring criteria, ensuring consistent user experience across the application.
2026-05-21 08:24:23 +02:00
Lars f67bf280c3 Add Skill Profiles API Integration for Phase 3
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 35s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
2026-05-21 08:11:46 +02:00
Lars 732b322c52 Implement Phase 3 Features for Skill Profiles and Discovery
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m27s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Updated the framework program documentation to reflect the completion of Phase 3 v1.0, including new skill scoring and API enhancements.
- Added new API endpoints for skill profile retrieval and suggestions, improving the ability to aggregate and display skills based on training data.
- Introduced new UI components for skill profiles and discovery in the frontend, enhancing user interaction with training frameworks and skills.
- Updated version information to 0.8.151, reflecting the addition of skill profiles and related features.
2026-05-20 16:42:25 +02:00
Lars d42eb3ac52 Merge pull request 'Verbesserung Darstellung Rahmenprogramme' (#42) from develop into main
Deploy Production / deploy (push) Successful in 47s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
Reviewed-on: #42
2026-05-20 16:29:53 +02:00
Lars e382b6ed35 Enhance Training Framework Program Edit Page with New Styling and Structure
Test Suite / build-frontend (push) Successful in 13s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / playwright-tests (pull_request) Successful in 1m16s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new PageFormEditorChrome component for improved layout and user experience.
- Updated CSS styles for the framework editor, including danger zone and delete button hover effects.
- Refactored the TrainingFrameworkProgramEditPage to utilize the new component and streamline the action configuration.
- Enhanced the page title handling for better clarity when creating or editing framework programs.
2026-05-20 16:23:10 +02:00
Lars a4548f5587 Refactor Training Framework Programs List Page with Enhanced Styling and New Utility Functions
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Has been cancelled
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Updated the TrainingFrameworkProgramsListPage to utilize new CSS classes for improved layout and styling.
- Removed deprecated components and functions, streamlining the codebase for better maintainability.
- Introduced utility functions for splitting aggregated strings, enhancing data handling for framework program attributes.
- Enhanced the user interface with loading and empty state indicators, improving overall user experience.
2026-05-20 16:21:16 +02:00
Lars 9d122d4808 Enhance Training Framework Programs List with Filtering and Styling Improvements
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new filter block for training framework programs, allowing users to refine their selections based on focus areas, training types, and target groups.
- Updated the TrainingFrameworkProgramsListPage to integrate the filter block and manage filter states effectively.
- Enhanced CSS styles for the filter block and program list, improving layout and spacing for better user experience.
- Removed unused filter-related logic from the TrainingPlanningFrameworkImportModal, streamlining the component's functionality.
2026-05-20 16:05:18 +02:00
Lars 9c3494a7ea Implement Framework Import Modal with Enhanced Filtering and Styling
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m27s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new modal for importing training framework sessions, featuring a backdrop and panel for improved user experience.
- Added comprehensive filtering options for focus areas, training types, and target groups, utilizing a structured filter state.
- Enhanced session duration handling with distinct duration collection and display, improving clarity in program selection.
- Updated utility functions to support new filtering capabilities and session duration management, ensuring a cohesive user interface.
2026-05-20 15:06:03 +02:00
Lars 9353909fda Enhance Training Framework Programs with Session Duration and Filtering Features
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m29s
Test Suite / lint-backend (push) Successful in 0s
- Added SQL aggregations for session duration (min/max) and goal titles in the training framework programs query.
- Updated the TrainingPlanningFrameworkImportModal component to include filtering options for focus areas, training types, and target groups.
- Implemented session duration display in the TrainingFrameworkProgramsListPage, improving user visibility of program details.
- Introduced utility functions for formatting session duration ranges, enhancing the overall user experience in training planning.
2026-05-20 13:19:40 +02:00
Lars 5a8a212f40 Update version information and add training duration features
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.150 and updated build date and database schema version.
- Introduced new SQL migration for planned duration fields in training units and sections.
- Added functions to handle focus areas and style directions in training framework programs.
- Enhanced training planning components to support planned duration input and display.
- Updated frontend components to manage and display planned duration for training units and sections.
2026-05-20 13:02:09 +02:00
Lars f9df2d31db Merge pull request 'Fähigkeitauswahl verbessert' (#41) from develop into main
Deploy Production / deploy (push) Successful in 46s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #41
2026-05-20 11:24:38 +02:00
Lars ab612a5335 Update Skill Tree Picker and Catalog Functions for Clarity
Test Suite / build-frontend (push) Successful in 12s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m14s
- Modified comments in `SkillTreePickerPanel` and `skillCatalogTree.js` to accurately reflect the default expansion behavior, specifying that only main groups are open by default.
- Refactored `defaultExpandedKeysForSkillTree` to simplify the logic, ensuring only main groups are returned as expanded.
- Adjusted tests in `skillCatalogTree.test.js` to validate the updated behavior, confirming that only main groups are opened in the skill tree.
2026-05-20 11:21:18 +02:00
Lars b2f77ca627 Refactor Skill Tree Picker and Catalog Functions for Clarity and Efficiency
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Simplified the rendering of skill group labels in `SkillTreePickerPanel` for improved readability.
- Updated comments in `skillCatalogTree.js` to clarify the structure of expandable nodes and default expansion behavior.
- Refactored the skill catalog tree building logic to streamline the mapping of categories and skills, enhancing performance and maintainability.
- Adjusted tests in `skillCatalogTree.test.js` to reflect changes in the structure of skill nodes, ensuring accurate validation of functionality.
2026-05-20 11:18:34 +02:00
Lars 39b1fd04f0 Enhance Skills Catalog Admin with Unassigned Skill Handling and Improved Selection Logic
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Has been cancelled
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced utility functions to count skills without main categories and categories, enhancing data management in the Skills Catalog Admin.
- Updated the SkillsCatalogAdmin component to handle unassigned main and category IDs, improving user experience when managing skills.
- Refactored skill selection logic to utilize new utility functions, ensuring accurate filtering of skills based on selected categories and main categories.
- Enhanced the UI to display unassigned skills clearly, improving overall usability and clarity in skill management.
2026-05-20 11:16:49 +02:00
Lars 9020e5eb16 Enhance Skill Tree Components with Improved Group Labeling and Default Expansion
Test Suite / build-frontend (push) Successful in 14s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
- Added CSS styles for skill group labels in the skill tree to improve visual hierarchy and readability.
- Updated `SkillTreePickerPanel` and `SkillTreeMultiSelect` components to utilize the new default expansion logic, ensuring main and category nodes are open by default while skill groups remain collapsed.
- Refactored state management in `SkillTreePickerPanel` to align with the new default expansion behavior.
- Enhanced utility functions to support the new default expansion logic for skill trees.
2026-05-20 11:13:34 +02:00
Lars 46feb4c867 Add defaultCollapsed prop to SkillTree components for improved user experience
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a `defaultCollapsed` prop in `SkillTreeMultiSelect` and `SkillTreePickerPanel` to control the initial expansion state of skill trees.
- Updated `SkillTreeSelect` to accept a `defaultCollapsed` prop, enhancing flexibility in component usage.
- Adjusted state management in `SkillTreePickerPanel` to respect the `defaultCollapsed` setting, improving user interaction with skill selection.
2026-05-20 11:05:27 +02:00
Lars 3067b2e6a8 Implement Skill Tree Selection Components and Update API Calls
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new `SkillTreeSelect` and `SkillTreeMultiSelect` components for enhanced skill selection in various modals and forms.
- Updated API calls to use `listSkillsCatalog` instead of `listSkills` for improved data retrieval.
- Enhanced CSS styles for skill selection components to improve user experience and visual consistency across the application.
2026-05-20 10:59:17 +02:00
Lars 1e2fdeeb0f Merge pull request 'UX Verbesserung, Navigationsspeicherung' (#40) from develop into main
Deploy Production / deploy (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m24s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #40
2026-05-20 10:44:00 +02:00
Lars 728b37ad5f Export PLANNING_HUB_PATH from navReturnContext.js to enhance navigation context management.
Test Suite / build-frontend (push) Successful in 13s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / build-frontend (pull_request) Successful in 13s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m14s
2026-05-20 08:01:53 +02:00
Lars 8afdd811db Refactor full-page editor navigation and update return context handling
Test Suite / build-frontend (push) Failing after 7s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Failing after 23s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m19s
Test Suite / lint-backend (push) Successful in 0s
- Adjusted `PageFormEditorChrome` to set `showReturn` to false by default, making the back button optional.
- Removed `PageReturnButton` from `TrainingFrameworkProgramEditPage`, `TrainingModuleEditPage`, and `TrainingPlanTemplateEditPage` to streamline navigation.
- Updated documentation to reflect changes in editor actions and return context behavior for improved clarity.
2026-05-20 07:56:22 +02:00
Lars 4588ef4c7e Refactor navigation components and enhance return context handling
Test Suite / build-frontend (push) Failing after 7s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Failing after 24s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
- Replaced `PageReturnLink` with `PageReturnButton` for consistent back navigation across various pages.
- Updated multiple components, including `ExercisePeekModal`, `PageFormEditorChrome`, and `ExerciseDetailPage`, to utilize the new return context features.
- Enhanced CSS styles for the new return button to improve visual consistency.
- Improved navigation logic in `TrainingFrameworkProgramEditPage` and `TrainingModuleEditPage` to ensure seamless user experience when navigating back to previous locations.
2026-05-20 07:42:46 +02:00
Lars 6e6270b717 Enhance navigation and return context in exercise and training module components
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m17s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new `PageReturnLink` component for consistent back navigation across pages.
- Updated `SaveSelectedExercisesAsModuleModal` and `SaveExercisesAsModuleModal` to utilize `navigateWithAppReturn`, preserving navigation context when redirecting after saving.
- Enhanced `TrainingModuleEditPage` and `TrainingUnitEditPage` with improved return context handling, allowing users to navigate back to their previous locations seamlessly.
- Added CSS styles for the new return link to improve visual consistency and user experience.
2026-05-20 07:25:05 +02:00
Lars 14b005e9b8 Enhance exercise selection and display features
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new CSS styles for exercise cards and selection sections, improving visual feedback for selected exercises.
- Updated ExerciseListCard to support a new `selectionPinned` prop, allowing for a badge display on selected exercises.
- Refactored selection handling in ExercisesListPageRoot to manage selected entries more effectively, replacing the previous Set-based approach.
- Enhanced SaveSelectedExercisesAsModuleModal to support appending exercises to existing modules, improving module management capabilities.
- Updated session state handling to include selected entries, ensuring persistence across sessions.
2026-05-20 07:03:15 +02:00
Lars ef4dd93324 Enhance exercise card interactivity and toolbar functionality
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- Added clickable behavior to exercise card body, allowing users to navigate to exercise details by clicking anywhere on the card.
- Introduced keyboard accessibility for exercise cards, enabling navigation via Enter and Space keys.
- Updated ExerciseListBulkToolbar to include a new button for saving selected exercises as a module, enhancing bulk action capabilities.
- Improved CSS styles for clickable exercise card body to indicate interactivity.
2026-05-20 06:56:58 +02:00
Lars 7450c269a5 Merge pull request 'Editor Verbesserung für Übungen' (#39) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #39
2026-05-20 06:42:07 +02:00
Lars e50c18f92e Enhance ExerciseFormPageRoot with save and close functionality
Test Suite / build-frontend (push) Successful in 14s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (pull_request) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- Added a new `handleSaveAndClose` function to allow users to save and navigate back to the exercise list.
- Updated `performSaveAttempt` to accept a `closeAfter` parameter for conditional navigation.
- Refactored form submission handling to include separate actions for saving and saving with closure.
- Integrated `PageFormEditorChrome` for improved layout and user experience, including a back navigation option.
2026-05-20 06:38:53 +02:00
Lars d19a1061d8 Enhance exercise listing with variant and media counts
Test Suite / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
- Updated the `list_exercises` function to include counts for exercise variants and media, improving data retrieval for exercise details.
- Added new CSS styles for the exercise card footer to display variant and media statistics in a visually appealing manner.
- Implemented `ExerciseCardContentStats` component to conditionally render variant and media counts, enhancing the user interface of exercise cards.
2026-05-20 06:37:40 +02:00
Lars 99a5fccaa5 Grafische Änderungen (kein Trainingsmodal). Diverse Verwaltungsdialoge
Deploy Production / deploy (push) Successful in 47s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #38
2026-05-19 14:56:41 +02:00
Lars cb868373f4 Enhance PlanningLayout and TrainingUnitEditPage with unsaved changes handling
Test Suite / build-frontend (push) Successful in 13s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / build-frontend (pull_request) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-tests (push) Successful in 1m16s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / playwright-tests (pull_request) Successful in 1m13s
Test Suite / lint-backend (push) Successful in 0s
- Updated PlanningLayout to conditionally render the PlanningRouteNav based on the current path, improving navigation for planning unit editors.
- Enhanced TrainingUnitEditPage with unsaved changes detection, integrating a prompt for users to confirm before leaving the page with unsaved changes.
- Introduced utility functions for creating a stable snapshot of form data to facilitate dirty-checking, ensuring better user experience during form editing.
- Added tests for the new utility functions to validate their behavior in various scenarios.
2026-05-19 14:39:46 +02:00
Lars 472cf1afdb Refactor full-page editor layout and enhance mobile dock functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated CSS styles for the full-page editor, modifying the header to include a back link and title, while fixing the action dock for all viewports.
- Removed the sticky header and integrated the action bar at the bottom for improved usability across devices.
- Simplified the PageFormEditorChrome component by eliminating unnecessary memoization and restructuring the header layout.
2026-05-19 12:55:08 +02:00
Lars 0cb0e81d27 Add AuthContext to App component for authentication management
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 40s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
2026-05-19 12:45:08 +02:00
Lars 6a9351874f Enhance full-page editor layout and integrate form editor actions
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Failing after 6m4s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated CSS styles for the full-page editor, introducing a sticky header and mobile dock for improved navigation.
- Refactored App component to include FormEditorActionsProvider and FormEditorBottomSlot for better form handling.
- Simplified TrainingUnitFormShell by removing the FormActionBar, streamlining the form structure and enhancing usability.
2026-05-19 11:18:54 +02:00
Lars 734d943d73 Implement full-page planning unit editor layout and enhance form behavior
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for the planning unit editor to manage scrolling and layout, ensuring a responsive design.
- Updated the TrainingUnitFormShell component to include new class names for better styling and structure.
- Modified the TrainingUnitEditPage to support the new layout, improving user experience when editing training units.
2026-05-19 11:13:18 +02:00
Lars 16eaf839e7 Enhance frontend testing setup and refactor TrainingPlanningPageRoot component
Test Suite / build-frontend (push) Successful in 19s
Deploy Development / deploy (push) Successful in 44s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
- Added Vitest as a testing framework and included test scripts in package.json for improved testing capabilities.
- Refactored TrainingPlanningPageRoot component by removing unused state variables and imports, streamlining the code for better readability and performance.
- Introduced new utility functions for planning routes to enhance navigation within the training planning interface.
2026-05-19 11:02:03 +02:00
Lars 295c7e7efc Refactor modal components to use FormModalOverlay for improved consistency and functionality
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 42s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Replaced div elements with FormModalOverlay in SaveExercisesAsModuleModal, TrainingPlanningUnitFormModal, and TrainingPublishToFrameworkModal for a unified modal structure.
- Enhanced modal styling and behavior, including adjustments for responsiveness and accessibility.
- Introduced new CSS rules to manage overflow and scrolling behavior when modals are active, improving user experience across devices.
2026-05-19 10:47:44 +02:00
Lars c9175bd2fd Refactor modal components and enhance FormActionBar functionality
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated modal components to utilize a consistent overlay and panel structure, improving layout and responsiveness.
- Enhanced FormActionBar to support short labels for action buttons, improving usability in mobile views.
- Introduced new styling for action buttons and modal titles, ensuring better alignment and visual consistency across forms.
- Improved accessibility by adding aria-labels and titles to buttons for better screen reader support.
2026-05-19 10:20:49 +02:00
Lars f15aa7c415 Update version to 0.8.148 and enhance training plan template functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m7s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Incremented app version to 0.8.148 and updated changelog to reflect new features.
- Improved the training plan template structure by adding a preview of sections, including support for split sessions.
- Introduced a new editing page for training plan templates, allowing users to modify templates directly.
- Enhanced the TrainingPlanningPageRoot to include a description field when saving templates, improving user guidance.
- Updated permissions to allow editing of training plan templates based on user roles.
2026-05-19 10:13:26 +02:00
Lars 1684892bcb Fix layout in TrainingPlanningUnitFormModal by closing the div tag for improved structure and rendering.
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 41s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
2026-05-19 10:05:33 +02:00
Lars 4fee5a2b47 Implement planning layout and enhance training module functionality
Test Suite / build-frontend (push) Failing after 6s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Failing after 23s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added a new PlanningLayout component to manage the training planning interface, allowing for better organization of related pages.
- Introduced a FormActionBar component across various modals and forms to standardize action buttons for saving and canceling.
- Updated the TrainingPlanningPageRoot and TrainingPlanningUnitFormModal to utilize the new FormActionBar for improved user experience.
- Enhanced the TrainingModuleEditPage and TrainingFrameworkProgramEditPage with save and close functionality, streamlining the editing process.
- Refactored existing modals to incorporate the new layout and action bar, ensuring consistency across the application.
2026-05-19 10:02:39 +02:00
Lars 82705f0c3e Update version to 0.8.146 and add changelog entry for new features
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / lint-backend (push) Successful in 0s
- Incremented app version to 0.8.146 and updated changelog to include the new version details.
- Documented the addition of the publish-to-framework feature for training units, enhancing the training planning capabilities.
2026-05-19 09:45:37 +02:00
Lars a51f794945 Update version to 0.8.147 and add functionality to save exercises as training modules
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Has been cancelled
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Failing after 0s
Test Suite / lint-backend (push) Successful in 0s
- Incremented app version to 0.8.147 and updated changelog to reflect the new version.
- Introduced a new modal for saving exercises as training modules within the training planning interface.
- Enhanced the TrainingPlanningPageRoot component to manage the new save module functionality, including state management for the modal.
- Updated the TrainingPlanningUnitFormModal to include an option for saving exercises as a module, improving user experience in training planning.
2026-05-19 09:41:27 +02:00
Lars 7693139242 Update version to 0.8.146 and implement publish-to-framework feature for training units
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 49s
Test Suite / playwright-tests (push) Successful in 1m19s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Incremented app version to 0.8.146 and updated build date to 2026-05-19.
- Added new API endpoint to publish training units as session blueprints to framework programs.
- Introduced frontend functionality to support publishing training units, including a modal for user interaction.
- Updated changelog to reflect the new feature and its associated changes.
2026-05-19 08:51:48 +02:00
Lars 55d87d8d17 Merge pull request 'Fähigkeitsimport verbessert' (#37) from develop into main
Deploy Production / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #37
2026-05-16 11:08:39 +02:00
Lars 623af621b4 Enhance MediaWiki import functionality with category normalization and skill attributes
Test Suite / build-frontend (push) Successful in 12s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m17s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m8s
- Introduced `_normalize_mw_category` function to clean category names for API calls, ensuring consistent handling of category prefixes.
- Updated `SmwClient` methods to utilize normalized category names, improving data retrieval accuracy.
- Added `_wiki_category_or_default` function to provide default categories based on import type, enhancing user experience during imports.
- Integrated new fields `karate_relevance` and `relevance_level` into various admin components, allowing for better skill management.
- Incremented app version to 0.8.145 and updated changelog to reflect these changes.
2026-05-16 11:05:15 +02:00
Lars 949a77fe38 Enhance skill model and import functionality with karate relevance and relevance level
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / lint-backend (push) Successful in 0s
- Added `karate_relevance` and `relevance_level` fields to the SkillCreate and SkillResponse models, allowing for more detailed skill attributes.
- Updated the SMW property mapping to include these new fields, facilitating their integration during data import.
- Implemented parsing logic for relevance levels from Wiki data, ensuring proper handling of values between 1 and 3.
- Modified the upsert and create skill functions to support the new fields, ensuring they are correctly stored and updated in the database.
- Incremented app version to 0.8.143 and updated changelog to reflect these changes.
2026-05-16 10:56:15 +02:00
Lars 0275f76432 Implement RBAC for library content management in club tenancy
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 1s
- Introduced new functions for managing edit, delete, and governance transition permissions for library content, aligning with role-based access control (RBAC) principles.
- Updated existing routers to utilize these new functions, ensuring consistent permission checks across training frameworks, modules, and progression graphs.
- Enhanced visibility and governance handling for training plan templates and library content, improving overall content management and user experience.
- Incremented app version to 0.8.142 and updated changelog to reflect these changes.
2026-05-16 10:53:00 +02:00
Lars bc1790bd82 Refactor section movement logic in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 1s
- Streamlined the section movement process by consolidating validation checks and enhancing the handling of parallel phase indices.
- Improved the overall clarity and efficiency of the section management functionality, ensuring a smoother user experience during edits.
2026-05-16 09:04:09 +02:00
Lars b35a5ae216 Merge pull request 'SplitSession auch für Rahmenprogramme' (#36) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #36
2026-05-16 09:02:51 +02:00
Lars 8c07cf36ee Enhance section movement functionality in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 13s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m8s
- Updated the onMoveSectionsAcrossSlots function to support additional parameters for improved section movement across slots, including handling for parallel phase indices and insertion points.
- Refined logic for moving sections between slots, ensuring proper handling of parallel streams and enhancing the overall section management experience.
2026-05-16 08:34:30 +02:00
Lars 7d2661a8e8 Remove redundant boundary checks for section movement in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 1s
- Eliminated the checks that prevented section movement across slots when crossing the boundary between 'parallel' and 'whole_group' phases, streamlining the section management logic and improving code clarity.
2026-05-16 08:17:35 +02:00
Lars 0fdee610ed Enhance section movement validation in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Added a new check to prevent section movement across slots that crosses the boundary between 'parallel' and 'whole_group' phases, improving the logic for section management and ensuring valid operations during edits.
2026-05-16 08:09:24 +02:00
Lars f1c470a8a3 Improve section movement validation in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
- Added a check to ensure that the source slot is not the same as the target slot when moving sections across slots, enhancing the logic for section management and preventing unnecessary operations.
2026-05-16 08:05:10 +02:00
Lars 736656bde8 Refactor enrichFrameworkSlotSections to improve section handling in training framework
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated the enrichFrameworkSlotSections function to utilize default sections when no sections are provided, enhancing data integrity.
- Simplified the normalization process by directly using base sections, improving code clarity and maintainability.
2026-05-16 07:53:05 +02:00
Lars e441f59bff Add delete functionality for training plan templates
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
2026-05-16 07:45:53 +02:00
Lars c3eb5a62c4 Update version to 0.8.141 and enhance training plan template handling
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Incremented app version to 0.8.141 and updated build date to 2026-05-14.
- Modified the planning module version to 0.12.0, improving template section handling with phase metadata.
- Introduced new functions for normalizing and inserting training plan template sections, ensuring accurate phase representation during saves.
- Updated frontend components to utilize new utility functions for managing training plan templates, enhancing user experience and data integrity.
2026-05-16 07:41:08 +02:00
Lars 79e748b470 Refactor phase handling in training unit sections for improved data integrity
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / lint-backend (push) Successful in 0s
- Introduced canonicalization for plan locations in phased saves to ensure consistent phase representation.
- Enhanced the `inheritPlanLocForPhasedSave` function to utilize the new canonicalization logic, improving data flow.
- Updated payload building logic to check for canonicalized plan locations, ensuring accurate phase detection during saves.
2026-05-16 07:35:35 +02:00
Lars 88c4201f80 Refactor training framework to improve phase management and user experience
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced phase handling in training unit hydration and insertion processes, ensuring better data integrity.
- Updated frontend components to support phase representation in training framework slots.
- Improved user interface controls for managing parallel phases, optimizing user experience during training program edits.
- Refactored payload building functions to accommodate phase adjustments, enhancing save functionality for training plans.
2026-05-16 07:27:18 +02:00
Lars 6e1cc62065 Enhance training framework with phase handling and payload adjustments
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 1s
- Updated backend logic to include phases in training unit hydration and insertion processes, improving data integrity.
- Modified frontend components to support phases in training framework slots, ensuring consistent data representation.
- Refactored payload building functions to accommodate phases, enhancing the save functionality for training plans.
- Improved user interface to enable controls for parallel phases, optimizing the user experience during training program edits.
2026-05-16 07:02:12 +02:00
Lars 76cc81a385 Update project documentation and enhance training features for parallel streams
Test Suite / build-frontend (push) Successful in 20s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated CLAUDE.md and PROJECT_STATUS.md to reflect the latest app version (0.8.140) and database schema (20260515063) as of 2026-05-14.
- Enhanced DOMAIN_MODEL.md and PARALLEL_TRAINING_STREAMS_CONCEPT.md to clarify the implementation of phases and parallel streams in training units.
- Improved HANDOVER.md with detailed descriptions of the coaching and breakout functionalities, including rejoin logic and session management.
- Updated FACHLICHE_NUTZERFUNKTIONEN.md to include new features related to training planning and execution, emphasizing the integration of phases and parallel streams.
- Revised FEATURES_DELIVERED_2026-Q2.md to document the latest changes and improvements in the training framework and media management.
2026-05-15 22:11:05 +02:00
Lars bd9cfaa6e4 Merge pull request 'Parlellsession- Plan' (#35) from develop into main
Deploy Production / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #35
2026-05-15 22:04:52 +02:00
Lars a4f11a8225 Enhance TrainingCoachPage and trainingPlanUtils with split rejoin transition logic
Test Suite / build-frontend (push) Successful in 13s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m20s
- Introduced a new utility function to determine when to prompt for a split rejoin transition between phases, improving user guidance during training sessions.
- Updated TrainingCoachPage to incorporate this logic, enhancing the flow of navigation through training timelines.
- Refactored button actions to provide clearer options for users when managing group transitions, optimizing the user experience during training.
2026-05-15 18:52:27 +02:00
Lars 5e5350d5ac Enhance TrainingCoachPage and trainingPlanUtils with session storage management and phase handling improvements
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function in TrainingCoachPage to clear session storage for coach steps, improving state management during training sessions.
- Updated the sectionsWithPlanLocForDisplay function in trainingPlanUtils to include logic for determining the maximum phase order index, enhancing phase handling.
- Enhanced the mapping of sections to include default plan locations for parallel phases, optimizing data representation and user experience.
2026-05-15 17:01:00 +02:00
Lars 73ac2218c7 Enhance TrainingCoachPage and trainingPlanUtils with split rejoin functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated TrainingCoachPage to implement a prompt for users to rejoin parallel phases, improving user guidance during training sessions.
- Refactored step management logic to ensure accurate navigation through the timeline, utilizing safe step calculations.
- Introduced new utility functions in trainingPlanUtils for building save payloads and determining when to prompt for split rejoin, optimizing data handling.
- Enhanced state management for split rejoin prompts, ensuring a seamless user experience during training.
2026-05-15 16:49:05 +02:00
Lars 352237bbb9 Refactor TrainingCoachPage and TrainingUnitRunPage to enhance coach branching functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
- Updated TrainingCoachPage to implement branching logic for coach steps, allowing for improved navigation through training phases.
- Enhanced session storage handling to manage branch picks and streamline state management during training sessions.
- Modified TrainingUnitRunPage to update links for coaching views, reflecting the new branching structure and improving user experience.
- Introduced new utility functions in trainingPlanUtils for managing coach branch picks and timeline navigation, optimizing data handling across components.
2026-05-15 16:31:54 +02:00
Lars 4cf7133bce Enhance TrainingCoachPage and TrainingUnitRunPage with improved coach focus handling and UI updates
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated TrainingCoachPage to incorporate coach focus parameters from search queries, allowing for more precise control over displayed training streams.
- Refactored session storage handling to better manage state related to coach focus, ensuring accurate step tracking during training sessions.
- Enhanced TrainingUnitRunPage with improved layout for stream titles and added links for direct navigation to coaching views, improving user experience.
- Introduced new utility functions in trainingPlanUtils for managing coach stream focus options and duration overrides, streamlining data handling across components.
2026-05-15 16:08:01 +02:00
Lars c182ced7cd Refactor TrainingUnitRunPage and trainingPlanUtils for improved section handling
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m26s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated TrainingUnitRunPage to utilize new utility functions for managing sections with plan locations, enhancing data representation.
- Refactored trainingPlanUtils to introduce functions for building view models from sections and for displaying sections with plan locations, streamlining the data flow.
- Improved logic for handling phase runs and section indices, ensuring accurate representation of training units during rendering.
2026-05-15 14:00:46 +02:00
Lars 5338871f36 Enhance TrainingCoachPage and TrainingUnitRunPage with improved context display and print functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Updated TrainingCoachPage to include coach context in timeline entries and section titles, enhancing clarity for users.
- Refactored TrainingUnitRunPage to support printing options for parallel streams, allowing for better organization during printouts.
- Introduced new CSS styles for page breaks and layout adjustments in app.css, improving print formatting for training plans.
- Enhanced utility functions in trainingPlanUtils.js to support new phase and stream management features, streamlining data handling.
2026-05-15 12:21:08 +02:00
Lars 3005f1cb3e Refactor TrainingUnitSectionsEditor to support new parallel stream functionality
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- Renamed functions and parameters to clarify the handling of sections within parallel streams, enhancing code readability.
- Updated drag-and-drop event handlers to accommodate additional parameters for managing sections in parallel streams.
- Introduced a new utility function to reorder sections as the first entry in a parallel stream, improving section management.
- Enhanced the visual representation of drop zones for sections, ensuring a better user experience during reordering operations.
2026-05-15 12:10:44 +02:00
Lars 72e8f31cff Enhance TrainingUnitSectionsEditor with new drag-and-drop functionality for parallel phases
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Added new event handlers for drag-and-drop operations to manage sections above and below split headers in parallel phases.
- Implemented utility functions to reorder sections as whole groups or as the first entry in parallel phases, improving section management.
- Updated CSS styles to visually represent new drop zones for sections, enhancing user experience during reordering.
- Refactored existing logic to accommodate new features and ensure proper handling of section placements within parallel streams.
2026-05-15 10:59:30 +02:00
Lars 73975d3402 Enhance TrainingUnitSectionsEditor and TrainingFrameworkProgramEditPage with parallel stream support
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
- Updated the TrainingUnitSectionsEditor to include additional parameters for moving sections across slots, allowing for better handling of parallel streams.
- Improved the removeSection function to ensure proper reordering and handling of sections in parallel phases.
- Enhanced the moveSectionsAcrossFrameworkSlots function to apply changes to sections when moved into parallel streams, ensuring accurate updates.
- Refactored the reorderBlocksImmutableWithPlanLoc function to accommodate new logic for managing phase orders and section types during reordering.
2026-05-15 10:21:15 +02:00
Lars 4902771772 Enhance TrainingUnitSectionsEditor with improved section visibility logic
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Added logic to determine visibility of drop bands for sections in parallel phases, enhancing user experience during reordering.
- Updated the reorderBlocksImmutableWithPlanLoc function to better handle plan location adjustments based on section types and their positions.
- Improved handling of section indices for parallel streams, ensuring accurate representation of active streams and their corresponding sections.
2026-05-15 10:14:17 +02:00
Lars c2efbee4ee Implement drag-and-drop functionality for parallel stream sections in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 1s
- Added new CSS styles for visual feedback during drag-and-drop operations, enhancing user experience.
- Introduced logic to manage section drops into parallel streams, allowing for intuitive reordering of sections.
- Implemented utility functions to facilitate the movement of sections within parallel streams, ensuring proper plan location adjustments.
- Updated the TrainingUnitSectionsEditor component to utilize the new drag-and-drop features, improving overall functionality and usability.
2026-05-15 09:10:54 +02:00
Lars 514b64682c Implement visual enhancements and logic for section drop bands in TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Added CSS styles for visual representation of section drop bands, differentiating between split and whole group regions.
- Introduced a new function to determine the appropriate drop band class based on section types, improving user experience during section reordering.
- Enhanced drag-and-drop functionality to support parallel phase management, allowing for more intuitive section placement within the editor.
- Updated utility functions to handle the movement of parallel phase runs, ensuring proper plan location adjustments during reordering.
2026-05-15 08:37:16 +02:00
Lars a0a0be8bef Enhance TrainingUnitSectionsEditor with advanced phase management features
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new utility functions for managing phase runs, including the ability to swap adjacent phase runs and move phase runs up or down by their order.
- Updated the TrainingUnitSectionsEditor to incorporate these new functions, allowing for improved reordering of sections within parallel phases.
- Enhanced the moveSection logic to support movement across different phase types, ensuring better user experience when managing sections.
- Refactored the reorderBlocksImmutable function to accommodate plan location adjustments during section reordering, improving overall functionality.
2026-05-15 08:20:43 +02:00
Lars 613fedfaff Refactor training phase handling in backend and enhance TrainingUnitSectionsEditor
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m7s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 1s
- Updated the backend logic to ensure strict ordering of phase indices, preventing UNIQUE constraint violations when phases are duplicated.
- Enhanced the TrainingUnitSectionsEditor component with new state management for editing phase titles and stream names, improving user interaction.
- Implemented conditional rendering for input fields to facilitate inline editing of phase titles and stream names, streamlining the editing process.
2026-05-15 08:02:18 +02:00
Lars 2e761161ef Enhance TrainingUnitSectionsEditor with new section management features
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 37s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m7s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced functions to add and manage parallel phases and sections, allowing for more flexible training unit configurations.
- Implemented logic to handle the addition of whole group sections and parallel streams, improving the user experience in the editor.
- Added utility functions for reordering sections and checking for content within parallel stream buckets.
- Updated state management to ensure proper handling of section titles and removal of streams, enhancing overall functionality.
2026-05-15 07:50:16 +02:00
Lars 0a203aaf75 Enhance TrainingUnitSectionsEditor with parallel phase management features
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m10s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced logic to limit the number of streams per parallel phase, ensuring compliance with the defined maximum.
- Added utility functions for managing stream indices and visual representation of streams.
- Implemented section movement within parallel streams, allowing for reordering while maintaining stream integrity.
- Updated UI components to reflect changes in stream handling, including disabling buttons when limits are reached.
- Enhanced state management for parallel stream tabs, improving user experience in navigating between streams.
2026-05-15 07:37:51 +02:00
Lars f50e9db523 chore(version): update version and changelog for release 0.8.140
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.140 and updated the changelog to reflect recent changes.
- Enhanced the Training Planning Module with new controls for managing whole group and parallel phases, including the ability to add streams to existing parallel phases.
- Introduced utility functions for handling phase and stream configurations, improving the overall structure and usability of the training unit sections editor.
- Updated the TrainingPlanningUnitFormModal to support the new phase controls, ensuring seamless integration with the frontend components.
2026-05-15 07:25:59 +02:00
Lars 749c185e3d chore(version): update version and changelog for release 0.8.139
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.139 and updated the changelog to reflect recent changes.
- Enhanced the Training Planning Module to support new phase handling, including improved labeling for sections in the editor.
- Updated the API payload structure to accommodate parallel streams and phases, ensuring better integration with the frontend components.
- Refactored utility functions for improved clarity and maintainability in handling training unit sections and phases.
2026-05-15 07:12:43 +02:00
Lars 214f90d39b chore(version): update version and changelog for release 0.8.138
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.138 and updated the changelog to reflect recent changes.
- Enhanced training unit planning with support for POST/PUT requests including phases and parallel streams.
- Fixed role assignment validation for stream co-trainers and added integration tests for phase handling.
- Updated the training planning API to improve data structure and retrieval for nested phases and sections.
2026-05-15 07:04:24 +02:00
Lars 0d34c0a73d Update pytest configuration and documentation for training planning integration
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 38s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced the pytest workflow in `.gitea/workflows/test.yml` to include `TRAINING_PLANNING_INTEGRATION` for improved testing against the PostgreSQL database.
- Updated `pytest.ini` to clarify integration marker usage, specifying both `ACCESS_LAYER_INTEGRATION` and `TRAINING_PLANNING_INTEGRATION`.
- Revised documentation in `test_training_planning_sections_integration.py` to provide clearer activation instructions for local and CI environments.
2026-05-14 22:35:12 +02:00
Lars ae51d201bc chore(version): update version and changelog for release 0.8.137
Test Suite / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Test Suite / playwright-tests (push) Waiting to run
Test Suite / pytest-backend (push) Waiting to run
Test Suite / lint-backend (push) Waiting to run
- Bumped APP_VERSION to 0.8.137 and updated the changelog to reflect recent changes.
- Introduced Migration 063 for training unit phases and parallel streams, enhancing the structure of training units.
- Updated the training planning API to support nested phases and sections, improving data retrieval for UI components.
- Enhanced section handling to accommodate new phase and stream structures, ensuring compatibility with existing workflows.
2026-05-14 22:35:02 +02:00
Lars 220a16429c Enhance training unit sections handling and documentation for parallel training streams
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Updated the backend to improve the fetching and insertion of training unit sections, including a new function for handling section items.
- Added documentation notes regarding the unique constraint on `training_unit_sections` and the implications for parallel training streams.
- Updated frontend components and utility functions to reflect changes in the training planning API and to prepare for future enhancements related to parallel streams.
2026-05-14 22:24:55 +02:00
Lars e759076a6c chore(version): update version and changelog for release 0.8.136
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.136 and updated the changelog to reflect recent changes.
- Fixed the Mandanten-Header handling in `api/exercises.js` for improved API requests.
- Continued Frontend Phase 4 with the addition of the `exercises.js` module, enhancing the API structure.
- Updated architecture documentation to include details on the new `exercises.js` API and its integration with the existing client structure.
- Enhanced `utils/api.js` to re-export the new exercises module, streamlining API access.
2026-05-14 21:49:56 +02:00
Lars 8175e239b4 chore(version): update version and changelog for release 0.8.134
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.134 and updated the changelog to reflect recent changes.
- Continued Frontend Phase 4 with the introduction of the `frontend/src/api/planning.js` module for training planning.
- Updated architecture documentation to include details on the new `planning.js` API and its integration with the existing client structure.
- Enhanced `utils/api.js` to re-export the new planning module, streamlining API access.
2026-05-14 21:39:45 +02:00
Lars 8f5af49a6f chore(version): update version and changelog for release 0.8.133
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 38s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m21s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.133 and updated the changelog to reflect recent changes.
- Initiated Frontend Phase 4 Welle 1, introducing a centralized HTTP client in `frontend/src/api/client.js` while maintaining `utils/api.js` as a facade.
- Documented the changes in the architecture roadmap and README for clarity on the new API structure.
2026-05-14 21:31:04 +02:00
Lars e7dc6a6cd3 chore(version): update version and changelog for release 0.8.132
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.132 and updated the changelog to reflect recent changes.
- Removed unused imports and refactored the ExerciseFormPage, ExercisesListPage, and TrainingPlanningPage for improved code clarity and maintainability.
- Enhanced the overall structure of the components by eliminating redundant code and optimizing imports.
2026-05-14 16:14:26 +02:00
Lars e09a2284e9 chore(version): update version and changelog for release 0.8.131
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.131 and updated the changelog to reflect recent changes.
- Added the TrainingPlanningUnitFormModal component to the TrainingPlanningPage for enhanced training unit management.
- Refactored frameworkLineageText utility function for better code organization and reusability in the training planning context.
- Updated BASELINE_SNAPSHOT documentation to include new metrics and logging details for k6 health checks.
2026-05-14 16:02:54 +02:00
Lars b0faa4bfab chore(version): update version and changelog for release 0.8.130
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.130 and updated the changelog to reflect recent changes.
- Fixed PUT/POST for training_units to handle assistant_trainer_profile_ids as JSONB using psycopg2.extras.Json, resolving a ProgrammingError during co-assignment.
2026-05-14 15:40:45 +02:00
Lars a1a3f2e0a1 chore(version): update version and changelog for release 0.8.129
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.129 and updated the changelog to reflect recent changes.
- Added the TrainingPlanningTrainerAssignModal component to the TrainingPlanningPage for enhanced trainer assignment functionality.
- Implemented new callback functions for managing lead trainer and assistant assignments in the training planning process.
2026-05-14 15:32:21 +02:00
Lars 45bc049c0d chore(version): update version and changelog for release 0.8.128
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 1m7s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.128 and updated the changelog to reflect recent changes.
- Added the TrainingPlanningModuleApplyModal component to the TrainingPlanningPage for enhanced training module application functionality.
- Implemented a new callback function onModuleApplySectionIndexChange to manage module application section index changes.
2026-05-14 13:44:37 +02:00
Lars e4e362b0a9 chore(version): update version and changelog for release 0.8.126
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m30s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.126 and updated the changelog to reflect recent changes.
- Added the TrainingPlanningFrameworkImportModal component to the TrainingPlanningPage for improved training session management.
- Implemented a new Playwright test to verify the functionality of the framework import dialog in the training planning page.
2026-05-14 13:26:02 +02:00
Lars 300d916fad chore(version): update version and changelog for release 0.8.125
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m12s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.125 and updated the changelog to reflect recent changes.
- Added new tests for the dashboard API to ensure proper HTTP 200 responses when inner lists are mocked.
- Enhanced the ExerciseListBulkToolbar component with a data-testid for improved testing capabilities.
- Refactored the TrainingPlanningPage by extracting utility functions to trainingPlanningPageHelpers for better code organization.
2026-05-14 12:48:33 +02:00
Lars 1631bd2e02 chore(version): update version and changelog for release 0.8.124
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 39s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 1s
- Bumped APP_VERSION to 0.8.124 and updated the changelog to reflect recent changes.
- Introduced the ExerciseListBulkToolbar component in ExercisesListPage for improved bulk action handling.
- Enhanced the user interface for selecting and managing exercises in bulk.
2026-05-14 12:30:04 +02:00
Lars 639392e133 Merge pull request 'Bug Fix Dashboard + Performance Phase 3a' (#34) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #34
2026-05-14 11:51:53 +02:00
Lars 2e105a99b8 chore(version): update version and changelog for release 0.8.123
Test Suite / build-frontend (push) Successful in 12s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Deploy Development / deploy (push) Successful in 41s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / build-frontend (pull_request) Successful in 12s
Test Suite / playwright-tests (push) Successful in 1m2s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m1s
- Bumped APP_VERSION to 0.8.123 and updated the changelog to reflect recent changes.
- Fixed internal calls in GET /api/dashboard/kpis to use unwrap_query_default, preventing 500 errors due to FastAPI query defaults.
- Enhanced list_exercises and list_training_units functions to utilize unwrap_query_default for improved query handling.
- Added unit tests for unwrap_query_default to ensure correct behavior in various scenarios.
2026-05-14 11:48:11 +02:00
Lars 4235246cd7 chore(version): update version and changelog for release 0.8.122
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.122 and updated the changelog to reflect new features.
- Integrated useExerciseListCatalogsAndQuery hook in ExercisesListPage for improved exercise list management and data fetching.
- Enhanced documentation to include new concepts for parallel training streams and their technical specifications.
- Updated DOMAIN_MODEL and related technical specs to clarify the structure and functionality of training streams within units.
2026-05-14 11:21:09 +02:00
Lars 57a8957c93 chore(version): update version and changelog for release 0.8.121
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.121 and updated the changelog to reflect new features.
- Introduced the ExerciseListFilterModal and ExerciseListBulkModal components, enhancing the exercise list functionality.
- Modularized the ExerciseListPage to improve code organization and maintainability.
- Added Playwright tests for the filter dialog functionality, ensuring proper user interaction and visibility.
2026-05-14 10:58:41 +02:00
Lars d153a22545 Merge pull request 'Bug Fixing Kombi-Übungen - Performance Update 1 (Phase 0-2)' (#33) from develop into main
Deploy Production / deploy (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 32s
Test Suite / playwright-tests (push) Successful in 58s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #33
2026-05-14 09:09:55 +02:00
Lars 930a786315 refactor(ui): enhance styling and structure of training unit sections and combination plan bracket
Test Suite / build-frontend (push) Successful in 12s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / build-frontend (pull_request) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m5s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m8s
- Updated CSS for training unit sections to improve layout and responsiveness, ensuring combo planning strips are displayed correctly.
- Refactored CombinationPlanBracket component to accept additional class names for better customization.
- Removed unused functions and streamlined imports in TrainingUnitSectionsEditor for cleaner code.
- Reintroduced ExercisePickerModal with improved placement in ExerciseFormPage for better user experience.
2026-05-14 09:05:15 +02:00
Lars 9da29a2231 chore(version): update version and changelog for release 0.8.119
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m2s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.119 and updated the changelog to reflect new features.
- Introduced the ExerciseListCard component and implemented lazy loading for the Progression Tab using React's Suspense.
- Enhanced the ExercisePickerModal with virtualization for improved performance using @tanstack/react-virtual.
- Updated documentation to reflect the new app version and its corresponding changes.
2026-05-14 08:59:06 +02:00
Lars b06d026dd0 chore(version): update version and changelog for release 0.8.118
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.118 and updated DB_SCHEMA_VERSION to 20260514062.
- Enhanced the dashboard API with a new endpoint that consolidates training home data, allowing for a single request to retrieve upcoming training sessions, planned sessions with notes, and review pending items.
- Updated the frontend Dashboard component to utilize the new API structure, improving data loading efficiency and user experience.
- Added migration details and changelog entries to reflect the latest changes and improvements.
2026-05-14 08:53:09 +02:00
Lars 32ba008660 chore(version): update version and changelog for release 0.8.117
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m2s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.117 and updated DB_SCHEMA_VERSION to 20260514061.
- Enhanced the training units API with optional keyset pagination, allowing for more efficient data retrieval.
- Updated the changelog to reflect the new features and improvements, including changes to the frontend API integration for training units.
- Adjusted documentation to align with the new app version and its corresponding changes.
2026-05-14 08:44:59 +02:00
Lars 657fcc241a chore(version): update version and changelog for release 0.8.116
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m0s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.116 and updated the changelog to reflect changes, including the implementation of a new loading strategy for the Org-Inbox that utilizes requestIdleCallback to optimize API calls during dashboard initialization.
- Updated documentation to reflect the new app version and its corresponding changes.
2026-05-14 08:36:31 +02:00
Lars c69edc6952 feat(ci): refactor Gitea workflow to separate k6 health baseline tests
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m5s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new job `k6-health-baseline` in the Gitea CI workflow to run health checks independently from Playwright tests, enhancing clarity and organization.
- Updated documentation to reflect the changes in the CI pipeline, specifying the execution order and purpose of each job.
- Adjusted environment variables and health check logic for both development and production modes, ensuring accurate testing conditions.
2026-05-14 08:32:26 +02:00
Lars 789b640ad0 chore(version): update version and changelog for release 0.8.115
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 1m28s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.115 and updated the changelog to reflect changes, including the introduction of keyset pagination for the GET /api/exercises endpoint.
- Enhanced the exercises router to support cursor-based pagination using cursor_updated_at and cursor_id, improving performance and user experience.
- Updated frontend components to utilize the new pagination method, removing offset-based loading logic.
2026-05-14 08:24:47 +02:00
Lars 14cf8a1a53 feat(tests): enhance smoke test for exercise navigation
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m42s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Added a check to ensure the loading spinner is not visible before navigating to the exercises page, improving test reliability.
- Updated navigation logic to wait for both the URL change and the click event on the exercises link, reducing race conditions.
- Modified the assertion to check for the visibility of the main heading on the exercises page, ensuring stricter validation of page load success.
2026-05-14 08:17:15 +02:00
Lars ea4c1f87f6 chore(version): update version and changelog for release 0.8.114
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Failing after 1m31s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.114 and updated DB_SCHEMA_VERSION to 20260514060.
- Added changelog entry for version 0.8.114, detailing migration 060 for exercise scaling and indexing improvements.
2026-05-14 08:06:39 +02:00
Lars 2fa1db55fd chore(version): update version and changelog for release 0.8.113
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m29s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.113 and updated DB_SCHEMA_VERSION to 20260514059.
- Added changelog entry for version 0.8.113, detailing migration 059 for training unit sorting without framework_slot_id.
2026-05-14 08:02:49 +02:00
Lars 75ddd06d6a chore(version): update version and changelog for release 0.8.112
Test Suite / build-frontend (push) Waiting to run
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 37s
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
- Bumped APP_VERSION to 0.8.112 and updated DB_SCHEMA_VERSION to 20260514058.
- Added changelog entry for version 0.8.112, detailing migration 058 for exercise sorting indices.
2026-05-14 08:01:52 +02:00
Lars 597486bef1 feat(dashboard): add GET /api/dashboard/kpis endpoint and integrate into frontend
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m32s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Implemented a new API endpoint for retrieving dashboard KPIs, providing a consolidated overview of drafts, personal exercises, and year-to-date completed units.
- Updated the Dashboard component to utilize the new endpoint, enhancing data retrieval efficiency and user experience.
- Added a helper function in the exercises router for programmatic access to exercise listings.
- Updated versioning and changelog to reflect the addition of the dashboard feature.
2026-05-14 07:47:27 +02:00
Lars ebad8025f4 fix(ci): update k6 installation script to support multiple architectures
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m30s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 1s
- Modified the k6 installation script in the Gitea CI workflow to dynamically select the appropriate binary for linux-amd64 or linux-arm64 based on the system architecture.
- Updated README.md to reflect the changes in architecture handling for k6 installation, providing clearer guidance for users on different platforms.
2026-05-14 07:03:37 +02:00
Lars c7650cac2f feat(ci): integrate k6 health baseline testing into Gitea workflow
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 5s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added a new job to the Gitea CI workflow to install k6 and run health baseline tests after the health wait period.
- Updated documentation to reflect the automatic execution of k6 in the CI pipeline and clarified local execution instructions.
- Enhanced architecture documentation to indicate the completion of Phase 0 for the pipeline part, with k6 running after each relevant deploy.
2026-05-14 06:56:50 +02:00
LarsandClaude Sonnet 4.6 4b2848c7c3 feat(docs): add performance baseline documentation and update architecture references
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new section for the Performance-Baseline in CLAUDE.md and updated HANDOVER.md to include references to the new BASELINE_SNAPSHOT.md.
- Enhanced architecture documentation in README.md to clarify the purpose of the baseline snapshot and its relevance to the refactor roadmap.
- Refactored OrgInboxContext to implement a unified loading logic for join requests and content reports, improving code maintainability and performance.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 06:53:37 +02:00
Lars 255fa45e90 feat(tests): add E2E test for Dashboard API budget and update documentation
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new E2E test to validate API call counts for `/api/profiles/me` and `/api/training-units` after reloading the Dashboard, ensuring compliance with refactor phase requirements.
- Updated architecture documentation to include details about the new test and its execution within the CI pipeline.
2026-05-14 06:49:15 +02:00
LarsandClaude Sonnet 4.6 7043addd15 feat(docs): update architecture documentation references and enhance handover details
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added references to the architecture target image, refactor roadmap, and binding Shinkan rules in CLAUDE.md and HANDOVER.md for better project clarity.
- Updated the Dashboard component to improve user authentication handling and optimize data loading, enhancing overall performance and user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 06:42:13 +02:00
LarsandClaude Sonnet 4.6 1c268555f6 feat(App): implement code-splitting for improved performance and user experience
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Refactored the App component to utilize React's lazy loading for page components, enhancing load times and performance.
- Introduced a fallback UI with a spinner during component loading, improving user feedback during navigation.
- Updated the AuthContext to use useCallback and useMemo for optimized performance in login and logout functions, reducing unnecessary re-renders.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 22:10:02 +02:00
224 changed files with 40167 additions and 9691 deletions

No files matched your search

+18 -11
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-12
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
**Stand:** 2026-05-14
**Version (Code):** 0.8.140 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260515063` (`backend/version.py`, DB_SCHEMA_VERSION)
**Branch:** develop
---
@@ -15,7 +15,7 @@
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
@@ -36,7 +36,8 @@
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
4. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
4. **Breakout / Coaching (Arbeitspaket):** Backend-Konsistenz `phases`↔`sections`, Run-UI vs. Spec (Stream-Tabs), Vorlagen phasenfähig, E2E-Smoke — siehe **`docs/HANDOVER.md`** (Tabelle „Coaching & Breakout“).
5. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
---
@@ -82,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)
@@ -92,6 +95,8 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
- [x] **Trainingsrahmenprogramm Bibliothek** (Ziele, Slots, Kontext) + **Slot‑Blueprints** in `training_units` (036–037)
- [x] **Materialisierung** aus Rahmen‑Slot (`POST …/training-units/from-framework-slot`; UI‑Anbindung optional)
- [x] **Phasenmodell & parallele Streams** pro Einheit (Migration **063**): `training_unit_phases`, `training_unit_parallel_streams`; GET mit **`phases`** + flachen **`sections`**; PUT mit **`phases`** (App **0.8.137–0.8.140**)
- [x] **Coaching-Modus** für Breakout: Timeline mit Split-Wahl, Rejoin vor Ganzgruppe/nächstem Split, Nachbereitung speichern → Plan & Ablauf (`TrainingCoachPage`, `trainingPlanUtils.js`)
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
**MediaWiki Import:**
@@ -101,6 +106,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
**Skills-System:**
- [x] Hierarchisches Schema, Fokusbereich-Zuordnung, Exercise-Skill mit Levels
- [x] **Gewichtetes Fähigkeiten-Profil (Phase 3):** Module, Rahmenprogramme, Regressionspfade; Peer-Kontext getrennt; Listen-Filter + Discovery — **`technical/SKILL_SCORING_SPEC.md`**
**Admin-UI:**
@@ -155,18 +161,19 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
| Dokument | Pfad | Stand | Status |
|----------|------|-------|--------|
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-12 | neu, Ist-Überblick |
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-12 | Verweis Version siehe `version.py` |
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-14 | Phasen/Coach/Rejoin |
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-14 | §11a Breakout |
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-14 | Parallele Streams Ist 063 |
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
| Parallele Streams (Fach/Technik) | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | 2026-05-14 | Ist-Stand P1 teils |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-14 | Keyset, KPIs, Breakout/Coach Kurzverweis |
---
@@ -177,4 +184,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
---
**Letzte Aktualisierung:** 2026-05-12 (Version 0.8.96, Executive Summary P-13/P-01, `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
**Letzte Aktualisierung:** 2026-05-14 (Version 0.8.140, DB 063, Handover Coaching/Breakout)
@@ -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.
+47 -11
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo - Fachliches Domänenmodell
**Version:** 0.4.5
**Stand:** 2026-05-12 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
**Version:** 0.4.6
**Stand:** 2026-05-14 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
---
@@ -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)
@@ -407,10 +407,9 @@ skill_level_definitions (
- Reaktion (Koordination, target_level: 2, intensity: mittel)
**Attribute pro Fähigkeitsbezug:**
- is_primary (Haupt- oder Nebenfähigkeit)
- intensity (niedrig/mittel/hoch)
- required_level (Voraussetzung, 1-5)
- target_level (Ziel-Level, 1-5)
- `intensity` — Nutzeneinschätzung: **niedrig | mittel | hoch** (Standard **mittel**)
- `required_level` / `target_level` — Stufen-Spanne (kanonische Slugs basis … optimierung)
- `is_primary` — Legacy-Feld; **nicht mehr in der UI**, beim Speichern immer false; Scoring ignoriert es
**🆕 Fokusbereich-Filterung:**
- Bei Übungen mit Fokusbereich "Karate" sollten primär KARATE-Fähigkeiten zugeordnet werden
@@ -474,7 +473,43 @@ skill_level_definitions (
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
---
### Trainingsmodul (Bibliothek)
**Abgrenzung:** Wiederverwendbare **Übungsfolge** (`training_modules` + `training_module_items`) — kein Kalendertermin, kein Rahmen-Slot. Übernahme in geplante Einheiten über Planung (`apply-training-module`).
**Governance:** wie andere Bibliotheksartefakte (`visibility`, `club_id`, `library_content_visibility_sql`).
### Gewichtetes Fähigkeiten-Profil (Planungs-Bausteine, Phase 3)
**Zweck:** Aus den verknüpften Übungen eines Planungsartefakts wird ein **Fähigkeiten-Profil** berechnet (Trainingsgewicht je Fähigkeit). Trainer vergleichen Bausteine **innerhalb desselben Typs**, um z. B. das passendste Modul für eine Ziel-Fähigkeit zu finden.
**Artefakttypen (getrennte Peer-Kontexte):**
| Typ | Vergleich |
|-----|-----------|
| `training_module` | nur sichtbare **Module** |
| `framework_program` | nur sichtbare **Rahmenprogramme** |
| `progression_graph` | nur sichtbare **Regressionspfade** |
**Metriken (Nutzer):**
- **Score / Gewicht** — absolut (Dauer × Häufigkeit × Intensität × Stufen-Spanne)
- **Prozent** — Anteil am stärksten sichtbaren Peer **desselben Typs** für diese Fähigkeit (max. 100 %)
- **★** — stärkster Peer in diesem Kontext
**UI:** Profile in Editoren; KPI-Kacheln und Filter in Listen (`/planning/framework-programs`, `/planning/training-modules`); Discovery auf der Fähigkeiten-Seite.
**Technik:** `backend/skill_scoring.py`, `routers/skill_profiles.py` — Spec **`technical/SKILL_SCORING_SPEC.md`**.
### Parallele Trainingsstreams (Breakout)
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
**Sonderfall Stationen:** Rotation kann **innerhalb** einer Stream‑Planung über **Kombinationsübungen** (Methodenprofil/Archetyp) abgebildet werden; hallenweit **synchron** getaktete Rotation ist eine **erweiterte** Ausbaustufe (siehe Fachkonzept).
**Umsetzung (2026-05, Migration 063, App 0.8.137 ff.):** Tabellen **`training_unit_phases`** und **`training_unit_parallel_streams`**; **`training_unit_sections`** mit **`phase_id`** und **`parallel_stream_id`** (exakt eine Zuordnung pro Sektion). **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und flache **`sections`**. **Coaching** und **Durchführung** nutzen dieselbe Phasenlogik im Frontend (`trainingPlanUtils.js`).
**Dokumentation:** `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, Umsetzung `technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
@@ -482,7 +517,7 @@ skill_level_definitions (
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
- **`platform_media_storage`:** Konfiguration effektiver Medienwurzel (Superadmin, relativ zu `MEDIA_ROOT`).
- **Produkt:** Medienbibliothek **`/media`**; in der Übungsbearbeitung Upload, Entfernen der Verknüpfung, **Aus Archiv verknüpfen**; Governance **`official`** und Copyright-Regeln wie in der Norm beschrieben.
- **Geplant:** **Inline-Verweise** in Fließtextfeldern auf dieselbe Verknüpfung (`exercise_media.id`) — **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
- **Inline-Verweise** in Fließtextfeldern: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**, **`docs/HANDOVER.md`** §5.
---
@@ -640,12 +675,13 @@ skill_level_definitions (
- [ ] Level-Definitionen aus Fähigkeitsmatrix extrahieren (optional)
- [ ] Skills-Beschreibungen aus Wiki importieren (Migration 024)
- [ ] Admin-UI für Fähigkeiten-Kategorien (CRUD)
- [ ] Skill-Filter in Übungssuche integrieren
- [x] Skill-Filter in Übungssuche (SkillTreeMultiSelect + Stufen)
- [x] Gewichtetes Fähigkeiten-Profil für Planungs-Bausteine (Module, Rahmen, Pfade) — siehe `technical/SKILL_SCORING_SPEC.md`
- [ ] Reifegradmodelle definieren (Kombination Fokusbereich + Stil + Zielgruppe)
- [ ] KI-Unterstützung für Trainingsplanung (basierend auf Fähigkeiten-Level)
---
**Letzte Aktualisierung:** 2026-04-27
**Letzte Aktualisierung:** 2026-05-20
**Verantwortlich:** Claude Code
**Review:** Pending
@@ -0,0 +1,114 @@
# Parallele Trainingsstreams (Breakout) — Fachkonzept
**Status:** MVP-Umsetzung **teilweise** (Code) · **Stand:** 2026-05-14
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
**Domänenbegriffe (Überblick):** `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
---
## 1. Ausgangslage und Problem
In Kinder- und Breitensport-Training ist ein typischer Ablauf:
1. **Gemeinsam:** Aufwärmen, Koordination, Ansagen.
2. **Getrennt:** Kinder in mehrere Gruppen teilen; **Co-Trainer** leiten jeweils eigene Inhalte **gleichzeitig**.
3. **Gemeinsam:** Abschluss, gemeinsame Übungen, Verabschiedung.
Die aktuelle Shinkan-Planung modelliert pro Termin **eine lineare Folge von Abschnitten und Übungen** pro Einheit. Das genügt nicht, wenn **mehrere gleichzeitige „Unter-Sessions“** mit unterschiedlichen Plänen dokumentiert und auf der Matte geführt werden sollen.
---
## 2. Ziele (fachlich)
| ID | Ziel |
|----|------|
| PT‑01 | Eine **Kalender-Einheit** bleibt **ein** Termin (eine Halle, eine Gruppe, ein Datum) — kein Splitten in künstlich mehrere Kalendereinträge nur für Parallelität. |
| PT‑02 | **Unbegrenzte** Anzahl paralleler **Streams** (Teilstrecken) in einer oder mehreren **Parallelphasen**. |
| PT‑03 | **Phasenmodell:** klar erkennbar **Gemeinsam** vs. **Parallel** vs. wieder **Gemeinsam** (auch mehrfach hintereinander möglich). |
| PT‑04 | **Rollen:** Leitung (Haupttrainer) und Co-Trainer; Zuordnung der Co-Trainer **soll** an konkrete Streams anschließbar sein (heute: nur flache Liste pro Einheit — siehe technische Spec). |
| PT‑05 | **Sonderfall Stationen:** rotierender Ablauf (z. B. Wechsel alle 20 Min.) **inhaltlich** unterscheiden zwischen (a) Rotation **innerhalb** einer Teilstrecke und (b) **synchron** getakteter Hallen-Rotation — siehe §5. |
| PT‑06 | **Durchführung:** Trainer können „ihre“ Spur auf dem Gerät abarbeiten; Fortschritt pro Spur nachvollziehbar. |
**Nicht-Ziel (frühe Stufen):** Echtzeit-Synchronisation mehrerer Geräte; individuelles Athleten-Tracking; automatische Raumbelegung.
---
## 3. Begriffe
| Begriff | Definition |
|---------|------------|
| **Einheit / Termin** | Geplante `training_unit` für Gruppe und Datum — übergeordneter Rahmen des Abends. |
| **Phase** | Organisatorischer Block innerhalb der Einheit: entweder **ganze Gruppe** oder **parallel**. |
| **Stream / Teilstrecke** | Innerhalb einer Parallelphase: eine von N **gleichzeitig** stattfindenden Unter-Abläufen mit **eigenem** Miniplan (Abschnitte, Übungen, Notizen — analog heutiger Planung). |
| **Synchronisationspunkt** | Fachlich: alle treffen sich wieder (Beginn einer **Gemeinschaftsphase** nach Parallelität). |
| **Station (Rotation)** | Inhaltlicher Fokus oder Platz, den Teilnehmer **wechselnd** anlaufen; kann als Kombinations-/Zirkellogik oder als koordinierter Hallenrhythmus modelliert werden (§5). |
**Abgrenzung „Rahmenprogramm-Slot“:** Ein Slot im **Rahmenprogramm** ist eine **Session in einer Serie** (z. B. Woche 1 vs. Woche 2), **nicht** „Teilgruppe A gleichzeitig mit Teilgruppe B in derselben Stunde“. Parallele Streams sind **innerhalb einer Einheit**, orthogonal zum Rahmen-Slot.
**Abgrenzung **Kombinationsübung**:** Eine Kombi-Übung bündelt **mehrere Einzelübungen** mit Methodenprofil (Archetyp, ggf. Rotation) **in einem Plan-Item**. Sie ersetzt **nicht** mehrere Trainer mit **jeweils eigenem Gesamtablauf**, kann aber **pro Stream** für Stationslogik genutzt werden.
---
## 4. Szenarien
### 4.1 Klassischer Breakout
30 Min. gemeinsam → 25 Min. drei parallele Streams (Gruppe an Matte / an Schlagsack / Fußarbeit) → 15 Min. gemeinsam.
### 4.2 Viele Kinder, mehrere Co-Trainer
Haupttrainer plant die Gesamtstruktur; jeder Co-Trainer sieht in der Durchführung primär die zugewiesene Teilstrecke.
### 4.3 Rollierendes Stationssystem
Alle Gruppen arbeiten an **verschiedenen Schwerpunkten** und **wechseln** nach festem Intervall die Station — entweder **nur innerhalb einer Spur** oder **hallenweit synchron** (offene fachliche Präzisierung in MVP vs. später, §5).
---
## 5. Sonderfall: Stationen und Kombinationsübungen
### 5.1 Variante A — Rotation innerhalb einer Teilstrecke
Eine Teilgruppe rotiert durch mehrere Übungen (Zeit oder Runden). Das liegt nah an einer **Kombinationsübung** mit Archetyp z. B. „Zirkel / zeitgesteuerte Rotation“ und Parametern (Wechselintervall). **Empfehlung:** Diese Variante über **bestehendes** Kombinationsübungs-Konzept in der jeweiligen **Stream-Planung** abbilden (`planning_method_profile`).
### 5.2 Variante B — Synchron getaktete Hallen-Rotation
Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächsten Station; Startstation kann pro Teilgruppe **versetzt** sein. Das ist **organisatorisch** schwerer: es braucht entweder **Phasen-Metadaten** (globaler Takt) oder eine explizite **Rot/Matrix**. **Empfehlung:** In einer **zweiten Ausbaustufe** abbilden; MVP kann bei Variante A starten, sofern fachlich ausreichend.
---
## 6. Rollen und Verantwortlichkeiten
- **Leitungstrainer:** Hält den Faden, startet Gemeinschaftsphasen, koordiniert Parallelbeginn/-ende (fachlich; ggf. später UI-Hinweise).
- **Co-Trainer:** Verantwortlich für **zugeteilte** Streams; Zuordnung soll **pro Stream** möglich werden (Erweiterung gegenüber reiner Einheits-Co-Trainer-Liste).
---
## 7. Offene fachliche Entscheidungen
1. **MVP Umfang:** Reicht **freie Parallelität** ohne **synchronen** Hallenwechsel (Variante B)?
2. **Dauer:** Sollen Phasen oder Streams **Soll-Minuten** tragen (nur Anzeige vs. später Timer)?
3. **Vorlagen:** Müssen `training_plan_templates` parallel-fähig werden **vor** oder **mit** der ersten Implementierung?
4. **Sichtbarkeit:** Dürfen alle Co-Trainer alle Streams sehen, oder „nur meine Spur“?
---
## 9. Umsetzungsstand (kurz, 2026-05-14)
- **Erreicht:** Datenmodell Phasen/Streams (**063**), API **GET/PUT** mit **`phases`**, Planungs-Breakout-UI, Durchführung und Coach nutzen dieselbe Phasen-/Stream-Logik im Frontend (`trainingPlanUtils.js`). **Synchronisationspunkt** fachlich umgesetzt: vor nächster Ganzgruppenphase oder nächstem Split erscheint im Coach die **Rejoin-Karte** (mehrere Streams), sofern nicht am absoluten Planende.
- **Noch offen:** vollständige **Persistenz-Konsistenz** bei nachträglich geänderten Sektionen, **Vorlagen** mit Phasen, **Trainer pro Stream** in der UI, ggf. **Stream-Tabs** in der Durchführungsansicht wie in §5.2 skizziert — siehe **`docs/HANDOVER.md`** (Arbeitspaket-Tabelle).
---
## 10. Verwandte Dokumente
| Dokument | Bezug |
|----------|--------|
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slots = Serien-Sessions, **nicht** Intra-Einheit-Parallelität |
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
| `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` | Fachliche Tiefe Kombi |
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick |
| `docs/HANDOVER.md` | Ist-Stand Coach, offene Breakout-Punkte |
| `technical/DATABASE_SCHEMA.md` | Aktueller Stand Tabellen |
@@ -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`**.
@@ -1,6 +1,6 @@
# Gelieferte Features & technische Basis (Q2 2026)
**Stand:** 2026-05-12
**Stand:** 2026-05-20
**Referenz:** `backend/version.py` — aktuelle **APP_VERSION** / **DB_SCHEMA_VERSION** (Stand Code u. a. **0.8.96**)
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
@@ -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`)
@@ -123,7 +156,16 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
---
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
## 12. Trainingsplan: Phasen & parallele Streams (DB **063**, App **0.8.137–0.8.140**)
- **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` / `parallel_stream_id`; Default-Ganzgruppenphase für Bestand.
- **API:** `GET /api/training-units/:id` mit **`phases`** + **`sections`**; `PUT`/`POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); Rahmen-Slot-Materialisierung kopiert Phasen (**0.8.138**).
- **Frontend:** Planung Breakout-Panel (**0.8.139–0.8.140**); **`trainingPlanUtils.js`** — `sectionsWithPlanLocForDisplay`, `flattenPlanTimeline`, `buildCoachSavePlanPayload`, Split-Rejoin (`coachShouldPromptSplitRejoinTransition`); **`TrainingCoachPage`**, **`TrainingUnitRunPage`**.
- **Doku:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`, `docs/HANDOVER.md` §3, Arbeitspaket „offen“.
---
## 13. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
@@ -150,7 +192,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
---
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
## 14. Nächste sinnvolle Schritte (nicht Lieferstand)
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
@@ -160,15 +202,55 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
---
## 14. Verweise
## 15. Gewichtetes Fähigkeiten-Scoring (Phase 3, Stand 2026-05-20)
Norm: **`technical/SKILL_SCORING_SPEC.md`**.
### 15.1 Backend
- **`skill_scoring.py`:** Gewichtung (Dauer × Vorkommen × Intensität × Stufen); `compute_planning_corpus_by_type()` mit getrennten Corpora; `universal_percent` capped auf 100 %
- **`routers/skill_profiles.py`:** Profile-GET pro Artefakt; `POST /api/skill-profiles/batch-summaries`; `GET /api/skill-discovery/suggestions`
- Sichtbarkeit: **`library_content_visibility_sql`** (Planungs-Bibliothek, nicht „nur Verein club“)
### 15.2 Frontend
- **Listen:** Rahmenprogramme + Trainingsmodule — Filter-Modal (wie Übungen), Chips, `SkillTreeMultiSelect` (Portal-Dropdown)
- **KPI:** `SkillProfileCompact` — Top je Unterkategorie, Score + Peer-%
- **Editoren + Modal:** `SkillProfilePanel`, `SkillProfileFullModal`
- **Discovery:** `SkillDiscoveryPanel` auf Fähigkeiten-Seite
### 15.3 Offen
- Corpus-Caching; pytest für Typ-Trennung; Filter-Persistenz; Skill-Filter Import-Dialog „Rahmen übernehmen“
---
## 16. Ü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 |
|--------|----------|
| Rahmenprogramm / Progressionsgraph | `technical/TRAINING_FRAMEWORK_SPEC.md` |
| Fähigkeiten-Scoring Planung | `technical/SKILL_SCORING_SPEC.md` |
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
| Parallele Phasen/Streams | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` |
| Coaching/Breakout-Handover | `docs/HANDOVER.md` |
| Fachlicher Nutzerüberblick | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` (Repo-Root) |
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
@@ -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
@@ -0,0 +1,202 @@
# KI-gestützte Trainingsplanung – Zentrales Konzept
**Version:** 0.3
**Datum:** 2026-05-22
**Status:** Arbeitsdokument (Verfeinerung durch fachliche Konzept-Agentur vorgesehen)
**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/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`
---
## 1. Produktliche Leitlinien
- **Nutzer:** Trainer/Vereinskontext, **Gruppenplanung** – keine Pflicht zur individuellen Sportler-Verfolgung; Kontext soll primär aus **Gruppe**, **bereits geplanten/durchgeführten Einheiten**, **Rahmen-/Zielen** und **berechtigtem Übungskorpus** bestehen.
- **Human-in-the-loop:** KI liefert **Vorschläge** (Liste, Reihenfolge, Begründung); schreibende Übernahme in Pläne nur nach **Trainer-Bestätigung** oder expliziter Aktion (analog „Manual First“ in `KI_FEATURES_SPEC.md`).
- **Governance-first:** Nur Übungen, die die API bereits für den Mandanten/Kontext **sichtbar** freigibt, dürfen in Kandidatenlisten landen – **vor** Retrieval und **vor** jedem Prompt.
### 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.
**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 |
|-----------|--------|
| **Auftrag** | z. B. Sektionstyp, Dauerbudget, Schwierigkeit, erlaubte Phasen/Streams |
| **Hard Constraints** | Gruppe, Termin/Zeitraum, Governance-Filter bereits angewendet |
| **Komprimierte Historie** | Letzte *N* Einheiten als **Liste von Übungs-IDs + Kurzlabels** (+ optional Haupt-Skills), keine vollen Fließtexte |
| **Ziele / Rahmen** | Kurztexte aus Rahmen-Slot/Zielblöcken oder Trainer-Prompt |
| **Kandidaten-Top‑K** | z. B. 30–120 Übungen, **je Zeile gekürzt** (Titel, `summary`, 2–5 Skill-Namen/Stufen); **nie** der gesamte Katalog |
| **Strukturierte Kanten optional** | Kleine Mengen Kanten aus Progressionsgraph: „Nachbarn von zuletzt genutzten Übungen“ |
**Zahlen‑Richtwerte (überarbeitungsfähig):**
Kandidaten **vor** dem LLM typischerweise **50–150** Einträge; im Prompt durch Token-Limit weiter **truncate** oder **zweistufig** (grober Ranking-Schritt ohne LLM, dann finer mit LLM auf Top‑40).
---
## 3. Pipeline: „Selektion vor dem Prompt“
Die **„optimale“** Auswahl entsteht **nicht**, indem das Modell den Katalog „im Kopf“ hält, sondern über eine **mehrstufige Pipeline**:
### Stufe 1 – Harte Filter (deterministisch, DB)
Synchron zur bestehenden Suche/List-API-Logik, z. B.:
- Sichtbarkeit / Verein / `official`‑Regeln
- Aktivitäts-/Archiv-Status der Übung
- Fokusbereich, Stil, Zielgruppe (wenn Trainings-/Gruppenkontext das vorgibt)
- Ausschluss bereits in **dieser Einheit** fester Übernutzung (optional)
Ergebnis: Menge \(M\) – kann noch sehr groß sein.
### Stufe 2 – Kontext-Verankerung (deterministisch + Graph)
- **Historie:** aus letzten *N* Gruppeneinheiten extrahierte `exercise_id`s (optional Variant).
- **Progressionsgraph:** ausgehend davon Nachbarn (eingehend/ausgehend begrenzte Tiefe) – bereits im Produkt als **unterstützend** modelliert (**CURR‑013**).
- **Rahmen/Slot-Ziele:** Überlapp mit Skill-Tags oder Stichwortliste (falls formalisiert).
- **Variantenketten:** `prerequisite_variant_id` / `progression_level` nur innerhalb bereits gewählter Übung prüfen oder als Hint an den LLM-Block durchreichen.
Ergebnis: **„Anker‑Menge“** + **„Graph‑Nachbarschaft“** → priorisierte Kandidaten.
### Stufe 3 – Weiches Ranking / Retrieval (halb-strukturiert)
Mindestens **eine** der folgenden Optionen – kombinierbar:
1. **Skill-/Facet-Overlap:** Punktezahl, wenn Übungs-Skills mit Ziel-/Matrix-Schwerpunkten übereinstimmen (bereits Daten in `exercise_skills`).
2. **Diversitäts-/Wiederholungsstrafe:** häufig in letzten Wochen geübte Übungen abwerten.
3. **Textsuche:** PostgreSQL **`tsvector`/Volltext** auf `title`, `summary`, ggf. gekürzte `goal` – für Trainer-Stichwort „Koordination Sprung“.
4. **Semantische Suche:** Embeddings + **Ähnlichkeitsuche** auf Kurztexte (siehe §5).
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.
### Stufe 4 – LLM (optional zweistufig)
- **Optional 1:** LLM nur **sortiert/rankted** bereits vorgegebene IDs (Ranking mit kurzer Begründung).
- **Optional 2:** Zwei Calls: erst „welche drei Schwerpunkte“ / „Welche Constraints habe ich übersehen?“, zweiter Call nur mit gekürztem Top‑K – nur wenn UX den Mehraufwand rechtfertigt.
**Ausgabe-Contract:** Zurückkommen dürfen **nur gültige `exercise_id`s** aus der übergebenen Kandidatenliste (Server validiert gegen Set); **Halluzinationsrisiko damit entschärft**.
---
## 4. Antwort auf die konkrete Frage: „Alle Übungen in den Prompt?“
**Nein.** Workflow:
1. **DB + Regeln + Graph + Historie** reduzieren auf **einige Hundert bis wenige tausend** Rohzeilen höchstens **intern** – aber
2. in den **LLM-Prompt** gehen nur **Top‑K kompakte Artefakte** (siehe §2).
Das LLM löst dann **Ranking, Reihenfolge, Timing-Hinweise, Trainer-sprachliche Kurzkommentare** – nicht die Frage „gibt es diese Übung überhaupt im System?“.
---
## 5. Vector DB (z. B. Qdrant) – wann nötig, wann nicht?
### 5.1 Ziel embeddings
Semantic Retrieval: „wie springt Coordinative Belastung ohne das Wort ‚Koordination‘ im Titel zu stehen.“ Das ist **über** reine Filtersuche und oft **über** stumpfe Volltextsuche erreichbar.
### 5.2 Option A – ohne separate Vector DB
- **PostgreSQL + `pgvector`** (Extension): Embeddings-Spalte an `exercises` (oder an „Search Document“-Zeilen), Indices, Abfrage zusammen mit SQL-Filtern in **einer Transaktions-DB**.
- **Größenordnung** einige 10 k–100 k Zeilen für Übungen: für Shinkan **oft ausreichend**.
- Vorteile: ein Betriebspfad, Mandanten-/Governance weiter in SQL lösen; Backup wie heute.
### 5.3 Option B – Qdrant (oder anderer Dediz-Vektorstore)
Sinnvoller zeitlicher Punkt oder technische Auslöser:
- sehr hohe Latenz-Anforderung mit **Hybrid-Filter** über viele kombinierte Metadaten in nahezu Echtzeit,
- Entkopplung: Embedding-Pipeline läuft asynchron und soll die **Operational DB** nicht beschweren,
- später **mehrsprachig** oder **mehrere Embedding-Versionen**/Re-Index ohne großen Migrationstress,
- Team bevorzugt **Dedicated** Vector-Ops gegenüber Postgres-Ops.
### 5.4 Empfehlung für diese Codebasis (überarbeitungsfähig)
1. **Phase 1:** Harte Filter + Graph + Historie + **PostgreSQL-Volltext** + Top‑K; LLM erst auf komprimierten Kandidaten → hoher Nutzen ohne neuen Infrastructure-Typen.
2. **Phase 2:** Bei nachweisbaren „Recall-Lücken“ (Trainer findet nichts Passendes trotz großem Korpus) **`pgvector` in Postgres** evaluieren – **vor** zusätzlicher Infrastruktur wie Qdrant.
3. **Phase 3:** Qdrant (o. ä.) wenn Größenordnung, Betrieb oder Produkt-Anforderungen **pgvector** sprengen oder klar eine **embedding-first** Produktstraße geplant wird.
**Fazit:** Eine dedizierte **Vector DB ist nicht zwingende Voraussetzung** für vernünftige Selektion; sie ist eine **Ausbaustufe**, wenn **semantische Lücke** und Skalierung es rechtfertigen. **Selektion** ist immer **„Filter + Ranking + kleines Top‑K“**, unabhängig vom Speicherort der Vektoren.
---
## 6. Datenpflege für gutes Retrieval (fachlicher Hebel)
Retrieval‑Qualität hängt stärker an **Metadaten** als an der Embedding-Technologie allein:
- verlässliche **Skills** (`exercise_skills`, ggf. KI-geholfen bereits laut Spez beim Übungs-Anlegen); `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.
Das fachliche Konzept sollte entscheiden: **wie viel automatische Pflege vs. Trainer-Pflichtfelder**.
---
## 7. Produkt-/Release-Stufen (Anknüpfung)
Priorität **jetzt**: **Übungsanlage**, danach **Planung**.
| Stufe | Nutzen | Technik-Schwerpunkt |
|-------|--------|---------------------|
| **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) | 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 für **Planungs**-KI konsistent und wird parametrierbar erweitert; **§1.1** spiegelt den **aktuellen Implementierungs**-Vorsprung (Skill-Scoring ohne LLM) wider.
---
## 8. Compliance & Datenschutz (Kurzhinweis)
- Datenminimierung: **keine Teilnehmerliste** ohne expliziten Scope; Kontext über **Einheiten-Metadaten** und Übungen.
- **OpenRouter**/Modellwahl: Organisation intern klären (AV/Verarbeitungsvertrag, Datenflüsse außerhalb EU – siehe Repo-Compliance-Dokumente).
- **Logging:** Prompts keine unnötigen personenbezogenen Daten; wenn Debug: Retention definieren.
---
## 9. Offene Punkte für die fachliche Verfeinerung
- Gewichtung „**Wiederholung** vs. **Progression** vs. **Motivation**“ (domänenspezifisch).
- Umgang mit **Kombinationsübungen** und **Coach-Stufen B/C** in der Datenübergabe.
- Soll das System **„Lücken“** aus der **Matrix-Auflösung** aktiv quantifizieren oder nur Narrative verwenden?
- Akzeptierte **Übersetzungen**: nur Deutsch oder mehrsprachige Embeddings erforderlich?
---
## 10. Glossar
| Begriff | Bedeutung |
|---------|-----------|
| **Top‑K** | Feste kleine Obergrenze Übungen pro LLM-Anfrage |
| **Hard filter** | Deterministische SQL-/Policy-Einschränkung vor KI |
| **Kontext-Paket** | Zusammengesetztes, tokenlimitiertes Eingabeobjekt für den Prompt |
| **Retrieval** | algorithmischer Schritt ohne Generierung („wer kommt überhaupt in Frage“) |
+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
}
]
@@ -0,0 +1,144 @@
# Navigation — Return-Kontext (Rücksprung)
**Stand:** 2026-05-20
**Status:** Spezifikation + Phase 1–2 umgesetzt
**Ziel:** In der PWA (ohne Browser-Back) zuverlässig an den fachlichen Ausgangspunkt zurückkehren — inkl. sinnvollem Label und optional UI-State.
---
## Problem
Viele Flows navigieren von Kontext A zu Editor/Detail B (z. B. Übungsliste → Modulbearbeitung). Die Zielseite kennt A nicht und bietet nur einen **fest verdrahteten** Zurück-Link (z. B. immer „Modul-Bibliothek“). In der installierten PWA fehlt zusätzlich die Browser-Chrome.
Betroffen u. a.:
- Übungsliste → Modul anlegen/bearbeiten
- Planung → Einheiten-Editor (teilweise gelöst via `planningReturn`)
- Modals mit Speichern + Redirect auf Vollseite
---
## Strategie (Hybrid)
| Mechanismus | Wann |
|-------------|------|
| **Expliziter Return-Kontext** (`appReturn` in Router-State) | Seitenwechsel, bei denen das Ziel einen fachlichen Rücksprung anbieten soll |
| **History-Back** (`navigate(-1)`) | Fallback, wenn kein Kontext gesetzt ist und History-Eintrag existiert |
| **Default-Pfad** | Fallback der Zielseite (z. B. Modul-Bibliothek) |
| **Modal schließen** | Overlays/Peek — kein Routing-Return |
**Nicht** als alleinige Lösung: reines Browser-Back (History durch `replace`, Deep Links, Reload unzuverlässig).
---
## Datenmodell
Router-State-Schlüssel: **`appReturn`**
```javascript
{
v: 1, // Schema-Version
path: '/exercises', // Ziel-URL (inkl. Query, falls nötig)
label: 'Zurück zur Übungsliste', // Anzeige im UI (vollständiger Satz)
kind: 'exerciseList', // optional: Typ für erweiterte Wiederherstellung
payload: { ... } // optional: kind-spezifische Daten
}
```
### `kind`-Werte (erweiterbar)
| kind | payload | path-Ableitung |
|------|---------|----------------|
| `exerciseList` | — | `/exercises` (Filter/Auswahl via sessionStorage) |
| `planningHub` | `buildPlanningHubReturnState(...)` | `planningHubPathFromReturnState(payload)` |
| `trainingModulesList` | — | `/planning/training-modules` |
| `planTemplatesList` | — | `/planning/plan-templates` |
| `frameworkProgramsList` | — | `/planning/framework-programs` |
| `settings` | — | `/settings` |
| `dashboard` | — | `/` |
| `mediaLibrary` | — | `/media` |
| `trainingRun` | `{ unitId }` | `/planning/run/:unitId` |
| `currentLocation` | — | aktuelle Route (z. B. Einheiten-Editor) |
| (frei) | — | `path` direkt gesetzt |
### Legacy-Kompatibilität
Bestehendes Feld **`planningReturn`** (Planung ↔ Einheiten-Editor) wird beim Lesen in `appReturn` **bridged** — keine Big-Bang-Migration nötig.
---
## API (Frontend)
Zentrale Datei: `frontend/src/utils/navReturnContext.js`
| Funktion | Zweck |
|----------|--------|
| `buildNavReturnContext({ path, label, kind?, payload? })` | Kontext-Objekt erzeugen |
| `buildExercisesListReturnContext()` | Standard-Rückkehr Übungsliste |
| `buildPlanningHubReturnContext(hubState)` | Planungs-Hub inkl. Filter-Query |
| `buildTrainingModulesListReturnContext()` | Modul-Bibliothek |
| `readNavReturnFromLocation(location)` | Kontext aus `location.state` (+ Legacy) |
| `resolveNavReturnTarget(location, fallback)` | `{ path, label }` für UI |
| `goNavReturn(navigate, location, fallback?)` | Programmatischer Rücksprung (priorisiert: Kontext → History → Fallback) |
| `navigateWithAppReturn(navigate, to, returnContext, options?)` | Navigation mit gesetztem `appReturn` |
| `preserveAppReturnOnNavigate(navigate, location, to, options?)` | Weiterleiten, bestehenden Kontext behalten (z. B. nach `replace`) |
UI-Komponente: **`PageReturnButton`** — app-typischer Zurück-Schalter (Button mit Pfeil, kein Router-Link).
Links **zum** Ziel: **`NavStateLink`** mit `returnContext` der Quellseite.
### Editor-Aktionen
Auf Vollseiten-Editoren mit **`FormActionBar`** (`placement="bottom"`) oder **`PageFormEditorChrome`**:
- **Kein** separater Zurück-Link/Button oben (wirkt in der App redundant)
- **Abbrechen** → `goBack()` / `goNavReturn(...)` (Einsprungspunkt)
- **Speichern & Schließen** → nach erfolgreichem Save ebenfalls `goBack()`
- Sticky Action Bar unten nutzen
**PageReturnButton** nur auf **Leseseiten** ohne Editor-Leiste (z. B. Übungsdetail, Einstellungen-Unterseiten, Trainingsablauf).
---
## Regeln für Entwickler
1. **Jede Navigation** von Kontext A zu Editor B, wo der Nutzer „weitermachen“ soll, setzt `appReturn` (oder nutzt `navigateWithAppReturn`).
2. **Zielseite** zeigt `PageReturnButton` mit sinnvollem **Default-Fallback** (Bibliothek/Hub).
3. **Nach Create + `replace: true`:** Return-Kontext mit `preserveAppReturnOnNavigate` erhalten.
4. **Modals:** Schließen reicht; Redirect nach Speichern = Seiten-Navigation → Return setzen.
5. **Kein Return-Kontext** in `location.state` für interne Bibliothek → Detail → Bearbeiten, wenn Herkunft = offensichtliche Elternliste (Default-Fallback genügt).
6. **UI-State** (Filter, Auswahl): weiter über bestehende Session-Mechanismen (z. B. `exerciseListSessionState`), nicht im Return-Payload duplizieren, außer kind erfordert Query-Reconstruction (Planung).
---
## Umsetzungsstand
### Phase 1 (Pilot)
- [x] Spec + Utility + Tests
- [x] `PageReturnButton` (ersetzt Link-Variante)
- [x] Übungsliste → Modul speichern → Modul-Editor
- [x] Planung: `SaveExercisesAsModuleModal` leitet Return-Kontext weiter
- [x] `TrainingUnitEditPage`: `goBack` über `goNavReturn` (Legacy-bridge)
### Phase 2 (Flows verbinden)
- [x] Listen → Editoren: Übungen, Module, Vorlagen, Rahmenprogramme
- [x] Dashboard → Übung bearbeiten / Trainingsablauf / Einheit bearbeiten
- [x] Einstellungen-Unterseiten (Rechtliches, Systeminfo)
- [x] Trainingsablauf + Coach-Modus (`trainingRun`, Planungs-Fallback)
- [x] Medienbibliothek → verknüpfte Übungen/Einheiten
- [x] `ExercisePeekModal` → Vollseite mit Return
- [x] Editoren: Abbrechen + Speichern & Schließen → Einsprungspunkt
### Optional (später)
- Globaler Zurück-Button in App-Chrome (Mobile)
- Nach Speichern: explizite Aktion „Zurück zum Ausgang“ im Toast
---
## Referenzen
- Bestehend: `frontend/src/utils/planningUnitRoutes.js` (`planningReturn`)
- Session Übungsliste: `frontend/src/utils/exerciseListSessionState.js`
- PWA-Kontext: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`, App-Shell in `App.jsx`
@@ -0,0 +1,136 @@
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
**Status:** Umsetzung **Phase 1 (teils)** · **Stand:** 2026-05-14
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand 2026-05-14): **`training_unit_phases` / `training_unit_parallel_streams`** (Migration **063**) und **`training_unit_sections`** mit Phasen-/Stream-Bezug; **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung und Coaching über **`TrainingUnitRunPage`**, **`TrainingCoachPage`** und **`trainingPlanUtils.js`**.
---
## 1. Ist-Stand (Code, 2026-05-14)
| Bereich | Aktuell |
|---------|---------|
| **Schema** | Migration **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` **oder** `parallel_stream_id`. |
| **API** | `GET /api/training-units/:id` — **`phases`** (verschachtelt) + flache **`sections`**. `PUT/POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); höchstens eines von `phases`, `sections`, `exercises` pro Request (Planning-Router). Legacy-PUT mit nur `sections` erzeugt/ergänzt Ganzgruppen-Phase. |
| **Planung (UI)** | Breakout-Panel: Ganzgruppen-/parallele Phasen, Streams; Speichern phasenbasiert (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`). |
| **Durchführung** | `TrainingUnitRunPage.jsx` + `trainingPlanUtils.js` (`sectionsWithPlanLocForDisplay`, `buildPlanRunViewModelFromSections`) — Phasenfolge in „Plan & Ablauf“. |
| **Coaching** | `TrainingCoachPage.jsx` + `flattenPlanTimeline`, Stream-Picks, Rejoin vor Ganzgruppe/nächstem Split (`coachShouldPromptSplitRejoinTransition`), Nachbereitung mit `buildCoachSavePlanPayload`, danach Navigation zu `/planning/run/:id`. |
| **Kombinationsübung** | Unverändert je Item; `planning_method_profile`, Coach-Kombi-Stufe A. |
| **Trainer-Zuweisung** | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am Einheitskopf; **Stream-**`assigned_trainer_profile_ids` im Schema — UI/Policy noch nicht vollständig (siehe **§8 offen**). |
| **Rahmenprogramm** | Blueprint-`training_units` können dieselbe Phasenstruktur tragen; Kopie aus Slot (`from-framework-slot`, **0.8.138**). |
**Hinweis:** Die frühere Planungsvariante „nur lineare `training_unit_sections` ohne Phasen“ gilt weiter für Alt-Daten; Migration **063** ordnet Bestand einer Default-Ganzgruppenphase zu.
---
## 2. Zielarchitektur (logisch)
```
training_unit (Kalender-Einheit)
├── phase (order, kind: whole_group | parallel, optional Metadaten)
│ ├── [whole_group] → sections[] → items[] (wie heute)
│ └── [parallel] → stream (order, label, optional trainer_ids[])
│ └── sections[] → items[]
```
**Abwärtskompatibilität:** Einheiten **ohne** explizite Phasen/Streams verhalten sich wie heute: **implizit** eine einzige „Gemeinschaftsphase“ mit den vorhandenen Sektionen (Migration: alle bestehenden Sektionen an diese Default-Hülle hängen).
---
## 3. Datenmodell — Optionen
**Ist (063):** Die unten skizzierte **empfohlene** Normalform ist unter den genannten Tabellennamen produktiv; die Abschnitte 3.1/3.2 bleiben zur Einordnung erhalten.
### 3.1 Empfohlen: explizite Phasen + Streams (normalisiert)
Die Tabellen sind **umgesetzt** (Namen final):
| Tabelle | Zweck |
|---------|--------|
| `training_unit_phases` | `training_unit_id`, `order_index`, `phase_kind` (`whole_group` \| `parallel`), optional `title`, `guidance_notes`, optional `planned_duration_min` |
| `training_unit_parallel_streams` | `phase_id` (FK, nur wenn parent parallel), `order_index`, `title`/`label`, optional `notes`, optional `assigned_trainer_profile_ids` JSONB (oder 1:n-Hilfstabelle) |
**Anpassung `training_unit_sections`:** Zusätzliche FK-Spalte(n), z. B.:
- `phase_id` **NULL** und `parallel_stream_id` **NULL** → **Legacy / Default-Einheitsphase** (Migration setzt Default-Phase); oder
- genau einer von `phase_id` (whole group) oder `parallel_stream_id` gesetzt.
**Constraints:** CHECK: nicht beide gesetzt; bei `phase_kind = parallel` Sektionen nur unter `parallel_stream_id`; bei `whole_group` nur unter `phase_id`.
**Vorteil:** Klare Semantik, Reporting, API-Shape konsistent.
### 3.2 Minimalvariante (nicht ideal fachlich)
Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; Phasen implizit durch „Marker“-Sektionen oder Konvention. **Nicht empfohlen**, erschwert UI und Erklärbarkeit.
---
## 4. API
- **`GET /api/training-units/:id`** (und Listen-Payloads wo vollständiger Plan nötig): verschachtelte Struktur **Phasen → Streams → sections → items** oder flache `sections` mit ausgefüllten `phase_id` / `parallel_stream_id` (Frontend kann normalisieren).
- **`PUT/PATCH`:** Atomares Ersetzen der Phasen/Streams/Sektionen analog zu bestehendem `_replace_unit_sections`-Muster; **Validierung** der CHECK-Regeln serverseitig.
- **Blueprint / Rahmen:** Blueprint-`training_units` dürfen dieselbe Struktur tragen; `GET` Kalenderliste blendet Blueprints weiter aus (`framework_slot_id IS NOT NULL`).
**Governance / Mandant:** Unverändert über Einheit → `group_id`; keine neuen Mandanten-Entitäten.
---
## 5. Frontend
### 5.1 Planung (`TrainingPlanningPage`)
- Darstellung als **vertikale Phasen**: Gemeinschaftsblöcke + Parallelphase mit **N Spalten** (Streams).
- **Wiederverwendung:** `TrainingUnitSectionsEditor` **pro Stream** und pro Gemeinschaftsphase — analog zur Wiederverwendung **pro Rahmen-Slot** in `TrainingFrameworkProgramEditPage`.
- **Co-Trainer:** UI pro Stream (`assigned_trainer_profile_ids`); Regel zur **Kopfliste** `assistant_trainer_profile_ids` festlegen (z. B. Union aller Stream-Zuweisungen für „Wer ist heute dabei“ + Rückwärtskompatibilität wenn Stream-Felder leer).
### 5.2 Durchführung (`TrainingUnitRunPage`)
- Gemeinschaftsphasen: heutiges **lineares** Verhalten.
- Parallelphase: **Tabs, Akkordeon oder Swipe** zwischen Streams; Fortschritt **pro Stream** (Storage-Key z. B. `${unitId}:${streamId}`).
- Kombi-Items: unverändert `CombinationPlanBracket` / `effectiveComboMethodProfile`.
- Optional später: Filter „nur meine Spur“ anhand Session-Profil vs. Stream-Zuweisung.
### 5.3 Vorlagen (`training_plan_templates`)
- Erweiterung um **dieselbe** Phasen/Streams-Semantik (Kindtabellen oder serialisiertes JSON — Abgleich mit Kopierlogik aus Vorlage in Einheit).
- **Kein** Live-Spiegel: weiterhin Materialisierung beim Anwenden.
---
## 6. Bezug Kombinationsübungen
- **Variante A** (Rotation innerhalb einer Teilstrecke): ein oder mehrere **Items** vom Typ Kombi im jeweiligen Stream; Archetyp und Parameter wie in `TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`.
- **Variante B** (synchron Hallenweit): erweiterte **Phasen-** oder **Stream-übergreifende** Metadaten — **nicht** in MVP-Zwang; eigenes Teilpaket nach fachlicher Freigabe (`PARALLEL_TRAINING_STREAMS_CONCEPT.md` §5.2).
---
## 7. Migration und Risiken
1. **Datenmigration:** Alle existierenden `training_unit_sections` einer Einheit einer **Default-Phase** `whole_group` zuordnen.
2. **API-Versionierung:** Clients, die nur flache `sections` erwarten, müssen angepasst werden (oder Server liefert **beides** kurzzeitig — nur wenn nötig).
3. **Performance:** Tiefe Kopien (Rahmen-Slot, Duplikat Einheit) müssen rekursiv Phasen/Streams mitsamt Sektionen/Items kopieren.
4. **Tests:** pytest für PUT/GET mit gemischten Phasen; ggf. Playwright-Smoke für Planung/Run.
---
## 8. Implementierungsphasen (Abgleich)
| Phase | Inhalt | Stand 2026-05-14 |
|-------|--------|------------------|
| **P1** | Schema Phasen + Streams; Migration **063**; GET/PUT verschachtelt; Planungs-UI; Run + Coach phasenbasiert | **Teilweise erledigt** — Run-UI nutzt Phasen-Timeline in der Anzeige; **Stream-Tabs** optional noch zu vereinheitlichen (§5.2) |
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert | **Offen** |
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) | **Offen** |
**Offene Punkte (kurz):** siehe **`docs/HANDOVER.md`** Tabelle „Coaching & Breakout“.
## 9. Verwandte Dokumente
| Dokument | Bezug |
|----------|--------|
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md` | Fachziele, Begriffe, Entscheidungsfragen |
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
| `TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Planung, Durchführung, Rahmen |
| `frontend/src/utils/trainingPlanUtils.js`, `TrainingCoachPage.jsx` | Phasen-Timeline, Rejoin, Coach-Speichern |
@@ -0,0 +1,184 @@
# Gewichtetes Fähigkeiten-Scoring (Phase 3)
**Stand:** 2026-05-20
**Status:** Variante A (regelbasiert) umgesetzt — **v1.3** (Peer-Kontext getrennt + Listen-Filter)
**Modul:** `backend/skill_scoring.py`, Router `backend/routers/skill_profiles.py`
## Ziel
Trainer wählen **Schwerpunkt-Fähigkeiten** und finden passende **Bausteine** für die Trainingsplanung:
- **Trainingsmodule** — wiederverwendbare Übungsfolgen
- **Rahmenprogramme** — Programme mit Zielen und Session-Slots
- **Regressionspfade** (Progressionsgraphen) — Übungsketten
Das Scoring beantwortet: *Wie stark trainiert dieser Baustein eine Fähigkeit?* und *Wie stark ist er im Vergleich zu anderen **sichtbaren** Bausteinen **desselben Typs**?*
## Fachliche Kernregel: Peer-Kontext (nicht vermischen)
| Planungs-Artefakt | Vergleichsgruppe (`universal_percent`) |
|-------------------|----------------------------------------|
| Trainingsmodul | nur andere **sichtbare Module** |
| Rahmenprogramm | nur andere **sichtbare Rahmenprogramme** |
| Regressionspfad | nur andere **sichtbare Pfade** |
**Nicht** verglichen werden:
- Module vs. Rahmenprogramme vs. Pfade (kein Mix)
- Artefakte anderer Vereine, auf die der Nutzer keinen Planungszugriff hat
**Sichtbarkeit:** `library_content_visibility_sql` — private, vereinsinterne und offizielle Inhalte gemäß Mandant/Rolle, analog zu anderen Bibliothekslisten.
## Datenquellen
| Artefakt | Übungen aus |
|----------|-------------|
| Rahmenprogramm (gesamt) | Alle Blueprint-`training_units` der Slots → `training_unit_section_items` |
| Rahmenprogramm (pro Slot) | Blueprint einer Session |
| Trainingsmodul | `training_module_items` (nur `item_type = exercise`) |
| Progressionsgraph | `from_exercise_id` + `to_exercise_id` je Kante (Vorkommen zählt) |
Fähigkeiten je Übung: `exercise_skills` → `skills` (nur `status = active`).
## Gewichtungsformel (v1.1 / v1.2)
Pro **Übungsvorkommen** (eine Zeile im Ablauf / Modul / Kanten-Endpunkt):
1. **Basis-Minuten** = `planned_duration_min` der Position, sonst Default (Einheit/Modul: 8 Min, Graph: 10 Min).
2. Pro verknüpfte Fähigkeit der Übung:
- `Beitrag = Basis-Minuten × Anzahl Vorkommen × Link-Faktor`
- **Link-Faktor** = Intensität × Stufen-Faktor
### Intensität (Nutzeneinschätzung, UI-Feld)
| Wert | Faktor |
|------|--------|
| niedrig | 0,85 |
| mittel / leer | 1,0 |
| hoch | 1,2 |
### Stufen-Spanne (`required_level` → `target_level`, UI „von/bis“)
Kanonische Slugs: basis … optimierung (1–5). Fehlen beide: Faktor 1,0.
- **Spanne** = Anzahl Stufen von „von“ bis „bis“ (1–5)
- **Mittelpunkt** = durchschnittliche Stufe
- Faktor ≈ `(0,92 + 0,04 × Spanne) × (0,95 + 0,025 × Mittelpunkt)` → typisch 0,96–1,20
### Bewusst nicht im Scoring
| Feld | Grund |
|------|--------|
| `is_primary` | Perspektivabhängig; bleibt in Übungs-UI, fließt nicht ins Profil ein |
| `development_contribution` | Legacy-DB-Feld, in UI nicht gepflegt |
## Aggregierte Metriken
| Feld | Bedeutung |
|------|-----------|
| `weight` / `score` | Absolutes **Trainingsgewicht** (gewichtete Minuten) — über alle Fähigkeiten eines Artefakts vergleichbar |
| `share_percent` | Anteil am `total_weight` **innerhalb dieses Artefakts** (summiert 100 %) — sekundär |
| `by_main_category[]` | Je Unterkategorie `top_skill` (stärkste Fähigkeit nach Gewicht) |
| `universal_percent` | Anteil am **Maximum derselben Fähigkeit im Peer-Kontext** (max. 100 %) |
| `is_club_best_for_skill` | Stärkster sichtbarer Peer für diese Fähigkeit (★ in UI) |
| `club_best` | Referenz-Peer (Titel, Typ, Gewicht) — **Legacy-Name**, fachlich Peer-Best |
### Berechnung `universal_percent`
```
effective_ref = max(max_weight_in_peer_corpus(skill_id), eigenes_gewicht)
universal_percent = min(100, weight / effective_ref × 100)
```
Corpus je Typ: `compute_planning_corpus_by_type()` scannt sichtbare Artefakte getrennt nach `framework_program`, `training_module`, `progression_graph`.
Discovery-Sortierung nutzt **`match_score`** (= Summe absoluter Gewichte der gewählten Fähigkeiten), nicht den Plan-internen Anteil. Discovery verwendet typ-getrennte Referenz (`fw_ref`, `mod_ref`, `graph_ref`).
## API
| Methode | Pfad | Beschreibung |
|---------|------|--------------|
| GET | `/api/training-framework-programs/{id}/skill-profile` | `overall` + `slots[]` mit je `profile`; `reference_scale` (Peer-Kontext Rahmenprogramme) |
| GET | `/api/training-modules/{id}/skill-profile` | `overall`; `reference_scale` (Peer-Kontext Module) |
| GET | `/api/exercise-progression-graphs/{id}/skill-profile` | `overall`; `reference_scale` (Peer-Kontext Pfade) |
| POST | `/api/skill-profiles/batch-summaries` | Kompakte Profile für Listen; Body: `frameworkProgramIds`, `trainingModuleIds`, …; Response: `summaries`, `reference_scale_by_type`, `club_best_by_skill` |
| GET | `/api/skill-discovery/suggestions?skill_ids=1,2,3` | Ranking sichtbarer Artefakte; Query `types`, `limit` |
Zugriff: `get_tenant_context` + `library_content_visibility_sql` wie Parent-Artefakt.
### `reference_scale` / `reference_scale_by_type`
```json
{
"scope": "planning_peer",
"artifact_type": "training_module",
"artifacts_scanned": 12,
"skills_in_corpus": 34,
"description": "Prozent = Anteil am stärksten sichtbaren Eintrag unter Trainingsmodulen …"
}
```
## UI
### Bearbeitung (Vollprofil)
| Ort | Panel | `artifactType` |
|-----|-------|----------------|
| Rahmenprogramm bearbeiten | Fähigkeiten-Schwerpunkte (+ Sessions) | `framework_program` |
| Trainingsmodul bearbeiten | Fähigkeiten im Modul | `training_module` |
| Progressionsgraph | Fähigkeiten entlang des Pfads | `progression_graph` |
Anzeige: Top je Kategorie (Editor) oder alle Fähigkeiten (Modal). Hinweise nennen Peer-Kontext explizit (z. B. „72 % Rahmenpr.“).
### Listen & Filter (UX wie Übungsliste)
| Liste | Filter |
|-------|--------|
| Rahmenprogramme (`/planning/framework-programs`) | Suche, Katalog (Fokus/Trainingsart/Zielgruppe), Session-Dauer, **Fähigkeiten** (`SkillTreeMultiSelect`), Mindest-% im Peer-Kontext, Sortierung nach Stärke |
| Trainingsmodule (`/planning/training-modules`) | Suche, **Fähigkeiten** (+ Min-%, Sortierung) |
- **Filter-Button** mit Badge, entfernbare **Chips**, Einstellungen im **Modal** (`PlanningArtifactFilterModal`)
- KPI-Kacheln: Top-Fähigkeit **je Unterkategorie** mit Score + Peer-%
- Vollprofil-Modal: `SkillProfileFullModal` mit `displayMode=full`
Profil wird nach Speichern neu geladen (`skillProfileTick` in Editoren).
### Discovery
**Fähigkeiten-Seite → Planungs-Vorschläge:** Multi-Select + API `/api/skill-discovery/suggestions` (optional Filter `types`).
## Frontend-Module (Auswahl)
| Pfad | Rolle |
|------|--------|
| `frontend/src/components/planning/PlanningArtifactFilterModal.jsx` | Filter-Modal |
| `frontend/src/components/planning/PlanningSkillFilterSection.jsx` | Fähigkeiten-Block im Modal |
| `frontend/src/utils/planningArtifactFilterChips.js` | Chip-Labels + Entfernen |
| `frontend/src/utils/frameworkProgramListHelpers.js` | Client-Filter Rahmenprogramme |
| `frontend/src/utils/trainingModuleListHelpers.js` | Client-Filter Module |
| `frontend/src/components/skills/SkillProfileCompact.jsx` | KPI-Kacheln in Listen |
| `frontend/src/components/SkillTreeMultiSelect.jsx` | Baumauswahl (Portal-Dropdown in Modals) |
## Grenzen / später
- Kein DB-Cache (`skill_profile_json`) — on-the-fly; bei >50 Artefakten pro Typ serverseitiger Index/Caching
- Entwicklungsziele am Rahmenkopf bleiben Freitext (kein Scoring)
- KI-Zusammenfassung (Variante B) nicht Teil von v1.0
- Trainings**einheiten** (Kalender) optional als nächste Erweiterung
- Filter-Persistenz („Als Standard speichern“) wie bei Übungen — noch nicht für Planungslisten
- Fähigkeiten-Filter im Dialog **Planung → Rahmen übernehmen** — Katalog ja, Skill-Filter optional nachziehen
- API-Feldnamen `club_*` / `skillMinClubPercent` — technische Altlast, semantisch Peer-Kontext
## Tests
- `backend/tests/test_skill_scoring.py` — Multiplikator, Aggregation, Match-Score, Cap 100 %
- **Offen:** dedizierte Tests für `compute_planning_corpus_by_type` (Typ-Trennung)
## Verweise
| Dokument | Inhalt |
|----------|--------|
| `functional/DOMAIN_MODEL.md` | Domänenabschnitt Planungs-Fähigkeiten-Profil |
| `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | Nutzerüberblick Listen/Filter |
| `docs/HANDOVER.md` | Handover-Abschnitt Phase 3 |
| `technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` | Sichtbarkeit / Mandant |
@@ -15,6 +15,8 @@
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | **Parallele Streams / Breakout innerhalb einer Einheit** — orthogonale Domäne zu **Rahmen‑Slots** (Serien‑Sessions). |
| `technical/SKILL_SCORING_SPEC.md` | **Fähigkeiten-Profil** der Rahmen‑Slots / Module / Pfade; Listen-Filter und Peer‑Vergleich (nur gleicher Artefakttyp). |
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
@@ -15,6 +15,7 @@
| Dokument | Bezug |
|----------|--------|
| `TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Bibliothek, Slot-Blueprint, Kopiersemantik (`from-framework-slot`) |
| `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | Parallele Teilstrecken **innerhalb einer Einheit**; Kombi-Übungen weiter nutzbar **pro Stream** für Stationsrotation |
| `DATABASE_SCHEMA.md` | Aktueller Stand `training_units`, Sektionen, Items |
| `functional/DOMAIN_MODEL.md` | Domänenbegriffe (bei Bedarf zu erweitern) |
| `EXERCISES_*` (Katalog) | Einzelübungen, Varianten |
@@ -13,8 +13,10 @@ 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) |
| training_modules | `/api/training-modules*` | ja | `get_tenant_context` | ja | Bibliotheks-Module wie Vorlagen/Rahmen; POST Default `club_id` bei `visibility=club` |
| training_framework_programs | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Liste + POST Default club_id |
| admin_users | `GET /api/admin/users` | Plattform | `require_auth` | Admin-Rolle | EXEMPT `check_access_layer_hints.py` |
@@ -31,19 +33,26 @@ 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-12 — Trainingsmodule (`/api/training-modules*`); Governance wie Planungsbibliothek.
Letzte Änderung: 2026-05-30 — Superadmin `/api/admin/ai-prompts*` (Prompt-Pflege, Vorschau ohne OpenRouter); weiterhin suggest + Retrieval-Profile.
---
### Changelog (Fortführung)
- **2026-05-12:** `training_modules` Router dokumentiert.
- **2026-05-30:** Superadmin-API `ai_prompts_admin` (`/api/admin/ai-prompts*`) dokumentiert.
- **2026-05-29:** Superadmin-API `ai_skill_retrieval_admin` (Retrieval-Profile) dokumentiert.
- **2026-05-22:** Übungs-KI-Endpunkte (Suggest/Regenerate) dokumentiert.
- **2026-05-13:** Dashboard-KPI-Endpunkt dokumentiert.
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
@@ -0,0 +1,67 @@
# Umsetzungsplan – KI bei Übungen (stufenweise, Driftschutz)
**Version:** 0.2
**Datum:** 2026-05-29
**Bezüge:** `functional/AI_EXERCISE_ASSISTANT_VISION.md` · **`working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`** · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `technical/AI_TRAINING_PLANNING_CONCEPT.md` (§1.1 Ist-Stand)
---
## 1. Drift vermeiden – verbindliche Regeln
1. **Spec vor Code:** Request/Response-Felder und Statuscodes an `KI_FEATURES_SPEC.md` ausrichten; Abweichungen zuerst Spec oder dieses Dokument anpassen.
2. **Prompts in der DB:** Keine produktionskritischen Prompt-Langtexte nur im Code; Defaults per **Migration** in `ai_prompts`, Anpassung durch Admins über vorgesehene Oberfläche (später) oder SQL.
3. **Skill-Retrieval-Profile:** Gewichte/Quotes in **`ai_skill_retrieval_profiles.config`** — Spezifikation `working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`; kein zweites gleichzeitiges Truth-Repo im Sourcecode außer defensiver Fallback `_FALLBACK_RETRIEVAL_CONFIG` in `exercise_ai.py`.
4. **Stufen-Slugs & Intensität:** Nur **kanonische** Werte wie in `exercises.py` (`basis` … `optimierung`, `niedrig|mittel|hoch`); LLM-Ausgaben **normalisieren**, ungültige `skill_id` verwerfen.
5. **Kein stiller DB-Write:** KI liefert **Vorschläge**; Persistenz nur über bestehende **PUT/POST exercises** inkl. Trainer-Aktion (und optional `summary_ai_generated` / `ai_suggested` wie Spec).
6. **Mandant:** Übungsbezogene KI-Endpunkte nutzen `Depends(get_tenant_context)`; keine Ausnahme ohne Eintrag in `ACCESS_LAYER_ENDPOINT_AUDIT.md`.
7. **Schema:** Neue DB-Objekte nur nummerierte Migration **`backend/migrations/`** (aktuell bis **068**) und `DB_SCHEMA_VERSION` anheben.
---
## 2. Stufen (Releases)
| Stufe | Inhalt | Exit-Kriterium |
|-------|--------|------------------|
| **S0** | Dieses Dokument + Verweise konsistent | Review abgehakt |
| **S1** | Migration `ai_prompts` + Defaults `exercise_summary`, `exercise_skill_suggestions`; `exercises.summary_ai_generated` | Migrierte DB, App startet |
| **S2** | `httpx`-Client OpenRouter; Modul lädt Prompt, ersetzt Platzhalter, parst Antwort | Unit-/Smoke: 503 ohne Key |
| **S3** | `POST /api/exercises/ai/suggest`, `POST /api/exercises/{id}/ai/regenerate` | OpenAPI/Handtest mit Key |
| **S4** | Frontend: KI-Vorschlag, **Änderungsdialog** (Vorschau, Kurzfassung wählbar, Fähigkeiten pro Zeile an-/abwählbar), dann Übernahme ins Formular | Manuelle UX-Prüfung |
| **S4b** | **Skill-Retrieval:** Migration **`ai_skill_retrieval_profiles`**, `focus_areas_context` am **`POST …/ai/suggest`**, `exercise_ai` kontextbezogener Katalog (Gewichte, Caps, Keyword-Patches) | Migration 068 angelegt; Smoke mit Gewaltschutz / ohne Fokus |
| **S5** | (später) Auto-Fallback beim Speichern laut `KI_FEATURES_SPEC` §7 | Feature-Flag / Config |
| **S6** | (später) Zielausbau, Anleitung-only, Varianten, Admin-Masse laut Vision | Separate Epics |
**Aktueller Implementierungsstand:** **S4 + S4b** im Code (`exercise_ai` + Formular übermittelt `focus_areas_context`).
---
## 3. Implementierungs-Checkliste (Technik)
- [ ] `OPENROUTER_API_KEY` / `OPENROUTER_MODEL` in `.env.example` dokumentiert (bereits teils vorhanden – prüfen).
- [ ] Fehlerbilder: `400` zu wenig Inhalt, `503` KI nicht konfiguriert, `502` Upstream-Fehler mit kurzer Message.
- [ ] Logging: **keine** vollständigen Prompts mit personenbezogenen Daten in Prod-Logs (optional DEBUG).
- [ ] Optional: Rate-Limit KI-Endpunkte (`slowapi`) – nach Bedarf.
- [ ] `MODULE_VERSIONS["exercises"]` / Changelog bei API-Erweiterung setzen.
---
## 4. Changelog dieses Plans
- **2026-05-22:** Initial; S1–S4 als erster Umsetzungspfad.
- **2026-05-22:** S1–S4 im Code umgesetzt (Migration 067, `exercise_ai` + Router, Übungsformular); S5 weiter offen.
- **2026-05-29:** **S4b:** Migration **068**, `ai_skill_retrieval_profiles`; suggest `focus_areas_context`; Frontend sendet gesetzte Fokusbereiche; Spec `working/AI_SKILL_RETRIEVAL_PROFILES_SPEC.md`.
---
## 5. Umsetzungsstand (Zwischencheckpoint)
**Erledigt (2026-05-22):** Migration **`067_ai_prompts_exercise_assistant`**, **`openrouter_chat`**, **`exercise_ai`**, **`POST /api/exercises/ai/suggest`** und **`POST /api/exercises/{id}/ai/regenerate`**, Formular-Schaltflächen (Kurzfassung / Fähigkeiten / kombiniert).
**Erledigt (2026-05-29):** Migration **`068`** / Profil **`ai_skill_retrieval_profiles`** (Standard + Profil Gewaltschutz wenn `focus_areas.name` vorhanden); **`exercise_ai`** — Score/Kategorie-Zapfen/Text-Overlap/Keyword-Zuschläge; **API:** `ExerciseAiSuggestBody.focus_areas_context`; **Regenerate** nutzt DB-Fokuszeilen.
**Nacharbeit S4 UX:** Übernahmedialog **`ExerciseFormPageRoot`**: keine sofortige Überschreibung; Kurzfassung mit Vergleich + Checkbox; Fähigkeiten mit Neu/Aktualisierung, Checkboxen, „Alle auswählen/abwählen“; **`Escape`** schließt; KI-Schaltflächen blockiert solange Dialog offen.
**Offen nächste Schritte Pflege/Umsetzung:** weitere Retrieval-Profile (z. B. Karate-/Fitness-Schwerpunkt) per SQL später Admin-UI; optionales Feld **`skills.ai_context`** Kurzbeschreibung für KI; automatische KI beim Speichern (**S5**); Prompt-/Profil-Admin-UI ohne SQL; Rate-Limits.
**Bewusst noch nicht (`summary_ai_generated`):** zurücksetzen bei manueller Kurzfassung im UI; Admin-Pflege `ai_skill_retrieval_profiles`.
@@ -0,0 +1,112 @@
# Mehrstufige KI für Trainingsplanung – Architektur-Vorschau (Anti-Refactoring)
**Version:** 0.1
**Datum:** 2026-05-22
**Status:** Planungs-/Architektur-Arbeitspapier (keine Implementierungspflicht)
**Ziel:** Für die **spätere** Planungs-KI bereits **Schnittstellen und Schichten** vorzeichnen, damit die **kleinere, starre** Übungs-KI nicht zur impliziten Vorlage für einen viel größeren Kopf wird — **ohne** jetzt eine Mitai-artige Workflow-Engine zu bauen.
**Bezüge:** `technical/AI_TRAINING_PLANNING_CONCEPT.md` · `functional/AI_EXERCISE_ASSISTANT_VISION.md` · `technical/SKILL_SCORING_SPEC.md` · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR-003) · Schwesterprojekt Mitai: `c:/dev/mitai-jinkendo` (Referenz: `prompt_executor`, `placeholder_resolver`, `workflow_*` — **nicht** Pflicht-Port).
---
## 1. Zwei getrennte Produktlinien (bewusst entkoppelt)
| Linie | Rolle | Orchestrator |
|--------|--------|----------------|
| **Übungs-KI** | wenige Eingaben → Kurzfassung / Skills; **starrer** Ablauf (1–2 Calls), kleines Kontextfenster | z. B. `exercise_ai.py` (heute) |
| **Planungs-KI** | Gruppe, Zeit, Ziele, Historie, Katalogausschnitt, Phasen/Streams → **strukturierte Planelemente** | **eigenes** Modul + **mehrstufig** (siehe §3) |
**Regel:** Shared Library nur auf **niedriger Ebene** (`openrouter_chat`-Art: HTTP, Timeouts, Modellname, Fehler-Mapping) und **gemeinsame Prompt-Tabelle** `ai_prompts`. **Keine** Vermischung der Geschäftslogik „Übung erstellen“ mit „Einheit füllen“, um später keine Abhängigkeiten reißen zu müssen.
---
## 2. Konzeptioneller „Planungs-Graph“ (Daten, nicht zwingend Graph-DB)
Für die Planungs-KI ist ein **Graph als Denkmodell** hilfreich — technisch reicht meist **PostgreSQL + bestehende FKs** (+ optional `exercise_progression_graphs`):
**Knoten-Typen (Auszug):** `training_groups`, `training_units`, `training_unit_sections` / Items, `exercises`, `skills`, `training_framework_programs` / Slots / Goals, ggf. Nachbearbeitungs-/Debrief-Metadaten.
**Kanten-Typen (Auszug):**
- **Zeitliche Folge:** Einheiten einer Gruppe nach `planned_date` / Reihenfolge
- **Inhalt:** Section-Item → `exercise_id` (± Variante)
- **Ziele:** Slot-/Framework-Ziele, Kopf-Notizen, Trainer-Zieltexte
- **Progression:** Kanten aus `exercise_progression_graphs` (optional erweitern um „empfohlene Folge im Gruppenkontext“, bleibt Spekulationsfeld)
- **Skills:** bereits über `exercise_skills`; aggregiert über `skill_scoring`-Pfad
**Wichtig:** Für KI **nicht** einen Riesen-Graphen serialisieren, sondern **Projektionen** („letzte *N* Einheiten“, „Nachbarn im Progressionsgraph zu zuletzt verwendeten Übungen“, „Skill-Gap Heuristik“).
---
## 3. Mehrstufiger Prozess (Pflichtidee für Planungs-KI)
Statt einem Prompt „mach den ganzen Plan“ mehrere **Schritte mit kleinen, validierbaren Outputs**:
| Stufe | Beispiel-Aufgabe | Deterministisch möglich? | Typischer LLM-Einsatz |
|-------|-------------------|--------------------------|------------------------|
| **S0** | Governance + Filter + Historie + Slot-Ziele zusammenstellen | Ja (SQL/API) | Nein |
| **S1** | Kandidaten-Übungen auf Top‑K schrumpfen (Skills, Volltext, Score, Wiederholungsstrafe) | Teilweise | Optional Ranking |
| **S2** | Reihenfolge je Section / Phase unter Constraints (Aufwärmen, Graphen-Nachbarn) | Teilweise | Ja (auf kleiner Liste) |
| **S3** | Zeiten auf Section/Item vorschlagen oder Plausibilisieren | Teilweise | Ja |
| **S4** | Trainer-sprachliche Kurzbegründung / Alternativen | Nein | Ja |
**Zwischen jeder Stufe:** starkes **Schema / Validierung** (z. B. nur erlaubte `exercise_id`s, nur erlaubte Slot-Struktur zu Phasen/Streams). So bleibt das System auch bei Modell-Fehlern stabil.
---
## 4. Schnittstellen-Vorsorge im Code (ohne Big-Bang)
Minimal-Ausbaustufe später, die Refactoring vermeidet:
1. **`PlanningContextPack` (internes DTO)** — reines Python-`dict`/`dataclass` oder Pydantic: aggregierte, **tokenbewusst gekürzte** Ansicht (Gruppe, nächste Einheit-Ziele, Historie-IDs, Top‑K-Kandidaten, Constraints).
2. **`planning_ai_steps` als rein **funktionale** Pipeline** — jede Stufe `(context) → context` oder `(context) → partial_suggestion`; keine globale „Prompt-String-Bastelei“ überall im Router.
3. **Prompt-Slugs pro Stufe** in `ai_prompts` (analog Übung), z. B. `planning_rank_section_items`, `planning_explain_sequence`, mit **eigenem** Platzhalter-Katalog (nicht `{{skills_catalog}}` aus Übungen recyclen).
4. **Router** `training_planning.py` (oder neuer `planning_ai.py`): nur **dünne** HTTP-Schicht, ruft Orchestrator.
Optional **später**, wenn nötig: zweite Tabelle `ai_prompt_chains` oder externe Workflow-Definition — **erst** wenn 3–4 feste Stufen nicht mehr reichen. Mitai-Workflow-Engine dann **bewusste** Option, kein Default.
---
## 5. Kontextfenster und „Kaskade“
**Kerngedanke:** Je Stufe nur **neue** Information hinzufügen, die vorherige Stufen **ersetzen** oder **verdichten**, nicht duplizieren.
Beispiel:
- Stufe A (LLM oder Heuristik): „Priorisierte Skill-Ziele für diese Session“ (kurz)
- Stufe B: Top‑40 Übungen mit **einer** Zeile pro Übung
- Stufe C: Reihenfolge für 8 IDs + 2-Satz-Begründung
So bleibt dieselbe fachliche Tiefe erreichbar ohne Kontext-Explosion.
---
## 6. Schnittstellen zu bereits vorhandenen Bausteinen
- **`skill_profiles` / `skill-discovery`:** liefern **deterministische** Ziel-/Profil-Signale für S0/S1 (`SKILL_SCORING_SPEC.md`).
- **`training_planning_prefs`:** weiche Constraints (Tone, Dauer, Split-Vorlieben).
- **`exercise_progression_graphs`:** lokale Nachbarschaft um „zuletzt verwendet“.
- **Mitai-Referenz:** Platzhalter-Katalog + Preview-API als **Inspiration** für Admin-UX; Workflow-Graph nur wenn Shinkan **wirklich** viele verzweigte Pipelines braucht.
---
## 7. Was wir **nicht** jetzt tun müssen
- Keine zweite Graph-Datenbank nur für KI.
- Keine Workflow-UI-Kopie aus Mitai.
- Keine Vereinheitlichung der Übungs-KI mit Planungs-KI über einen „Mega-Orchestrator“.
---
## 8. Kurz-Checkliste „Refactoring vermeiden“ vor erster Planungs-KI-Zeile Code
- [ ] Eigenes Modulbaum-„Root“ für Planung (nicht `exercise_ai` erweitern).
- [ ] Prompt-Slugs mit **Planungs-**Präfix und **eigenem** Platzhalter-Set dokumentieren.
- [ ] Outputs pro Stufe **JSON-Schema** oder Pydantic validieren.
- [ ] Kandidatenlisten **immer** serverseitig auf erlaubte IDs begrenzen.
---
## 9. Changelog
- **2026-05-22:** Erstfassung als Vorschau-Dokument für mehrstufige Planungs-KI.
@@ -0,0 +1,121 @@
# KI Skill-Retrieval-Profile (`ai_skill_retrieval_profiles`)
**Version:** 0.1
**Datum:** 2026-05-29
**Status:** Umsetzung gestartet (Migration **068**)
**Ziel:** Für `POST /api/exercises/ai/suggest` (Skill-Katalogauszug) **Gewichte und Quoten** steuerbar machen:
- gebunden an **Übungs-Fokusbereich** (`focus_areas.id`),
- ein **Standardprofil** ohne Fokus,
- **optional zusammengeführte** Profile bei mehreren Fokusbereichen,
- **optional Keyword-Übersteuerungen** aus Ziel/Durchführung (z. B. Rollenspiel vs. Befreiung).
**Technische Basis:** Skills mit `skills.main_category_id` → `skill_main_categories.slug` (`karate` | `allgemeine`) und `skills.category_id` → `skill_categories.slug` (`kondition`, `selbstverteidigung`, …).
**Bezüge:** `.claude/docs/working/AI_EXERCISE_IMPLEMENTATION_PLAN.md` · `backend/exercise_ai.py`
---
## 1. Datenmodell
### Tabelle `ai_skill_retrieval_profiles`
| Spalte | Typ | Beschreibung |
|--------|-----|--------------|
| `id` | serial | Primärschlüssel |
| `focus_area_id` | int NULL FK → `focus_areas(id)` ON DELETE SET NULL | **`NULL`** nur für Standardeintrag möglich (siehe `is_default`) |
| `is_default` | boolean | Genau **eine** Zeile mit `true` |
| `name` | varchar | Kurzer Name (Admin später) |
| `description` | text | Hinweise für Pflege |
| `active` | boolean | Nur aktive werden geladen |
| `config` | jsonb | Siehe §2 |
**Constraints / Indizes**
- Eindeutig: `(focus_area_id)` WHERE `focus_area_id IS NOT NULL`
- Eindeutig: `(is_default)` WHERE `is_default = true`
---
## 2. JSON-Konfiguration `config.version = 1`
Alle Schlüssel **optional**; fehlende Werte fallen auf **einprogrammierten Fallback** in `exercise_ai.py` zurück (entspricht bisher grob „neutral“).
### 2.1 Gewichtungen (Ranking)
| Schlüssel | Typ | Bedeutung |
|-----------|-----|------------|
| `main_slug_weights` | `object[str, float]` | Multiplikator pro Hauptkategorie-Slug (`karate`, `allgemeine`) |
| `category_slug_weights` | `object[str, float]` | Multiplikator pro `skill_categories.slug` |
Basis-Score (vereinfacht):
`(importance oder 3) × main_w × cat_w × text_overlap_bonus × importance_multiplier`
### 2.2 Kapazitätsbegrenzung (Liste)
`_MAX_SKILLS_CATALOG_LINES` (aktuell **240**) Zeilen Gesamt:
| Schlüssel | Typ | Bedeutung |
|-----------|-----|------------|
| `category_max_share` | `object[str, float]` | Max. Anteil dieser **Unterkategorie** am Endergebnis (0–1), z. B. `{ "kondition": 0.25 }` |
| `main_min_share` | `object[str, float]` | Mindest-Zielanteil Hauptkategorie beim **Auswahl-Greedy** (weich; Rest nach Score aufgefüllt) |
### 2.3 Text / Token-Sparen
| Schlüssel | Typ | Standard | Bedeutung |
|-----------|-----|----------|------------|
| `description_plain_max_len` | int | 160 | Gekürzte Beschreibung pro Zeile |
| `karate_relevance_max_len` | int | **0** oder 80 | **`0`** = Feld `karate_relevance`/`relevance_level` in der Promptzeile **weglassen** |
### 2.4 Keyword-Overrides (optional)
Liste `keyword_overrides`: jedes Element:
```json
{
"keywords_any": ["befreiung", "haltegriff"],
"case_insensitive": true,
"patch": {
"category_slug_weights": { "selbstverteidigung": 2.5 },
"category_max_share": { "koordination": 0.1 }
}
}
```
Textsuche in verkettetem Korpus **Titel, Ziel, Durchführung, Focus-Hint** (bereits plaintext). Reihenfolge: erst Basis-Profile zusammenmergen, dann **alle treffenden Overrides**‑`patch`‑Objekte **flach zusammenführen** (Gewichte multiplikativ übereinander, Caps den strengsten Wert nehmen – aktuelle Implementierung im Code dokumentiert).
---
## 3. Mehrere Fokusbereiche auf der Übung
Request-Body: `focus_areas_context: [{ "focus_area_id": n, "is_primary": bool }, …]`
**Aktuelle Merge-Strategie (v1):** Profile laden → **gleichgewichtete Mittelwert-Bildung** der numerischen Gewichte / Caps (implementiert für `main_slug_weights`, `category_slug_weights`, `category_max_share`, `main_min_share`, `*_max_len`). Anschließend **Keyword-Overrides** anwenden.
**Primär-Fokus:** Im Frontend soll die **primäre** Zeile aus `focus_areas_multi` **zuerst** in der Liste stehen; die Merge-Strategie kann später zu „Primär dominate“ erweitert werden.
Ohne Kontext oder ohne Treffer auf aktive Profile: **nur Standardprofil** (`is_default`).
---
## 4. Seed-Daten (Migration)
- **`is_default=true`:** ausgewogene Standard-Gewichte, moderate Caps auf `kondition`/`koordination`, Karate-Relevanz gekürzt.
- **`Gewaltschutz`:** `focus_area_id` per `(SELECT id FROM focus_areas WHERE name = 'Gewaltschutz' LIMIT 1)` — höhere Gewichte für `kognition`, `psychische_faehigkeiten`, `soziale_faehigkeiten`, `selbstverteidigung`; gedrosseltes `kondition`/`koordination`; `karate_relevance_max_len`: 0; Keyword-Patches wie oben können nachgeschärft werden.
Weitere Profile (Karate-Schwerpunkt etc.) später per Admin-SQL oder UI.
---
## 5. API
`ExerciseAiSuggestBody` erweitert um **`focus_areas_context`** (Liste). Feld **`focus_area_hint`** bleibt für den **Prompt-Kontext** (bestehende Prompts).
`POST …/ai/regenerate` nutzt gespeicherte `exercise_focus_areas` zur gleichen Retrieval-Logik wie Suggest.
**Pflege der Profile:** Superadmin ohne Mandantenwahl — **`GET|POST /api/admin/ai-skill-retrieval-profiles`**, **`GET|PUT|DELETE /api/admin/ai-skill-retrieval-profiles/{id}`** (`routers/ai_skill_retrieval_admin.py`); Web-UI Superadmin unter **`/admin/ai-skill-retrieval`**.
## 6. Changelog
- **2026-05-29:** Superadmin-Pflege-Endpoints + UI‑Route dokumentiert (`/admin/ai-skill-retrieval`).
- **2026-05-29:** Erstellt; gekoppelt an Migration **068** und erste `exercise_ai`-Integration.
@@ -0,0 +1,58 @@
# Rahmenprogramm: Filter, Dauer, Fähigkeiten-Schwerpunkte (Roadmap)
**Stand:** 2026-05-20
**Status:** Phase 1 umgesetzt; Phase 3 v1.0 umgesetzt (regelbasiert); Phase 2 teilweise offen
## Phase 1 (umgesetzt)
### Listen-Anzeige Session-Dauer
- **GET `/api/training-framework-programs`:** `session_duration_min`, `session_duration_max` (aus Blueprint-`training_units.planned_duration_min`), `goal_titles_agg`, ID-Arrays für Katalog-M:N.
- **UI:** Rahmenprogramm-Liste, Trainingsplanung (Einheiten-Liste/Kalender), Import-Dialog (Programm + pro Slot).
### Import-Filter (clientseitig)
- Textsuche (Titel, Beschreibung, Ziele, Katalog-Namen)
- Fokusbereich, Trainingsart, Zielgruppe (Checkboxen, Katalog-API)
- Ziel-Session-Dauer in Minuten (±10 Min Toleranz gegen Min/Max der Slots)
**Grenze:** Entwicklungsziele sind **freie Texte** pro Rahmen (`training_framework_goals.title`), keine kontrollierte Taxonomie → Filter nur Volltext, keine homogene „Ziel-Tags“-Liste.
## Phase 2 (empfohlen, ohne KI)
| Kriterium | Datenquelle heute | Verbesserung |
|-----------|-------------------|--------------|
| Fokusbereich / Stil / Trainingsart / Zielgruppe | M:N am Rahmenkopf | bereits filterbar |
| Entwicklungsziele | Freitext-Ziele | Optional: Ziel-Vorlagen-Katalog oder Tags (Migration) |
| Session-Dauer | `planned_duration_min` pro Slot | erledigt |
| Fähigkeiten-Schwerpunkt | noch nicht | siehe Phase 3 |
**API-Erweiterung (optional):** `GET /api/training-framework-programs?focus_area_id=&training_type_id=&duration_min=` serverseitig — sinnvoll ab >50 Rahmen in der Bibliothek.
## Phase 3 — Fähigkeiten aus Übungen (umgesetzt v1.0)
**Spec:** `.claude/docs/technical/SKILL_SCORING_SPEC.md`
- Gewichtetes Profil: Rahmenprogramm (gesamt + pro Slot), Trainingsmodul, Progressionsgraph
- `GET /api/skill-discovery/suggestions?skill_ids=…` für Bibliotheks-Vorschläge
- UI: Profil-Panels in Editoren + Tab „Planungs-Vorschläge“ auf der Fähigkeiten-Seite
- **Kein** automatisches Überschreiben der Stammdaten-Fokusbereiche
### Variante B — KI-Zusammenfassung (OpenRouter, optional, offen)
1. Input: Titel Rahmen, Ziele (Text), Liste Übungstitel + Dauer + vorhandene Skill-Namen.
2. Prompt: strukturiertes JSON (`suggested_focus_areas[]`, `skill_emphasis[]`, `rationale_de`).
3. Speichern als `ai_context_summary` (Version, Modell, Timestamp) — **nur Vorschlag**, manuelle Bestätigung vor Übernahme in Stammdaten.
**Vorteil:** natürliche Schwerpunkte auch bei unvollständigen Skill-Links.
**Risiko:** Halluzination, Kosten, Datenschutz (Vereinsdaten in Prompt).
### Empfehlung
Zuerst **Variante A** für Listen/Filter und Abgleich mit manuell gesetzten Fokusbereichen; KI nur als **„Vorschlag generieren“-Button** im Rahmen-Editor, wenn Regelwerk und Katalog-Zuordnung zu dünn sind.
## Offene Produktfragen
1. Soll Filter **UND** (alle Kriterien) oder **ODER** (mindestens eines) sein? — Import aktuell **UND**.
2. Rahmen mit **unterschiedlichen** Slot-Dauern: Liste zeigt Min–Max; Filter „90 Min“ trifft Range.
3. Sollen homogenisierte **Entwicklungsziel-Tags** ein eigener Katalog werden (Admin), analog `target_groups`?
@@ -0,0 +1,125 @@
# Parallele Trainingsstreams — Ist-Analyse und risikoarmer Umsetzungsplan
**Status:** Stufe A (Analyse/Plan, ohne produktive Umsetzung in jener Session)
**Stand:** 2026-05-14
**Verbindliche fachliche Basis:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
Dieses Dokument **persistiert** die strukturierte Prüfung der realen Codebasis (`training_planning.py`, `training_framework_programs.py`, `training_unit_sections`/`items`, Frontend Planung/Run/Coach) und den empfohlenen Implementierungspfad.
---
## 1. Zusammenfassung
- Plan-Inhalt pro Einheit ist heute **eine flache Liste** `training_unit_sections` mit **`UNIQUE (training_unit_id, order_index)`** (Migration 031) und `training_unit_section_items`; zentral: **`_fetch_sections`**, **`_replace_unit_sections`**, **`_hydrate_training_unit_payload`** in `backend/routers/training_planning.py`.
- Parallele Phasen/Streams **passen** zu den Produktregeln (ein Kalendertermin, N Streams, je Miniplan), sind im Schema aber **nicht** abbildbar ohne Erweiterung und **ohne Auflösung** des globalen `order_index`-Modells.
- **Empfehlung:** **Normalisierte** Tabellen `training_unit_phases`, `training_unit_parallel_streams`, erweiterte `training_unit_sections` mit FK auf Phase bzw. Stream, **partielle Unique-Indizes** statt `UNIQUE (training_unit_id, order_index)` für alle Sektionen.
- **Blocker im Code:** u. a. `POST /api/training-units/{id}/apply-training-module` mit **`section_order_index` global pro Einheit** (`_resolve_training_unit_section_id`).
- **Nicht persistiert an anderer Stelle:** Erste Fassung existierte nur als Chat-Antwort; dieses File ist die **kanonische** Arbeitskopie im Repo.
---
## 2. Ist-Analyse (kurz)
### Datenbank
- `training_unit_sections`: u. a. `training_unit_id`, `order_index`, `UNIQUE (training_unit_id, order_index)`.
- `training_unit_section_items`: Übung/Notiz, `planning_method_profile` (Kombi), `source_training_module_id`.
### Backend (`training_planning.py`)
- `_replace_unit_sections`: DELETE aller Sektionen der Einheit + INSERT (vollständiger Ersetzungsbaum).
- `_sections_clone_payload` + `_copy_blueprint_into_scheduled_unit`: tiefe Kopie für `from-framework-slot`.
- `_flatten_exercises_from_sections`: flaches `exercises` am Unit-Payload.
- `apply_training_module_to_training_unit`: Sektion per **`section_order_index`** global.
### Rahmen (`training_framework_programs.py`)
- Blueprint-`training_units` pro Slot; gleiche `_replace_unit_sections`-Semantik.
### Frontend
- Planung: `TrainingPlanningPageRoot.jsx`, `TrainingUnitSectionsEditor`, `buildSectionsPayload` / `normalizeUnitToForm`.
- Run: `TrainingUnitRunPage.jsx` — Fortschritt `sessionStorage` Key `sj_training_run_checked_${unitId}`.
- Coach: `TrainingCoachPage.jsx` — `flattenPlanTimeline` (linearer Ablauf).
### Tests
- Kaum Abdeckung für Plan-Inhalt; vorhanden u. a. `test_training_unit_assignments.py` (Merge Co-Trainer, ohne DB), `test_training_units_list_keyset.py` (Keyset-Validierung).
---
## 3. Technische Optionen und Empfehlung
| Option | Kurz |
|--------|------|
| A JSONB nur auf `training_units` | Niedriges DDL-Risiko, hohes Drift-/Wartungsrisiko — **nicht empfohlen** |
| B Normalisiert Phasen/Streams | **Empfohlen** — eine Wahrheit, saubere Kopie, Rahmen kompatibel |
| C Nur UI-Konvention ohne DB | Widerspricht Produkt — **abgelehnt** |
---
## 4. Migrations- und Kompatibilitätsstrategie
- Default **`whole_group`‑Phase** für alle bestehenden Einheiten; alle bisherigen Sektionen erhalten `phase_id`.
- Unique-Regel: **pro Phase** bzw. **pro Stream** `order_index` eindeutig (partielle Unique-Indizes).
- API optional: zusätzlich abgeleitetes flaches `sections` für Übergang — Entscheidung je nach Consumer (praktisch nur dieses Frontend).
---
## 5. API- / Frontend-Hotspots
- `GET`/`PUT` `/api/training-units/{id}`: verschachtelte `phases` / `streams` / `sections` / `items`.
- `POST .../apply-training-module`: Kontext **Phase/Stream + Sektionsindex im Träger**.
- Run/Coach: stream-spezifischer Fortschritt; `flattenPlanTimeline` phase-aware oder pro Stream.
---
## 6. Implementierungspakete (Überblick)
0. Spike DDL + Contract-Doku
1. **Erledigt (2026-05-14):** Migration **063** + `training_planning`: Phasen/Streams-Schema, Backfill whole_group, `GET` mit `phases`, Legacy-`sections`-PUT unverändert (eine whole_group-Phase).
2. PUT mit echten Parallelphasen / Streams, `apply-training-module` mit Stream-Kontext, `from-framework-slot`-Kopie
3. Planung UI
4. Run + Coach
5. Co-Trainer pro Stream
6. MVP+ (Duplizieren, Verschieben, „nur meine Spur“)
---
## 7. Risiken
- Migration Unique-Constraint / bestehende Daten.
- Regression Run/Coach / Dashboard-Joins (meist unkritisch, solange `training_unit_id` auf Sektionen bleibt).
- Rahmen-Blueprints: gleiche Struktur wie Kalender-Einheiten anstreben (oder bewusst zweite Phase nur Kalender).
---
## 8. Offene Produkt-/Technikfragen
- Rahmen-Blueprint parallel im MVP oder erst nach Kalender-Einheit?
- Semantik `exercises`-Flatlist bei Parallelität.
- Merge-Regel `assistant_trainer_profile_ids` Kopf vs. Stream-Zuweisungen.
---
## 9. Verweise
- Fachkonzept: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
- Technische Spec (Entwurf): `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
- Domänenüberblick: `.claude/docs/functional/DOMAIN_MODEL.md` (Abschnitt Parallele Streams)
- `./PARALLEL_TRAINING_STREAMS_PREREQ_PROMPT.md` — **Prompt** für Folgesession (Performance/Wartung/Vorbereitung)
---
## 10. Vorbereitende Arbeiten (Session 2026-05-13)
Ohne produktives Parallel-Feature, nur Risikoabbau und Transparenz:
- **`training_planning.py`:** Lesepfad `_fetch_sections` in SQL-Konstanten + `_fetch_section_items_for_section` / `_hydrate_section_item_combination_slots` strukturiert; `_replace_unit_sections` delegiert an `_insert_one_replacement_section`; `_hydrate_training_unit_payload` dokumentiert.
- **Tests:** `tests/test_training_planning_sections_pure.py` (flatten, ohne DB); `tests/test_training_planning_sections_integration.py` (Roundtrip replace↔fetch bei `TRAINING_PLANNING_INTEGRATION=1`).
- **Frontend:** Kurzkommentare an Planung (`TrainingPlanningPageRoot`, `buildSectionsPayload`), Run, Coach, `flattenPlanTimeline` — Anbindungspunkte für spätere Phase/Stream-Logik.
- **DOMAIN_MODEL:** UNIQUE-Hinweis und „keine Migration ohne Freigabe“.
**Empfohlene nächste Schritte:** Pakete **0** (DDL/Contract festzurren) und **1** (Schema + Migration + hydrate/replace laut Plan Abschnitt 4–6) in einer dedizierten Feature-Session; danach Paket **2** (PUT/Module/Clone).
---
@@ -0,0 +1,41 @@
# Prompt: Vorbereitungs- / Vorarbeit-Session (Performance & Wartung) für „Parallele Trainingsstreams“
**Kontext:** Du arbeitest in **Shinkan Jinkendo** (`c:\Dev\shinkan-jinkendo`). Das Feature **Parallele Trainingsstreams / Breakout** ist **inhaltlich** spezifiziert; eine **Ist-Analyse und ein risikoarmer Umsetzungsplan** liegen **persistiert** in:
- `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`
- Fachlich: `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
- Technik-Entwurf: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
**Deine Rolle:** Du hast bereits **Refaktorierungs- und Wartungsaufgaben** mit Fokus **Performance, Lesbarkeit und Testbarkeit** durchgeführt. In **dieser** Session geht es **nicht** darum, das komplette Parallel-Feature zu bauen, sondern um **Vorarbeiten („Prerequisites“)**, die die geplante Komplexitätsauflösung **sicherer und billiger** machen.
## Ziele
1. **Lesepfad Planung vereinheitlichen:** `backend/routers/training_planning.py` ist zentral für `_fetch_sections`, `_replace_unit_sections`, `_hydrate_training_unit_payload`, Klonen, Blueprint-Kopie, `apply-training-module`. Prüfe, ob klar abgegrenzte Hilfsfunktionen (ohne Verhaltensänderung) die **nächste** große Änderung erleichtern — **keine** Feature-Logik für Phasen/Streams hinzufügen, nur Struktur/Tests/Docs wenn nötig.
2. **Test-Lücken schließen (minimal, hoher Nutzen):** Heute fehlen **DB/API-Tests** für kritische Pfade (`_replace_unit_sections` Roundtrip, `from-framework-slot` Struktur-Kopie, optional `apply-training-module`). Ergänze **kleine, deterministische** Tests (pytest mit DB, falls im Projekt üblich), ohne riesige Fixtures.
3. **Frontend-Schneidstellen markieren:** kurze Kommentare oder ein **Working-Doc-Update**, wo `TrainingPlanningPageRoot`, `buildSectionsPayload`, `TrainingUnitRunPage`, `TrainingCoachPage` + `trainingPlanUtils.flattenPlanTimeline` später angebunden werden — **kein** großes UI-Rewrite.
4. **Migrations-Sicherheit:** Dokumentiere in **einem Absatz** im `ANALYSIS`-Dokument oder hier, welche **Unique-Constraints** (`training_unit_sections`: `UNIQUE (training_unit_id, order_index)`) die Parallelität blockieren — **ohne** sie schon zu ändern, außer es ist Teil einer **explizit** freigegebenen ersten Migration.
5. **Performance nur berührensensible Stellen:** Einzelabruf `GET /api/training-units/{id}` wird mit mehr JOINs kommen. Falls du **jetzt** N+1 oder redundante Arbeit in `_fetch_sections` siehst und das **risikoarm** verbesserbar ist, nur mit **Messpunkt/Messvorstellung** (kein unnötiger Micro-Optimismus).
## Leitplanken
- **Stabilität vor Geschwindigkeit:** Keine Änderung, die bestehende Einheiten, Rahmen-Blueprints oder Run-Modus bricht.
- **Keine pauschalen Refactors:** Nur Änderungen mit **klarem** Träger für das Parallel-Feature oder mit **Test-Regression-Schutz**.
- **Regeln:** `.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht wo relevant.
## Erwartete Ausgabe
1. Kurze **Liste erledigter Vorarbeiten** (Dateien, was warum).
2. **Empfohlene Reihenfolge** für die **nächste** Session, die Phasen/Streams **implementiert** (verweis auf `PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md` Pakete 0–2).
3. Falls nichts Sinnvolles ohne Feature-Branch riskiert werden kann: **explizit** „keine Code-Änderung“, nur Risiko-Notiz.
## Optionaler Startbefehl
```
Lies zuerst:
.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md
dann backend/routers/training_planning.py (Abschnitte um _fetch_sections, _replace_unit_sections).
```
@@ -2,7 +2,7 @@
**Bezug:** `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (Kopf „V3“, inkl. **§ 10.2.1**, **§ 10.4 Coaching-Stufen**, **Anhang A** Implementierungsabgleich — Drift-Schutz)
**Technische Entwurfsspezifikation:** `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md`
**Stand dieses Dokuments:** 2026-05-12 (Abgleich mit Code App **0.8.110**, siehe `backend/version.py`)
**Stand dieses Dokuments:** 2026-05-20 (Abgleich mit Code, siehe `backend/version.py`)
## Ziele
@@ -12,7 +12,7 @@ Umsetzung der MVP-Punkte aus der Fachspezifikation ohne die bestehende Planung z
| Phase | Inhalt | Status |
|-------|--------|--------|
| **1** | **Trainingsmodule (Bibliothek):** Tabellen `training_modules`, `training_module_items`; REST CRUD mit Governance wie andere Bibliotheken; Übernahme in eine bestehende Einheit per `POST /api/training-units/{id}/apply-training-module` (Anfügen ans Ende eines Abschnitts via `section_order_index`); optionale Lineage-Spalte `source_training_module_id` auf Planungsitems; UI: Liste/Editor unter `/planning/training-modules`, Link von der Planung, Modal „Modul übernehmen“ | **umgesetzt (MVP Schritt 1)** |
| **1** | **Trainingsmodule (Bibliothek):** Tabellen `training_modules`, `training_module_items`; REST CRUD mit Governance wie andere Bibliotheken; Übernahme in eine bestehende Einheit per `POST /api/training-units/{id}/apply-training-module` (Anfügen ans Ende eines Abschnitts via `section_order_index`); optionale Lineage-Spalte `source_training_module_id` auf Planungsitems; UI: Liste/Editor unter `/planning/training-modules`, Link von der Planung, Modal „Modul übernehmen“; **Ergänzung 2026-05-20:** Fähigkeiten-Profil + Listen-Filter (Peer-Vergleich nur unter Modulen) — `technical/SKILL_SCORING_SPEC.md` | **umgesetzt (MVP Schritt 1)** |
| **2** | Kombinationsübungen: `exercise_kind`/`combination_*`, Slots, Pools, `method_archetype`, `method_profile` (JSON) | **teilweise** — wie links; zusätzlich **057** `planning_method_profile`; Planungs-Merge Client (`effectiveComboMethodProfile`); Archetypen weiterhin **nur Code-Konstanten** (kein Admin) | **Offen:** Archetyp-Admin-UI; Profil↔Archetyp-Validierung Backend; „alle Slots vorbelegen“ / Presets (siehe Fachspez **§ 10.6**); Haupt-/Nebenmethoden an Kombi wo Spec es verlangt |
| **3** | Planungsblöcke: Gruppierung, Auflösen, „als Modul speichern“, erweiterter Übernahmemodus (Zwischenposition) | geplant |
| **4** | Coaching: Archetyp-Support | **teilweise:** **Stufe A** — Merge Katalog+Planung; `CombinationPlanBracket` in Peek/Run; globale Profilzahlen mit Labels (`describeGlobalComboProfile`); Stations-/Timing-Zusammenfassung inkl. Wdh.-Hinweise. **Stufe B/C** — **offen** (§ 10.6, Anhang A) |
+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
+86 -2
View File
@@ -10,7 +10,7 @@ on:
types: [completed]
jobs:
# Wie Mitai-Jinkendo: pytest im laufenden backend-Container (Python aus Image, gleiche DB wie Deploy).
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
pytest-backend:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
@@ -39,7 +39,7 @@ jobs:
cd /app &&
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
python scripts/security_release_checks.py &&
ACCESS_LAYER_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
ACCESS_LAYER_INTEGRATION=1 TRAINING_PLANNING_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
"
lint-backend:
@@ -88,6 +88,90 @@ jobs:
npm run build
echo "✓ Frontend build OK"
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
k6-health-baseline:
name: k6 /health Baseline
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
env:
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
id: e2e
run: |
EVENT="${{ github.event_name }}"
WF_NAME="${{ github.event.workflow_run.name }}"
DEV_BASE="${{ env.E2E_TARGET_URL }}"
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
echo "mode=prod" >> $GITHUB_OUTPUT
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
echo "→ k6 gegen Prod-Basis."
else
echo "mode=dev" >> $GITHUB_OUTPUT
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
echo "→ k6 gegen Dev (${DEV_BASE})."
fi
- name: Dev /health abwarten
if: ${{ steps.e2e.outputs.mode == 'dev' }}
run: |
BASE="${{ steps.e2e.outputs.base_url }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 90); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
echo "Health OK (Versuch $i)"
exit 0
fi
sleep 2
done
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
curl -v "$BASE/health" || true
exit 1
- name: Prod /health abwarten
if: ${{ steps.e2e.outputs.mode == 'prod' }}
run: |
BASE="${{ steps.e2e.outputs.base_url }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 60); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
echo "Health OK (Versuch $i)"
exit 0
fi
sleep 5
done
echo "Timeout: Prod /health nicht erreichbar"
curl -v "$BASE/health" || true
exit 1
- name: Install k6
run: |
set -e
K6_VER="v0.55.0"
ARCH=$(uname -m)
case "$ARCH" in
x86_64) K6_ARCH=amd64 ;;
aarch64|arm64) K6_ARCH=arm64 ;;
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
esac
echo "Installing k6 ${K6_VER} linux-${K6_ARCH}"
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
tar -xzf /tmp/k6.tgz -C /tmp
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
k6 version
- name: k6 Health-Baseline (parallele /health)
env:
BASE_URL: ${{ steps.e2e.outputs.base_url }}
run: |
set -e
echo "k6 gegen BASE_URL=$BASE_URL"
k6 run scripts/load/k6-health-baseline.js
echo "✓ k6 Health-Baseline passed"
playwright-tests:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
+6 -1
View File
@@ -12,8 +12,12 @@
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
> | Fähigkeiten-Scoring (Planungs-Bausteine) | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
> | Fachlicher Nutzerüberblick (Design/Product) | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
> | KI-Prompt-System — Zielarchitektur | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
## Projekt-Übersicht
@@ -84,10 +88,11 @@ frontend/src/
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
Kurz (Stand 2026-05-12): App **0.8.96**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
Kurz (Stand 2026-05-14): App- und DB-Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit **Phasen & parallelen Streams (Breakout, 063)**, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `PARALLEL_TRAINING_STREAMS_SPEC.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
### Log (Auszug)
- 2026-05-20: **Fähigkeiten-Scoring Phase 3** — gewichtete Profile für Module/Rahmen/Pfade; Peer-Vergleich getrennt nach Artefakttyp; Listen-Filter + Discovery — siehe `SKILL_SCORING_SPEC.md`, `docs/HANDOVER.md` §2.6, `FEATURES_DELIVERED_2026-Q2.md` §15.
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
+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",
]
+160 -1
View File
@@ -3,7 +3,7 @@ Vereins-Mandanten: Mitgliedschaften, aktiver Vereinskontext, einfache Berechtigu
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
"""
from typing import Any, Dict, List, Optional, Set
from typing import Any, Dict, List, Mapping, Optional, Set, Union
from fastapi import HTTPException
@@ -155,6 +155,165 @@ def club_ids_for_profile_with_roles(cur, profile_id: int, *role_codes: str) -> S
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
def _library_governance_triplet(
row: Mapping[str, Any],
) -> tuple[str, Optional[int], Optional[int]]:
"""visibility, club_id, created_by als normalisierte Werte für Bibliotheks-/Planungsartefakte."""
vis = str(row.get("visibility") or "private").strip().lower()
if vis not in _GOVERNANCE_VISIBILITY:
vis = "private"
cid_raw = row.get("club_id")
try:
ex_cid = int(cid_raw) if cid_raw is not None else None
except (TypeError, ValueError):
ex_cid = None
cr_raw = row.get("created_by")
try:
creator = int(cr_raw) if cr_raw is not None else None
except (TypeError, ValueError):
creator = None
return vis, ex_cid, creator
def assert_library_content_editable(
cur,
profile_id: int,
role: Optional[str],
row: Union[Dict[str, Any], Mapping[str, Any]],
) -> None:
"""Inhalt bearbeiten: wie Übungen — Ersteller, Plattform-Admin oder Planungsberechtigter im Verein."""
pid = int(profile_id)
ex_vis, ex_cid, creator = _library_governance_triplet(row)
if creator is not None and creator == pid:
return
if is_platform_admin(role):
return
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, pid, ex_cid, role):
return
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Bearbeiten dieses Inhalts")
def assert_library_content_deletable(
cur,
profile_id: int,
role: Optional[str],
row: Union[Dict[str, Any], Mapping[str, Any]],
) -> None:
"""Löschen: wie Übungen — privat Eigentümer/Vereins-Admin-Kontext, Verein nur Vereinsadmin, offiziell nur Plattform."""
pid = int(profile_id)
if is_platform_admin(role):
return
vis, cid, creator = _library_governance_triplet(row)
try:
creator_int = int(creator) if creator is not None else None
except (TypeError, ValueError):
creator_int = None
if vis == "official":
raise HTTPException(
status_code=403,
detail="Offizielle Inhalte dürfen nur von Plattform-Admins gelöscht werden.",
)
if vis == "club":
try:
ex_club = int(cid) if cid is not None else None
except (TypeError, ValueError):
ex_club = None
if ex_club is None:
raise HTTPException(status_code=400, detail="Vereinsinhalt ohne gültige Vereinszuordnung")
if not has_club_role(cur, pid, ex_club, "club_admin"):
raise HTTPException(
status_code=403,
detail="Nur Vereins-Admins dürfen Vereins-Inhalte löschen.",
)
return
if creator_int is not None and creator_int == pid:
return
if creator_int is not None and club_admin_shares_club_with_creator(cur, pid, creator_int):
return
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Löschen dieses Inhalts")
def assert_library_content_governance_transition(
cur,
profile_id: int,
role: Optional[str],
prev_row: Union[Dict[str, Any], Mapping[str, Any]],
next_visibility: str,
next_club_id: Optional[int],
) -> None:
"""
Zusätzliche Regeln beim Ändern von visibility/club_id (Zielzustand vor assert_valid_governance_visibility prüfen).
- Abwahl „official“: nur Plattform-Admin.
- private → club: nur Ersteller (oder Plattform-Admin).
- club → private: Ersteller, Vereinsadmin im bisherigen Verein oder Plattform-Admin.
- club → club mit Wechsel club_id: Vereinsadmin im alten oder neuen Verein oder Plattform-Admin.
"""
nv = str(next_visibility or "").strip().lower()
if nv not in _GOVERNANCE_VISIBILITY:
raise HTTPException(status_code=400, detail="Ungültige visibility")
old_vis, old_cid, creator = _library_governance_triplet(prev_row)
new_cid: Optional[int]
try:
new_cid = int(next_club_id) if next_club_id is not None else None
except (TypeError, ValueError):
new_cid = None
pid = int(profile_id)
try:
creator_int = int(creator) if creator is not None else None
except (TypeError, ValueError):
creator_int = None
if old_vis == nv and (nv != "club" or old_cid == new_cid):
return
if old_vis == "official" and nv != "official":
if not is_platform_admin(role):
raise HTTPException(
status_code=403,
detail="Nur Plattform-Admins dürfen offizielle Inhalte auf Verein oder privat setzen.",
)
if nv == "official":
return
if old_vis == "private" and nv == "club":
if creator_int is not None and creator_int != pid and not is_platform_admin(role):
raise HTTPException(
status_code=403,
detail="Nur der Ersteller darf private Inhalte für den Verein freigeben.",
)
return
if old_vis == "club" and nv == "private":
if is_platform_admin(role):
return
if creator_int is not None and creator_int == pid:
return
if old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin"):
return
raise HTTPException(
status_code=403,
detail="Nur Ersteller, Vereins-Admins oder Plattform-Admins dürfen Vereins-Inhalte auf privat setzen.",
)
if old_vis == "club" and nv == "club" and old_cid != new_cid:
if is_platform_admin(role):
return
ok_old = old_cid is not None and has_club_role(cur, pid, old_cid, "club_admin")
ok_new = new_cid is not None and has_club_role(cur, pid, new_cid, "club_admin")
if ok_old or ok_new:
return
raise HTTPException(
status_code=403,
detail="Nur Vereins-Admins oder Plattform-Admins dürfen die Vereinszuordnung ändern.",
)
def assert_valid_governance_visibility(
cur,
profile_id: int,
+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
+16
View File
@@ -0,0 +1,16 @@
"""Hilfen für direkte Python-Aufrufe von FastAPI-Route-Handlern (ohne Request-Kontext)."""
from __future__ import annotations
from typing import Any
def unwrap_query_default(value: Any) -> Any:
"""
Parameter mit Annotation ``= Query(default=…)`` sind im Funktionskörper ``fastapi.params.Query``-Instanzen,
solange FastAPI sie nicht durch echte Werte ersetzt hat (interne Aufrufe, Aggregat-Endpunkte).
"""
try:
from fastapi.params import Query
except ImportError:
return value
return value.default if isinstance(value, Query) else value
+6 -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, training_planning, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, skill_profiles, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, 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)
@@ -208,16 +208,21 @@ app.include_router(media_assets.router)
app.include_router(media_assets.admin_rights_router)
app.include_router(media_assets.admin_legal_hold_router)
app.include_router(skills.router)
app.include_router(skill_profiles.router)
app.include_router(training_planning.router)
app.include_router(dashboard.router)
app.include_router(training_modules.router)
app.include_router(training_framework_programs.router)
app.include_router(catalogs.router)
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,7 @@
-- Unterstützung für GET /api/exercises: ORDER BY e.updated_at DESC
-- und häufiger Pfad created_by_me (= e.created_by = Profil) mit derselben Sortierung.
-- Hinweis: idx_exercises_created_at (014) betrifft created_at, nicht updated_at.
CREATE INDEX IF NOT EXISTS idx_exercises_updated_at_desc ON exercises (updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_exercises_created_by_updated_at_desc ON exercises (created_by, updated_at DESC);
@@ -0,0 +1,7 @@
-- GET /api/training-units: Liste nutzt immer tu.framework_slot_id IS NULL (keine Rahmen-Blueprints)
-- und sortiert nach planned_date, planned_time_start (ASC/DESC mit NULLS LAST).
-- Teilindex verkleinert die Menge und unterstützt die Sortierung.
CREATE INDEX IF NOT EXISTS idx_training_units_scheduled_order
ON training_units (planned_date DESC, planned_time_start DESC NULLS LAST)
WHERE framework_slot_id IS NULL;
@@ -0,0 +1,33 @@
-- Migration 060: Übungslisten bei großem Bestand (Ziel: Tausende Übungen, viele Filterkombinationen).
-- Ergänzt 058 (globale Sortierung / created_by): kleinere Partial-Indizes für häufige
-- Sichtbarkeits-Pfade der Bibliothek sowie Junction-Indizes für die List-Subqueries
-- (primary_focus_name / JSON-Aggregate mit is_primary).
--
-- Bereits vorhanden und sinnvoll: UNIQUE(exercise_id, …) auf den M:N-Tabellen für EXISTS-Joins;
-- GIN auf exercises.search_vector (014); idx_exercises_exercise_kind (056).
-- Official: OR-Zweig der Bibliothek — kompakter als Full-Table-Scan bei BitmapOr mit anderen Partial-Indizes
CREATE INDEX IF NOT EXISTS idx_exercises_list_official_updated
ON exercises (updated_at DESC)
WHERE visibility = 'official'
AND COALESCE(status, '') <> 'archived';
-- Club: häufig club_id + Sortierung nach updated_at (Mandanten-Bibliothek)
CREATE INDEX IF NOT EXISTS idx_exercises_list_club_updated
ON exercises (club_id, updated_at DESC)
WHERE visibility = 'club'
AND club_id IS NOT NULL
AND COALESCE(status, '') <> 'archived';
-- List-SELECT: Subqueries / json_agg sortieren zuerst nach is_primary (siehe exercises.py)
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_exercise_primary
ON exercise_focus_areas (exercise_id, is_primary DESC NULLS LAST, focus_area_id);
CREATE INDEX IF NOT EXISTS idx_exercise_style_directions_exercise_primary
ON exercise_style_directions (exercise_id, is_primary DESC NULLS LAST, style_direction_id);
CREATE INDEX IF NOT EXISTS idx_exercise_training_types_exercise_primary
ON exercise_training_types (exercise_id, is_primary DESC NULLS LAST, training_type_id);
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_exercise_primary
ON exercise_target_groups (exercise_id, is_primary DESC NULLS LAST, target_group_id);
@@ -0,0 +1,22 @@
-- GET /api/training-units: Keyset über (planned_date, planned_time_start NULLS LAST per Sort, id)
-- Ersetzt den reinen Datum/Uhrzeit-Teilindex 059 durch zwei Richtungen mit Tie-Break id.
DROP INDEX IF EXISTS idx_training_units_scheduled_order;
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_desc
ON training_units (
planned_date DESC,
(planned_time_start IS NULL) ASC,
planned_time_start DESC NULLS LAST,
id DESC
)
WHERE framework_slot_id IS NULL;
CREATE INDEX IF NOT EXISTS idx_training_units_list_keyset_asc
ON training_units (
planned_date ASC,
(planned_time_start IS NULL) ASC,
planned_time_start ASC NULLS LAST,
id ASC
)
WHERE framework_slot_id IS NULL;
@@ -0,0 +1,41 @@
-- list_exercises mit skill_min_level / skill_max_level: EXISTS auf exercise_skills mit numerischem Stufen-Rang.
-- Ausdruck muss mit backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL (Alias „es“) übereinstimmen.
CREATE INDEX IF NOT EXISTS idx_exercise_skills_exercise_level_rank
ON exercise_skills (
exercise_id,
(CASE COALESCE(
NULLIF(TRIM(LOWER(target_level::text)), ''),
NULLIF(TRIM(LOWER(required_level::text)), '')
)
WHEN 'basis' THEN 1
WHEN 'grundlagen' THEN 2
WHEN 'aufbau' THEN 3
WHEN 'fortgeschritten' THEN 4
WHEN 'optimierung' THEN 5
WHEN 'einsteiger' THEN 1
WHEN 'experte' THEN 5
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN '4' THEN 4
WHEN '5' THEN 5
ELSE NULL END)
)
WHERE (CASE COALESCE(
NULLIF(TRIM(LOWER(target_level::text)), ''),
NULLIF(TRIM(LOWER(required_level::text)), '')
)
WHEN 'basis' THEN 1
WHEN 'grundlagen' THEN 2
WHEN 'aufbau' THEN 3
WHEN 'fortgeschritten' THEN 4
WHEN 'optimierung' THEN 5
WHEN 'einsteiger' THEN 1
WHEN 'experte' THEN 5
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN '4' THEN 4
WHEN '5' THEN 5
ELSE NULL END) IS NOT NULL;
@@ -0,0 +1,85 @@
-- Migration 063: Phasen und parallele Streams pro Trainingseinheit (Grundlage Breakout).
-- Bestehende Sektionen werden einer Default-whole_group-Phase zugeordnet.
-- UNIQUE (training_unit_id, order_index) auf Sektionen entfällt zugunsten
-- eindeutiger order_index je Phase bzw. je parallel_stream.
-- ── Phasen ───────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS training_unit_phases (
id SERIAL PRIMARY KEY,
training_unit_id INT NOT NULL REFERENCES training_units(id) ON DELETE CASCADE,
order_index INT NOT NULL,
phase_kind VARCHAR(20) NOT NULL CHECK (phase_kind IN ('whole_group', 'parallel')),
title VARCHAR(200),
guidance_notes TEXT,
UNIQUE (training_unit_id, order_index)
);
CREATE INDEX IF NOT EXISTS idx_training_unit_phases_unit ON training_unit_phases(training_unit_id);
-- ── Streams innerhalb einer Parallelphase ──────────────────────────────────
CREATE TABLE IF NOT EXISTS training_unit_parallel_streams (
id SERIAL PRIMARY KEY,
phase_id INT NOT NULL REFERENCES training_unit_phases(id) ON DELETE CASCADE,
order_index INT NOT NULL,
title VARCHAR(200),
notes TEXT,
assigned_trainer_profile_ids JSONB,
UNIQUE (phase_id, order_index)
);
CREATE INDEX IF NOT EXISTS idx_training_unit_parallel_streams_phase
ON training_unit_parallel_streams(phase_id);
COMMENT ON COLUMN training_unit_parallel_streams.assigned_trainer_profile_ids IS
'Optionale Co-Trainer-IDs (JSON-Array von Profil-IDs) für diese Teilstrecke; MVP+';
-- ── Sektionen: Zuordnung zu Phase (gemeinsam) oder Stream (parallel) ─────
ALTER TABLE training_unit_sections
ADD COLUMN IF NOT EXISTS phase_id INT REFERENCES training_unit_phases(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS parallel_stream_id INT REFERENCES training_unit_parallel_streams(id) ON DELETE CASCADE;
-- Backfill: je Einheit mit Sektionen eine whole_group-Phase, alle Sektionen dorthin
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title)
SELECT tu.id, 0, 'whole_group', NULL
FROM training_units tu
WHERE EXISTS (SELECT 1 FROM training_unit_sections s WHERE s.training_unit_id = tu.id)
AND NOT EXISTS (
SELECT 1 FROM training_unit_phases p
WHERE p.training_unit_id = tu.id AND p.order_index = 0 AND p.phase_kind = 'whole_group'
);
UPDATE training_unit_sections tus
SET phase_id = p.id
FROM training_unit_phases p
WHERE tus.phase_id IS NULL
AND p.training_unit_id = tus.training_unit_id
AND p.order_index = 0
AND p.phase_kind = 'whole_group';
-- Alte globale Reihenfolge-Eindeutigkeit pro Einheit entfernen
ALTER TABLE training_unit_sections
DROP CONSTRAINT IF EXISTS training_unit_sections_training_unit_id_order_index_key;
-- Genau eine Zielspalte gesetzt: gemeinsame Phase ODER paralleler Stream
ALTER TABLE training_unit_sections
DROP CONSTRAINT IF EXISTS training_unit_sections_phase_or_stream_chk;
ALTER TABLE training_unit_sections
ADD CONSTRAINT training_unit_sections_phase_or_stream_chk CHECK (
(phase_id IS NOT NULL AND parallel_stream_id IS NULL)
OR (phase_id IS NULL AND parallel_stream_id IS NOT NULL)
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_phase_order
ON training_unit_sections (phase_id, order_index)
WHERE phase_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_training_unit_sections_stream_order
ON training_unit_sections (parallel_stream_id, order_index)
WHERE parallel_stream_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_phase
ON training_unit_sections(phase_id) WHERE phase_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_parallel_stream
ON training_unit_sections(parallel_stream_id) WHERE parallel_stream_id IS NOT NULL;
@@ -0,0 +1,8 @@
-- Vorlagen: Phasen/Parallel-Streams wie im Einheiten-Editor (planLoc-Abbild)
ALTER TABLE training_plan_template_sections
ADD COLUMN IF NOT EXISTS phase_kind VARCHAR(20) NOT NULL DEFAULT 'whole_group',
ADD COLUMN IF NOT EXISTS phase_order_index INT NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS parallel_stream_order_index INT NULL;
COMMENT ON COLUMN training_plan_template_sections.parallel_stream_order_index IS
'NULL = Ganzgruppen-Abschnitt; 0..n = Stream innerhalb paralleler Phase';
@@ -0,0 +1,11 @@
-- Migration 065: Wiki-spezifische Felder fuer Fähigkeiten (KarateRelevanz, RelevanzLevel)
-- SMW karatetrainer.net; Import mappt in strukturierte Spalten statt nur Freitext in description
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS karate_relevance TEXT;
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS relevance_level SMALLINT CHECK (relevance_level IS NULL OR relevance_level BETWEEN 1 AND 3);
COMMENT ON COLUMN skills.karate_relevance IS 'Wiki Karate-Relevanz (Plaintext aus SMW Property KarateRelevanz)';
COMMENT ON COLUMN skills.relevance_level IS 'Wiki-RelevanzLevel 1–3 (Semantic MediaWiki)';
@@ -0,0 +1,36 @@
-- Geplante Gesamt- und Abschnittsdauer; Rahmenprogramm: Fokus/Stil als M:N (wie Trainingsarten/Zielgruppen)
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
ALTER TABLE training_unit_sections
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
ALTER TABLE training_plan_template_sections
ADD COLUMN IF NOT EXISTS planned_duration_min INT;
CREATE TABLE IF NOT EXISTS training_framework_program_focus_areas (
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
PRIMARY KEY (framework_program_id, focus_area_id)
);
CREATE INDEX IF NOT EXISTS idx_tfpfa_focus ON training_framework_program_focus_areas(focus_area_id);
CREATE TABLE IF NOT EXISTS training_framework_program_style_directions (
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
style_direction_id INT NOT NULL REFERENCES style_directions(id) ON DELETE CASCADE,
PRIMARY KEY (framework_program_id, style_direction_id)
);
CREATE INDEX IF NOT EXISTS idx_tfpsd_style ON training_framework_program_style_directions(style_direction_id);
INSERT INTO training_framework_program_focus_areas (framework_program_id, focus_area_id)
SELECT id, focus_area_id FROM training_framework_programs
WHERE focus_area_id IS NOT NULL
ON CONFLICT DO NOTHING;
INSERT INTO training_framework_program_style_directions (framework_program_id, style_direction_id)
SELECT id, style_direction_id FROM training_framework_programs
WHERE style_direction_id IS NOT NULL
ON CONFLICT DO NOTHING;
@@ -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) = '');
+4
View File
@@ -117,6 +117,8 @@ class SkillCreate(BaseModel):
description: Optional[str] = None
importance: Optional[int] = Field(None, ge=1, le=5)
keywords: Optional[List[str]] = []
karate_relevance: Optional[str] = None
relevance_level: Optional[int] = Field(None, ge=1, le=3)
class SkillResponse(BaseModel):
id: int
@@ -125,6 +127,8 @@ class SkillResponse(BaseModel):
description: Optional[str]
importance: Optional[int]
keywords: Optional[List[str]]
karate_relevance: Optional[str] = None
relevance_level: Optional[int] = None
status: str
created_at: datetime
+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 -1
View File
@@ -6,5 +6,5 @@ python_functions = test_*
addopts = -q --tb=short
markers =
smoke: Schnelle Kern-Regression.
integration: PostgreSQL-Mandanten-Integration (ACCESS_LAYER_INTEGRATION=1).
integration: PostgreSQL-Integration (z. B. ACCESS_LAYER_INTEGRATION=1, TRAINING_PLANNING_INTEGRATION=1).
slow: Lange/schwere Tests; in CI wie Mitai-Jinkendo ausgeschlossen (Auswahl: not slow).
+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}
+103
View File
@@ -0,0 +1,103 @@
"""
Dashboard: zusammengefasste Kennzahlen (ein Roundtrip statt mehrerer Listen).
"""
from __future__ import annotations
from datetime import date
from typing import Any, Dict, List
from fastapi import APIRouter, Depends
from tenant_context import TenantContext, get_tenant_context
from routers.exercises import list_exercises_like_get
from routers.training_planning import list_training_units
router = APIRouter(prefix="/api", tags=["dashboard"])
def _slice_training_home_notes(planned_pool: List[Dict[str, Any]], max_notes: int = 5) -> List[Dict[str, Any]]:
out = []
for u in planned_pool:
tn = (u.get("trainer_notes") or "").strip()
n = (u.get("notes") or "").strip()
if tn or n:
out.append(u)
if len(out) >= max_notes:
break
return out
@router.get("/dashboard/kpis")
def get_dashboard_kpis(tenant: TenantContext = Depends(get_tenant_context)):
"""
Kurzüberblick: Übungs-KPIs + YTD-Einheiten + Trainings-Home (nächste Termine, Vermerke, offene Rückschau)
in einem Roundtrip — gleiche Filter wie zuvor im Dashboard (mehrere Client-Calls).
"""
year = date.today().year
year_start = f"{year}-01-01"
year_end = f"{year}-12-31"
today = date.today().isoformat()
draft_list = list_exercises_like_get(
tenant, created_by_me=True, status="draft", limit=100
)
mine_list = list_exercises_like_get(
tenant, created_by_me=True, status=None, limit=100
)
ytd_completed = list_training_units(
group_id=None,
club_id=None,
start_date=year_start,
end_date=year_end,
status="completed",
assigned_to_me=True,
debrief_pending=False,
sort="desc",
limit=250,
tenant=tenant,
)
planned_pool = list_training_units(
group_id=None,
club_id=None,
start_date=today,
end_date=None,
status="planned",
assigned_to_me=True,
debrief_pending=False,
sort="asc",
limit=40,
tenant=tenant,
)
review_pending = list_training_units(
group_id=None,
club_id=None,
start_date=None,
end_date=None,
status=None,
assigned_to_me=True,
debrief_pending=True,
sort="desc",
limit=8,
tenant=tenant,
)
draft_preview = [
{"id": int(ex["id"]), "title": ex.get("title") or f"Übung #{ex['id']}"}
for ex in draft_list[:8]
]
return {
"year": year,
"draft_count": len(draft_list),
"draft_capped": len(draft_list) >= 100,
"draft_preview": draft_preview,
"mine_count": len(mine_list),
"mine_capped": len(mine_list) >= 100,
"ytd_completed_count": len(ytd_completed),
"ytd_capped": len(ytd_completed) >= 250,
"training_home": {
"upcoming": planned_pool[:8],
"planned_with_notes": _slice_training_home_notes(planned_pool),
"review_pending": review_pending,
},
}
+9 -10
View File
@@ -1,7 +1,7 @@
"""
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
AuthZ analog training_plan_templates (_template_access / _has_planning_role).
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
"""
from typing import Any, List, Optional
@@ -12,8 +12,10 @@ from psycopg2 import IntegrityError
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
from club_tenancy import (
assert_library_content_deletable,
assert_library_content_editable,
assert_library_content_governance_transition,
assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile,
)
@@ -111,13 +113,7 @@ def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
if is_platform_admin(role):
return
created_by = row.get("created_by")
if created_by is not None:
created_by = int(created_by)
if created_by != profile_id:
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
assert_library_content_editable(cur, profile_id, role, row)
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
@@ -333,6 +329,7 @@ def update_progression_graph(
)
gov_club = next_club if next_vis == "club" else None
assert_library_content_governance_transition(cur, profile_id, role, row, next_vis, gov_club)
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
fields: List[str] = []
@@ -376,7 +373,9 @@ def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
row = _graph_row(cur, graph_id)
_assert_graph_readable(cur, row, profile_id, role)
assert_library_content_deletable(cur, profile_id, role, row)
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
conn.commit()
return {"ok": True}
+301 -6
View File
@@ -9,6 +9,7 @@ import json
import logging
import os
import re
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple
from urllib.parse import quote
@@ -18,6 +19,8 @@ from fastapi.responses import FileResponse, Response, StreamingResponse
from pydantic import BaseModel, Field, model_validator
from psycopg2.extras import Json
from fastapi_param_unwrap import unwrap_query_default
from db import get_db, get_cursor, r2d
from club_tenancy import (
assert_valid_governance_visibility,
@@ -32,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,
@@ -96,6 +102,7 @@ CASE COALESCE(
WHEN '5' THEN 5
ELSE NULL END
""".strip()
# Bei Änderung: Migration 062 idx_exercise_skills_exercise_level_rank (SQL-Ausdruck) synchron halten.
def normalize_exercise_skill_level(value) -> Optional[str]:
@@ -109,6 +116,25 @@ def normalize_exercise_skill_level(value) -> Optional[str]:
return s
return _LEGACY_SKILL_LEVEL_SLUG.get(s)
_ALLOWED_SKILL_INTENSITY = frozenset({"niedrig", "mittel", "hoch"})
def normalize_exercise_skill_intensity(value) -> str:
"""Kanonische Nutzeneinschätzung; leer/ungültig → mittel (kein leerer Wert)."""
if value is None:
return "mittel"
key = str(value).strip().lower()
if key in ("low",):
return "niedrig"
if key in ("medium",):
return "mittel"
if key in ("high",):
return "hoch"
if key in _ALLOWED_SKILL_INTENSITY:
return key
return "mittel"
MEDIA_ROOT = Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent.parent / "media")))
MAX_EXERCISE_MEDIA = 10
# Upload-Limits (Übungs-Medien): Trainer wie bisher kleiner; Admin/Superadmin höheres Limit für große Videos
@@ -333,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
@@ -1098,13 +1184,15 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
FROM exercise_skills es
JOIN skills s ON es.skill_id = s.id
WHERE es.exercise_id = %s
ORDER BY es.is_primary DESC, s.name""",
ORDER BY s.name""",
(exercise_id,)
)
exercise["skills"] = [r2d(r) for r in cur.fetchall()]
for sk in exercise["skills"]:
sk["required_level"] = normalize_exercise_skill_level(sk.get("required_level"))
sk["target_level"] = normalize_exercise_skill_level(sk.get("target_level"))
sk["intensity"] = normalize_exercise_skill_intensity(sk.get("intensity"))
sk["is_primary"] = False
# Variants (1:N) - mit Progression (Reihenfolge: sequence_order, dann progression_level)
cur.execute(
@@ -1219,8 +1307,8 @@ def assign_exercise_relations(
(
exercise_id,
skill["skill_id"],
skill.get("is_primary", False),
skill.get("intensity"),
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")),
skill.get("ai_suggested", False),
@@ -1653,6 +1741,20 @@ def bulk_patch_exercises_metadata(
}
def _parse_cursor_updated_at_list(raw: Optional[str]) -> datetime:
s = (raw or "").strip()
if not s:
raise HTTPException(status_code=400, detail="cursor_updated_at leer")
if s.endswith("Z"):
s = s[:-1] + "+00:00"
try:
return datetime.fromisoformat(s)
except ValueError:
raise HTTPException(
status_code=400, detail="cursor_updated_at ungültig (ISO-8601 erwartet)"
)
@router.get("/exercises")
def list_exercises(
focus_area_ids: list[int] = Query(default=[], description="ODER: mind. einer dieser Fokusbereiche"),
@@ -1678,6 +1780,15 @@ def list_exercises(
),
limit: int = Query(default=50, ge=1, le=100),
offset: int = Query(default=0, ge=0),
cursor_updated_at: Optional[str] = Query(
default=None,
description="Keyset: ISO-8601 von updated_at der letzten Zeile; zusammen mit cursor_id (offset dann 0)",
),
cursor_id: Optional[int] = Query(
default=None,
ge=1,
description="Keyset: id der letzten Zeile (Tie‑break bei gleichem updated_at); mit cursor_updated_at",
),
include_variants: bool = Query(
default=False,
description="Wenn true: Feld variants[] pro Übung (id, variant_name, sequence_order) für Planung/UI",
@@ -1746,9 +1857,31 @@ def list_exercises(
Liste aller Übungen mit Filtern.
Lightweight Response (ohne M:N Details, nur IDs und Namen).
Optional include_variants für Variantenauswahl in der Trainingsplanung.
Keyset: cursor_updated_at + cursor_id ersetzt große OFFSET-Werte (Sortierung: updated_at DESC, id DESC).
"""
cursor_updated_at = unwrap_query_default(cursor_updated_at)
cursor_id = unwrap_query_default(cursor_id)
limit = unwrap_query_default(limit)
offset = unwrap_query_default(offset)
profile_id = tenant.profile_id
c_ts_raw = (cursor_updated_at or "").strip() or None
use_keyset = c_ts_raw is not None and cursor_id is not None
if (c_ts_raw is not None) != (cursor_id is not None):
raise HTTPException(
status_code=400,
detail="cursor_updated_at und cursor_id müssen zusammen gesetzt werden",
)
if use_keyset and offset != 0:
raise HTTPException(
status_code=400,
detail="Keyset-Pagination: offset nicht kombinieren (nur cursor_* oder nur offset)",
)
cursor_ts_val: Optional[datetime] = None
if use_keyset:
cursor_ts_val = _parse_cursor_updated_at_list(c_ts_raw)
with get_db() as conn:
cur = get_cursor(conn)
@@ -1981,6 +2114,12 @@ def list_exercises(
where.append("e.search_vector @@ plainto_tsquery('german', %s)")
params.append(qtext)
if cursor_ts_val is not None and cursor_id is not None:
where.append(
"(e.updated_at < %s OR (e.updated_at = %s AND e.id < %s))"
)
params.extend([cursor_ts_val, cursor_ts_val, cursor_id])
variants_sql = ""
if include_variants:
variants_sql = """,
@@ -2040,16 +2179,26 @@ def list_exercises(
FROM exercise_training_types ett
JOIN training_types tt ON tt.id = ett.training_type_id
WHERE ett.exercise_id = e.id
) AS training_type_names
) AS training_type_names,
(
SELECT COUNT(*)::int
FROM exercise_variants ev
WHERE ev.exercise_id = e.id
) AS variant_count,
(
SELECT COUNT(*)::int
FROM exercise_media em
WHERE em.exercise_id = e.id
) AS media_count
{variants_sql}
FROM exercises e
LEFT JOIN profiles p ON e.created_by = p.id
LEFT JOIN clubs c ON e.club_id = c.id
WHERE {' AND '.join(where)}
ORDER BY e.updated_at DESC
ORDER BY e.updated_at DESC, e.id DESC
LIMIT %s OFFSET %s
"""
params.extend([limit, offset])
params.extend([limit, 0 if use_keyset else offset])
cur.execute(query, params)
rows = cur.fetchall()
@@ -2063,6 +2212,8 @@ def list_exercises(
d["focus_area_names"] = _coerce_json_str_list(d.get("focus_area_names"))
d["style_direction_names"] = _coerce_json_str_list(d.get("style_direction_names"))
d["training_type_names"] = _coerce_json_str_list(d.get("training_type_names"))
d["variant_count"] = int(d.get("variant_count") or 0)
d["media_count"] = int(d.get("media_count") or 0)
if include_variants:
v = d.get("variants")
if isinstance(v, str):
@@ -2076,6 +2227,150 @@ def list_exercises(
return out
def list_exercises_like_get(
tenant: TenantContext,
*,
created_by_me: bool,
status: Optional[str],
limit: int,
) -> List[Dict[str, Any]]:
"""
Programmatischer Aufruf mit gleicher Semantik wie GET /api/exercises
(ohne FastAPI-Query-Default-Objekte an list_exercises zu übergeben).
"""
return list_exercises(
focus_area_ids=[],
focus_area=None,
visibility_any=[],
visibility=None,
status_any=[],
status=status,
skill_ids=[],
skill_id=None,
style_direction_ids=[],
style_direction_id=None,
training_type_ids=[],
training_type_id=None,
target_group_ids=[],
target_group_id=None,
skill_min_level=None,
skill_max_level=None,
search=None,
ai_search=None,
limit=limit,
offset=0,
include_variants=False,
visibility_exclude_any=[],
status_exclude_any=[],
exclude_without_focus=False,
focus_only_without_focus_areas=False,
focus_area_must_include_ids=[],
focus_area_must_exclude_ids=[],
style_direction_must_include_ids=[],
style_direction_must_exclude_ids=[],
training_type_must_include_ids=[],
training_type_must_exclude_ids=[],
target_group_must_include_ids=[],
target_group_must_exclude_ids=[],
include_archived=False,
created_by_me=created_by_me,
exercise_kind_any=[],
tenant=tenant,
)
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,
+42 -16
View File
@@ -18,6 +18,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth
from smw_client import SmwClient, SmwClientError
from smw_mapper import map_wiki_to_exercise, map_wiki_to_skill, map_wiki_to_method, build_skill_assignments
from routers.exercises import normalize_exercise_skill_intensity
logger = logging.getLogger(__name__)
@@ -30,6 +31,17 @@ CATEGORY_METHODS = os.getenv("MEDIAWIKI_CATEGORY_METHODS", "Methodenbeschrei
CATEGORY_MODELS = os.getenv("MEDIAWIKI_CATEGORY_MODELS", "Reifegradmodelle")
def _wiki_category_or_default(category: Optional[str], import_type: str) -> str:
"""Leeres category ⇒ Standard je import_type."""
if (category or "").strip():
return category.strip()
if import_type == "skill":
return CATEGORY_SKILLS
if import_type == "method":
return CATEGORY_METHODS
return CATEGORY_EXERCISES
# ------------------------------------------------------------------ #
# Pydantic Models #
# ------------------------------------------------------------------ #
@@ -59,7 +71,7 @@ def require_admin(session: dict = Depends(require_auth)) -> dict:
@router.get("/import/mediawiki/preview")
async def preview_import(
category: str = Query(default=CATEGORY_EXERCISES),
category: Optional[str] = Query(default=None),
import_type: str = Query(default="exercise"),
limit: int = Query(default=10, ge=1, le=500),
session: dict = Depends(require_admin),
@@ -68,9 +80,10 @@ async def preview_import(
Zeigt Vorschau: Welche Seiten würden importiert werden?
Überprüft Duplikate und mapped Felder ohne zu speichern.
"""
resolved_category = _wiki_category_or_default(category, import_type)
client = SmwClient()
try:
members = await client.get_category_members(category, limit=limit)
members = await client.get_category_members(resolved_category, limit=limit)
except SmwClientError as e:
raise HTTPException(status_code=502, detail=f"Wiki-API nicht erreichbar: {e}")
@@ -129,7 +142,7 @@ async def preview_import(
})
return {
"category": category,
"category": resolved_category,
"import_type": import_type,
"total_found": len(members),
"preview": preview,
@@ -151,6 +164,7 @@ async def execute_import(
Gibt sofort log_id zurück – Status via GET /import/mediawiki/status/{log_id}.
"""
profile_id = session["profile_id"]
resolved_category = _wiki_category_or_default(body.category, body.import_type)
# Log-Eintrag anlegen
with get_db() as conn:
@@ -160,7 +174,7 @@ async def execute_import(
(import_type, import_status, category, dry_run, reimport, imported_by)
VALUES (%s, 'running', %s, %s, %s, %s)
RETURNING id""",
(body.import_type, body.category, body.dry_run, body.reimport_existing, profile_id)
(body.import_type, resolved_category, body.dry_run, body.reimport_existing, profile_id)
)
log_id = cur.fetchone()['id']
conn.commit()
@@ -169,7 +183,7 @@ async def execute_import(
background_tasks.add_task(
_run_import,
log_id=log_id,
category=body.category,
category=resolved_category,
import_type=body.import_type,
reimport=body.reimport_existing,
dry_run=body.dry_run,
@@ -602,21 +616,23 @@ def _assign_exercise_skills(cur, conn, exercise_id: int, skill_assignments: list
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (exercise_id, skill_id) DO UPDATE SET
target_level = EXCLUDED.target_level,
is_primary = EXCLUDED.is_primary""",
required_level = EXCLUDED.required_level,
intensity = EXCLUDED.intensity,
is_primary = false""",
(
exercise_id,
sid,
assignment.get("target_level"),
assignment.get("required_level"),
assignment.get("intensity"),
assignment.get("is_primary", False),
normalize_exercise_skill_intensity(assignment.get("intensity")),
False,
)
)
conn.commit()
def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
"""Legt Skill an oder überspringt bei Duplikat."""
def _upsert_skill(mapped: dict, _reimport: bool) -> Optional[int]:
"""Legt Skill an oder aktualisiert bestehenden Datensatz bei Namenskonflikt (Wiki-Reimport)."""
with get_db() as conn:
cur = get_cursor(conn)
@@ -626,17 +642,27 @@ def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
cur.execute("SELECT id FROM skill_categories WHERE name ILIKE %s", (mapped["category_name"],))
row = cur.fetchone()
if row:
category_id = row['id']
category_id = row["id"]
cur.execute(
"""INSERT INTO skills (name, description, category_id)
VALUES (%s, %s, %s)
"""INSERT INTO skills (name, description, category_id, karate_relevance, relevance_level)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (name) DO UPDATE SET
description = EXCLUDED.description
description = COALESCE(EXCLUDED.description, skills.description),
category_id = COALESCE(EXCLUDED.category_id, skills.category_id),
karate_relevance = COALESCE(EXCLUDED.karate_relevance, skills.karate_relevance),
relevance_level = COALESCE(EXCLUDED.relevance_level, skills.relevance_level),
updated_at = NOW()
RETURNING id""",
(mapped["name"], mapped.get("description"), category_id)
(
mapped["name"],
mapped.get("description"),
category_id,
mapped.get("karate_relevance"),
mapped.get("relevance_level"),
),
)
skill_id = cur.fetchone()['id']
skill_id = cur.fetchone()["id"]
conn.commit()
return skill_id
+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,
}
+689
View File
@@ -0,0 +1,689 @@
"""
Fähigkeiten-Profile und Vorschläge (Phase 3) für Planungsartefakte.
GET …/skill-profile — gewichtetes Profil aus verknüpften Übungen.
GET /api/skill-discovery/suggestions — Rahmenprogramme, Module, Progressionsgraphen nach Fähigkeiten.
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
from skill_scoring import (
GRAPH_DEFAULT_ITEM_MINUTES,
ExerciseOccurrence,
batch_compute_profiles,
batch_framework_occurrences_by_id,
batch_module_occurrences_by_id,
collect_module_exercise_occurrences,
collect_progression_graph_exercise_occurrences,
collect_unit_exercise_occurrences,
compact_profile_summary,
compute_planning_corpus_by_type,
compute_club_corpus_reference,
compute_corpus_skill_max_weights,
compute_skill_profile,
corpus_for_artifact_type,
fetch_exercise_skills_bulk,
match_score_for_skill_ids,
profile_for_occurrences,
reference_scale_meta,
top_categories_summary,
)
from routers.training_framework_programs import _framework_access
from routers.training_modules import _module_access
from routers.exercise_progression_graphs import _require_graph_read
router = APIRouter(prefix="/api", tags=["skill_profiles"])
def _parse_skill_ids_param(raw: Optional[str]) -> List[int]:
if not raw or not str(raw).strip():
return []
out: List[int] = []
for part in str(raw).split(","):
part = part.strip()
if not part:
continue
try:
n = int(part)
except ValueError:
raise HTTPException(status_code=400, detail="skill_ids: ungültige ID") from None
if n > 0 and n not in out:
out.append(n)
return out
@router.get("/training-framework-programs/{framework_id}/skill-profile")
def framework_program_skill_profile(
framework_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
row = _framework_access(cur, framework_id, profile_id, role)
cur.execute(
"""
SELECT s.id, s.sort_order, s.title,
tu.id AS blueprint_unit_id
FROM training_framework_slots s
LEFT JOIN training_units tu ON tu.framework_slot_id = s.id
WHERE s.framework_program_id = %s
ORDER BY s.sort_order
""",
(framework_id,),
)
slots_raw = [r2d(r) for r in cur.fetchall()]
bundle = _load_planning_corpus(cur, tenant)
tc = corpus_for_artifact_type(bundle, "framework_program")
ref_max = tc["max_by_skill"]
ref_by_skill = tc["ref_by_skill"]
all_occurrences: List[ExerciseOccurrence] = []
slot_profiles: List[Dict[str, Any]] = []
for slot in slots_raw:
uid = slot.get("blueprint_unit_id")
slot_occ: List[ExerciseOccurrence] = []
slot_label = (slot.get("title") or "").strip() or f"Session {(slot.get('sort_order') or 0) + 1}"
if uid:
raw_occ = collect_unit_exercise_occurrences(cur, int(uid))
slot_occ = [
ExerciseOccurrence(
exercise_id=o.exercise_id,
planned_duration_min=o.planned_duration_min,
context_label=slot_label,
)
for o in raw_occ
]
all_occurrences.extend(slot_occ)
else:
slot_occ = []
slot_profile = (
profile_for_occurrences(cur, slot_occ, reference_max_by_skill=ref_max)
if slot_occ
else _empty_profile()
)
slot_profiles.append(
{
"slot_id": slot["id"],
"slot_title": slot.get("title"),
"sort_order": slot.get("sort_order"),
"blueprint_training_unit_id": uid,
"exercise_occurrence_count": len(slot_occ),
"profile": slot_profile,
}
)
overall = (
profile_for_occurrences(cur, all_occurrences, reference_max_by_skill=ref_max)
if all_occurrences
else _empty_profile()
)
_enrich_profile_club_best(overall, ref_by_skill, "framework_program", framework_id)
for slot in slot_profiles:
_enrich_profile_club_best(
slot.get("profile") or {},
ref_by_skill,
"framework_program",
framework_id,
)
return {
"artifact_type": "framework_program",
"artifact_id": framework_id,
"artifact_title": row.get("title"),
"reference_scale": reference_scale_meta(
tc, "framework_program", effective_club_id=tenant.effective_club_id
),
"club_best_by_skill": {
str(k): v for k, v in ref_by_skill.items()
},
"overall": overall,
"slots": slot_profiles,
}
@router.get("/training-modules/{module_id}/skill-profile")
def training_module_skill_profile(
module_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
row = _module_access(cur, module_id, profile_id, role)
bundle = _load_planning_corpus(cur, tenant)
tc = corpus_for_artifact_type(bundle, "training_module")
ref_max = tc["max_by_skill"]
ref_by_skill = tc["ref_by_skill"]
occurrences = collect_module_exercise_occurrences(cur, module_id)
overall = (
profile_for_occurrences(cur, occurrences, reference_max_by_skill=ref_max)
if occurrences
else _empty_profile()
)
_enrich_profile_club_best(overall, ref_by_skill, "training_module", module_id)
return {
"artifact_type": "training_module",
"artifact_id": module_id,
"artifact_title": row.get("title"),
"reference_scale": reference_scale_meta(
tc, "training_module", effective_club_id=tenant.effective_club_id
),
"club_best_by_skill": {
str(k): v for k, v in ref_by_skill.items()
},
"overall": overall,
}
@router.get("/exercise-progression-graphs/{graph_id}/skill-profile")
def progression_graph_skill_profile(
graph_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
row = _require_graph_read(cur, graph_id, profile_id, role)
bundle = _load_planning_corpus(cur, tenant)
tc = corpus_for_artifact_type(bundle, "progression_graph")
ref_max = tc["max_by_skill"]
ref_by_skill = tc["ref_by_skill"]
occurrences = collect_progression_graph_exercise_occurrences(cur, graph_id)
overall = (
profile_for_occurrences(
cur,
occurrences,
default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES,
reference_max_by_skill=ref_max,
)
if occurrences
else _empty_profile()
)
_enrich_profile_club_best(overall, ref_by_skill, "progression_graph", graph_id)
return {
"artifact_type": "progression_graph",
"artifact_id": graph_id,
"artifact_title": row.get("name"),
"reference_scale": reference_scale_meta(
tc, "progression_graph", effective_club_id=tenant.effective_club_id
),
"club_best_by_skill": {
str(k): v for k, v in ref_by_skill.items()
},
"overall": overall,
}
@router.post("/skill-profiles/batch-summaries")
def batch_skill_profile_summaries(
data: dict,
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Kompakte Fähigkeiten-Profile für Listen (ein Corpus-Scan, Batch-SQL).
Body: { framework_program_ids?: number[], training_module_ids?: number[] }
"""
fp_ids = _parse_id_list(data.get("framework_program_ids"))
mod_ids = _parse_id_list(data.get("training_module_ids"))
if not fp_ids and not mod_ids:
raise HTTPException(
status_code=400,
detail="framework_program_ids oder training_module_ids erforderlich",
)
profile_id = tenant.profile_id
role = tenant.global_role
summaries: Dict[str, Dict[str, Any]] = {}
with get_db() as conn:
cur = get_cursor(conn)
bundle = compute_planning_corpus_by_type(
cur,
profile_id=tenant.profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
include_artifact_summaries=True,
)
allowed_fp: List[int] = []
if fp_ids:
for fid in fp_ids:
try:
_framework_access(cur, fid, profile_id, role)
allowed_fp.append(fid)
except HTTPException:
pass
allowed_mod: List[int] = []
if mod_ids:
for mid in mod_ids:
try:
_module_access(cur, mid, profile_id, role)
allowed_mod.append(mid)
except HTTPException:
pass
summaries = _merge_batch_summaries(
cur,
bundle=bundle,
allowed_fp=allowed_fp,
allowed_mod=allowed_mod,
)
ref_by_skill = {}
for t in ("framework_program", "training_module", "progression_graph"):
ref_by_skill.update(corpus_for_artifact_type(bundle, t).get("ref_by_skill") or {})
skill_ids_seen: set[int] = set()
for summary in summaries.values():
for sk in summary.get("skills") or []:
if sk.get("skill_id") is not None:
skill_ids_seen.add(int(sk["skill_id"]))
club_best_subset = {
str(sid): ref_by_skill[sid]
for sid in skill_ids_seen
if sid in ref_by_skill
}
return {
"reference_scale_by_type": {
t: reference_scale_meta(
corpus_for_artifact_type(bundle, t),
t,
effective_club_id=tenant.effective_club_id,
)
for t in ("framework_program", "training_module", "progression_graph")
},
"club_best_by_skill": club_best_subset,
"summaries": summaries,
}
@router.get("/skill-discovery/suggestions")
def skill_discovery_suggestions(
skill_ids: str = Query(..., description="Komma-getrennte skill-IDs"),
types: Optional[str] = Query(
default="framework_program,training_module,progression_graph",
description="Artefakttypen, komma-getrennt",
),
limit: int = Query(default=20, ge=1, le=50),
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Findet Bibliotheksartefakte, deren Übungs-Fähigkeiten-Profil die gewünschten Fähigkeiten stark abdeckt.
"""
wanted = _parse_skill_ids_param(skill_ids)
if not wanted:
raise HTTPException(status_code=400, detail="skill_ids ist Pflicht (mindestens eine ID)")
type_set = {t.strip() for t in (types or "").split(",") if t.strip()}
profile_id = tenant.profile_id
role = tenant.global_role
results: List[Dict[str, Any]] = []
with get_db() as conn:
cur = get_cursor(conn)
planning_bundle = _load_planning_corpus(cur, tenant)
fw_ref = corpus_for_artifact_type(planning_bundle, "framework_program")["max_by_skill"]
mod_ref = corpus_for_artifact_type(planning_bundle, "training_module")["max_by_skill"]
graph_ref = corpus_for_artifact_type(planning_bundle, "progression_graph")["max_by_skill"]
if "framework_program" in type_set:
vis_clause, vis_params = library_content_visibility_sql(
alias="fp",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
SELECT fp.id, fp.title
FROM training_framework_programs fp
WHERE ({vis_clause})
ORDER BY fp.updated_at DESC NULLS LAST
LIMIT 80
""",
vis_params,
)
for fp_row in cur.fetchall():
fid = int(fp_row["id"])
try:
_framework_access(cur, fid, profile_id, role)
except HTTPException:
continue
cur.execute(
"""
SELECT tu.id
FROM training_framework_slots s
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
WHERE s.framework_program_id = %s
""",
(fid,),
)
occ: List[ExerciseOccurrence] = []
for u in cur.fetchall():
occ.extend(collect_unit_exercise_occurrences(cur, int(u["id"])))
if not occ:
continue
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=fw_ref)
match = match_score_for_skill_ids(prof, wanted)
if match["match_weight"] <= 0:
continue
results.append(
{
"artifact_type": "framework_program",
"artifact_id": fid,
"artifact_title": fp_row["title"],
"path": f"/planning/framework-programs/{fid}",
"match": match,
"skill_profile_summary": {
"total_score": prof.get("total_score"),
"top_by_category": top_categories_summary(prof),
},
}
)
if "training_module" in type_set:
vis_clause, vis_params = library_content_visibility_sql(
alias="m",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
SELECT m.id, m.title
FROM training_modules m
WHERE ({vis_clause})
ORDER BY m.updated_at DESC NULLS LAST
LIMIT 80
""",
vis_params,
)
for m_row in cur.fetchall():
mid = int(m_row["id"])
try:
_module_access(cur, mid, profile_id, role)
except HTTPException:
continue
occ = collect_module_exercise_occurrences(cur, mid)
if not occ:
continue
prof = profile_for_occurrences(cur, occ, reference_max_by_skill=mod_ref)
match = match_score_for_skill_ids(prof, wanted)
if match["match_weight"] <= 0:
continue
results.append(
{
"artifact_type": "training_module",
"artifact_id": mid,
"artifact_title": m_row["title"],
"path": f"/planning/training-modules/{mid}",
"match": match,
"skill_profile_summary": {
"total_score": prof.get("total_score"),
"top_by_category": top_categories_summary(prof),
},
}
)
if "progression_graph" in type_set:
vis_clause, vis_params = library_content_visibility_sql(
alias="g",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
SELECT g.id, g.name
FROM exercise_progression_graphs g
WHERE ({vis_clause})
ORDER BY g.updated_at DESC NULLS LAST
LIMIT 80
""",
vis_params,
)
for g_row in cur.fetchall():
gid = int(g_row["id"])
try:
_require_graph_read(cur, gid, profile_id, role)
except HTTPException:
continue
occ = collect_progression_graph_exercise_occurrences(cur, gid)
if not occ:
continue
prof = profile_for_occurrences(
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES,
reference_max_by_skill=graph_ref,
)
match = match_score_for_skill_ids(prof, wanted)
if match["match_weight"] <= 0:
continue
results.append(
{
"artifact_type": "progression_graph",
"artifact_id": gid,
"artifact_title": g_row["name"],
"path": None,
"match": match,
"skill_profile_summary": {
"total_score": prof.get("total_score"),
"top_by_category": top_categories_summary(prof),
},
}
)
results.sort(
key=lambda x: -float(x.get("match", {}).get("match_score") or x.get("match", {}).get("match_weight") or 0),
)
return {
"skill_ids": wanted,
"types": sorted(type_set),
"suggestions": results[:limit],
}
def _top_categories_summary(profile: Dict[str, Any], limit: int = 6) -> List[Dict[str, Any]]:
"""Kurzliste Top-Fähigkeit je Unterkategorie für Discovery-Treffer."""
out: List[Dict[str, Any]] = []
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if not top:
continue
out.append(
{
"main_category_name": mc.get("main_category_name"),
"category_name": cat.get("category_name"),
"skill_id": top.get("skill_id"),
"skill_name": top.get("skill_name"),
"score": top.get("score") or top.get("weight"),
}
)
if len(out) >= limit:
return out
return out
def _parse_id_list(raw: Any, *, max_count: int = 120) -> List[int]:
if not raw:
return []
if not isinstance(raw, list):
raise HTTPException(status_code=400, detail="ID-Listen müssen Arrays sein")
out: List[int] = []
for item in raw:
try:
n = int(item)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="Ungültige ID in Liste") from None
if n > 0 and n not in out:
out.append(n)
if len(out) >= max_count:
break
return out
def _load_planning_corpus(cur, tenant: TenantContext) -> Dict[str, Any]:
return compute_planning_corpus_by_type(
cur,
profile_id=tenant.profile_id,
role=tenant.global_role,
effective_club_id=tenant.effective_club_id,
)
def _enrich_profile_club_best(
profile: Dict[str, Any],
ref_by_skill: Dict[int, Dict[str, Any]],
artifact_type: Optional[str] = None,
artifact_id: Optional[int] = None,
) -> None:
"""Hängt Vereins-Referenz-Artefakt an Fähigkeiten an (wenn nicht selbst Spitze)."""
if not profile or not ref_by_skill:
return
def attach(sk: Optional[Dict[str, Any]]) -> None:
if not sk or sk.get("skill_id") is None:
return
sid = int(sk["skill_id"])
ref = ref_by_skill.get(sid)
if not ref:
return
if (
artifact_type
and artifact_id is not None
and ref.get("artifact_type") == artifact_type
and int(ref.get("artifact_id") or 0) == int(artifact_id)
):
return
w = float(sk.get("weight") or 0)
if w < float(ref.get("weight") or 0) - 0.01:
sk["club_best"] = ref
for sk in profile.get("skills") or []:
attach(sk)
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
attach(cat.get("top_skill"))
def _empty_profile() -> Dict[str, Any]:
return compute_skill_profile([], {})
def _summarize_framework_program(
cur,
framework_id: int,
ref_max: Dict[int, float],
ref_by_skill: Dict[int, Dict[str, Any]],
) -> Dict[str, Any]:
cur.execute(
"""
SELECT tu.id
FROM training_framework_slots s
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
WHERE s.framework_program_id = %s
""",
(int(framework_id),),
)
occ: List[ExerciseOccurrence] = []
for u in cur.fetchall():
occ.extend(collect_unit_exercise_occurrences(cur, int(u["id"])))
prof = (
profile_for_occurrences(cur, occ, reference_max_by_skill=ref_max)
if occ
else _empty_profile()
)
_enrich_profile_club_best(prof, ref_by_skill, "framework_program", int(framework_id))
return compact_profile_summary(prof, ref_by_skill)
def _summarize_training_module(
cur,
module_id: int,
ref_max: Dict[int, float],
ref_by_skill: Dict[int, Dict[str, Any]],
) -> Dict[str, Any]:
occ = collect_module_exercise_occurrences(cur, int(module_id))
prof = (
profile_for_occurrences(cur, occ, reference_max_by_skill=ref_max)
if occ
else _empty_profile()
)
_enrich_profile_club_best(prof, ref_by_skill, "training_module", int(module_id))
return compact_profile_summary(prof, ref_by_skill)
def _merge_batch_summaries(
cur,
*,
bundle: Dict[str, Any],
allowed_fp: List[int],
allowed_mod: List[int],
) -> Dict[str, Dict[str, Any]]:
"""Summaries für angeforderte IDs — Referenz je Planungs-Kontext (Typ getrennt)."""
fw_tc = corpus_for_artifact_type(bundle, "framework_program")
mod_tc = corpus_for_artifact_type(bundle, "training_module")
fw_cached = fw_tc.get("artifact_summaries") or {}
mod_cached = mod_tc.get("artifact_summaries") or {}
out: Dict[str, Dict[str, Any]] = {}
fw_ref_max = fw_tc["max_by_skill"]
fw_ref_by = fw_tc["ref_by_skill"]
missing_fp = [fid for fid in allowed_fp if f"framework_program:{fid}" not in fw_cached]
if missing_fp:
occ_map = batch_framework_occurrences_by_id(cur, missing_fp)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
profiles = batch_compute_profiles(
occ_map, skills_map, reference_max_by_skill=fw_ref_max
)
for fid in missing_fp:
key = f"framework_program:{fid}"
prof = profiles.get(fid) or _empty_profile()
_enrich_profile_club_best(prof, fw_ref_by, "framework_program", fid)
out[key] = compact_profile_summary(prof, fw_ref_by)
mod_ref_max = mod_tc["max_by_skill"]
mod_ref_by = mod_tc["ref_by_skill"]
missing_mod = [mid for mid in allowed_mod if f"training_module:{mid}" not in mod_cached]
if missing_mod:
occ_map = batch_module_occurrences_by_id(cur, missing_mod)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
profiles = batch_compute_profiles(
occ_map, skills_map, reference_max_by_skill=mod_ref_max
)
for mid in missing_mod:
key = f"training_module:{mid}"
prof = profiles.get(mid) or _empty_profile()
_enrich_profile_club_best(prof, mod_ref_by, "training_module", mid)
out[key] = compact_profile_summary(prof, mod_ref_by)
for fid in allowed_fp:
key = f"framework_program:{fid}"
if key in fw_cached:
out[key] = fw_cached[key]
elif key not in out:
out[key] = _summarize_framework_program(cur, fid, fw_ref_max, fw_ref_by)
for mid in allowed_mod:
key = f"training_module:{mid}"
if key in mod_cached:
out[key] = mod_cached[key]
elif key not in out:
out[key] = _summarize_training_module(cur, mid, mod_ref_max, mod_ref_by)
return out
+7 -2
View File
@@ -181,9 +181,10 @@ def create_skill(data: dict, session=Depends(require_auth)):
"""
INSERT INTO skills (
name, category, description, importance, keywords, status,
category_id, main_category_id, focus_areas, sort_order
category_id, main_category_id, focus_areas, sort_order,
karate_relevance, relevance_level
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s)
RETURNING id
""",
(
@@ -197,6 +198,8 @@ def create_skill(data: dict, session=Depends(require_auth)):
main_id,
focus if focus is not None else "[]",
data.get("sort_order"),
data.get("karate_relevance"),
data.get("relevance_level"),
),
)
@@ -232,6 +235,8 @@ def update_skill(skill_id: int, data: dict, session=Depends(require_auth)):
"category_id",
"main_category_id",
"sort_order",
"karate_relevance",
"relevance_level",
):
if key in data:
sets.append(f"{key} = %s")
+200 -45
View File
@@ -3,13 +3,16 @@ Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
nicht über group_id oder training_unit_id am Rahmen.
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
Lesen wie Übungen (official / private / club); Bearbeiten wie Übungen; Löschen nach Rolle (s. club_tenancy).
"""
from typing import Any, Dict, List, Optional, Sequence
from fastapi import APIRouter, Depends, HTTPException
from club_tenancy import (
assert_library_content_deletable,
assert_library_content_editable,
assert_library_content_governance_transition,
assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile,
@@ -21,6 +24,7 @@ from routers.training_planning import (
_hydrate_training_unit_payload,
_optional_positive_int,
_insert_sections_from_legacy_exercises,
_replace_unit_phases,
_replace_unit_sections,
_validate_variant_for_exercise,
)
@@ -55,13 +59,6 @@ def _framework_assert_readable(
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
def _framework_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
if is_platform_admin(role):
return
if row.get("created_by") != profile_id:
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
row = _fetch_framework_row(cur, framework_id)
_framework_assert_readable(cur, row, profile_id, role)
@@ -102,6 +99,32 @@ def _target_group_ids(cur, framework_id: int) -> List[int]:
return [r["target_group_id"] for r in cur.fetchall()]
def _focus_area_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT focus_area_id
FROM training_framework_program_focus_areas
WHERE framework_program_id = %s
ORDER BY focus_area_id
""",
(framework_id,),
)
return [r["focus_area_id"] for r in cur.fetchall()]
def _style_direction_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT style_direction_id
FROM training_framework_program_style_directions
WHERE framework_program_id = %s
ORDER BY style_direction_id
""",
(framework_id,),
)
return [r["style_direction_id"] for r in cur.fetchall()]
def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
fid = row["id"]
cur.execute(
@@ -132,18 +155,30 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
row_b = cur.fetchone()
if not row_b:
s["blueprint_training_unit_id"] = None
s["phases"] = []
s["sections"] = []
s["exercises"] = []
continue
uid = row_b["id"]
s["blueprint_training_unit_id"] = uid
unit_min: Dict[str, Any] = {"id": uid}
cur.execute(
"SELECT planned_duration_min FROM training_units WHERE id = %s",
(uid,),
)
urow = cur.fetchone()
s["planned_duration_min"] = (
urow["planned_duration_min"] if urow else None
)
_hydrate_training_unit_payload(cur, unit_min)
s["phases"] = unit_min.get("phases", [])
s["sections"] = unit_min.get("sections", [])
s["exercises"] = unit_min.get("exercises", [])
row["slots"] = slots
row["training_type_ids"] = _training_type_ids(cur, fid)
row["target_group_ids"] = _target_group_ids(cur, fid)
row["focus_area_ids"] = _focus_area_ids(cur, fid)
row["style_direction_ids"] = _style_direction_ids(cur, fid)
return row
@@ -210,6 +245,53 @@ def _replace_target_groups(cur, framework_id: int, ids: Sequence[int]) -> None:
)
def _replace_focus_areas(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_focus_areas WHERE framework_program_id = %s",
(framework_id,),
)
for fid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_focus_areas (framework_program_id, focus_area_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, fid),
)
def _replace_style_directions(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_style_directions WHERE framework_program_id = %s",
(framework_id,),
)
for sid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_style_directions (framework_program_id, style_direction_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, sid),
)
def _parse_context_ids_from_payload(data: dict) -> tuple:
"""focus_area_ids / style_direction_ids (M:N); Legacy focus_area_id / style_direction_id."""
fa_ids = _parse_positive_int_ids(data.get("focus_area_ids"), "focus_area_ids")
if not fa_ids and data.get("focus_area_id") not in (None, ""):
one = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
if one is not None:
fa_ids = [one]
sd_ids = _parse_positive_int_ids(data.get("style_direction_ids"), "style_direction_ids")
if not sd_ids and data.get("style_direction_id") not in (None, ""):
one = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
if one is not None:
sd_ids = [one]
return fa_ids, sd_ids
def _insert_goal_rows(cur, framework_id: int, goals_in: List[Any]) -> None:
if not goals_in:
raise HTTPException(status_code=400, detail="Mindestens ein Entwicklungsziel (goals) ist erforderlich")
@@ -250,6 +332,7 @@ def _insert_slots_and_blueprints(
framework_id: int,
slots_in: Optional[List[Any]],
profile_id: int,
role: str,
) -> None:
if slots_in is None:
return
@@ -277,29 +360,35 @@ def _insert_slots_and_blueprints(
)
sid = cur.fetchone()["id"]
slot_pdur = _optional_positive_int(
slot.get("planned_duration_min"), "planned_duration_min"
)
cur.execute(
"""
INSERT INTO training_units (
group_id, planned_date,
planned_time_start, planned_time_end, planned_focus,
planned_time_start, planned_time_end, planned_duration_min, planned_focus,
status, notes, trainer_notes,
created_by, plan_template_id, framework_slot_id
) VALUES (
NULL, NULL,
NULL, NULL, NULL,
NULL, NULL, %s, NULL,
'planned', NULL, NULL,
%s, NULL, %s
)
RETURNING id
""",
(profile_id, sid),
(slot_pdur, profile_id, sid),
)
bid = cur.fetchone()["id"]
phases_in = slot.get("phases")
sections_in = slot.get("sections")
exercises_in = slot.get("exercises")
if sections_in is not None:
if phases_in is not None and isinstance(phases_in, list) and len(phases_in) > 0:
_replace_unit_phases(cur, bid, phases_in, profile_id, role, profile_id)
elif sections_in is not None:
if len(sections_in) == 0:
_insert_default_blueprint_section(cur, bid)
else:
@@ -324,8 +413,6 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
cur = get_cursor(conn)
base_sel = """
SELECT fp.*,
fa.name AS focus_area_name,
sd.name AS style_direction_name,
(SELECT COUNT(*)::int FROM training_framework_goals g WHERE g.framework_program_id = fp.id)
AS goals_count,
(SELECT COUNT(*)::int FROM training_framework_slots s WHERE s.framework_program_id = fp.id)
@@ -334,6 +421,18 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
WHERE t.framework_program_id = fp.id) AS training_types_count,
(SELECT COUNT(*)::int FROM training_framework_program_target_groups tg
WHERE tg.framework_program_id = fp.id) AS target_groups_count,
(
SELECT STRING_AGG(fa.name::text, ', ' ORDER BY fa.name)
FROM training_framework_program_focus_areas j
JOIN focus_areas fa ON fa.id = j.focus_area_id
WHERE j.framework_program_id = fp.id
) AS focus_area_names_agg,
(
SELECT STRING_AGG(sd.name::text, ', ' ORDER BY sd.name)
FROM training_framework_program_style_directions j
JOIN style_directions sd ON sd.id = j.style_direction_id
WHERE j.framework_program_id = fp.id
) AS style_direction_names_agg,
(
SELECT STRING_AGG(typ.name::text, ', ' ORDER BY typ.sort_order NULLS LAST, typ.name)
FROM training_framework_program_training_types j
@@ -345,10 +444,47 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
FROM training_framework_program_target_groups j
JOIN target_groups tg ON tg.id = j.target_group_id
WHERE j.framework_program_id = fp.id
) AS target_group_names_agg
) AS target_group_names_agg,
(
SELECT STRING_AGG(g.title::text, ' | ' ORDER BY g.sort_order)
FROM training_framework_goals g
WHERE g.framework_program_id = fp.id
) AS goal_titles_agg,
(
SELECT MIN(tu.planned_duration_min)::int
FROM training_framework_slots fs
INNER JOIN training_units tu ON tu.framework_slot_id = fs.id
WHERE fs.framework_program_id = fp.id
AND tu.planned_duration_min IS NOT NULL
) AS session_duration_min,
(
SELECT MAX(tu.planned_duration_min)::int
FROM training_framework_slots fs
INNER JOIN training_units tu ON tu.framework_slot_id = fs.id
WHERE fs.framework_program_id = fp.id
AND tu.planned_duration_min IS NOT NULL
) AS session_duration_max,
(
SELECT COALESCE(json_agg(j.focus_area_id ORDER BY j.focus_area_id), '[]'::json)
FROM training_framework_program_focus_areas j
WHERE j.framework_program_id = fp.id
) AS focus_area_ids,
(
SELECT COALESCE(json_agg(j.style_direction_id ORDER BY j.style_direction_id), '[]'::json)
FROM training_framework_program_style_directions j
WHERE j.framework_program_id = fp.id
) AS style_direction_ids,
(
SELECT COALESCE(json_agg(j.training_type_id ORDER BY j.training_type_id), '[]'::json)
FROM training_framework_program_training_types j
WHERE j.framework_program_id = fp.id
) AS training_type_ids,
(
SELECT COALESCE(json_agg(j.target_group_id ORDER BY j.target_group_id), '[]'::json)
FROM training_framework_program_target_groups j
WHERE j.framework_program_id = fp.id
) AS target_group_ids
FROM training_framework_programs fp
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
"""
vis_clause, vis_params = library_content_visibility_sql(
alias="fp",
@@ -400,10 +536,11 @@ def create_training_framework_program(
if not isinstance(goals_in, list) or not goals_in:
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
fa_id = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
sd_id = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
fa_ids, sd_ids = _parse_context_ids_from_payload(data)
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
fa_legacy = fa_ids[0] if len(fa_ids) == 1 else None
sd_legacy = sd_ids[0] if len(sd_ids) == 1 else None
with get_db() as conn:
cur = get_cursor(conn)
@@ -415,26 +552,26 @@ def create_training_framework_program(
planned_period_start, planned_period_end,
visibility, club_id, created_by,
focus_area_id, style_direction_id
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
) VALUES (%s, %s, NULL, NULL, %s, %s, %s, %s, %s)
RETURNING id
""",
(
title[:200],
data.get("description"),
data.get("planned_period_start"),
data.get("planned_period_end"),
vis,
club_id,
profile_id,
fa_id,
sd_id,
fa_legacy,
sd_legacy,
),
)
fid = cur.fetchone()["id"]
_insert_goal_rows(cur, fid, goals_in)
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id)
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id, role)
_replace_training_types(cur, fid, tt_ids)
_replace_target_groups(cur, fid, tg_ids)
_replace_focus_areas(cur, fid, fa_ids)
_replace_style_directions(cur, fid, sd_ids)
conn.commit()
return _response_framework_detail(fid, profile_id, role)
@@ -452,7 +589,7 @@ def update_training_framework_program(
with get_db() as conn:
cur = get_cursor(conn)
row_prev = _fetch_framework_row(cur, framework_id)
_framework_assert_writable(cur, row_prev, profile_id, role)
assert_library_content_editable(cur, profile_id, role, row_prev)
merged_vis = row_prev.get("visibility") or "private"
merged_club = row_prev.get("club_id")
@@ -465,7 +602,12 @@ def update_training_framework_program(
merged_club = data.get("club_id")
if merged_club in ("", []):
merged_club = None
if merged_vis == "club" and merged_club is None:
merged_club = tenant.effective_club_id
if "visibility" in data or "club_id" in data:
assert_library_content_governance_transition(
cur, profile_id, role, row_prev, merged_vis, merged_club
)
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
header_fields = []
@@ -481,13 +623,6 @@ def update_training_framework_program(
if "description" in data:
header_fields.append("description = %s")
header_params.append(data.get("description"))
if "planned_period_start" in data:
header_fields.append("planned_period_start = %s")
header_params.append(data.get("planned_period_start"))
if "planned_period_end" in data:
header_fields.append("planned_period_end = %s")
header_params.append(data.get("planned_period_end"))
if "visibility" in data:
header_fields.append("visibility = %s")
header_params.append(merged_vis)
@@ -495,18 +630,26 @@ def update_training_framework_program(
header_fields.append("club_id = %s")
header_params.append(merged_club)
if "focus_area_id" in data:
fidv = data.get("focus_area_id")
if "focus_area_ids" in data or "focus_area_id" in data:
fa_ids = _parse_positive_int_ids(data.get("focus_area_ids"), "focus_area_ids")
if not fa_ids and data.get("focus_area_id") not in (None, ""):
one = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
if one is not None:
fa_ids = [one]
header_fields.append("focus_area_id = %s")
header_params.append(
None if fidv in (None, "") else _optional_positive_int(fidv, "focus_area_id")
header_params.append(fa_ids[0] if len(fa_ids) == 1 else None)
_replace_focus_areas(cur, framework_id, fa_ids)
if "style_direction_ids" in data or "style_direction_id" in data:
sd_ids = _parse_positive_int_ids(
data.get("style_direction_ids"), "style_direction_ids"
)
if "style_direction_id" in data:
sidv = data.get("style_direction_id")
if not sd_ids and data.get("style_direction_id") not in (None, ""):
one = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
if one is not None:
sd_ids = [one]
header_fields.append("style_direction_id = %s")
header_params.append(
None if sidv in (None, "") else _optional_positive_int(sidv, "style_direction_id")
)
header_params.append(sd_ids[0] if len(sd_ids) == 1 else None)
_replace_style_directions(cur, framework_id, sd_ids)
if header_fields:
header_fields.append("updated_at = NOW()")
@@ -543,9 +686,21 @@ def update_training_framework_program(
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
(framework_id,),
)
_insert_slots_and_blueprints(cur, framework_id, data.get("slots") or [], profile_id)
_insert_slots_and_blueprints(
cur, framework_id, data.get("slots") or [], profile_id, role
)
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
if (
header_fields
or "goals" in data
or "slots" in data
or "training_type_ids" in data
or "target_group_ids" in data
or "focus_area_ids" in data
or "focus_area_id" in data
or "style_direction_ids" in data
or "style_direction_id" in data
):
cur.execute(
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
(framework_id,),
@@ -565,7 +720,7 @@ def delete_training_framework_program(
with get_db() as conn:
cur = get_cursor(conn)
row_fw = _fetch_framework_row(cur, framework_id)
_framework_assert_writable(cur, row_fw, profile_id, role)
assert_library_content_deletable(cur, profile_id, role, row_fw)
cur.execute(
"DELETE FROM training_framework_programs WHERE id = %s",
(framework_id,),
+11 -11
View File
@@ -2,7 +2,7 @@
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
Liste/Detail über `library_content_visibility_sql`; Schreiben: Ersteller oder Plattform‑Admin.
Liste/Detail über `library_content_visibility_sql`; Bearbeiten/Löschen wie Übungen (s. club_tenancy).
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
"""
@@ -13,6 +13,9 @@ from fastapi import APIRouter, Depends, HTTPException
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
from club_tenancy import (
assert_library_content_deletable,
assert_library_content_editable,
assert_library_content_governance_transition,
assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile,
@@ -47,13 +50,6 @@ def _module_assert_readable(cur, row: Dict[str, Any], profile_id: int, role: Opt
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
def _module_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
if is_platform_admin(role):
return
if row.get("created_by") != profile_id:
raise HTTPException(status_code=403, detail="Nur der Ersteller darf dieses Modul ändern")
def _module_access(cur, mid: int, profile_id: int, role: str) -> Dict[str, Any]:
row = _fetch_training_module_row(cur, mid)
_module_assert_readable(cur, row, profile_id, role)
@@ -288,7 +284,7 @@ def update_training_module(
with get_db() as conn:
cur = get_cursor(conn)
row_prev = _fetch_training_module_row(cur, module_id)
_module_assert_writable(cur, row_prev, profile_id, role)
assert_library_content_editable(cur, profile_id, role, row_prev)
merged_vis = row_prev.get("visibility") or "club"
merged_club = row_prev.get("club_id")
@@ -303,8 +299,12 @@ def update_training_module(
merged_club = data.get("club_id")
if merged_club in ("", []):
merged_club = None
if merged_vis == "club" and merged_club is None:
merged_club = tenant.effective_club_id
if "visibility" in data or "club_id" in data:
assert_library_content_governance_transition(
cur, profile_id, role, row_prev, merged_vis, merged_club
)
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
fields: List[str] = []
@@ -375,7 +375,7 @@ def delete_training_module(module_id: int, tenant: TenantContext = Depends(get_t
with get_db() as conn:
cur = get_cursor(conn)
row_del = _fetch_training_module_row(cur, module_id)
_module_assert_writable(cur, row_del, profile_id, role)
assert_library_content_deletable(cur, profile_id, role, row_del)
cur.execute("DELETE FROM training_modules WHERE id = %s", (module_id,))
conn.commit()
return {"ok": True}
File diff suppressed because it is too large. Load diff
@@ -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",
}
+985
View File
@@ -0,0 +1,985 @@
"""
Gewichtetes Fähigkeiten-Scoring aus Übungsvorkommen (Phase 3, regelbasiert).
Aggregiert exercise_skills über alle Übungen eines Artefakts mit Gewichten aus:
geplanter Dauer, Vorkommen, Intensität (Nutzeneinschätzung) und Stufen-Spanne (von/bis).
is_primary wird bewusst nicht genutzt (perspektivabhängig). development_contribution ist
in der UI nicht gepflegt und wird ignoriert.
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
DEFAULT_ITEM_MINUTES = 8
GRAPH_DEFAULT_ITEM_MINUTES = 10
_INTENSITY_MULT = {
"niedrig": 0.85,
"low": 0.85,
"mittel": 1.0,
"medium": 1.0,
"hoch": 1.2,
"high": 1.2,
}
# Synchron zu backend/routers/exercises.py _EXERCISE_SKILL_LEVEL_RANK_SQL / skillLevels.js
_LEVEL_RANK = {
"basis": 1,
"grundlagen": 2,
"aufbau": 3,
"fortgeschritten": 4,
"optimierung": 5,
"einsteiger": 1,
"experte": 5,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
}
def _level_rank(value: Optional[str]) -> Optional[int]:
if value is None:
return None
key = str(value).strip().lower()
if not key:
return None
rank = _LEVEL_RANK.get(key)
return rank if rank is not None else None
def _level_range_multiplier(
required_level: Optional[str] = None,
target_level: Optional[str] = None,
) -> float:
"""
Stufen-Spanne (von/bis): breitere und höhere Entwicklungsstufen → etwas höheres Gewicht.
Fehlen beide Angaben: neutral (1.0).
"""
rr = _level_rank(required_level)
rt = _level_rank(target_level)
if rr is None and rt is None:
return 1.0
if rr is None:
rr = rt
if rt is None:
rt = rr
if rr > rt:
rr, rt = rt, rr
span = max(1, min(5, rt - rr + 1))
midpoint = (rr + rt) / 2.0
span_mult = 0.92 + 0.04 * span
depth_mult = 0.95 + 0.025 * midpoint
return span_mult * depth_mult
@dataclass(frozen=True)
class ExerciseOccurrence:
exercise_id: int
planned_duration_min: Optional[int] = None
"""Optional label for UI (e.g. slot title)."""
context_label: Optional[str] = None
def _item_base_minutes(planned: Optional[int], default: int = DEFAULT_ITEM_MINUTES) -> float:
if planned is not None:
try:
m = int(planned)
if m > 0:
return float(m)
except (TypeError, ValueError):
pass
return float(default)
def _skill_link_multiplier(
*,
intensity: Optional[str] = None,
required_level: Optional[str] = None,
target_level: Optional[str] = None,
) -> float:
mult = 1.0
if intensity:
key = str(intensity).strip().lower()
mult *= _INTENSITY_MULT.get(key, 1.0)
mult *= _level_range_multiplier(required_level, target_level)
return mult
def _round2(val: float) -> float:
return round(val, 2)
def _build_by_main_category(skills_out: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Hierarchie Hauptkategorie → Unterkategorie, je Top-Fähigkeit nach absolutem Gewicht."""
main_map: Dict[int, Dict[str, Any]] = {}
for sk in skills_out:
mc_id = int(sk.get("main_category_id") or 0)
mc_name = (sk.get("main_category_name") or "").strip() or "—"
cat_id = int(sk.get("category_id") or 0)
cat_name = (sk.get("category_name") or sk.get("category") or "").strip() or "—"
if mc_id not in main_map:
main_map[mc_id] = {
"main_category_id": mc_id if mc_id else None,
"main_category_name": mc_name,
"weight": 0.0,
"categories": {},
}
main = main_map[mc_id]
main["weight"] += float(sk.get("weight") or 0)
if cat_id not in main["categories"]:
main["categories"][cat_id] = {
"category_id": cat_id if cat_id else None,
"category_name": cat_name,
"weight": 0.0,
"skills": [],
}
cat = main["categories"][cat_id]
cat["weight"] += float(sk.get("weight") or 0)
cat["skills"].append(sk)
result: List[Dict[str, Any]] = []
for mc in sorted(main_map.values(), key=lambda x: (-x["weight"], x.get("main_category_name") or "")):
cats_out: List[Dict[str, Any]] = []
for cat in sorted(
mc["categories"].values(),
key=lambda x: (-x["weight"], x.get("category_name") or ""),
):
cat_skills = sorted(
cat["skills"],
key=lambda x: (-float(x.get("weight") or 0), x.get("skill_name") or ""),
)
top = cat_skills[0] if cat_skills else None
cats_out.append(
{
"category_id": cat["category_id"],
"category_name": cat["category_name"],
"weight": _round2(cat["weight"]),
"skills_count": len(cat_skills),
"top_skill": top,
}
)
result.append(
{
"main_category_id": mc["main_category_id"],
"main_category_name": mc["main_category_name"],
"weight": _round2(mc["weight"]),
"categories": cats_out,
}
)
return result
def _club_universal_percent(
weight: float,
corpus_ref: float,
) -> tuple[Optional[float], bool]:
"""
Anteil am Vereins-Maximum (max. 100 %).
effective_ref = max(Korpus-Max, eigenes Gewicht) — verhindert Werte >100 %,
wenn das Artefakt stärker ist als der bisherige Vereins-Vergleich (z. B. official).
"""
w = float(weight or 0)
ref = float(corpus_ref or 0)
if w <= 0:
return None, False
effective_ref = max(ref, w)
pct = min(100.0, w / effective_ref * 100.0)
is_best = ref <= 0 or w >= ref - 0.01
return _round2(pct), is_best
def _apply_reference_universal_percent(
skills_out: List[Dict[str, Any]],
reference_max_by_skill: Optional[Dict[int, float]] = None,
) -> None:
"""
Stärke relativ zum Vereins-Maximum je Fähigkeit (gecappt auf 100 %).
"""
if not reference_max_by_skill:
for sk in skills_out:
sk["universal_percent"] = None
sk["is_club_best_for_skill"] = False
return
for sk in skills_out:
sid = int(sk["skill_id"])
ref = float(reference_max_by_skill.get(sid) or 0)
w = float(sk.get("weight") or 0)
pct, is_best = _club_universal_percent(w, ref)
sk["universal_percent"] = pct
sk["is_club_best_for_skill"] = is_best
def compute_skill_profile(
occurrences: Sequence[ExerciseOccurrence],
skill_rows_by_exercise: Dict[int, List[Dict[str, Any]]],
*,
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
reference_max_by_skill: Optional[Dict[int, float]] = None,
) -> Dict[str, Any]:
"""
Erzeugt ein normalisiertes Fähigkeiten-Profil aus Übungsvorkommen und exercise_skills.
"""
exercise_meta: Dict[int, Dict[str, Any]] = defaultdict(
lambda: {"occurrence_count": 0, "minutes": 0.0, "context_labels": []}
)
total_occurrences = 0
for occ in occurrences or []:
eid = int(occ.exercise_id)
mins = _item_base_minutes(occ.planned_duration_min, default_item_minutes)
exercise_meta[eid]["occurrence_count"] += 1
exercise_meta[eid]["minutes"] += mins
total_occurrences += 1
if occ.context_label and occ.context_label not in exercise_meta[eid]["context_labels"]:
exercise_meta[eid]["context_labels"].append(occ.context_label)
skill_acc: Dict[int, Dict[str, Any]] = {}
total_weight = 0.0
exercises_with_skills: set[int] = set()
for eid, meta in exercise_meta.items():
links = skill_rows_by_exercise.get(eid) or []
if not links:
continue
exercises_with_skills.add(eid)
occ_count = meta["occurrence_count"]
minutes_per_occ = meta["minutes"] / occ_count if occ_count else float(default_item_minutes)
for link in links:
sid = link.get("skill_id")
if sid is None:
continue
sid = int(sid)
link_mult = _skill_link_multiplier(
intensity=link.get("intensity"),
required_level=link.get("required_level"),
target_level=link.get("target_level"),
)
contribution = minutes_per_occ * occ_count * link_mult
if contribution <= 0:
continue
if sid not in skill_acc:
skill_acc[sid] = {
"skill_id": sid,
"skill_name": link.get("skill_name") or f"Fähigkeit #{sid}",
"category": link.get("category_name") or link.get("category"),
"category_id": link.get("category_id"),
"category_name": link.get("category_name") or link.get("category"),
"main_category_id": link.get("main_category_id"),
"main_category_name": link.get("main_category_name"),
"focus_areas": link.get("focus_areas"),
"weight": 0.0,
"occurrence_count": 0,
"exercises": {},
}
acc = skill_acc[sid]
acc["weight"] += contribution
acc["occurrence_count"] += occ_count
ex_key = str(eid)
if ex_key not in acc["exercises"]:
acc["exercises"][ex_key] = {
"exercise_id": eid,
"title": link.get("exercise_title") or f"Übung #{eid}",
"weight": 0.0,
"occurrence_count": occ_count,
}
acc["exercises"][ex_key]["weight"] += contribution
total_weight += contribution
skills_out: List[Dict[str, Any]] = []
for sid, acc in skill_acc.items():
share = (acc["weight"] / total_weight * 100.0) if total_weight > 0 else 0.0
ex_list = sorted(
acc["exercises"].values(),
key=lambda x: (-x["weight"], x.get("title") or ""),
)[:8]
for ex in ex_list:
ex["weight"] = _round2(ex["weight"])
if total_weight > 0:
ex["share_percent"] = _round2(ex["weight"] / total_weight * 100.0)
else:
ex["share_percent"] = 0.0
skills_out.append(
{
"skill_id": sid,
"skill_name": acc["skill_name"],
"category": acc.get("category_name") or acc.get("category"),
"category_id": acc.get("category_id"),
"category_name": acc.get("category_name") or acc.get("category"),
"main_category_id": acc.get("main_category_id"),
"main_category_name": acc.get("main_category_name"),
"focus_areas": acc.get("focus_areas"),
"weight": _round2(acc["weight"]),
"score": _round2(acc["weight"]),
"artifact_share_percent": _round2(share),
"share_percent": _round2(share),
"occurrence_count": acc["occurrence_count"],
"top_exercises": ex_list,
}
)
skills_out.sort(key=lambda x: (-x["weight"], x.get("skill_name") or ""))
_apply_reference_universal_percent(skills_out, reference_max_by_skill)
by_main_category = _build_by_main_category(skills_out)
for mc in by_main_category:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if top and reference_max_by_skill:
sid = int(top["skill_id"])
ref = float(reference_max_by_skill.get(sid) or 0)
pct, is_best = _club_universal_percent(float(top.get("weight") or 0), ref)
top["universal_percent"] = pct
top["is_club_best_for_skill"] = is_best
unique_exercises = len(exercise_meta)
return {
"computed_at": datetime.now(timezone.utc).isoformat(),
"scoring_version": "1.2",
"score_unit": "weighted_minutes",
"score_unit_label": "Trainingsgewicht (gewichtete Minuten, über Programme vergleichbar)",
"total_weight": _round2(total_weight),
"total_score": _round2(total_weight),
"exercise_occurrence_count": total_occurrences,
"distinct_exercise_count": unique_exercises,
"exercises_with_skills_count": len(exercises_with_skills),
"skills": skills_out,
"by_main_category": by_main_category,
"has_reference_scale": bool(reference_max_by_skill),
}
def fetch_exercise_skills_bulk(
cur, exercise_ids: Iterable[int]
) -> Dict[int, List[Dict[str, Any]]]:
ids = sorted({int(x) for x in exercise_ids if x})
if not ids:
return {}
ph = ",".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT es.exercise_id, es.skill_id, es.is_primary, es.intensity,
es.development_contribution, es.required_level, es.target_level,
s.name AS skill_name, s.category,
sc.id AS category_id, sc.name AS category_name,
mc.id AS main_category_id, mc.name AS main_category_name,
s.focus_areas,
e.title AS exercise_title
FROM exercise_skills es
JOIN skills s ON s.id = es.skill_id
LEFT JOIN skill_categories sc ON sc.id = s.category_id
LEFT JOIN skill_main_categories mc ON mc.id = COALESCE(s.main_category_id, sc.main_category_id)
JOIN exercises e ON e.id = es.exercise_id
WHERE es.exercise_id IN ({ph})
AND (s.status = 'active' OR s.status IS NULL)
ORDER BY es.exercise_id, s.name, es.skill_id
""",
ids,
)
out: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
for row in cur.fetchall():
d = dict(row)
eid = int(d["exercise_id"])
fa = d.get("focus_areas")
if fa is not None and not isinstance(fa, list):
try:
import json
fa = json.loads(fa) if isinstance(fa, str) else fa
except Exception:
fa = []
d["focus_areas"] = fa if isinstance(fa, list) else []
out[eid].append(d)
return dict(out)
def collect_unit_exercise_occurrences(cur, unit_id: int) -> List[ExerciseOccurrence]:
cur.execute(
"""
SELECT tusi.exercise_id, tusi.planned_duration_min
FROM training_unit_section_items tusi
INNER JOIN training_unit_sections tus ON tus.id = tusi.section_id
WHERE tus.training_unit_id = %s
AND tusi.item_type = 'exercise'
AND tusi.exercise_id IS NOT NULL
ORDER BY tus.order_index, tusi.order_index
""",
(int(unit_id),),
)
return [
ExerciseOccurrence(
exercise_id=int(r["exercise_id"]),
planned_duration_min=r.get("planned_duration_min"),
)
for r in cur.fetchall()
]
def collect_module_exercise_occurrences(cur, module_id: int) -> List[ExerciseOccurrence]:
cur.execute(
"""
SELECT exercise_id, planned_duration_min
FROM training_module_items
WHERE module_id = %s
AND item_type = 'exercise'
AND exercise_id IS NOT NULL
ORDER BY order_index
""",
(int(module_id),),
)
return [
ExerciseOccurrence(
exercise_id=int(r["exercise_id"]),
planned_duration_min=r.get("planned_duration_min"),
)
for r in cur.fetchall()
]
def collect_progression_graph_exercise_occurrences(cur, graph_id: int) -> List[ExerciseOccurrence]:
"""Jedes Vorkommen als from- oder to-Endpunkt einer Kante zählt (ohne Dauer → Default)."""
cur.execute(
"""
SELECT from_exercise_id AS exercise_id FROM exercise_progression_edges WHERE graph_id = %s
UNION ALL
SELECT to_exercise_id AS exercise_id FROM exercise_progression_edges WHERE graph_id = %s
""",
(int(graph_id), int(graph_id)),
)
return [
ExerciseOccurrence(
exercise_id=int(r["exercise_id"]),
planned_duration_min=None,
context_label=None,
)
for r in cur.fetchall()
]
def profile_for_occurrences(
cur,
occurrences: Sequence[ExerciseOccurrence],
*,
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
reference_max_by_skill: Optional[Dict[int, float]] = None,
) -> Dict[str, Any]:
eids = [o.exercise_id for o in occurrences]
skills_map = fetch_exercise_skills_bulk(cur, eids)
return compute_skill_profile(
occurrences,
skills_map,
default_item_minutes=default_item_minutes,
reference_max_by_skill=reference_max_by_skill,
)
def merge_skill_weights_into_max(
target: Dict[int, float],
profile: Dict[str, Any],
) -> None:
for sk in profile.get("skills") or []:
sid = int(sk["skill_id"])
w = float(sk.get("weight") or 0)
if w > target.get(sid, 0.0):
target[sid] = w
def merge_skill_weights_with_reference(
max_by_skill: Dict[int, float],
ref_by_skill: Dict[int, Dict[str, Any]],
profile: Dict[str, Any],
*,
artifact_type: str,
artifact_id: int,
artifact_title: Optional[str] = None,
) -> None:
"""Aktualisiert Vereins-Maximum je Fähigkeit inkl. Quell-Artefakt."""
for sk in profile.get("skills") or []:
sid = int(sk["skill_id"])
w = float(sk.get("weight") or 0)
if w <= 0:
continue
if w > max_by_skill.get(sid, 0.0):
max_by_skill[sid] = w
ref_by_skill[sid] = {
"artifact_type": artifact_type,
"artifact_id": int(artifact_id),
"artifact_title": (artifact_title or "").strip() or None,
"weight": _round2(w),
}
def top_categories_summary(profile: Dict[str, Any], limit: int = 6) -> List[Dict[str, Any]]:
"""Top-Fähigkeit je Unterkategorie (kompakt für Listen/Discovery)."""
out: List[Dict[str, Any]] = []
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if not top:
continue
out.append(
{
"main_category_name": mc.get("main_category_name"),
"category_name": cat.get("category_name"),
"skill_id": top.get("skill_id"),
"skill_name": top.get("skill_name"),
"score": top.get("score") or top.get("weight"),
"weight": top.get("weight"),
"universal_percent": top.get("universal_percent"),
"is_club_best_for_skill": top.get("is_club_best_for_skill"),
}
)
if len(out) >= limit:
return out
return out
def _apply_reference_to_profile(
profile: Dict[str, Any],
reference_max_by_skill: Optional[Dict[int, float]],
) -> None:
_apply_reference_universal_percent(profile.get("skills") or [], reference_max_by_skill)
profile["by_main_category"] = _build_by_main_category(profile.get("skills") or [])
for mc in profile.get("by_main_category") or []:
for cat in mc.get("categories") or []:
top = cat.get("top_skill")
if top and reference_max_by_skill:
sid = int(top["skill_id"])
ref = float(reference_max_by_skill.get(sid) or 0)
pct, is_best = _club_universal_percent(float(top.get("weight") or 0), ref)
top["universal_percent"] = pct
top["is_club_best_for_skill"] = is_best
profile["has_reference_scale"] = bool(reference_max_by_skill)
def compact_profile_summary(
profile: Dict[str, Any],
ref_by_skill: Optional[Dict[int, Dict[str, Any]]] = None,
*,
skills_limit: int = 0,
category_limit: int = 48,
) -> Dict[str, Any]:
"""Leichtgewichtiges Profil für Listen — ohne Übungsdetails. skills_limit=0 → alle Fähigkeiten."""
skills_out: List[Dict[str, Any]] = []
for s in profile.get("skills") or []:
sid = int(s["skill_id"])
w = float(s.get("weight") or 0)
entry: Dict[str, Any] = {
"skill_id": sid,
"skill_name": s.get("skill_name"),
"category_name": s.get("category_name") or s.get("category"),
"main_category_name": s.get("main_category_name"),
"weight": s.get("weight"),
"score": s.get("score") or s.get("weight"),
"universal_percent": s.get("universal_percent"),
}
ref = (ref_by_skill or {}).get(sid)
if ref and w < float(ref.get("weight") or 0) - 0.01:
entry["club_best"] = ref
if s.get("is_club_best_for_skill"):
entry["is_club_best_for_skill"] = True
skills_out.append(entry)
if skills_limit > 0 and len(skills_out) >= skills_limit:
break
return {
"total_score": profile.get("total_score"),
"total_weight": profile.get("total_weight"),
"exercise_occurrence_count": profile.get("exercise_occurrence_count"),
"skills_count": len(profile.get("skills") or []),
"top_by_category": top_categories_summary(profile, limit=category_limit),
"skills": skills_out,
}
def batch_framework_occurrences_by_id(
cur, framework_ids: Sequence[int]
) -> Dict[int, List[ExerciseOccurrence]]:
ids = sorted({int(x) for x in framework_ids if x})
if not ids:
return {}
ph = ",".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT s.framework_program_id,
COALESCE(NULLIF(TRIM(s.title), ''), 'Session ' || (s.sort_order + 1)::text) AS slot_label,
tusi.exercise_id,
tusi.planned_duration_min
FROM training_framework_slots s
INNER JOIN training_units tu ON tu.framework_slot_id = s.id
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
WHERE s.framework_program_id IN ({ph})
AND tusi.item_type = 'exercise'
AND tusi.exercise_id IS NOT NULL
ORDER BY s.framework_program_id, s.sort_order, tus.order_index, tusi.order_index
""",
ids,
)
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
for row in cur.fetchall():
fid = int(row["framework_program_id"])
out[fid].append(
ExerciseOccurrence(
exercise_id=int(row["exercise_id"]),
planned_duration_min=row.get("planned_duration_min"),
context_label=row.get("slot_label"),
)
)
return dict(out)
def batch_module_occurrences_by_id(
cur, module_ids: Sequence[int]
) -> Dict[int, List[ExerciseOccurrence]]:
ids = sorted({int(x) for x in module_ids if x})
if not ids:
return {}
ph = ",".join(["%s"] * len(ids))
cur.execute(
f"""
SELECT module_id, exercise_id, planned_duration_min
FROM training_module_items
WHERE module_id IN ({ph})
AND item_type = 'exercise'
AND exercise_id IS NOT NULL
ORDER BY module_id, order_index
""",
ids,
)
out: Dict[int, List[ExerciseOccurrence]] = defaultdict(list)
for row in cur.fetchall():
mid = int(row["module_id"])
out[mid].append(
ExerciseOccurrence(
exercise_id=int(row["exercise_id"]),
planned_duration_min=row.get("planned_duration_min"),
)
)
return dict(out)
def batch_compute_profiles(
occ_by_artifact: Dict[int, List[ExerciseOccurrence]],
skills_map: Dict[int, List[Dict[str, Any]]],
*,
reference_max_by_skill: Optional[Dict[int, float]] = None,
default_item_minutes: int = DEFAULT_ITEM_MINUTES,
) -> Dict[int, Dict[str, Any]]:
return {
aid: compute_skill_profile(
occ,
skills_map,
default_item_minutes=default_item_minutes,
reference_max_by_skill=reference_max_by_skill,
)
for aid, occ in occ_by_artifact.items()
}
def _empty_type_corpus() -> Dict[str, Any]:
return {
"max_by_skill": {},
"ref_by_skill": {},
"artifact_count": 0,
"artifact_summaries": {},
}
def corpus_for_artifact_type(
bundle: Dict[str, Any],
artifact_type: str,
) -> Dict[str, Any]:
by_type = bundle.get("by_type") or {}
return by_type.get(artifact_type) or _empty_type_corpus()
def _scan_artifact_type_corpus(
cur,
*,
artifact_type: str,
profile_id: int,
role: Optional[str],
effective_club_id: Optional[int],
include_artifact_summaries: bool,
) -> Dict[str, Any]:
"""Referenz je Fähigkeit nur innerhalb eines Planungs-Kontexts (ein Artefakttyp, sichtbare Bibliothek)."""
from tenant_context import library_content_visibility_sql
max_by_skill: Dict[int, float] = {}
ref_by_skill: Dict[int, Dict[str, Any]] = {}
artifact_count = 0
raw_profiles: Dict[str, Dict[str, Any]] = {}
def ingest(aid: int, title: Optional[str], prof: Dict[str, Any]) -> None:
nonlocal artifact_count
if not prof.get("skills"):
return
artifact_count += 1
merge_skill_weights_with_reference(
max_by_skill,
ref_by_skill,
prof,
artifact_type=artifact_type,
artifact_id=aid,
artifact_title=title,
)
if include_artifact_summaries:
raw_profiles[f"{artifact_type}:{aid}"] = prof
if artifact_type == "framework_program":
vis_clause, vis_params = library_content_visibility_sql(
alias="fp",
profile_id=profile_id,
role=role or "",
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT fp.id, fp.title
FROM training_framework_programs fp
WHERE ({vis_clause})
ORDER BY fp.updated_at DESC NULLS LAST
""",
vis_params,
)
rows = cur.fetchall()
if rows:
ids = [int(r["id"]) for r in rows]
titles = {int(r["id"]): r.get("title") for r in rows}
occ_map = batch_framework_occurrences_by_id(cur, ids)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
profiles = batch_compute_profiles(occ_map, skills_map)
for aid, prof in profiles.items():
ingest(aid, titles.get(aid), prof)
elif artifact_type == "training_module":
vis_clause, vis_params = library_content_visibility_sql(
alias="m",
profile_id=profile_id,
role=role or "",
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT m.id, m.title
FROM training_modules m
WHERE ({vis_clause})
ORDER BY m.updated_at DESC NULLS LAST
""",
vis_params,
)
rows = cur.fetchall()
if rows:
ids = [int(r["id"]) for r in rows]
titles = {int(r["id"]): r.get("title") for r in rows}
occ_map = batch_module_occurrences_by_id(cur, ids)
all_eids = {o.exercise_id for occs in occ_map.values() for o in occs}
skills_map = fetch_exercise_skills_bulk(cur, all_eids) if all_eids else {}
profiles = batch_compute_profiles(occ_map, skills_map)
for aid, prof in profiles.items():
ingest(aid, titles.get(aid), prof)
elif artifact_type == "progression_graph":
vis_clause, vis_params = library_content_visibility_sql(
alias="g",
profile_id=profile_id,
role=role or "",
effective_club_id=effective_club_id,
)
cur.execute(
f"""
SELECT g.id, g.name
FROM exercise_progression_graphs g
WHERE ({vis_clause})
ORDER BY g.updated_at DESC NULLS LAST
""",
vis_params,
)
for row in cur.fetchall():
gid = int(row["id"])
occ = collect_progression_graph_exercise_occurrences(cur, gid)
if not occ:
continue
prof = profile_for_occurrences(
cur, occ, default_item_minutes=GRAPH_DEFAULT_ITEM_MINUTES
)
ingest(gid, row.get("name"), prof)
artifact_summaries: Dict[str, Dict[str, Any]] = {}
if include_artifact_summaries and raw_profiles:
for key, prof in raw_profiles.items():
_apply_reference_to_profile(prof, max_by_skill)
artifact_summaries[key] = compact_profile_summary(prof, ref_by_skill)
return {
"max_by_skill": max_by_skill,
"ref_by_skill": ref_by_skill,
"artifact_count": artifact_count,
"artifact_summaries": artifact_summaries,
}
def compute_planning_corpus_by_type(
cur,
*,
profile_id: int,
role: Optional[str],
effective_club_id: Optional[int],
include_artifact_summaries: bool = False,
) -> Dict[str, Any]:
"""
Referenz je Fähigkeit getrennt nach Planungs-Kontext:
Rahmenprogramme, Trainingsmodule und Regressionspfade jeweils für sich,
jeweils über die sichtbare Bibliothek (library_content_visibility_sql).
"""
by_type = {
"framework_program": _scan_artifact_type_corpus(
cur,
artifact_type="framework_program",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
include_artifact_summaries=include_artifact_summaries,
),
"training_module": _scan_artifact_type_corpus(
cur,
artifact_type="training_module",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
include_artifact_summaries=include_artifact_summaries,
),
"progression_graph": _scan_artifact_type_corpus(
cur,
artifact_type="progression_graph",
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
include_artifact_summaries=include_artifact_summaries,
),
}
return {
"effective_club_id": effective_club_id,
"by_type": by_type,
}
def compute_club_corpus_reference(
cur,
*,
profile_id: int,
effective_club_id: Optional[int],
include_artifact_summaries: bool = False,
role: Optional[str] = None,
) -> Dict[str, Any]:
"""Legacy-Hülle — merged summaries über alle Typen (vermeiden für neue Aufrufer)."""
bundle = compute_planning_corpus_by_type(
cur,
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
include_artifact_summaries=include_artifact_summaries,
)
tc = corpus_for_artifact_type(bundle, "framework_program")
merged_summaries: Dict[str, Dict[str, Any]] = {}
for t in ("framework_program", "training_module", "progression_graph"):
merged_summaries.update((bundle["by_type"][t].get("artifact_summaries") or {}))
return {
"club_id": effective_club_id,
"max_by_skill": tc["max_by_skill"],
"ref_by_skill": tc["ref_by_skill"],
"artifact_count": sum(
(bundle["by_type"][t].get("artifact_count") or 0)
for t in bundle["by_type"]
),
"artifact_summaries": merged_summaries,
}
_ARTIFACT_TYPE_LABELS = {
"framework_program": "Rahmenprogrammen",
"training_module": "Trainingsmodulen",
"progression_graph": "Regressionspfaden",
}
def reference_scale_meta(
type_corpus: Dict[str, Any],
artifact_type: str,
*,
effective_club_id: Optional[int] = None,
) -> Dict[str, Any]:
label = _ARTIFACT_TYPE_LABELS.get(artifact_type, artifact_type)
return {
"scope": "planning_peer",
"artifact_type": artifact_type,
"effective_club_id": effective_club_id,
"skills_in_corpus": len(type_corpus.get("max_by_skill") or {}),
"artifacts_scanned": type_corpus.get("artifact_count") or 0,
"description": (
f"Prozent = Anteil am stärksten sichtbaren Eintrag unter {label} je Fähigkeit "
f"(nicht gemischt mit anderen Planungs-Artefakttypen)"
),
}
def compute_corpus_skill_max_weights(
cur,
*,
profile_id: int,
role: Optional[str],
effective_club_id: Optional[int],
limit_per_type: int = 50,
artifact_type: str = "framework_program",
) -> Dict[int, float]:
"""Referenz je Fähigkeit innerhalb eines Planungs-Kontexts (Legacy-Hülle)."""
del limit_per_type
bundle = compute_planning_corpus_by_type(
cur,
profile_id=profile_id,
role=role,
effective_club_id=effective_club_id,
)
return corpus_for_artifact_type(bundle, artifact_type)["max_by_skill"]
def match_score_for_skill_ids(profile: Dict[str, Any], skill_ids: Sequence[int]) -> Dict[str, Any]:
"""Überlappung eines Profils mit gewünschten Fähigkeiten (für Vorschläge)."""
wanted = {int(x) for x in skill_ids if x is not None}
if not wanted:
return {
"match_weight": 0.0,
"match_score": 0.0,
"match_percent": 0.0,
"artifact_focus_percent": 0.0,
"matched_skill_ids": [],
"matched_skills": [],
}
matched = []
match_weight = 0.0
total = float(profile.get("total_weight") or 0)
for sk in profile.get("skills") or []:
sid = int(sk["skill_id"])
if sid in wanted:
matched.append(sk)
match_weight += float(sk.get("weight") or 0)
artifact_focus = (match_weight / total * 100.0) if total > 0 else 0.0
return {
"match_weight": _round2(match_weight),
"match_score": _round2(match_weight),
"match_percent": _round2(artifact_focus),
"artifact_focus_percent": _round2(artifact_focus),
"matched_skill_ids": [int(m["skill_id"]) for m in matched],
"matched_skills": matched,
}
+26 -4
View File
@@ -20,6 +20,26 @@ class SmwClientError(Exception):
pass
def _normalize_mw_category(category: str) -> str:
"""
Bereinigt Kategorienamen für API cmtitle=Kategorie:…
Erlaubt z. B. 'Fähigkeitsbeschreibung', ' Kategorie:X ', 'kategorie:X' ohne Doppel-Prefix.
"""
c = (category or "").strip()
if not c:
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
pref = "kategorie:"
while c.lower().startswith(pref):
c = c[len(pref) :].lstrip()
remaining = (c or "").strip()
if not remaining:
raise SmwClientError("Kategorie (Seitenlisten-Name ohne Präfix) darf nicht leer sein")
return remaining
class SmwClient:
"""Stateless MediaWiki/SMW API Client mit Session-Login."""
@@ -110,12 +130,13 @@ class SmwClient:
"""
members = []
cmcontinue = None
cat = _normalize_mw_category(category)
while True:
params = {
"action": "query",
"list": "categorymembers",
"cmtitle": f"Kategorie:{category}",
"cmtitle": f"Kategorie:{cat}",
"cmlimit": min(limit, 500),
"cmtype": "page", # Nur Seiten, keine Unterkategorien
"cmprop": "ids|title",
@@ -134,8 +155,8 @@ class SmwClient:
# Rekursiv durch Unterkategorien gehen
if recursive:
subcats = await self._get_subcategories(category)
logger.info(f"Kategorie '{category}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
subcats = await self._get_subcategories(cat)
logger.info(f"Kategorie '{cat}': {len(members)} direkte Seiten, {len(subcats)} Unterkategorien")
for subcat in subcats:
if len(members) >= limit:
@@ -150,12 +171,13 @@ class SmwClient:
"""Gibt alle Unterkategorien einer Kategorie zurück."""
subcats = []
cmcontinue = None
cat = _normalize_mw_category(category)
while True:
params = {
"action": "query",
"list": "categorymembers",
"cmtitle": f"Kategorie:{category}",
"cmtitle": f"Kategorie:{cat}",
"cmlimit": 500,
"cmtype": "subcat", # Nur Unterkategorien
"cmprop": "ids|title",
+54 -11
View File
@@ -63,8 +63,8 @@ EXERCISE_PROPERTY_MAP = {
# Fähigkeiten (skills) – Kategorie: Fähigkeitsbeschreibung
SKILL_PROPERTY_MAP = {
"Summary": "description",
"KarateRelevanz": "karate_relevance", # Wird in description ergänzt
"RelevanzLevel": "relevance_level", # 1-3, nicht direkt in skills DB
"KarateRelevanz": "karate_relevance", # Spalte skills.karate_relevance (+ Wiki-Import)
"RelevanzLevel": "relevance_level", # Spalte skills.relevance_level 1–3
}
# Trainingsmethoden – Kategorie: Methodenbeschreibung
@@ -172,6 +172,27 @@ def map_capability_level(level_str: str) -> str:
return CAPABILITY_LEVEL_MAP.get(level_str.strip(), "basis")
def parse_wiki_relevance_level(raw: str | None) -> Optional[int]:
"""
RelevanzLevel aus Wiki (typisch 1–3). Erlaubt Zahl oder Text mit Ziffer z.B. "Level_2".
"""
if raw is None:
return None
s = str(raw).strip()
if not s:
return None
digits = re.findall(r"\d+", s)
if not digits:
return None
try:
n = int(digits[0])
except ValueError:
return None
if n < 1 or n > 3:
return None
return n
# ------------------------------------------------------------------ #
# SMW-Property-Label → Mapper-Zielfeld (Werte wie in EXERCISE_PROPERTY_MAP) #
# browse_subject liefert Anzeigenamen, nicht zwingend interne Property-IDs. #
@@ -184,6 +205,23 @@ def _norm_prop_synonym(name: str) -> str:
return "".join(c for c in s if c.isalnum())
# Alternative SMW-Anzeigelabel → Zielfeld (gleiche Targets wie SKILL_PROPERTY_MAP)
SKILL_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
"karaterelevanz": "karate_relevance",
"karatebezug": "karate_relevance",
"relevanzlevel": "relevance_level",
"wikirelevanz": "karate_relevance",
}
def _skill_property_target(prop_name: str) -> str | None:
"""Ermittelt Zielfeld für eine Skill-SMW-Property."""
if prop_name in SKILL_PROPERTY_MAP:
return SKILL_PROPERTY_MAP[prop_name]
n = _norm_prop_synonym(prop_name)
return SKILL_PROPERTY_SYNONYM_TO_TARGET.get(n)
# alternative Labels → Zielfeld-Name (gleiche Strings wie Werte in EXERCISE_PROPERTY_MAP)
EXERCISE_PROPERTY_SYNONYM_TO_TARGET: dict[str, str] = {
"primarycapability": "skill_names",
@@ -339,8 +377,8 @@ def build_skill_assignments(mapped: dict) -> list[dict]:
"skill_name": skill_name,
"target_level": target_slug,
"required_level": None,
"intensity": None,
"is_primary": idx == 0,
"intensity": "mittel",
"is_primary": False,
})
return assignments
@@ -359,24 +397,29 @@ def map_wiki_to_skill(
"warnings": [],
}
description_parts = []
description_text: Optional[str] = None
for prop_name, values in smw_props.items():
if not values:
continue
target = SKILL_PROPERTY_MAP.get(prop_name)
target = _skill_property_target(prop_name)
if not target:
continue
first_value = values[0] if isinstance(values, list) else values
if target == "description":
description_parts.insert(0, wikitext_to_plaintext(first_value))
description_text = wikitext_to_plaintext(str(first_value))
elif target == "karate_relevance":
rel = wikitext_to_plaintext(first_value)
description_parts.append(f"\nKarate-Relevanz: {rel}")
mapped["karate_relevance"] = wikitext_to_plaintext(str(first_value))
elif target == "relevance_level":
parsed = parse_wiki_relevance_level(first_value if isinstance(first_value, str) else str(first_value))
if parsed is None:
mapped["warnings"].append(f"Unbekanntes RelevanzLevel: {first_value!r}")
else:
mapped["relevance_level"] = parsed
if description_parts:
mapped["description"] = "\n".join(description_parts).strip()
if description_text:
mapped["description"] = description_text
return mapped
+27
View File
@@ -107,6 +107,33 @@ def library_content_visibility_sql(
return "(" + " OR ".join(parts) + ")", params
def club_library_visibility_sql(
*,
alias: str,
profile_id: int,
effective_club_id: Optional[int],
) -> tuple[str, List[Any]]:
"""
Nur Inhalte des aktiven Vereins (visibility=club, club_id=active).
Für Skill-Vergleiche im Vereinskontext — ohne official/private anderer Mandanten.
"""
if effective_club_id is None:
return "(1=0)", []
return (
f"""(
{alias}.visibility = 'club'
AND {alias}.club_id = %s
AND EXISTS (
SELECT 1 FROM club_members cm
WHERE cm.profile_id = %s
AND cm.club_id = {alias}.club_id
AND cm.status = 'active'
)
)""",
[effective_club_id, profile_id],
)
@dataclass
class TenantContext:
profile_id: int
+69
View File
@@ -0,0 +1,69 @@
"""GET /api/dashboard/kpis: Auth + interne Aufruf-Hilfen."""
from __future__ import annotations
import os
from unittest.mock import patch
import pytest
from fastapi import Query
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from fastapi_param_unwrap import unwrap_query_default
from main import app
from tenant_context import TenantContext, get_tenant_context
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
def test_unwrap_query_default_for_direct_route_calls() -> None:
assert unwrap_query_default(Query(default=None)) is None
assert unwrap_query_default("2026-01-01") == "2026-01-01"
assert unwrap_query_default(7) == 7
def test_dashboard_kpis_unauthenticated_401(client: TestClient) -> None:
r = client.get("/api/dashboard/kpis")
assert r.status_code == 401
def _fake_tenant_for_kpis() -> TenantContext:
return TenantContext(
profile_id=42,
global_role="trainer",
effective_club_id=7,
club_ids=frozenset({7}),
memberships=[],
)
@patch("routers.dashboard.list_training_units")
@patch("routers.dashboard.list_exercises_like_get")
def test_dashboard_kpis_200_when_inner_lists_mocked(
mock_list_ex: object,
mock_list_tu: object,
client: TestClient,
) -> None:
mock_list_ex.return_value = []
mock_list_tu.return_value = []
app.dependency_overrides[get_tenant_context] = _fake_tenant_for_kpis
try:
r = client.get("/api/dashboard/kpis")
assert r.status_code == 200, r.text
data = r.json()
assert "year" in data
assert data["draft_count"] == 0
assert data["mine_count"] == 0
assert data["ytd_completed_count"] == 0
th = data["training_home"]
assert th["upcoming"] == []
assert th["planned_with_notes"] == []
assert th["review_pending"] == []
assert mock_list_ex.call_count == 2
assert mock_list_tu.call_count == 3
finally:
app.dependency_overrides.clear()
@@ -0,0 +1,20 @@
"""Normalisierung Übung ↔ Fähigkeit Intensität."""
from routers.exercises import normalize_exercise_skill_intensity
def test_normalize_exercise_skill_intensity_defaults_to_mittel():
assert normalize_exercise_skill_intensity(None) == "mittel"
assert normalize_exercise_skill_intensity("") == "mittel"
assert normalize_exercise_skill_intensity("—") == "mittel"
def test_normalize_exercise_skill_intensity_canonical():
assert normalize_exercise_skill_intensity("niedrig") == "niedrig"
assert normalize_exercise_skill_intensity("mittel") == "mittel"
assert normalize_exercise_skill_intensity("hoch") == "hoch"
def test_normalize_exercise_skill_intensity_legacy_aliases():
assert normalize_exercise_skill_intensity("low") == "niedrig"
assert normalize_exercise_skill_intensity("medium") == "mittel"
assert normalize_exercise_skill_intensity("high") == "hoch"
@@ -0,0 +1,82 @@
"""GET /api/exercises: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
from __future__ import annotations
import os
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(get_tenant_context, None)
def test_list_exercises_keyset_incomplete_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get(
"/api/exercises",
params={"cursor_id": "42"},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
assert "cursor_updated_at" in r.json().get("detail", "").lower()
def test_list_exercises_keyset_with_offset_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get(
"/api/exercises",
params={
"cursor_id": "1",
"cursor_updated_at": "2026-01-01T12:00:00.000Z",
"offset": "10",
},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
assert "offset" in r.json().get("detail", "").lower()
def test_list_exercises_keyset_bad_timestamp_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get(
"/api/exercises",
params={"cursor_id": "1", "cursor_updated_at": "not-a-date"},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
@@ -0,0 +1,18 @@
"""Resolver für leere/fehlende Kategorie je import_type."""
from routers.import_wiki import (
CATEGORY_EXERCISES,
CATEGORY_METHODS,
CATEGORY_SKILLS,
_wiki_category_or_default,
)
def test_wiki_category_or_default_explicit():
assert _wiki_category_or_default(" MeineKat ", "skill") == "MeineKat"
def test_wiki_category_or_default_falls_through():
assert _wiki_category_or_default(None, "exercise") == CATEGORY_EXERCISES
assert _wiki_category_or_default("", "skill") == CATEGORY_SKILLS
assert _wiki_category_or_default(" ", "method") == CATEGORY_METHODS
+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
+125
View File
@@ -0,0 +1,125 @@
"""Unit-Tests für gewichtetes Fähigkeiten-Scoring (Phase 3)."""
from skill_scoring import (
ExerciseOccurrence,
compute_skill_profile,
match_score_for_skill_ids,
_club_universal_percent,
_level_range_multiplier,
_skill_link_multiplier,
)
def test_skill_link_multiplier_intensity_and_levels():
assert _skill_link_multiplier(intensity="hoch") == 1.2
assert _skill_link_multiplier(intensity="niedrig") == 0.85
wide = _skill_link_multiplier(
intensity="mittel",
required_level="basis",
target_level="optimierung",
)
narrow = _skill_link_multiplier(
intensity="mittel",
required_level="grundlagen",
target_level="grundlagen",
)
assert wide > narrow
def test_level_range_multiplier_span():
assert _level_range_multiplier(None, None) == 1.0
assert _level_range_multiplier("aufbau", "fortgeschritten") > _level_range_multiplier("basis", "basis")
def test_compute_skill_profile_aggregates_weights():
occurrences = [
ExerciseOccurrence(exercise_id=1, planned_duration_min=60),
ExerciseOccurrence(exercise_id=1, planned_duration_min=30),
]
skills_map = {
1: [
{
"skill_id": 10,
"skill_name": "Distanz",
"category": "kihon",
"category_id": 1,
"category_name": "kihon",
"main_category_id": 100,
"main_category_name": "Technik",
"intensity": "hoch",
"required_level": "grundlagen",
"target_level": "aufbau",
"exercise_title": "Übung A",
},
{
"skill_id": 11,
"skill_name": "Balance",
"category": "kihon",
"category_id": 1,
"category_name": "kihon",
"main_category_id": 100,
"main_category_name": "Technik",
"intensity": "niedrig",
"required_level": "basis",
"target_level": "basis",
"exercise_title": "Übung A",
},
],
}
profile = compute_skill_profile(occurrences, skills_map)
assert profile["scoring_version"] == "1.2"
assert profile["exercise_occurrence_count"] == 2
assert profile["distinct_exercise_count"] == 1
assert len(profile["skills"]) == 2
assert profile["skills"][0]["skill_id"] == 10
assert profile["total_weight"] > profile["skills"][1]["weight"]
assert abs(sum(s["share_percent"] for s in profile["skills"]) - 100.0) < 0.1
assert len(profile["by_main_category"]) == 1
assert profile["by_main_category"][0]["categories"][0]["top_skill"]["skill_id"] == 10
def test_universal_percent_against_corpus_max():
occurrences = [ExerciseOccurrence(exercise_id=1, planned_duration_min=50)]
skills_map = {
1: [
{
"skill_id": 10,
"skill_name": "Koordination",
"category_name": "Koordination",
"category_id": 2,
"main_category_id": 200,
"main_category_name": "Körper",
},
],
}
profile = compute_skill_profile(
occurrences,
skills_map,
reference_max_by_skill={10: 100.0},
)
assert profile["has_reference_scale"] is True
assert profile["skills"][0]["universal_percent"] == 50.0
assert profile["skills"][0]["is_club_best_for_skill"] is False
def test_club_universal_percent_capped_at_100():
pct, is_best = _club_universal_percent(150.0, 100.0)
assert pct == 100.0
assert is_best is True
pct2, _ = _club_universal_percent(72.6, 100.0)
assert pct2 == 72.6
def test_match_score_for_skill_ids():
profile = {
"total_weight": 100.0,
"skills": [
{"skill_id": 1, "skill_name": "A", "weight": 40.0},
{"skill_id": 2, "skill_name": "B", "weight": 60.0},
],
}
m = match_score_for_skill_ids(profile, [1])
assert m["match_weight"] == 40.0
assert m["match_score"] == 40.0
assert m["match_percent"] == 40.0
assert m["artifact_focus_percent"] == 40.0
assert m["matched_skill_ids"] == [1]
@@ -0,0 +1,21 @@
import pytest
from smw_client import _normalize_mw_category, SmwClientError
def test_normalize_strips_optional_kategorie_prefix():
assert _normalize_mw_category("Fähigkeitsbeschreibung") == "Fähigkeitsbeschreibung"
assert _normalize_mw_category(" Kategorie:Fähigkeitsbeschreibung ") == "Fähigkeitsbeschreibung"
assert _normalize_mw_category("kategorie:test") == "test"
def test_normalize_strips_duplicate_prefix_chain():
assert _normalize_mw_category("Kategorie:Kategorie:Foo") == "Foo"
def test_normalize_rejects_empty():
with pytest.raises(SmwClientError, match="leer"):
_normalize_mw_category("")
with pytest.raises(SmwClientError, match="leer"):
_normalize_mw_category(" Kategorie: ")
@@ -0,0 +1,49 @@
"""Tests: Wiki → Skill Mapping (KarateRelevanz, RelevanzLevel)."""
from smw_mapper import (
map_wiki_to_skill,
parse_wiki_relevance_level,
)
def test_parse_wiki_relevance_level_accepted_range():
assert parse_wiki_relevance_level("1") == 1
assert parse_wiki_relevance_level("3") == 3
assert parse_wiki_relevance_level("Level_2_-_foo") == 2
def test_parse_wiki_relevance_level_rejects():
assert parse_wiki_relevance_level("") is None
assert parse_wiki_relevance_level("4") is None
assert parse_wiki_relevance_level("0") is None
assert parse_wiki_relevance_level("text") is None
def test_map_wiki_to_skill_karate_and_level():
out = map_wiki_to_skill(
"Test_Skill",
99,
{
"Summary": ["Kurztext"],
"KarateRelevanz": ["''Wichtig'' für [[Kumite]]"],
"RelevanzLevel": ["2"],
},
)
assert out["name"] == "Test_Skill"
assert out["description"] == "Kurztext"
assert "Kumite" in out["karate_relevance"]
assert out["relevance_level"] == 2
assert out["warnings"] == []
def test_map_wiki_to_skill_synonym_props():
out = map_wiki_to_skill("S", None, {"relevanzlevel": ["3"], "karaterelevanz": ["Nur Karate"]})
assert out["relevance_level"] == 3
assert out["karate_relevance"] == "Nur Karate"
def test_map_wiki_to_skill_invalid_level_warning():
out = map_wiki_to_skill("S", None, {"RelevanzLevel": ["9"]})
assert "relevance_level" not in out
assert len(out["warnings"]) == 1
assert "9" in out["warnings"][0]
@@ -0,0 +1,206 @@
"""
PostgreSQL-Integration: Rahmenprogramm-Slot mit verschachtelten `phases` (Blueprint-Unit).
Aktivierung:
- Lokal: TRAINING_PLANNING_INTEGRATION=1
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf.
Prüft `_insert_slots_and_blueprints` → `_replace_unit_phases` wie beim API-PUT mit Slot-Payload.
"""
from __future__ import annotations
import os
import uuid
import pytest
from db import get_db, get_cursor
from routers.training_framework_programs import _insert_slots_and_blueprints
from routers.training_planning import _fetch_phases_nested
def _integration_enabled() -> bool:
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
not _integration_enabled(),
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
),
]
def _db_ping() -> bool:
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT 1 AS ok")
row = cur.fetchone()
return row is not None and row.get("ok") == 1
except Exception:
return False
@pytest.fixture(scope="module")
def db_ready():
if not _db_ping():
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
def test_framework_blueprint_slot_phases_roundtrip(db_ready):
"""Ein Slot mit `phases` erzeugt eine Blueprint-Unit mit identischer Phasenstruktur."""
suffix = uuid.uuid4().hex[:12]
club_name = f"fw_ph_club_{suffix}"
email = f"fw_ph_{suffix}@test.local"
from auth import hash_pin
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_name, "F", "active"),
)
club_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email, hash_pin("x"), f"FWPH {suffix}", "trainer", club_id),
)
profile_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(f"Übung FWPH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
)
ex_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_framework_programs (
title, description,
planned_period_start, planned_period_end,
visibility, club_id, created_by,
focus_area_id, style_direction_id
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
f"Rahmen FWPH {suffix}",
None,
None,
None,
"private",
club_id,
profile_id,
None,
None,
),
)
fw_id = int(cur.fetchone()["id"])
phases_in = [
{
"phase_kind": "whole_group",
"order_index": 0,
"title": "Aufwärmen",
"sections": [
{
"title": "Gemeinsam",
"order_index": 0,
"items": [
{"item_type": "note", "order_index": 0, "note_body": "Los"},
],
},
],
},
{
"phase_kind": "parallel",
"order_index": 1,
"title": "Breakout",
"streams": [
{
"order_index": 0,
"title": "Matte A",
"sections": [
{
"title": "Technik A",
"order_index": 0,
"items": [
{
"item_type": "exercise",
"order_index": 0,
"exercise_id": ex_id,
"planned_duration_min": 10,
},
],
},
],
},
],
},
]
slots_in = [
{
"sort_order": 0,
"title": "Session 1",
"notes": None,
"phases": phases_in,
},
]
_insert_slots_and_blueprints(cur, fw_id, slots_in, profile_id, "trainer")
cur.execute(
"""
SELECT id FROM training_framework_slots
WHERE framework_program_id = %s
ORDER BY sort_order
LIMIT 1
""",
(fw_id,),
)
slot_row = cur.fetchone()
assert slot_row is not None
slot_id = int(slot_row["id"])
cur.execute(
"SELECT id FROM training_units WHERE framework_slot_id = %s",
(slot_id,),
)
bu_row = cur.fetchone()
assert bu_row is not None
blueprint_unit_id = int(bu_row["id"])
nested = _fetch_phases_nested(cur, blueprint_unit_id)
conn.commit()
try:
assert len(nested) == 2
assert nested[0]["phase_kind"] == "whole_group"
assert len(nested[0].get("sections") or []) == 1
assert nested[1]["phase_kind"] == "parallel"
streams = nested[1].get("streams") or []
assert len(streams) == 1
assert len(streams[0].get("sections") or []) == 1
assert streams[0]["sections"][0]["title"] == "Technik A"
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
finally:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM training_framework_programs WHERE id = %s", (fw_id,))
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
conn.commit()
@@ -0,0 +1,290 @@
"""
PostgreSQL-Integration: Roundtrip _replace_unit_sections / _replace_unit_phases ↔ Fetch-Helfer.
Aktivierung:
- Lokal: TRAINING_PLANNING_INTEGRATION=1
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf (deployter Backend-Container + PostgreSQL).
Voraussetzung: migrierte DB, DB_* wie Docker-Compose.
"""
from __future__ import annotations
import os
import uuid
import pytest
from db import get_db, get_cursor
from routers.training_planning import (
_fetch_phases_nested,
_fetch_sections,
_replace_unit_phases,
_replace_unit_sections,
)
def _integration_enabled() -> bool:
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
not _integration_enabled(),
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
),
]
def _db_ping() -> bool:
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT 1 AS ok")
row = cur.fetchone()
return row is not None and row.get("ok") == 1
except Exception:
return False
@pytest.fixture(scope="module")
def db_ready():
if not _db_ping():
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
def test_replace_sections_roundtrip(db_ready):
"""INSERT-Hilfsdaten, replace, fetch — gleiche Semantik wie produktiver PUT-Pfad."""
suffix = uuid.uuid4().hex[:12]
club_name = f"tpl_it_club_{suffix}"
email = f"tpl_it_{suffix}@test.local"
from auth import hash_pin
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_name, "T", "active"),
)
club_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email, hash_pin("x"), f"TP {suffix}", "trainer", club_id),
)
profile_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_groups (club_id, name, trainer_id, status)
VALUES (%s, %s, %s, %s)
RETURNING id
""",
(club_id, f"Gruppe {suffix}", profile_id, "active"),
)
group_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(f"Übung {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
)
ex_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_units (
group_id, planned_date, status, created_by
) VALUES (%s, %s, %s, %s)
RETURNING id
""",
(group_id, "2026-06-01", "planned", profile_id),
)
unit_id = int(cur.fetchone()["id"])
sections_in = [
{
"title": "A1",
"order_index": 0,
"guidance_notes": "gn",
"items": [
{
"item_type": "note",
"order_index": 0,
"note_body": "Hinweis",
},
{
"item_type": "exercise",
"order_index": 1,
"exercise_id": ex_id,
"planned_duration_min": 5,
"notes": "n1",
},
],
},
{
"title": "B2",
"order_index": 1,
"items": [],
},
]
_replace_unit_sections(cur, unit_id, sections_in)
loaded = _fetch_sections(cur, unit_id)
conn.commit()
try:
assert len(loaded) == 2
assert loaded[0]["title"] == "A1"
assert loaded[0]["guidance_notes"] == "gn"
assert loaded[0]["order_index"] == 0
assert len(loaded[0]["items"]) == 2
assert loaded[0]["items"][0]["item_type"] == "note"
assert loaded[0]["items"][0]["note_body"] == "Hinweis"
assert loaded[0]["items"][1]["item_type"] == "exercise"
assert int(loaded[0]["items"][1]["exercise_id"]) == ex_id
assert loaded[0]["items"][1]["planned_duration_min"] == 5
assert loaded[1]["title"] == "B2"
assert loaded[1]["items"] == []
finally:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
conn.commit()
def test_replace_phases_roundtrip_parallel_stream(db_ready):
"""Phasen inkl. parallel-Stream-Sektionen ersetzen und wieder laden."""
suffix = uuid.uuid4().hex[:12]
club_name = f"ph_it_club_{suffix}"
email = f"ph_it_{suffix}@test.local"
from auth import hash_pin
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_name, "P", "active"),
)
club_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email, hash_pin("x"), f"PH {suffix}", "trainer", club_id),
)
profile_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_groups (club_id, name, trainer_id, status)
VALUES (%s, %s, %s, %s)
RETURNING id
""",
(club_id, f"Gruppe PH {suffix}", profile_id, "active"),
)
group_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(f"Übung PH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
)
ex_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_units (
group_id, planned_date, status, created_by
) VALUES (%s, %s, %s, %s)
RETURNING id
""",
(group_id, "2026-06-02", "planned", profile_id),
)
unit_id = int(cur.fetchone()["id"])
phases_in = [
{
"phase_kind": "whole_group",
"order_index": 0,
"title": "Aufwärmen",
"sections": [
{
"title": "Gemeinsam",
"order_index": 0,
"items": [
{"item_type": "note", "order_index": 0, "note_body": "Los"},
],
},
],
},
{
"phase_kind": "parallel",
"order_index": 1,
"title": "Breakout",
"streams": [
{
"order_index": 0,
"title": "Matte A",
"sections": [
{
"title": "Technik A",
"order_index": 0,
"items": [
{
"item_type": "exercise",
"order_index": 0,
"exercise_id": ex_id,
"planned_duration_min": 10,
},
],
},
],
},
],
},
]
_replace_unit_phases(cur, unit_id, phases_in, profile_id, "trainer", profile_id)
nested = _fetch_phases_nested(cur, unit_id)
flat_sec = _fetch_sections(cur, unit_id)
conn.commit()
try:
assert len(nested) == 2
assert nested[0]["phase_kind"] == "whole_group"
assert len(nested[0].get("sections") or []) == 1
assert nested[1]["phase_kind"] == "parallel"
streams = nested[1].get("streams") or []
assert len(streams) == 1
assert len(streams[0].get("sections") or []) == 1
assert streams[0]["sections"][0]["title"] == "Technik A"
assert len(streams[0]["sections"][0].get("items") or []) == 1
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
assert len(flat_sec) == 2
finally:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
conn.commit()
@@ -0,0 +1,32 @@
"""Unit-Tests ohne DB: abgeleitete Trainingseinheit-Payload-Helfer."""
import pytest
from routers.training_planning import _flatten_exercises_from_sections
def test_flatten_exercises_from_sections_order():
unit = {
"sections": [
{
"order_index": 1,
"items": [
{"order_index": 1, "item_type": "exercise", "exercise_id": 10},
{"order_index": 0, "item_type": "note"},
{"order_index": 2, "item_type": "exercise", "exercise_id": 20},
],
},
{
"order_index": 0,
"items": [{"order_index": 0, "item_type": "exercise", "exercise_id": 5}],
},
]
}
_flatten_exercises_from_sections(unit)
# Sektionen nach order_index; innerhalb nur exercise-Items nach order_index
assert [x["exercise_id"] for x in unit["exercises"]] == [5, 10, 20]
def test_flatten_exercises_from_sections_empty():
unit = {"sections": []}
_flatten_exercises_from_sections(unit)
assert unit["exercises"] == []
@@ -0,0 +1,108 @@
"""GET /api/training-units: Keyset-Parameter-Validierung (ohne DB-Zwang)."""
from __future__ import annotations
import os
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(get_tenant_context, None)
def _tenant() -> TenantContext:
return TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
def test_list_training_units_keyset_incomplete_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = _tenant
r = client.get(
"/api/training-units",
params={"cursor_id": "42"},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
assert "cursor_planned_date" in r.json().get("detail", "").lower()
def test_list_training_units_keyset_without_limit_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = _tenant
r = client.get(
"/api/training-units",
params={
"cursor_id": "1",
"cursor_planned_date": "2026-05-10",
},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
assert "limit" in r.json().get("detail", "").lower()
def test_list_training_units_keyset_bad_date_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = _tenant
r = client.get(
"/api/training-units",
params={
"cursor_id": "1",
"cursor_planned_date": "not-a-date",
"limit": "10",
},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
def test_list_training_units_keyset_bad_time_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = _tenant
r = client.get(
"/api/training-units",
params={
"cursor_id": "1",
"cursor_planned_date": "2026-05-10",
"cursor_planned_time": "25:99",
"limit": "10",
},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
assert "cursor_planned_time" in r.json().get("detail", "").lower()
def test_list_training_units_keyset_time_without_id_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = _tenant
r = client.get(
"/api/training-units",
params={
"cursor_planned_time": "18:00",
"limit": "10",
},
headers={"X-Auth-Token": "test"},
)
assert r.status_code == 400
+426 -9
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.110"
BUILD_DATE = "2026-05-12"
DB_SCHEMA_VERSION = "20260512057"
APP_VERSION = "0.8.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,15 +18,22 @@ 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.0",
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
"methods": "0.1.0",
"exercises": "2.27.3", # load_combination_slots_for_exercise (gemeinsam mit GET Übung); Hydrate für Planung
"training_units": "0.2.0",
"exercises": "2.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.9.3", # GET training-units/:id Sektions-Items: combination_slots + Kandidaten-Titel für Druck/Run
"training_modules": "1.0.0",
"import_wiki": "1.0.0",
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
"dashboard": "1.1.0", # GET /api/dashboard/kpis inkl. training_home (ein Client-Roundtrip für KPIs + nächste Termine)
"training_modules": "1.1.0", # PUT/DELETE: assert_library_content_* (Vereinsadmin löscht Vereins-Inhalt, Trainer bearbeitet club wie Übungen)
"import_wiki": "1.0.3", # Default-Kategorie Fähigkeiten: Fähigkeitsbeschreibung; cmtitle-Normalisierung; UI Preview/Execute Defaults je Typ
"admin": "1.0.0",
"membership": "1.0.0",
"catalogs": "1.5.0", # Updated: Trainer Contexts API (Migration 012)
@@ -35,6 +42,416 @@ 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",
"changes": [
"Phase 3 Fähigkeiten-Scoring: skill_scoring.py (Dauer × Vorkommen × Primär/Intensität/Beitrag)",
"GET skill-profile für Rahmenprogramm (gesamt + pro Slot), Trainingsmodul, Progressionsgraph",
"GET /api/skill-discovery/suggestions nach skill_ids",
],
},
{
"version": "0.8.149",
"date": "2026-05-19",
"changes": [
"Trainingsplanung: Einheiten-Editor als Vollseite (/planning/units/new|/:id/edit); Hub ohne Modal; Legacy ?unit= Redirect",
"Drift-Schutz: planningUnitRoutes.js, trainingUnitEditorCore.js, Vitest; Playwright 14–15",
],
},
{
"version": "0.8.148",
"date": "2026-05-19",
"changes": [
"Planung Vorlagen: Strukturvorschau (Split-Sessions), Kurzbeschreibung, Bearbeitungsseite; Liste liefert sections[] mit",
],
},
{
"version": "0.8.147",
"date": "2026-05-19",
"changes": [
"Planung: Liste – Rahmen-Session & Übungen→Modul; Dialog Modul aus Einheit; klarere Rahmen-Unit-ID aus Liste",
],
},
{
"version": "0.8.146",
"date": "2026-05-19",
"changes": [
"Planung: Trainingseinheit → Rahmenprogramm (Session-Slot) speichern; API POST /api/training-units/{id}/publish-to-framework",
],
},
{
"version": "0.8.145",
"date": "2026-05-16",
"changes": [
"Wiki-Import: Standard-Kategorie Fähigkeiten korrigiert auf „Fähigkeitsbeschreibung“ (korrekter Wiki-Name).",
],
},
{
"version": "0.8.144",
"date": "2026-05-16",
"changes": [
"Wiki-Import: Default-Kategorie Fähigkeiten; SMW-Client entfernt versehentliches „Kategorie:“-Prefix; Vorschau/Ausführung nutzen Default-Kategorie je import_type wenn leer.",
"Admin UI Wiki-Import: Wechsel Import-Typ setzt passende Standard-Kategorie.",
],
},
{
"version": "0.8.143",
"date": "2026-05-16",
"changes": [
"DB 065: skills.karate_relevance + skills.relevance_level (Wiki KarateRelevanz / RelevanzLevel 1–3); smw_mapper + Wiki-Import upsert.",
],
},
{
"version": "0.8.142",
"date": "2026-05-16",
"changes": [
"Bibliothek Planung: Bearbeiten/Löschen von Vorlagen, Rahmenprogrammen, Trainingsmodulen, Progressionsgraphen nach RBAC wie Übungen (club_tenancy.assert_library_content_* + Governance-Übergänge)",
"Planungs-UI: Sichtbarkeit/Verein beim Speichern neuer Trainingsvorlage",
],
},
{
"version": "0.8.141",
"date": "2026-05-14",
"changes": [
"DB 064: Vorlagen-Sektionen mit phase_kind / phase_order_index / parallel_stream_order_index; Speichern und Anwenden behält Split-Sessions; Server: Vorlage → Einheit über Phasen-Replace.",
],
},
{
"version": "0.8.140",
"date": "2026-05-14",
"changes": [
"Frontend Trainingsplanung: Breakout-Panel (neue Ganzgruppen-/parallele Phase, Stream in letzter parallelen Phase); pro Abschnitt Zuordnung zu Phase/Stream oder klassischer Ein-Ganzgruppen-Ablauf.",
],
},
{
"version": "0.8.139",
"date": "2026-05-14",
"changes": [
"Frontend Trainingsplanung: GET phases → Editor mit planLoc pro Abschnitt; Speichern sendet PUT phases bei Breakout-Einheiten (sonst weiter sections); Modul-Dialog zeigt Phase/Stream in der Abschnittsauswahl.",
],
},
{
"version": "0.8.138",
"date": "2026-05-14",
"changes": [
"Planung Paket 2: POST/PUT training_units mit phases (voller Phasen-/Stream-Plan); höchstens eines von phases, sections, exercises pro Request; Rahmen-Blueprint→Termin kopiert verschachtelten Plan; apply-training-module optional phase_order_index + parallel_stream_order_index.",
"Fix: POST from-framework-slot übergibt role an _copy_blueprint_into_scheduled_unit (Stream-Trainer-Validierung).",
"Integrationstest test_replace_phases_roundtrip_parallel_stream.",
],
},
{
"version": "0.8.137",
"date": "2026-05-14",
"changes": [
"DB 063: training_unit_phases, training_unit_parallel_streams; Sektionen mit phase_id oder parallel_stream_id; Default whole_group für Bestand.",
"Planung: GET training_unit liefert phases (verschachtelt) + sections (flach sortiert); Legacy-PUT sections weiterhin eine whole_group-Phase.",
],
},
{
"version": "0.8.136",
"date": "2026-05-13",
"changes": [
"Fix: api/exercises.js — Mandanten-Header für Raw-fetch (PUT Übung, Medien-Upload, Bulk-Archiv) über lokale withActiveClubHeaders statt mergeActiveClubHeader-Import (ReferenceError beim Speichern).",
],
},
{
"version": "0.8.135",
"date": "2026-05-13",
"changes": [
"Frontend Phase 4 Welle 3: frontend/src/api/exercises.js (Übungen, Medien/Archiv, Progressionsgraphen, KI); client.js exportiert API_URL und mergeActiveClubHeader; utils/api.js re-exportiert Modul, api-Objekt spread exercises.",
],
},
{
"version": "0.8.134",
"date": "2026-05-14",
"changes": [
"Frontend Phase 4 Welle 2: frontend/src/api/planning.js (Trainingsplanung); utils/api.js re-exportiert Modul, api-Objekt spread planning.",
],
},
{
"version": "0.8.133",
"date": "2026-05-14",
"changes": [
"Frontend Phase 4 Welle 1: frontend/src/api/client.js (request, ACTIVE_CLUB_STORAGE_KEY); utils/api.js importiert Client, bleibt Facade. Roadmap Phase 4 gestartet.",
],
},
{
"version": "0.8.132",
"date": "2026-05-14",
"changes": [
"Frontend Phase 3 abgeschlossen: TrainingPlanningPageRoot, ExerciseFormPageRoot, ExercisesListPageRoot unter components/; pages/ nur Re-Export (Soft-Limit). Roadmap UMSETZUNGSPLAN Phase 3 / M3 aktualisiert.",
],
},
{
"version": "0.8.131",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3: TrainingPlanningUnitFormModal (Neu/Bearbeiten-Einheit); frameworkLineageText in trainingPlanningPageHelpers; BASELINE_SNAPSHOT §3.4 k6-Log-Mapping.",
],
},
{
"version": "0.8.130",
"date": "2026-05-13",
"changes": [
"Fix: PUT/POST training_units — assistant_trainer_profile_ids als JSONB mit psycopg2.extras.Json schreiben (rohe Python-Liste → ProgrammingError/500 bei Co-Zuweisung).",
],
},
{
"version": "0.8.129",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3: TrainingPlanningTrainerAssignModal (Trainer zuweisen) aus Trainingsplanungsseite; Handler per useCallback.",
],
},
{
"version": "0.8.128",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3: TrainingPlanningModuleApplyModal (Trainingsmodul einfügen) aus Trainingsplanungsseite; gemeinsamer Callback onModuleApplySectionIndexChange.",
],
},
{
"version": "0.8.126",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3: TrainingPlanningFrameworkImportModal aus Trainingsplanungsseite; Playwright-Test 13 (Rahmen-Dialog, skip ohne Gruppe).",
],
},
{
"version": "0.8.125",
"date": "2026-05-13",
"changes": [
"Tests: Playwright 11 (Übungsliste Bulk-Toolbar), 12 (Trainingsplanung); Dashboard-Test 8 prüft HTTP 200 auf /api/dashboard/kpis; pytest test_dashboard_kpis_200_when_inner_lists_mocked.",
"Frontend Phase 3: trainingPlanningPageHelpers.js aus TrainingPlanningPage; ExerciseListBulkToolbar data-testid.",
],
},
{
"version": "0.8.124",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3 (Teil): ExerciseListBulkToolbar-Komponente; Übungsliste nur Verdrahtung.",
],
},
{
"version": "0.8.123",
"date": "2026-05-13",
"changes": [
"Fix: GET /api/dashboard/kpis — interne Aufrufe von list_exercises / list_training_units erhielten FastAPI-Query-Defaults statt None; .strip() auf Query-Objekt → 500. unwrap_query_default in beiden Handlern (Hilfsmodul fastapi_param_unwrap.py).",
],
},
{
"version": "0.8.122",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3 (Teil): useExerciseListCatalogsAndQuery — Katalog-Fetch und Übungslisten-Laden/Keyset-Pagination aus ExercisesListPage in Hook ausgelagert.",
],
},
{
"version": "0.8.121",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3 (Teil): Übungsliste — Suchleiste/Chips in ExerciseListSearchBar; API-Query-Bau und Filter-Chips in utils/exerciseListQuery.js bzw. exerciseListFilterChips.js.",
],
},
{
"version": "0.8.120",
"date": "2026-05-13",
"changes": [
"Frontend: Übungsliste — Filter- und Massenänderungs-Dialoge in ExerciseListFilterModal / ExerciseListBulkModal ausgelagert; Playwright-Test 10 (Filter-Dialog).",
],
},
{
"version": "0.8.119",
"date": "2026-05-13",
"changes": [
"Frontend Phase 3 (Teil): Übungsliste — ExerciseListCard-Komponente, Progressions-Tab lazy (Suspense); Übungspicker-Modal mit @tanstack/react-virtual; content-visibility auf Karten im Übungs-Gitter; Playwright-Test 9 Übungsliste.",
],
},
{
"version": "0.8.118",
"date": "2026-05-14",
"changes": [
"GET /api/dashboard/kpis liefert training_home (upcoming, planned_with_notes, review_pending) — gleiche Logik wie zuvor zwei listTrainingUnits-Calls; Dashboard-Frontend ein Request.",
"Migration 062: Index exercise_skills(exercise_id, level_rank_expr) für list_exercises Stufenfilter; Ausdruck wie _EXERCISE_SKILL_LEVEL_RANK_SQL.",
"Phase 2: Vorlagen EXPLAIN unter scripts/load/explain-readpaths.sql; Playwright-Test 8 erwartet 0× GET /api/training-units auf dem Dashboard.",
],
},
{
"version": "0.8.117",
"date": "2026-05-14",
"changes": [
"GET /api/training-units: optionale Keyset-Pagination (cursor_planned_date YYYY-MM-DD, cursor_id, optional cursor_planned_time bei gesetzter Startzeit; bei Keyset ist limit erforderlich). Sortierung um stabile Tie-Breaks ergänzt: (planned_time_start IS NULL), id.",
"Migration 061: Teilindizes training_units für ASC/DESC-Keyset inkl. id (ersetzt idx_training_units_scheduled_order).",
"frontend api.listTrainingUnits: Query-Parameter für Cursor durchreichen.",
],
},
{
"version": "0.8.116",
"date": "2026-05-14",
"changes": [
"Frontend: Org-Posteingang lädt beim ersten Mount per requestIdleCallback (Fallback setTimeout), um parallele API-Aufrufe beim Dashboard-Start zu entzerren; refresh/Inbox-Seite unverändert sofort.",
],
},
{
"version": "0.8.115",
"date": "2026-05-14",
"changes": [
"GET /api/exercises: optionale Keyset-Pagination (cursor_updated_at ISO-8601 + cursor_id), stabile Sortierung updated_at DESC, id DESC; „Mehr laden“ in Übungsliste und Picker nutzt Keyset statt OFFSET.",
],
},
{
"version": "0.8.114",
"date": "2026-05-14",
"changes": [
"Migration 060: Skalierung GET /api/exercises — Partial-Indizes official/club (+ updated_at, ohne archiviert); Junction-Indizes (exercise_id, is_primary) für List-Subqueries.",
],
},
{
"version": "0.8.113",
"date": "2026-05-14",
"changes": [
"Migration 059: Teilindex training_units(planned_date, planned_time_start) nur für Zeilen ohne framework_slot_id — list_training_units Sortierung.",
],
},
{
"version": "0.8.112",
"date": "2026-05-14",
"changes": [
"Migration 058: Indizes exercises(updated_at DESC) und (created_by, updated_at DESC) für list_exercises-Sortierung und „meine Übungen“.",
],
},
{
"version": "0.8.111",
"date": "2026-05-13",
"changes": [
"GET /api/dashboard/kpis: Kurzüberblick (meine Entwürfe, meine Übungen, abgeschlossene Einheiten Kalenderjahr) in einem Aufruf; Dashboard-UI nutzt den Endpunkt.",
"Hilfsfunktion list_exercises_like_get in exercises-Router für programmatische Listen ohne Query-Defaults.",
],
},
{
"version": "0.8.110",
"date": "2026-05-12",
+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}
+21 -7
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).
@@ -66,6 +67,8 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
- **Globaler Fähigkeitskatalog** mit hierarchischer Struktur (Kategorien, Stufen); Zuordnung zu Übungen.
- **Trainingsmethoden-Katalog** (bestehende Domäne).
- **Admin/Katalog-Pflege** für Fokusbereiche, Stile, Zielgruppen und Zusammenhänge (Plattform-Admin-Bereich).
- **Planungs-Vorschläge (Phase 3):** Auf der Fähigkeiten-Seite können Schwerpunkte gewählt werden; Shinkan schlägt passende **Rahmenprogramme**, **Trainingsmodule** und **Regressionspfade** vor (Sortierung nach Trainingsgewicht).
- **Fähigkeiten-Profile an Planungs-Bausteinen:** Listen zeigen pro Modul/Rahmenprogramm KPI-Kacheln (Top je Kategorie) mit **Score** und **Peer-Prozent** — Vergleich nur unter sichtbaren Bausteinen **desselben Typs** (Modul vs. Modul, nicht Modul vs. Plan). Filter analog zur Übungsliste (Modal, Chips, Baumauswahl).
### 4.3 Reifegradmodelle (Fähigkeitsmatrix)
@@ -75,10 +78,14 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
### 4.4 Trainingsplanung
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden.
- **Phasen & parallele Streams (Breakout):** Eine Einheit kann aus abwechselnden **Ganzgruppenphasen** und **Parallelphasen** bestehen; in einer Parallelphase führen **mehrere Streams** (Teilstrecken) je eigene Abschnitte/Übungen. Planung über Breakout-UI; API liefert **`phases`** und flache **`sections`** (Migration **063**, siehe **`docs/HANDOVER.md`**). Technische Details: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden (Phasen in Vorlagen: Ausbau siehe Handover „offen“).
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
- **Trainingsmodule (Bibliothek):** wiederverwendbare Übungsfolgen; Übernahme in geplante Einheiten; **Fähigkeiten-Profil** und **Filter** in der Modul-Liste (Peer-Vergleich nur unter Modulen).
- **Rahmenprogramm-Liste:** Suche und Filter (Katalog, Dauer, Fähigkeiten) — Peer-Vergleich nur unter Rahmenprogrammen.
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
- **Durchführung:** Ansicht zum Abarbeiten einer Einheit; **Coaching-Modus** als separater Erlebnispfad (generischer Zeit-Block pro Platzierung); bei **Kombinationsübungen** zusätzliche **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** siehe Kombination-Fachspez **Anhang A** (implementierter Umfang vs. nächste Stufen).
- **Durchführung („Plan & Ablauf“):** Ablauf anhand Phasen/Streams darstellen und abarbeiten (inkl. Split-Logik in der Anzeige).
- **Coaching-Modus:** eigener Ablauf mit Schritt-für-Schritt-Timeline, Stream-Wahl pro Parallelphase, Hinweis **„Parallelphase · Abschluss“** (Gruppen zusammenführen) vor der nächsten Ganzgruppenphase oder vor dem nächsten Split; **Nachbereitung** mit Ist-Minuten und Speichern wie in der Planung (inkl. **`phases`**). Nach erfolgreichem Speichern Wechsel zur **Plan- und Ablaufsicht** derselben Einheit. Bei **Kombinationsübungen** zusätzlich **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** (Fachspez **Anhang A**; Ausbauschritte B/C).
### 4.5 Medienbibliothek und Archiv
@@ -94,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)
@@ -118,7 +129,8 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
- **Coach / Kombination:** nächste Stufen **Zeitleisten-Splitting** und **Archetyp-Timer** (Fachspez § 10.4 Stufe B/C; Umsetzungsplan Phase 4b–d); **geführtes Erfassen** von `method_profile` im Übungseditor.
- **Coach / Kombination:** Kombi-spezifische **Archetyp-Stufen B/C** (Zeitleisten-Splitting, archetypnahe Timer — Fachspez § 10.4); **geführtes Erfassen** von `method_profile` im Übungseditor.
- **Breakout:** vollständige **Server-Spiegelung** neuer Abschnitte in **`phases`**; **Vorlagen** phasengleich mit Kalendereinheit; optional **Stream-Tabs** in der Durchführungsansicht laut technischer Spec — siehe **`docs/HANDOVER.md`** (Arbeitspaket „Coaching & Breakout“).
---
@@ -126,5 +138,7 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
| Datum | Änderung |
|-------|----------|
| 2026-05-20 | Fähigkeiten-Scoring Phase 3: Peer-Kontext, Listen-Filter Module/Rahmen, Planungs-Vorschläge. |
| 2026-05-14 | Trainingsplanung: Phasen/parallele Streams, Coaching (Rejoin, Nachbereitung → Planansicht); Lücken §5 ergänzt. Verweis `HANDOVER.md`. |
| 2026-05-12 | Erstfassung für Übergabe an fachliches Design; Abgleich mit Code-Navigation, `version.py`, `HANDOVER.md`, `FEATURES_DELIVERED`, `DOMAIN_MODEL`. |
| 2026-05-12 | Kombinationsübungen + Coaching Stufe A; Verweise auf Fachspezifikation (`…Kombinationsuebungen…` V3 Anhang A) und `TRAINING_MODULES_IMPLEMENTATION_PLAN.md`. |
+85 -16
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-05-12
**App-Version / DB-Schema:** App **0.8.110**, DB-Schema **`20260512057`** (`backend/version.py`: `APP_VERSION`, `DB_SCHEMA_VERSION`)
**Stand:** 2026-05-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**.
@@ -20,6 +20,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Thema | Pfad |
|--------|------|
| **Architektur-Zielbild, Refaktor, Roadmap, Regeln** | **`docs/architecture/README.md`** |
| **Performance-Baseline (Phase 0)** | **`docs/architecture/BASELINE_SNAPSHOT.md`**, **`scripts/load/README.md`** |
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
@@ -27,13 +29,15 @@ 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) |
| **Umsetzungsplan** (Module/Kombination/Coach) | `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` |
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
| **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
| **Lieferliste inkl. Medien & Formular-UX** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §6, §16 |
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
---
@@ -67,6 +71,37 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
### 2.6 Gewichtetes Fähigkeiten-Scoring (Phase 3, Stand 2026-05-20)
- **Spec:** `.claude/docs/technical/SKILL_SCORING_SPEC.md`
- **Backend:** `skill_scoring.py`, `routers/skill_profiles.py` — Profile on-the-fly aus Übungsvorkommen + `exercise_skills`; **Peer-Kontext getrennt** (`framework_program` | `training_module` | `progression_graph`) über `library_content_visibility_sql`
- **Metriken:** Trainingsgewicht (`weight`); **Peer-%** (`universal_percent`, max. 100 %) nur unter sichtbaren Bausteinen **desselben Typs**; ★ = stärkster Peer je Fähigkeit
- **API:** Skill-Profile pro Artefakt; `POST /api/skill-profiles/batch-summaries` für Listen; `GET /api/skill-discovery/suggestions`
- **Frontend:** KPI-Kacheln + Filter-Modal (UX wie Übungsliste) auf **`/planning/framework-programs`** und **`/planning/training-modules`**; Panels in Editoren; Discovery auf Fähigkeiten-Seite; `SkillTreeMultiSelect` mit Portal-Dropdown in Modals
- **Offen (Backlog):** Corpus-Caching bei großen Bibliotheken; Tests für Typ-Trennung; Filter-Persistenz; Skill-Filter im Dialog „Rahmen übernehmen“; API-Umbenennung `club_*` → Peer-Namen
### 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)
@@ -74,7 +109,39 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
### Trainingsmodule, Kombinationsübungen und Coach (Stand **0.8.110**)
### Trainingsplanung: Einheiten-Editor als Vollseite (Stand **0.8.149**)
- **Routen:** `/planning` (Hub), `/planning/units/new`, `/planning/units/:id/edit`; Legacy `/planning?unit={id}` → Redirect auf Edit-Route.
- **Code:** `TrainingUnitEditPage.jsx`, `TrainingUnitFormShell.jsx`, `planningUnitRoutes.js`, `trainingUnitEditorCore.js` (Payload-Drift-Schutz + Vitest).
- **Hub:** `TrainingPlanningPageRoot.jsx` ohne Einheiten-Modal; Modals nur noch Import, Trainer zuweisen, Rahmen-Session/Modul aus Liste.
- **Spec / DoD:** `docs/architecture/TRAINING_UNIT_EDIT_PAGE_MIGRATION.md`; Playwright **14–15** (Edit-Route, Legacy-Redirect).
### Trainingsplan: Phasen, parallele Streams und Coaching (Stand **0.8.137–0.8.140**)
- **Schema / API:** Migration **063** — `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` bzw. `parallel_stream_id`. **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und weiterhin flache **`sections`**. **`PUT/POST`** mit **`phases`** für Breakout-Einheiten (vgl. `CHANGELOG` **0.8.138**); Legacy: flache `sections` → implizite Ganzgruppen-Phase.
- **Planung (Frontend):** Breakout-Panel — neue Ganzgruppen-/parallele Phase, Streams in der Parallelphase; Speichern sendet `phases` bei phasierten Einheiten (`trainingUnitSectionsForm.js`, `TrainingPlanningPage`).
- **Durchführung „Plan & Ablauf“:** `TrainingUnitRunPage.jsx` nutzt **`sectionsWithPlanLocForDisplay`** / **`buildPlanRunViewModelFromSections`** aus **`frontend/src/utils/trainingPlanUtils.js`**, damit Anzeige mit Phasen/Streams konsistent ist (inkl. Normalisierung fehlender `planLoc` auf flachen Sektionen).
- **Coaching-Modus (`TrainingCoachPage.jsx`):**
- Flache Timeline aus Phasen (`flattenPlanTimeline`): **Split-Punkte** (`branch_gate`) bis Stream-Wahl, eine gewählte Spur pro Parallelphase, **Outline**, Timer, Ist-Minuten pro Item.
- **Rejoin nach Parallelphase:** Beim Übergang **Parallel → Ganzgruppe** (oder **Parallel → nächster Split** / `branch_gate`) erscheint die Karte „Parallelphase · Abschluss“ mit **„Gruppen zusammengeführt — weiter mit dem Plan“**, solange noch Einträge folgen; am Planende weiter **„Zur Nachbereitung“** (`coachShouldPromptSplitRejoinTransition` in `trainingPlanUtils.js`).
- **Nachbereitung / Speichern:** Payload über **`buildCoachSavePlanPayload`** (wie Planungseditor: **`phases`**, keine Zerstörung phasierter Struktur). Nach erfolgreichem Speichern: Coach-Session-Storage bereinigt, **`navigate('/planning/run/:unitId', { replace: true })`** (Plan & Ablauf).
- **Robustheit:** Abschnitte ohne Eintrag im `phases`-Baum, die nach Erben fälschlich **`parallel`** wären, werden für die **Anzeige** als **Ganzgruppenblock** nach der letzten bekannten Phasen-Ordnung ausgewiesen (`sectionsWithPlanLocForDisplay`).
- **Konzept / technische Spec:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
#### Arbeitspaket „Coaching & Breakout“ — noch offen
| # | Thema | Kurzbeschreibung |
|---|--------|------------------|
| 1 | **Backend / Datenkonsistenz** | Neue oder verschobene Sektionen konsistent in **`phases`** persistieren (nicht nur Client-Normalisierung). |
| 2 | **UX nach Speichern** | Optional: **im Coach bleiben** vs. **Planansicht** (aktuell: immer Plan & Ablauf). |
| 3 | **Kantenfälle Coach** | „Fertig“ bei abweichendem **Timer-Owner** vs. **Rejoin**/letzter Schritt prüfen. |
| 4 | **Tests** | Smoke: zwei Splitphasen, Ganzgruppe dazwischen/am Ende, Nachbereitung speichern, Rejoin. |
| 5 | **Run-UI vs. Spec** | Technische Spec §5.2 (Tabs pro Stream): Abgleich mit **`TrainingUnitRunPage`**. |
| 6 | **Trainer pro Stream** | UI und Policy zu **`assigned_trainer_profile_ids`** / Kopf-Co-Trainer offen. |
| 7 | **Vorlagen** | `training_plan_templates` phasen-/stream-kompatibel (Spec §5.3). |
| 8 | **Kombi-Coach B/C** | Fachspez **§ 10.4 / § 10.6**, `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` Phase **4**. |
### Trainingsmodule, Kombinationsübungen und Coach Stufe A
- **Fachspez & Drift-Schutz:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (**§ 10.2.1** IDs, **§ 10.4** Coaching-Stufen, **§ 10.6** Produkt-Backlog, **Anhang A** Abgleich).
- **Umsetzungsplan:** `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase **2** / **4** teilweise; Pakete **4a–g** — u. a. **4e** Archetyp-Admin, **4f** Massen-Vorbelegung, **4g** Backend-Validierung).
@@ -153,17 +220,18 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
## 7. Nächste Session — sinnvolle Arbeitspakete
1. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
2. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
3. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
4. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
5. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
6. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
7. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
8. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
9. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
10. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
11. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
---
@@ -172,7 +240,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Bereich | Einstieg |
|---------|----------|
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Coach-Kombination / Merge-Profil (Frontend) | `TrainingCoachPage.jsx`, `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
| Coach, Plan-Timeline, PUT-Payload phasiert | `TrainingCoachPage.jsx`, **`frontend/src/utils/trainingPlanUtils.js`** (`flattenPlanTimeline`, `buildCoachSavePlanPayload`, `sectionsWithPlanLocForDisplay`, Split-Rejoin-Helfer), `TrainingUnitRunPage.jsx` |
| Coach-Kombination / Merge-Profil (Frontend) | `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
| Frontend API | `frontend/src/utils/api.js` |
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
+121
View File
@@ -0,0 +1,121 @@
# Phase 0 – Performance-Baseline (Shinkan Jinkendo)
**Zweck:** Reproduzierbarer Startpunkt **vor** Phase 2 (Backend-Lesepfade, Summary-API).
**Stand:** 2026-05-13 · Backend-App-Version laut `backend/version.py`: **0.8.110**
Nach grösseren Deployments oder Schema-Änderungen: Bundle-Abschnitt neu erfassen (`npm run build`); API-/k6-Werte bei Bedarf aktualisieren.
---
## 1. Frontend-Bundle (`npm run build`)
Messung: Repo-Root → `cd frontend && npm run build` (Vite Production).
**Hinweis:** Dateinamen mit Hash (`index-*.js`) ändern sich pro Build; relevant sind Grössenordnungen und gzip.
### 1.1 Einstieg & globale Vendor-Chunks (Auszug letzter Lauf CI-lokal)
| Asset (Muster) | raw kB | gzip kB | Rolle |
|----------------|--------|---------|--------|
| `index.html` | 1.84 | 0.73 | Einstieg |
| `index-*.css` | 127.55 | 21.58 | Globale Styles |
| `index-*.js` (App-Shell / Router) | 64.83 | 17.45 | Haupteinstieg nach Code-Splitting |
| `vendor-react-*.js` | 142.42 | 45.67 | React + DOM |
| `vendor-router-*.js` | 65.94 | 22.51 | react-router |
| `vendor-markdown-*.js` | 161.54 | 49.31 | Markdown-Stack (wird mit Routen geladen) |
| `vendor-pdf-*.js` | 390.80 | 128.98 | jsPDF (Route-bezogen) |
### 1.2 Schwerste Route-Chunks (lazy, nach Route)
| Bereich | typ. Chunk-Grösse (raw / gzip) | Datei-Muster (Beispiel) |
|---------|-------------------------------|-------------------------|
| Trainingsplanung | 71.81 kB / 18.67 kB | `TrainingPlanningPage-*.js` |
| Übung bearbeiten | 91.31 kB / 22.49 kB | `ExerciseFormPage-*.js` |
| Medienbibliothek | 59.42 kB / 13.69 kB | `MediaLibraryPage-*.js` |
| Dashboard | 19.97 kB / 5.93 kB | `Dashboard-*.js` |
**Abnahme Phase 0 (Bundle):** Zahlen dokumentiert; Re-Run: `npm run build` und Tabelle abgleichen.
---
## 2. API-Latenz (p95) – Top-Routen
**Messung** erfolgt auf **Zielumgebung** (z. B. dev.shinkan / prod) mit gleicher Topologie wie Nutzer (HTTPS, Proxy). Nicht aus dem leeren Arbeitsverzeichnis ohne laufendes Backend messbar.
### 2.1 Vorgehen (empfohlen)
- **Access-Logs** des Reverse-Proxy (Request-Zeit), oder
- **APM** / OpenTelemetry, oder
- **k6** mit authentifizierten Szenarien (Token aus Testaccount; Header `X-Auth-Token`, ggf. `X-Active-Club-Id`), oder
- manuell: wiederholte `curl -w '%{time_total}\n'` mit gleichem Token
### 2.2 Vorlage (aus Umgebung ausfüllen)
| Route (Beispiel) | Methode | p95 (ms) | Datum / Umgebung | Bemerkung |
|------------------|---------|----------|------------------|-----------|
| `/api/profiles/me` | GET | *—* | *nach Messung* | |
| `/api/exercises` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
| `/api/training-units` (Liste, typ. Query) | GET | *—* | *nach Messung* | |
| `/api/media-assets` (Liste) | GET | *—* | *nach Messung* | |
| `/health` | GET | *—* | *nach Messung* | k6: siehe `scripts/load/` |
**Abnahme Phase 0 (API):** Verfahren steht; Tabelle mindestens für **`/health`** nach erstem k6-Lauf befüllbar; übrige Zeilen bei nächstem Monitoring-Export.
---
## 3. Lasttestszenario
### 3.1 E2E-Smoke (fachlicher Pfad)
- **Befehl:** Repository-Root, `npm run test:e2e` (setzt `PLAYWRIGHT_BASE_URL`, Testuser per Env, siehe `.gitea/workflows/test.yml`).
- **Abdeckung:** Login, Dashboard, Navigation u. a. – entspricht grob „Login → Dashboard → weitere Screens“.
- **Baseline notieren:** Dauer eines vollen Laufs, Anzahl passed (z. B. 26 Tests), Datum.
| Messung | Wert | Datum |
|---------|------|-------|
| Playwright Gesamtlauf (lokal/CI) | *—* | *nach Messung* |
| passed / total | 26 / 26 (Ziel) | |
### 3.2 EXPLAIN (Phase 2 – Lesepfade)
- **Datei:** **`scripts/load/explain-readpaths.sql`** — repräsentative Statements für `list_exercises` / Stufenfilter / `training_units`; auf der Ziel-DB mit `EXPLAIN (ANALYZE, BUFFERS)` ausführen (Token/Tenant nicht im Skript; wie bei echten API-Queries filtern).
### 3.3 k6 – parallele /health
- **Skript:** `scripts/load/k6-health-baseline.js`
- **CI:** Läuft **automatisch** im Gitea-Workflow im Job **`k6-health-baseline`** (eigenständig, ohne Playwright; `.gitea/workflows/test.yml`). Parallel dazu **Playwright** im Job **`playwright-tests`**.
- **Lokal:** siehe `scripts/load/README.md`
- **Baseline notieren:** k6-Ausgabe `http_req_duration` p(95), Checks succeeded.
| Szenario | p95 / Fehlerquote | Datum / BASE_URL |
|----------|-------------------|------------------|
| 10 VUs, 30 s `/health` | *—* | *nach Messung* |
### 3.4 Aus dem Deployment-/CI-Log übernehmen (k6 `k6-health-baseline`)
Das Skript `scripts/load/k6-health-baseline.js` nutzt **10 VUs**, **30 s**, Ziel **`GET {BASE_URL}/health`** (siehe Workflow-Env für `BASE_URL`).
**In die Tabelle oben (Abschnitt 3.3) eintragen — aus der k6-Zusammenfassung am Ende des Jobs:**
| Feld in BASELINE_SNAPSHOT | Wo im k6-Log (typisch) |
|---------------------------|-------------------------|
| **p95** (Latenz ms) | Zeile **`http_req_duration`** → Wert **`p(95)=…`** (ganze Zahl oder ms mit Einheit wie `12.34ms`) |
| **Fehlerquote** | Zeile **`http_req_failed`** → z. B. `0.00%` bzw. `✓ 0%` — oder kurz „0 %“ notieren |
| **Checks** (optional) | Zeile **`checks`** → Anteil **`✓`** (soll **100 %** sein, sonst Hinweis) |
| **Datum / BASE_URL** | Deploy-Datum + die **öffentliche** Basis-URL des Laufs (wie im Workflow gesetzt, z. B. `https://dev.shinkan.jinkendo.de`) |
| **App-Version** (optional) | dieselbe wie im Deploy (`backend/version.py` / Release), damit M2-Vergleich ressortfähig bleibt |
**Zusätzlich (Abschnitt 2.2):** nur die Zeile **`/health` GET`** mit dem **gleichen** p95 befüllen, wenn ihr dort noch Platzhalter habt — echte API-Routen (`/api/...`) kommen weiter aus Monitoring/k6 mit Auth, nicht aus diesem Job.
---
## 4. Nächster Schritt (Roadmap)
- **Phase 0** ist für den Pipeline-Teil **abgeschlossen**: Bundle dokumentiert; **k6** läuft in CI nach jedem relevanten Deploy (mit Test-Suite); API-p95-Tabellen kann das Team aus Monitoring weiter befüllen (optional, kein Deploy-Blocker).
- **Phase 2** (Backend Lesepfade) ist **abgeschlossen** — siehe [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md); nach Deploy **p95 erneut messen** und mit den Werten aus Abschnitt 2 dieser Datei vergleichen (**Meilenstein M2**).
---
## Verweise
- Roadmap: [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md)
- k6: [scripts/load/README.md](../../scripts/load/README.md)
+29
View File
@@ -0,0 +1,29 @@
# Architektur: Zielbild, Refaktor, Regeln (Shinkan Jinkendo)
Dieses Bündel ist die **Leitlinie für die große Refaktorierung** nach dem MVP. Es ergänzt die bestehenden Pflichtdokumente (`.claude/rules/ARCHITECTURE.md`, `CODING_RULES.md`, Zugriffsschicht, Media-Spec) und ist für **Wartbarkeit, Performance und sichere Erweiterung** verbindlich, soweit hier ausdrücklich festgelegt.
## Inhalt
| Datei | Zweck |
|--------|--------|
| [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md) | Zielarchitektur (Frontend, API, Daten), Qualitätsziele, Einbindung neuer Features |
| [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md) | Erfasste Architekturschuld, Reihenfolge und Massnahmen zur Behebung |
| [UMSETZUNGSPLAN_ROADMAP.md](./UMSETZUNGSPLAN_ROADMAP.md) | Phasen, Meilensteine, Abnahmekriterien, Aufwandsschwerpunkte |
| [`frontend/src/api/client.js`](../../frontend/src/api/client.js) | Phase 4: zentraler HTTP-Client (`request`, `ACTIVE_CLUB_STORAGE_KEY`, `API_URL`, `mergeActiveClubHeader`) |
| [`frontend/src/api/exercises.js`](../../frontend/src/api/exercises.js) | Phase 4: Übungen, Medien/Archiv, Progressionsgraphen, KI-Hilfen |
| [`frontend/src/api/planning.js`](../../frontend/src/api/planning.js) | Phase 4: Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, KPIs) |
| [BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md) | Phase 0: Bundle-, API- und Last-Baseline (Messvorlagen, Vergleich nach Phase 2) |
| [KI-Prompt-Zielarchitektur](../../.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md) | Roadmap: Kontext-Arten, Composition, Planung/Rahmen, Phasenplan (verbindliche Zielrichtung) |
## Tests (E2E / Refaktor-Budget)
- **`tests/dev-smoke-test.spec.js`** – Playwright-Suite (Smoke + Compliance). Enthält u. a. **Test 8:** nach Login und **Reload** des Dashboards werden GET-Aufrufe zu `/api/profiles/me` und `/api/training-units` gezählt (Absicherung Dashboard-Refaktor Phase 1). Ausführung: `npm run test:e2e`; CI: `.gitea/workflows/test.yml` Job **playwright-tests**. **k6**-Baseline: Job **`k6-health-baseline`** (siehe `scripts/load/README.md`).
## Pflege
- Bei abgeschlossenen Phasen: Roadmap und Remediation-Dokument aktualisieren; bei Regeländerungen: nur mit **expliziter Projektfreigabe** (gleiches Verfahren wie bei `.claude/rules/ARCHITECTURE.md`).
- Querschnitt: **`docs/HANDOVER.md`** soll auf die aktive Roadmap-Phase verweisen.
## Bezug MVP
Die aktuelle Codebasis ist funktional MVP-tauglich; strukturell bestehen bekannte Schwerpunkte (grosse Seiten-Monolithen, API-Monolith im Client, redundante Lesepfade, schwere Listenqueries). Dieses Bündel definiert, wie nach **dem** MVP weitergebaut wird, ohne jedes neue Feature erneut mit **architektonischer Schuld** zu überfrachten.
@@ -0,0 +1,133 @@
# Architekturschuld – Erfassung und Behebungsschritte
Dieses Dokument listet **bewusst** die aus MVP und Code-Review bekannten strukturellen Themen auf und ordnet **konkrete Massnahmen** zu. Reihenfolge ist an die Roadmap gekoppelt; hier die inhaltliche Detailierung.
---
## A. Frontend
### A1 – „God Pages“ (Training, Übungsformular, Vereine)
**Schuld:** Sehr grosse Dateien (tausende Zeilen) mit viel State, vielen Effekten und eingebetteten Modals.
**Risiko:** Hohe Re-Render-Kosten, schwerer zu testen, hoher RAM auf schwachen Geräten, neue Features vergrössern die Datei weiter.
**Behebungsschritte:**
1. **Inventar:** pro Page kurze Gliederung (Abschnitte) und Ziel-Komponenten benennen.
2. **Extrahieren:** Zuerst isolierbare Blöcke (Listen, Modals, Sidebar, Form-Sektionen) in Unterkomponenten; Props/Oberfläche dokumentieren.
3. **Hooks:** wiederkehrende Logik (`useEffect`-Ketten, Filter-State) in `useXxx`-Hooks pro Domäne.
4. **Optional `features/training/` o. ä.:** wenn 3+ zusammengehörige Komponenten entstehen.
**Erfolgskriterium:** Page-Datei unter dem in `VERBINDLICHE_REGELN_SHINKAN.md` genannten Soft-Limit oder dokumentierte Ausnahme.
---
### A2 – Monolithischer API-Client (`utils/api.js`)
**Schuld:** Eine Datei bündelt alle Endpoints; erschwert Tree-Shaking, Navigation und domänenweise Ownership.
**Behebungsschritte:**
1. Verzeichnisstruktur festlegen, z. B. `frontend/src/api/` mit `client.js` (Token, `request`), `exercises.js`, `planning.js`, …
2. Bestehende `api.js` schrittweise zur **Facade** (`export * from …`) degradieren oder re-exportieren.
3. Neue Features **nur** in domänenspezifischen Dateien implementieren.
**Erfolgskriterium:** Kein Wachstum des Monolithen über bestehende Endpoint-Anzahl hinaus; mittelfristig dominieren kleine Module.
---
### A3 – Redundante und „chatty“ Client-Requests
**Schuld (Beispiele):** Dashboard lädt Profil erneut trotz Auth; mehrere nahezu gleiche `listTrainingUnits`-Aufrufe; doppelte `listExercises` für KPIs.
**Risiko:** Mehr Last auf API/DB, schlechtere UX auf langsamen Geräten.
**Behebungsschritte:**
1. **Profil:** eine kanonische Quelle (Auth-Profil reicht für Anzeige; fehlende Felder gezielt nachladen oder Auth-Check erweitern – fachlich klären).
2. **Dashboard:** einen **Summary-Endpoint** spezifizieren und implementieren (siehe Backend B1) oder Client auf einen aggregierten Aufruf reduzieren.
3. **Org-Inbox / globale Fetches:** Ladestrategie definieren (on-demand vs. TTL vs. sichtbarkeitsabhängig) und `OrgInboxContext` entsprechend umbauen.
**Stand Umsetzung:** Gemeinsame Funktion `fetchOrgInboxSnapshot` für Mount und `refreshOrgInbox` (ein Codepfad, gleiche API-Calls). Optionales verzögertes Laden / TTL weiterhin offen.
**Erfolgskriterium:** Dashboard-Initialisierung ohne redundanten `getCurrentProfile`; ohne drei parallele fast gleiche Trainingslisten (oder dokumentierte Ausnahme).
---
### A4 – Schwere Abhängigkeiten
**Schuld:** PDF/Markdown/Canvas-Pfade ziehen grosse Chunks.
**Behebungsschritte:** Strikte `import()` an Nutzeraktion; keine statischen Top-Level-Imports schwerer Libs in gemeinsamen Einstiegspfaden.
**Erfolgskriterium:** Lighthouse / Bundle-Analyse zeigt schwere Libs nur auf betroffenen Routen.
---
## B. Backend
### B1 – Aggregations- und Summary-APIs
**Schuld:** Bildschirme holen mehrere Listen und aggregieren im Client.
**Behebungsschritte:**
1. Endpoint(s) z. B. `GET /api/dashboard/summary` oder domänenspezifisch mit gleicher Sichtbarkeitslogik wie Einzel-Listen.
2. Tests oder manuelle Checkliste gegen **Tenant-Leaks** (nur eigene/sehbare Daten).
3. Versionierung in `version.py` bei neuem Router-Block oder signifikantem Modul-Update.
**Erfolgskriterium:** Fertigest Dashboard mit einer serverseitigen Zusammenfassung (oder festgelegte Client-Reduktion mit Messung).
---
### B2 – Listenqueries (z. B. Übungsliste)
**Schuld:** Korrelierte Subqueries pro Zeile können bei Wachstum teuer werden.
**Behebungsschritte:**
1. `EXPLAIN (ANALYZE, BUFFERS)` auf Produktions-näher Konfiguration mit realistischem `limit`.
2. Indizes für Filter und Sortierung ergänzen.
3. Refactoring: JOINs/LATERAL statt N-facher Subquery, wo messbar besser.
**Erfolgskriterium:** Dokumentierte p95-Zielwerte erreicht oder Trend verbessert (siehe Roadmap).
---
### B3 – Pagination
**Schuld:** Tiefe `OFFSET`-Werte skalieren schlecht.
**Behebungsschritte:** Keyset-Pagination für grosse Listen in späteren Phasen einführen; API-Vertrag dokumentieren.
---
## C. Querschnitt
### C1 – Messbarkeit
**Schuld:** Optimierung ohne Baseline.
**Behebungsschritte:** Einmalig Baseline (API p95, Bundle-Grössen Haupt-Route, ein Lasttest-Szenario) festhalten; wiederholen nach grossen Phasen.
---
### C2 – Dokumentation und Audit
**Schuld:** Wissen nur in Chats.
**Behebungsschritte:** `HANDOVER.md` und `ACCESS_LAYER_ENDPOINT_AUDIT.md` bei jedem grösseren API-Block aktualisieren; Roadmap-Phase abhaken.
---
## Mapping: Schuld → Regel
| Schuld | Primär-Regel (Shinkan) |
|--------|-------------------------|
| God Pages | S1, S2 |
| API-Monolith | S3 |
| Globale Fetches | S4 |
| Chatty API | S5 |
| Caching-Ideen | S6 |
| Grössere Features ohne Messung | S7, S8 |
@@ -0,0 +1,126 @@
# Migration: Trainings-Einheit — Modal → Vollseiten-Editor
**Status:** Phase C abgeschlossen (Hub + Edit-Route produktiv)
**Stand:** 2026-05-19
**Bezug:** Architektur-Schuld A1 (`SCHULDEN_UND_REMEDIATION.md`), UX-Grundsatz Modals vs. Vollseiten
---
## 1. Ausgangslage
| Aspekt | Ist (Modal) | Soll (Vollseite) |
|--------|-------------|------------------|
| Bearbeiten / Neu | `TrainingPlanningUnitFormModal` über `TrainingPlanningPageRoot` | `TrainingUnitEditPage` unter eigener Route |
| Hub | Liste + Kalender auf `/planning` | unverändert — nur Übersicht & Kurzaktionen |
| Deep-Link | `/planning?unit={id}` (öffnet Modal, Query wird entfernt) | `/planning/units/{id}/edit` (bookmarkbar) |
| Vergleich | Rahmenprogramm, Modul, Vorlage, Run/Coach | gleiches Muster |
**Warum Modal historisch:** Frontend Phase 3 (0.8.131) — Extraktion aus God-Page, **kein** bewusstes UX-Zielbild.
---
## 2. Zielbild (verbindlich)
### 2.1 Routen
| Route | Zweck |
|-------|--------|
| `/planning` | Hub: Gruppe, Liste/Kalender, Import, Zuweisen, Löschen, Links „Bearbeiten“ |
| `/planning/units/new` | Neue Einheit (Query: `group`, `date`, optional `template`) |
| `/planning/units/:id/edit` | Bestehende Einheit bearbeiten (Query optional: `mode=debrief`) |
| `/planning/run/:unitId` | Durchführung (unverändert) |
| `/planning/run/:unitId/coach` | Coaching (unverändert) |
Implementierung: `frontend/src/utils/planningUnitRoutes.js` — **einzige** Quelle für Pfade und Rückkehr-Kontext (Drift-Schutz).
### 2.2 Was Modal bleibt (Hub + Editor)
| Dialog | Ort | Begründung |
|--------|-----|------------|
| Rahmen-Import | Hub | Mehrfachauswahl + Datums-Vorschläge |
| Trainer zuweisen | Hub | Kurzaktion aus Liste/Kalender |
| Rahmen-Session / Modul aus Liste | Hub | Aktion auf gespeicherter Einheit ohne Editor |
| Übungspicker, Modul einfügen, Peek | **Editor-Seite** | Kontext des Ablaufs |
| Rahmen übernehmen / Modul aus Editor | **Editor-Seite** | Nach Speichern des Ablaufs |
| Kombi-Ablauf bearbeiten | SectionsEditor (Sheet) | Fokussierter Sub-Dialog |
### 2.3 UI-Shell Editor
- `TrainingUnitFormShell.jsx` — reine Formular-UI (ohne Overlay), `page-form-shell` + `FormActionBar` (`variant="page"`).
- Kein `FormModalOverlay` / kein Scroll-Lock auf der Editor-Seite nötig.
### 2.4 Rückkehr zum Hub
Beim Navigieren vom Hub zum Editor wird `location.state.planningReturn` gesetzt (Gruppe, Ansicht, Monat, Datumsfilter).
Abbrechen / Speichern & schließen → `/planning?…` mit wiederhergestellten Query-Parametern.
Legacy: `/planning?unit={id}` → Redirect auf `/planning/units/{id}/edit` (301/Replace via Router).
---
## 3. Code-Struktur (Ziel)
```
frontend/src/
├── utils/
│ ├── planningUnitRoutes.js # Pfade, Return-State, Legacy-Redirect
│ ├── planningUnitRoutes.test.js # Vitest
│ └── trainingUnitEditorCore.js # Reine Payload-/Form-Helfer
│ └── trainingUnitEditorCore.test.js
├── hooks/
│ └── useTrainingUnitEditor.js # Laden, Speichern, Form-State (Edit-Page)
├── components/planning/
│ ├── TrainingUnitFormShell.jsx # Formular-UI (ex Modal-Inhalt)
│ └── TrainingPlanningPageRoot.jsx # Hub only (~ weniger State)
└── pages/
└── TrainingUnitEditPage.jsx # Route-Container
```
**Soft-Limit (S1):** `TrainingUnitEditPage.jsx` delegiert an Hook + Shell; PageRoot verliert Modal-State.
---
## 4. Phasen & Abnahme
| Phase | Inhalt | Abnahme / Tests |
|-------|--------|-----------------|
| **A** | Doku, `planningUnitRoutes`, `trainingUnitEditorCore`, Vitest | `npm run test --prefix frontend` grün |
| **B** | `TrainingUnitFormShell`, `TrainingUnitEditPage`, Routen, Hub-Navigation, Modal entfernen | Playwright 14–15; Build grün |
| **C** | Hub liest Return-Query; Dashboard-Links direkt auf Edit-Route; PageRoot weiter entschlacken | Manuell + E2E |
| **D** (optional) | `useTrainingUnitEditor` weiter modularisieren; ungespeichert-Blocker wie Modul-Edit | S8 Checkliste |
### Definition of Done (Phase B)
- [x] Kein `TrainingPlanningUnitFormModal` mehr in Produktionspfad
- [x] `data-testid="planning-unit-form"` auf Editor-Seite
- [x] Speichern sendet identisches Payload wie zuvor (`buildTrainingUnitSavePayload`)
- [x] Split-Sessions / `phases`-PUT unverändert (`buildPlanPayloadForSave`)
- [x] Playwright 12–13 weiter grün; 14–15 neu
- [x] `docs/HANDOVER.md` + Roadmap aktualisiert
---
## 5. Risiken & Mitigation
| Risiko | Mitigation |
|--------|------------|
| Payload-Drift beim Speichern | Logik in `trainingUnitEditorCore.js` + Unit-Tests |
| Kontextverlust Hub | `planningReturn` in `planningUnitRoutes.js` + Hub-Query-Restore |
| Modul-Einfügen / Picker | Nur auf Edit-Page; gleiche Handler wie zuvor |
| Doppelte Einträge Deep-Link | Legacy-Redirect; Dashboard später auf neue URL |
| Große Edit-Page | Hook + Shell; PageRoot schrumpft |
---
## 6. Nicht-Ziele (dieser Sprint)
- Backend-API-Änderungen
- Virtualisierung der Einheitenliste
- Refactor `TrainingUnitSectionsEditor`
- Coach/Run-Flows
---
## 7. Pflege
Nach Abschluss Phase B: Eintrag in `UMSETZUNGSPLAN_ROADMAP.md` (Phase 3 Nachzug), `SCHULDEN_UND_REMEDIATION.md` A1 Fortschritt, `backend/version.py` CHANGELOG.
+157
View File
@@ -0,0 +1,157 @@
# Umsetzungsplan und Roadmap – Refaktorierung Shinkan Jinkendo
**Aktueller Stand (laufend):**
- **Phase 0:** abgeschlossen – siehe **[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)** (Bundle festgehalten, API-/k6-Vorlagen + Skripte unter `scripts/load/`).
- **Phase 1 (Teil):** Dashboard: kein zweites `getCurrentProfile`; Trainings-Vorschau über **`GET /api/dashboard/kpis`** (`training_home`); Playwright **Test 8** sichert API-Budget ab.
- **Phase 1 (Teil):** Org-Inbox: **ein** gemeinsamer Ladepfad `fetchOrgInboxSnapshot` für Mount-`useEffect` und `refreshOrgInbox` (gleiche Requests, weniger Drift-Risiko; Verhalten unverändert).
- **Phase 2:** **abgeschlossen** (2026-05-14) — Indizes 058–062, Keyset `/api/exercises` + `/api/training-units`, **`/api/dashboard/kpis`** inkl. `training_home`, EXPLAIN-Vorlagen **`scripts/load/explain-readpaths.sql`**.
- **Offen Phase 1:** Inbox optional **TTL** / nur bei sichtbarem Widget.
- **Phase 3 (abgeschlossen 2026-05-14):** Übungsliste modularisiert; Trainingsplanung/Übungsformular: **Page-Dateien unter Soft-Limit** — Implementierung in `TrainingPlanningPageRoot.jsx`, `ExerciseFormPageRoot.jsx`, `ExercisesListPageRoot.jsx`; `pages/*.jsx` nur Re-Export. Playwright **Tests 9–10**.
- **Phase 4 (fortlaufend 2026-05-14):** API **Welle 1** `client.js`; **Welle 2** `planning.js`; **Welle 3** `exercises.js`; `utils/api.js` bleibt Facade (`export *`, `api`-Objekt `...exercises`, `...planning`).
- **Trainingsplan Breakout / Coach (2026-05-14):** Phasen + parallele Streams (**063**, Frontend **0.8.137–0.8.140**), Coach-Rejoin und Nachbereitung — siehe **`docs/HANDOVER.md`**, **`technical/PARALLEL_TRAINING_STREAMS_SPEC.md`**.
**Ziel:** Nach MVP eine **nachhaltige** Architektur für Wachstum, **Performance** (Server + schwache Clients) und **sichere Feature-Erweiterung**.
**Leitdokumente:** [ZIELBILD_ARCHITEKTUR.md](./ZIELBILD_ARCHITEKTUR.md), [SCHULDEN_UND_REMEDIATION.md](./SCHULDEN_UND_REMEDIATION.md), [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md).
---
## Leitplanken (vereinbart)
- **Kein Breaking** der Zugriffsschicht: neue und geänderte Endpoints folgen `get_tenant_context` / Audit wie bisher.
- **Inkrementell:** Jede Phase liefert **nutzbaren** Stand (kein Big-Bang-Stillstand).
- **Neue Features** während der Roadmap: **S8 Checkliste** und **S1/S3** strikt; wo möglich gleich im neuen API-Modul-Pfad.
---
## Phase 0 – Baseline (kurz, Pflicht)
**Status:** **Erledigt** (2026-05-13). Siehe **`docs/architecture/BASELINE_SNAPSHOT.md`** und **`scripts/load/`**.
| Task | Output |
|------|--------|
| API p95 der Top-5-Routen messen (z. B. `profiles/me`, `exercises` list, `training-units` list, `media-assets` list) | Vorlage + Messverfahren in **BASELINE_SNAPSHOT.md**; Werte nach erstem Lauf auf Dev/Prod eintragen |
| Ein Lasttestszenario (Login → Dashboard → Übungen → Planung) | Playwright `npm run test:e2e` + k6 **`scripts/load/k6-health-baseline.js`** (README dort) |
| Bundle: Grösse Einstieg + schwerste Route | In **BASELINE_SNAPSHOT.md** dokumentiert (Auszug `vite build`) |
**Abnahme:** Bundle dokumentiert; Mess- und Lastskripte vorhanden; API-Tabelle iterativ befüllbar. **Phase 2** beginnt nach diesem Freeze-Punkt.
---
## Phase 1 – Quick Wins Netzwerk (hoher ROI, geringes Risiko)
**Fokus:** Weniger redundante Requests, bessere Mobile-UX, kaum strukturelle Risiken.
| Task | Bezug Remediation | Status |
|------|-------------------|--------|
| Dashboard: Doppel-`getCurrentProfile` auflösen; kanonisches Profil klären | A3 | erledigt |
| Dashboard: `listTrainingUnits`-Reduktion (ein Call statt zweier identischer) | A3 | erledigt |
| Dashboard: `listExercises`-Doppelabruf / Summary-Call | A3, B1 | erledigt (`GET /api/dashboard/kpis`) |
| Org-Inbox: Ladestrategie; Umsetzung Teil 1 (gemeinsamer Ladepfad, keine doppelte Logik) | A3 | erledigt |
| Org-Inbox: TTL / verzögertes Laden (nur nach Bedarf) | A3 | teils (Erstlade per `requestIdleCallback`, max. 1,5s) |
**Abnahme:** Kein funktionales Leck; Netzwerk-Tab zeigt messbar weniger parallele gleiche Muster beim ersten Dashboard-Load.
---
## Phase 2 – Backend Lesepfade (Skalierung „viele Nutzer“)
**Status:** **Abgeschlossen** (2026-05-14).
**Voraussetzung:** Phase 0 abgeschlossen (**[BASELINE_SNAPSHOT.md](./BASELINE_SNAPSHOT.md)**). Nach Deploy: p95 der Top-Routen erneut messen und mit Baseline vergleichen ([M2](#meilensteine-empfohlen)).
**Fokus:** DB und API stabil unter parallelen Lesern.
| Task | Bezug | Status |
|------|-------|--------|
| `EXPLAIN` + Index-Tuning für `list_exercises` und nächste schwere Listen | B2 | erledigt (Indizes 058–060, 062; Vorlagen **[explain-readpaths.sql](../../scripts/load/explain-readpaths.sql)**; Messung Team) |
| Summary-API finalisieren/erweitern falls in P1 nur Teilbereich | B1 | erledigt (`GET /api/dashboard/kpis` + **`training_home`**) |
| Keyset-Pagination für Listen mit Sort-Key | B3 | erledigt (`/api/exercises`, `/api/training-units`) |
**Lieferung:** Migrationen **058–062**; Keyset-Parameter wie dokumentiert in OpenAPI/Router; Dashboard nutzt **ein** KPI-Request für Kennzahlen und Trainings-Vorschau.
**Abnahme:** p95 der optimierten Routen nach Messung dokumentiert verbessert ggü. Phase 0 oder Obergrenze notiert (siehe Baseline-Tabelle).
---
## Phase 3 – Frontend-Struktur (Wartbarkeit + Client-Performance)
**Fokus:** God-Pages abbauen, Virtualisierung wo nötig.
| Task | Bezug |
|------|--------|
| Eine Page komplett zerteilen als Referenz (z. B. `TrainingPlanningPage` **oder** `ExerciseFormPage`) – Rest priorisiert nach Nutzung | A1 |
| Virtualisierung für die längste produktive Liste | A1, S2 |
| Schwere Imports auf `import()` umziehen (gezielt) | A4 |
**Teil umgesetzt (2026-05-13):** `ExercisesListPage` — Karten `ExerciseListCard.jsx`; Filter/Massenänderung `ExerciseListFilterModal.jsx` / `ExerciseListBulkModal.jsx`; Tab „Progressionsgraphen“ **lazy**; **Picker** virtualisiert; Gitter `data-testid` + `content-visibility`; Playwright **Tests 9–10**.
**Abgeschlossen (2026-05-14):** Routen bleiben unter `frontend/src/pages/`; schwere Implementierung in **`components/planning/TrainingPlanningPageRoot.jsx`**, **`components/exercises/ExerciseFormPageRoot.jsx`**, **`components/exercises/ExercisesListPageRoot.jsx`** — **`pages/*` nur Re-Export** (Soft-Limit ~500 Zeilen laut `VERBINDLICHE_REGELN_SHINKAN.md`).
**Abnahme:** Referenz-Page unter Soft-Limit; Regel S1 für neue Änderungen durchsetzbar.
---
## Phase 4 – API-Client Modularisierung
**Status:** **fortlaufend** (2026-05-14) — Welle 1: **`client.js`**; Welle 2: **`planning.js`**; Welle 3: **`exercises.js`**; **`utils/api.js`** bleibt vollständige Facade.
**Fokus:** Wartbarkeit für viele neue Features.
| Task | Bezug | Status |
|------|-------|--------|
| `frontend/src/api/client.js` — zentraler HTTP-Client | A2 | erledigt (Welle 1) |
| `frontend/src/api/planning.js` — Trainingsplanung (Einheiten, Vorlagen, Module, Rahmen, Dashboard-KPIs) | A2 | erledigt (Welle 2) |
| `frontend/src/api/exercises.js` — Übungen, Medien/Archiv, Varianten, Progressionsgraphen, KI | A2 | erledigt (Welle 3) |
| Weitere Domänen-Module unter `frontend/src/api/` + Entlastung von `utils/api.js` | A2 | offen |
| Neue Endpoints primär in Domänen-Dateien | S3 | offen |
**Abnahme:** Anteil neuer Module > X% der neuen Zeilen (Team-Ziel); Monolith wächst nicht weiter.
---
## Phase 5 – Vertiefung DB & Pagination
**Fokus:** Wachstum Datenbestand.
| Task | Bezug |
|------|--------|
| Keyset für weitere Listen | B3 |
| Weitere Query-Refactorings nach Monitoring | B2 |
**Abnahme:** Dokumentierte Paginierungs-API; keine Regression in der Zugriffsschicht.
---
## Meilensteine (empfohlen)
| Meilenstein | Inhalt |
|-------------|--------|
| **M1** | Phase 0 + 1 abgeschlossen, HANDOVER aktualisiert |
| **M2** | Phase 2 abgeschlossen, Lasttest / p95 nachziehen |
| **M3** | Phase 3 abgeschlossen: Page-Dateien Soft-Limit (Re-Export); Virtualisierung Übungsliste |
| **M4** | Phase 4 migrationsbereit für alle neuen Features |
| **M5** | Phase 5 für Top-Listen abgeschlossen |
---
## Parallel: neue Features
- Jedes Feature: [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) **S8**.
- Berührung schwerer Pfade: kurzer Performance-Nachweis (S7).
---
## Risiken und Mitigation
| Risiko | Mitigation |
|--------|------------|
| Summary-Endpoint falsch gefiltert | Code-Review + Abgleich mit Einzel-Endpoint-Logik; Tests mit mehreren Rollen |
| Refaktor bricht PWA/Offline | Smoke-Test nach grossen Frontend-Phasen |
| Keyset bricht alte Clients | Versionierte Query-Parameter oder Übergangsfenster |
---
## Pflege
Nach jeder Phase: **README** dieses Bündels prüfen; **Roadmap** Checkboxen/Status; **HANDOVER** nächste Phase nennen.
@@ -0,0 +1,62 @@
# Verbindliche Architekturregeln – Shinkan (Ergänzung)
**Status:** verbindlich für die Shinkan-Codebasis, **ergänzend** zu:
- `.claude/rules/ARCHITECTURE.md`
- `.claude/rules/CODING_RULES.md`
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
Bei Widerspruch gewinnt die **spezifischere** Regel zur **Zugriffsschicht und Governance** (Sicherheit vor Komfort). Bei Widerspruch zwischen diesem Dokument und allgemeinen Mitai-Template-Resten in `ARCHITECTURE.md` gilt für **Shinkan** dieses Dokument und die Shinkan-Pflichtlektüre in `CLAUDE.md`.
---
## S1 – Frontend: Grösse und Zerlegung von Seiten
1. **Soft-Limit:** Neue oder stark erweiterte Seiten sollen **unter ~500 Zeilen** im Page-File bleiben. Darüber: Auslagern in Komponenten/Hooks/Feature-Module mit klaren Namen.
2. **Ausnahmen** nur mit Kurzbegründung im PR und Verweis auf Messung (Bundle/Performance) oder fachliche Unteilbarkeit.
3. **Wiederkehrende UI-Blöcke** nicht per Copy-Paste über Seiten hinweg duplizieren; extrahieren in `components/` oder `features/`.
## S2 – Frontend: Listen und Speicher
1. Listen, die **typischerweise > 100 sichtbare oder gehaltene Einträge** im DOM ermöglichen, **müssen** virtualisiert werden (oder serverseitig strikt begrenzt + „mehr laden“ mit dokumentiertem UX – nicht beides unbegründet ignorieren).
2. **Modals und zweite Raster** gleichzeitig zum Hauptbaum nur laden, wenn geöffnet (lazy mount), wo technisch machbar ohne UX-Bruch.
## S3 – Frontend: API-Zugriff
1. **Alle** API-Aufrufe über die zentrale Schicht (`utils/api` bzw. nach Modularisierung dessen Module). **Kein** `fetch('/api/...')` ohne diese Schicht.
2. Während der Migration vom API-Monolithen: **neue** Endpoints ausschliesslich im **domänenspezifischen** Modul anlegen; nur bei Bedarf Re-Export über die Facade.
## S4 – Frontend: Globale Daten und Context
1. Neue **global** geladene Daten (jede authentifizierte Session) **bedürfen** technischer Begründung (Badge-Kritikalität, Sicherheit). Alternative: **on-demand** beim ersten Bezug oder **TTL-Cache** mit dokumentierter Invalidierung (`shinkan:…`-Events bleiben möglich).
2. Context-`value`-Objekte **müssen** stabil gehalten werden (`useMemo` / `useCallback`), wenn nicht-triviale Unterbäume davon abhängen (bereits etabliert für Auth; gleiches Muster für neue Contexts).
## S5 – Backend: Lesepfad-Design
1. **Keine** mehrfachen fast identischen Listenaufrufe durch den Client für **denselben** zusammensetzbaren Bildschirm, wenn ein **einzelner** Summary-Endpoint unter gleicher Sichtbarkeitslogik möglich ist. Ausnahme: nachweislich unterschiedliche Cache-Lebensdauer oder unterschiedliche Rechte – dokumentieren.
2. Neue Listen-Endpoints: **Paginierung** (`limit`/`offset` oder Keyset nach Roadmap) und Obergrenzen; keine „unbegrenzt alles“-Defaults für grosse Tabellen.
3. Schwere SQL-Konstruktionen (viele korrelierte Subqueries pro Zeile) **nur** mit Kommentar **Warum** und Hinweis auf Indexlage oder geplantes Refactoring-Ticket.
## S6 – Backend: Mandanten und Caching
1. **Kein** HTTP- oder Anwendungs-Cache für mandantenspezifische oder nutzerspezifische Daten **ohne** expliziten Schlüssel (mindestens: Tenant-Kontext + relevante Parameter) und **Invalidierungsstrategie**.
2. Öffentliche oder global geteilte Katalogdaten dürfen mit `ETag` / kurzem Cache optimiert werden – **nach** Abgleich mit Governance.
## S7 – Performance und Messung (Definition of Done für grössere Features)
1. Features, die neue Listen schwerer als bestehende Top-10-Queries machen oder **> ~50 KB** zusätzliches Client-JS pro Route erzeugen: **kurz** messen (Lighthouse mobil oder Netzwerk-Timing) und im PR festhalten.
2. Regressions in **p95** der betroffenen API nach Deploy: bei Bedarf Rollback- oder Nachsteuerungskriterium mit Team vereinbaren (Zahlen Zielbild/Roadmap).
## S8 – Feature-Checkliste (DoD)
Vor Merge einer grösseren Erweiterung:
- [ ] Zugriffsschicht / Audit aktualisiert (falls zutreffend)
- [ ] Kein Verstoss gegen S1–S7 ohne dokumentierte Ausnahme
- [ ] Keine neue direkte DB-Nutzung im Frontend
- [ ] Medien/Lifecycle (falls Medien betroffen) nach Media-Spec
---
**Änderungen** an diesen Regeln nur mit **expliziter Projektfreigabe** (analog zu `ARCHITECTURE.md`).
+78
View File
@@ -0,0 +1,78 @@
# Architektur-Zielbild – Shinkan Jinkendo
**Geltungsbereich:** Trainer-/Vereinsplattform, Multi-Tenancy und Governance nach bestehender Zugriffsschicht.
**Ziele:** dauerhaft tragfähig, performant bei vielen gleichzeitigen Nutzern, akzeptabel auf **geringer Client-Leistung** (wenig RAM/CPU), **wartbar** und so strukturiert, dass **neue Features** ohne neue Grosseinkaufe an technischer Schuld einbindbar sind.
---
## 1. Leitprinzipien
1. **API-first, Mandanten-sicher** – Fachlogik und Sichtbarkeit serverseitig; das Frontend orchestriert und zeigt. Unverändert gemäss bestehender Regeln (`ACCESS_LAYER`, Governance-Helfer).
2. **Schlanke Client-Oberfläche** – JavaScript pro Route begrenzen; schwere Abhängigkeiten nur bei Bedarf laden; Listen dort virtualisieren, wo Grössenordnungen wachsen.
3. **Explizite Lesepfade** – Aggregation und Zusammenfassungen dort, wo mehrere fast gleiche Requests heute nötig sind (Dashboard, Badges), **statt** Chatty-Client-Muster.
4. **Vorhersehbarkeit für die DB** – Listenqueries ohne unnötige O(n)·Subquery-Kosten pro Zeile; Indizes und Paginierungsstrategie sind Teil des Designs.
5. **Feature-Einbindung per Checkliste** – Jedes neue Feature durchläuft die gleiche Architektur- und Performance-Checkliste (siehe Regeldokument), bevor es als „fertig“ gilt.
---
## 2. Zielbild Frontend
### 2.1 Struktur
- **Seiten (`pages/`)** bleiben Routing-Einstiege und Komposition; **keine** Dauerlösung für Logikblöcke > ~400–500 Zeilen in einer Datei – Auslagerung in `components/`, `hooks/`, `features/<name>/`.
- **Feature-Ordner (Ziel):** wo sinnvoll `frontend/src/features/<domäne>/` mit klarer Grenze: UI + feature-spezifische Hooks; geteilte Helfer in `utils/` nur wenn domänenübergreifend.
- **State:** Server-State über API (keine Business-Duplikation); UI-State lokal oder in bestehenden Contexts nur, wenn mehrere Schichten der Shell betroffen sind.
### 2.2 Performance und schwache Endgeräte
- Route-basiertes Code-Splitting bleibt Standard; **zusätzlich** innere `dynamic import()` für schwere Pakete (PDF, grosse Editoren), sobald eine Route sie braucht.
- Lange Listen: **Virtualisierung** ab einer projektdefinierten Schwelle (siehe Regeln).
- Globale Daten (Posteingang, Badges): **bedarfsgesteuert oder mit klar dokumentiertem Cache/TTL**, nicht pauschal jede Session mit voller Last – konkrete Strategie in Roadmap/Remediation.
### 2.3 API-Schicht im Client
- **Ziel:** Aufteilung des heutigen `utils/api.js`-Monolithen in **domänenspezifische Module** (z. B. `api/exercises`, `api/planning`, `api/media`), mit einer dünnen **Barrel- oder Facade-Export** für Kompatibilität während der Migration.
- **Konstante:** alle HTTP-Aufrufe mit Token/Mandanten-Headern zentral; kein Rohtransport aus Komponenten.
---
## 3. Zielbild Backend / API
- **Router-Disziplin** unverändert: ein fachliches Modul, ein Router (bestehende Architekturregeln).
- **Read-Model / Summary-Endpoints** für Dashboards und wiederkehrende Kacheln: **eine** abgestimmte Antwort pro Bildschirm, wo heute mehrere Listen parallel zusammengerechnet werden – unter strikt gleicher Sichtbarkeitslogik wie die Einzel-Endpoints.
- **Listen:** sortierte Indizes passend zu `WHERE` + `ORDER BY`; für grosse Datenmengen langfristig **Keyset-Pagination** statt tiefer Offsets.
- **Schwere Queries:** Korrelierte Subqueries pro Zeile nur, wenn messbar unkritisch; sonst JOIN-/Aggregate-Refactoring mit Review.
---
## 4. Zielbild Datenhaltung
- PostgreSQL bleibt System der Wahrheit; Migrationen nummeriert, wie heute.
- Kein Mandanten-Cache ohne expliziten Key und Invalidierungskonzept (Regeldokument).
---
## 5. Einbindung neuer Features (vereinbartes Muster)
1. Fachliche Kurzspez (oder Ticket) mit **Sichtbarkeit** und **Nutzungskontext** (Mobile/Desktop, erwartete Listenlängen).
2. API-Design: Endpoints, Payload-Grösse, Paginierung; Zugriffsschicht-Check.
3. UI-Modul: Route lazy, Komponentengrösse, ggf. Virtualisierung.
4. Messung: minimal Lighthouse/Netzwerk oder Server-Timing für den neuen Pfad.
5. Audit-Eintrag bei neuen geschützten Endpoints (bestehendes Verfahren).
---
## 6. Nicht-Ziele dieses Zielbilds
- Ersetzen der Zugriffsschicht oder der Medien-Spec.
- Microservices oder zweite Schreib-Datenbank ohne ausdrücklichen Projektbeschluss.
- „Framework-Wechsel“ (React bleibt, solange nicht separat entschieden).
---
## 7. Abnahme „Zielbild erreicht“ (high level)
- Keine bekannten **God-Pages** oberhalb dokumentierter Schwellen ohne dokumentierte Ausnahme.
- API-Client modularisiert oder klar phasierter Migrationsstand mit festem Enddatum.
- Dashboard und vergleichbare Homescreens ohne redundante Mehrfach-Listen desselben Objekttyps (oder dokumentierte technische Begründung + Messung).
- Datenbank-Lesepfade der Top-5-Listen unter definierter Latenz-Schwelle auf Referenz-Hardware in Lasttests (Werte in Roadmap festzulegen).
+6 -2
View File
@@ -5,9 +5,12 @@
"scripts": {
"dev": "vite --port 3098",
"build": "vite build",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@tanstack/react-virtual": "^3.13.24",
"jspdf": "^4.2.1",
"lucide-react": "^0.344.0",
"marked": "^18.0.3",
@@ -19,6 +22,7 @@
},
"devDependencies": {
"@vitejs/plugin-react": "^4.2.1",
"vite": "^5.1.4"
"vite": "^5.1.4",
"vitest": "^3.0.5"
}
}
+106 -46
View File
@@ -1,4 +1,4 @@
import React from 'react'
import React, { Suspense, lazy } from 'react'
import {
RouterProvider,
createBrowserRouter,
@@ -8,49 +8,77 @@ import {
Outlet,
} from 'react-router-dom'
import { AuthProvider, useAuth } from './context/AuthContext'
import { FormEditorActionsProvider, FormEditorBottomSlot } from './context/FormEditorActionsContext'
import { ToastProvider } from './context/ToastContext'
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
import DesktopSidebar from './components/DesktopSidebar'
import { getMainNavItems } from './config/appNav'
import LoginPage from './pages/LoginPage'
import VerifyPage from './pages/VerifyPage'
import Dashboard from './pages/Dashboard'
import AccountSettingsPage from './pages/AccountSettingsPage'
import SettingsSystemInfoPage from './pages/SettingsSystemInfoPage'
import ExercisesListPage from './pages/ExercisesListPage'
import ExerciseDetailPage from './pages/ExerciseDetailPage'
import ExerciseFormPage from './pages/ExerciseFormPage'
import ClubsPage from './pages/ClubsPage'
import InboxPage from './pages/InboxPage'
import SkillsPage from './pages/SkillsPage'
import TrainingPlanningPage from './pages/TrainingPlanningPage'
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
import TrainingFrameworkProgramEditPage from './pages/TrainingFrameworkProgramEditPage'
import TrainingModulesListPage from './pages/TrainingModulesListPage'
import TrainingModuleEditPage from './pages/TrainingModuleEditPage'
import TrainingUnitRunPage from './pages/TrainingUnitRunPage'
import TrainingCoachPage from './pages/TrainingCoachPage'
import AdminCatalogsPage from './pages/AdminCatalogsPage'
import AdminHierarchyPage from './pages/AdminHierarchyPage'
import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
import TrainerContextsPage from './pages/TrainerContextsPage'
import MediaWikiImportPage from './pages/MediaWikiImportPage'
import AdminUsersPage from './pages/AdminUsersPage'
import AdminHomeRedirect from './components/AdminHomeRedirect'
import PlatformAdminRoute from './components/PlatformAdminRoute'
import MediaLibraryPage from './pages/MediaLibraryPage'
import LegalPage from './pages/LegalPage'
import AdminLegalDocumentsPage from './pages/AdminLegalDocumentsPage'
import SettingsLegalPage from './pages/SettingsLegalPage'
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
import './app.css'
const LoginPage = lazy(() => import('./pages/LoginPage'))
const VerifyPage = lazy(() => import('./pages/VerifyPage'))
const Dashboard = lazy(() => import('./pages/Dashboard'))
const AccountSettingsPage = lazy(() => import('./pages/AccountSettingsPage'))
const SettingsSystemInfoPage = lazy(() => import('./pages/SettingsSystemInfoPage'))
const ExercisesListPage = lazy(() => import('./pages/ExercisesListPage'))
const ExerciseDetailPage = lazy(() => import('./pages/ExerciseDetailPage'))
const ExerciseFormPage = lazy(() => import('./pages/ExerciseFormPage'))
const ClubsPage = lazy(() => import('./pages/ClubsPage'))
const InboxPage = lazy(() => import('./pages/InboxPage'))
const SkillsPage = lazy(() => import('./pages/SkillsPage'))
const TrainingPlanningPage = lazy(() => import('./pages/TrainingPlanningPage'))
const TrainingPlanTemplatesListPage = lazy(() => import('./pages/TrainingPlanTemplatesListPage'))
const TrainingPlanTemplateEditPage = lazy(() => import('./pages/TrainingPlanTemplateEditPage'))
const PlanningLayout = lazy(() => import('./layouts/PlanningLayout'))
const TrainingFrameworkProgramsListPage = lazy(() =>
import('./pages/TrainingFrameworkProgramsListPage'),
)
const TrainingFrameworkProgramEditPage = lazy(() =>
import('./pages/TrainingFrameworkProgramEditPage'),
)
const TrainingModulesListPage = lazy(() => import('./pages/TrainingModulesListPage'))
const TrainingModuleEditPage = lazy(() => import('./pages/TrainingModuleEditPage'))
const TrainingUnitRunPage = lazy(() => import('./pages/TrainingUnitRunPage'))
const TrainingUnitEditPage = lazy(() => import('./pages/TrainingUnitEditPage'))
const TrainingCoachPage = lazy(() => import('./pages/TrainingCoachPage'))
const AdminCatalogsPage = lazy(() => import('./pages/AdminCatalogsPage'))
const AdminHierarchyPage = lazy(() => import('./pages/AdminHierarchyPage'))
const AdminMaturityModelsPage = lazy(() => import('./pages/AdminMaturityModelsPage'))
const TrainerContextsPage = lazy(() => import('./pages/TrainerContextsPage'))
const MediaWikiImportPage = lazy(() => import('./pages/MediaWikiImportPage'))
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. */
function computeShowAdminNav(currentUser) {
return currentUser?.role === 'superadmin'
}
function AppRouteFallback() {
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'var(--bg)',
}}
>
<div className="spinner"></div>
</div>
)
}
// Bottom Navigation (Mobile)
function Nav({ showAdminNav }) {
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
@@ -120,22 +148,26 @@ function ProtectedLayout() {
return (
<OrgInboxProvider user={user}>
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
<div className="app-shell">
<div className="app-shell__column">
<div className="app-header app-header--mobile app-header--mobile-stack">
<div className="app-header-mobile__top">
<div className="app-logo">🥋 Shinkan</div>
<FormEditorActionsProvider>
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
<div className="app-shell">
<div className="app-shell__column">
<div className="app-header app-header--mobile app-header--mobile-stack">
<div className="app-header-mobile__top">
<div className="app-logo">🥋 Shinkan</div>
</div>
<ActiveClubSwitcher variant="mobile" />
</div>
<ActiveClubSwitcher variant="mobile" />
<div className="app-main">
<InactiveMembershipBanner />
<Outlet />
</div>
<FormEditorBottomSlot>
<Nav showAdminNav={showAdminNav} />
</FormEditorBottomSlot>
</div>
<div className="app-main">
<InactiveMembershipBanner />
<Outlet />
</div>
<Nav showAdminNav={showAdminNav} />
</div>
</div>
</FormEditorActionsProvider>
</OrgInboxProvider>
)
}
@@ -202,15 +234,25 @@ const appRouter = createBrowserRouter([
{ path: 'clubs', element: <ClubsPage /> },
{ path: 'inbox', element: <InboxPage /> },
{ path: 'skills', element: <SkillsPage /> },
{
path: 'planning',
element: <PlanningLayout />,
children: [
{ index: true, element: <TrainingPlanningPage /> },
{ path: 'framework-programs', element: <TrainingFrameworkProgramsListPage /> },
{ path: 'training-modules', element: <TrainingModulesListPage /> },
{ path: 'plan-templates', element: <TrainingPlanTemplatesListPage /> },
{ path: 'units/new', element: <TrainingUnitEditPage /> },
{ path: 'units/:id/edit', element: <TrainingUnitEditPage /> },
],
},
{ path: 'planning/framework-programs/new', element: <TrainingFrameworkProgramEditPage /> },
{ path: 'planning/framework-programs/:id', element: <TrainingFrameworkProgramEditPage /> },
{ path: 'planning/framework-programs', element: <TrainingFrameworkProgramsListPage /> },
{ path: 'planning/training-modules/new', element: <TrainingModuleEditPage /> },
{ path: 'planning/training-modules/:id', element: <TrainingModuleEditPage /> },
{ path: 'planning/training-modules', element: <TrainingModulesListPage /> },
{ path: 'planning/plan-templates/:id', element: <TrainingPlanTemplateEditPage /> },
{ path: 'planning/run/:unitId/coach', element: <TrainingCoachPage /> },
{ path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
{ path: 'planning', element: <TrainingPlanningPage /> },
{ path: 'admin', element: <AdminHomeRedirect /> },
{
path: 'admin/users',
@@ -260,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 /> },
],
},
@@ -270,7 +328,9 @@ function App() {
return (
<AuthProvider>
<ToastProvider>
<RouterProvider router={appRouter} />
<Suspense fallback={<AppRouteFallback />}>
<RouterProvider router={appRouter} />
</Suspense>
</ToastProvider>
</AuthProvider>
)
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more