217 Commits
Author SHA1 Message Date
Lars a1b85cd865 Merge pull request 'Bug_fixes' (#45) from develop into main
Test Suite / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 44s
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 / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / lint-backend (pull_request) Successful in 0s
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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 45s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 15s
Deploy Development / deploy (push) Successful in 38s
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 / playwright-tests (push) Successful in 1m22s
Test Suite / pytest-backend (push) Successful in 37s
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 / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Failing after 22s
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
Test Suite / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 1m2s
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 / k6 /health Baseline (push) Successful in 48s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 1m28s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m16s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / k6 /health Baseline (push) Successful in 33s
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 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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
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 / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 42s
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 / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 42s
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 / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 38s
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
Deploy Development / deploy (push) Successful in 44s
Test Suite / k6 /health Baseline (push) Successful in 35s
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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 47s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / lint-backend (pull_request) Successful in 0s
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 / playwright-tests (push) Successful in 1m20s
Test Suite / pytest-backend (push) Successful in 37s
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 / playwright-tests (push) Successful in 1m27s
Test Suite / pytest-backend (push) Successful in 36s
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 / playwright-tests (push) Successful in 1m29s
Test Suite / pytest-backend (push) Successful in 39s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
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 / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m14s
Test Suite / lint-backend (push) Successful in 0s
- 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
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Waiting to run
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 / playwright-tests (push) Has been cancelled
Test Suite / pytest-backend (push) Successful in 38s
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
Test Suite / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 43s
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 / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 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 / playwright-tests (push) Successful in 1m19s
Test Suite / pytest-backend (push) Successful in 34s
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
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 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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 45s
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 / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
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
Test Suite / build-frontend (push) Successful in 16s
Deploy Production / deploy (push) Successful in 47s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
Test Suite / pytest-backend (push) Successful in 37s
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 / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 36s
Test Suite / lint-backend (pull_request) Successful in 0s
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
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 40s
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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 44s
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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 42s
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
Test Suite / k6 /health Baseline (push) Successful in 34s
Deploy Development / deploy (push) Successful in 41s
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 / playwright-tests (push) Successful in 1m12s
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 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
Test Suite / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 44s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 35s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
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 / playwright-tests (push) Successful in 1m11s
Test Suite / pytest-backend (push) Successful in 38s
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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 40s
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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 45s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 38s
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 / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
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
Test Suite / k6 /health Baseline (push) Successful in 34s
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
- 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 / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 36s
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 / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 41s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
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 / pytest-backend (push) Successful in 37s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / playwright-tests (pull_request) Successful in 1m20s
Test Suite / lint-backend (push) Successful in 0s
- 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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 37s
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
Test Suite / k6 /health Baseline (push) Successful in 33s
Deploy Development / deploy (push) Successful in 39s
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
Deploy Development / deploy (push) Successful in 42s
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
- 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
Test Suite / k6 /health Baseline (push) Successful in 33s
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 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
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
- 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
Test Suite / k6 /health Baseline (push) Successful in 33s
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 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 / 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.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 / playwright-tests (push) Successful in 1m21s
Test Suite / pytest-backend (push) Successful in 36s
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
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 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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 45s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 12s
Deploy Development / deploy (push) Successful in 41s
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
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 43s
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 / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (pull_request) Successful in 34s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m5s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
Test Suite / playwright-tests (pull_request) Successful in 1m8s
Test Suite / lint-backend (push) Successful in 0s
- 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 / playwright-tests (push) Successful in 1m28s
Test Suite / pytest-backend (push) Successful in 35s
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
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Waiting to run
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
Lars 81d1e9bdfd Merge pull request 'minor improvements. Darstellung, Handlung, Popups' (#32) from develop into main
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #32
2026-05-13 22:02:42 +02:00
LarsandClaude Sonnet 4.6 85163ad440 feat(exercise-detail): add embedded peek functionality for individual exercises
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 / build-frontend (pull_request) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 55s
- Introduced `ExercisePeekModal` to allow users to view details of individual exercises without navigating away from the Exercise Detail Page.
- Updated the UI to include a button interaction for peeking at exercises, enhancing user experience and accessibility.
- Modified the description in the Exercise Detail section to clarify the new peek feature and its functionality.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 21:58:24 +02:00
LarsandClaude Sonnet 4.6 502dddd3b3 feat(combo-planning): enhance candidate interaction and UI for combination exercises
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new CSS styles for interactive candidate buttons and links in the `CombinationPlanBracket` and `CombinationCoachSlots` components, improving user engagement.
- Updated `CombinationPlanBracket` to conditionally render candidates as buttons or links based on interaction type, enhancing navigation options.
- Refactored candidate handling in `CombinationCoachSlots` to support new interaction methods, streamlining candidate exercise display.
- Enhanced `ExercisePeekModal` and related components to support candidate peek functionality, allowing for a more seamless user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 21:51:52 +02:00
LarsandClaude Sonnet 4.6 00edc7a93d feat(exercise-detail): enhance combination exercise display with candidate links and bracket visualization
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `flattenCombinationCandidateLinks` function to streamline the extraction of unique candidate exercises for combination details.
- Updated the `ExerciseDetailPage` to conditionally render a `CombinationPlanBracket` for combination exercises, improving the visual representation of training runs.
- Enhanced the UI to display linked individual exercises associated with combination slots, providing clearer navigation and context for users.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 21:41:32 +02:00
LarsandClaude Sonnet 4.6 d50bed428b refactor(App): migrate to Data Router for improved routing and unsaved changes handling
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Replaced `BrowserRouter` and `Routes` with `createBrowserRouter` and `RouterProvider` to support unsaved changes blocking.
- Restructured route definitions for better organization and clarity, maintaining existing functionality.
- Added comments to clarify the necessity of the Data Router for handling unsaved changes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:19:59 +02:00
LarsandClaude Sonnet 4.6 49adb395dd feat(version): bump to 0.8.110 and update project specifications
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m15s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.110 and database schema version to 20260512057, reflecting recent enhancements.
- Revised project status documentation to include new versioning and next steps for development.
- Enhanced the functional specification for training modules and combination exercises, detailing upcoming features and improvements.
- Improved technical specifications to align with the latest code changes, ensuring consistency across documentation.
- Introduced new UI elements for toast notifications and unsaved changes prompts to enhance user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 16:34:38 +02:00
Lars 3214055531 Merge pull request 'Module und Kombinationsübnungen in Version 0.8' (#31) from develop into main
Test Suite / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 54s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #31
2026-05-13 16:16:49 +02:00
LarsandClaude Sonnet 4.6 81fd7d9b3b feat(training-unit-editor): enhance combo planning UI and functionality
Test Suite / build-frontend (push) Successful in 11s
Test Suite / pytest-backend (pull_request) Successful in 33s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 10s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m2s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 1m2s
- Updated CSS for the combo planning strip to improve layout and visual consistency.
- Refactored `compactComboPlanningCaption` to simplify the display of planning status.
- Introduced a new utility function to infer advance mode from stored slot rows, enhancing profile handling.
- Improved merging logic for slot profiles to ensure accurate representation of advance modes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 15:49:14 +02:00
LarsandClaude Sonnet 4.6 3898e8bc2c feat(training-planning): enhance planning method profile handling and UI updates
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Integrated PsycopgJson for improved handling of planning method profiles in the backend.
- Updated CombinationPlanBracket to display primary load labels for better clarity in the UI.
- Enhanced TrainingUnitSectionsEditor and utility functions to ensure proper serialization of planning profiles, preventing potential errors during API interactions.
- Improved CSS for combo plan brackets to enhance visual alignment and presentation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 15:28:37 +02:00
LarsandClaude Sonnet 4.6 d3ddc52118 feat(combo-planning): enhance combination profile handling and UI improvements
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated CombinationCoachSlots to integrate a new function for formatting inline profile values, improving data display consistency.
- Refactored CombinationMethodProfileEditor to streamline slot index handling and enhance title clarity.
- Improved CombinationPlanBracket by removing unnecessary elements for a cleaner UI.
- Enhanced ExerciseFullContent to support additional catalog method profile snapshots, improving exercise detail accuracy.
- Updated CSS for combo plan brackets to enhance visual presentation and alignment.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 14:42:01 +02:00
Lars 79dabbca5a feat(combo-planning): replace summarizeSlotProfileBrief with effectiveStationTimingSummary
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 43s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Updated CombinationCoachSlots, CombinationPlanBracket, and TrainingUnitSectionsEditor components to utilize effectiveStationTimingSummary for improved timing display.
- Adjusted station title handling to enhance clarity and consistency across components.
- Refactored utility functions to streamline slot timing summaries and improve overall user experience in combination planning.
2026-05-13 14:34:17 +02:00
LarsandClaude Sonnet 4.6 ed15f73727 feat(combo-planning): enhance modal UI and styling for combination planning editing
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Successful in 58s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 1s
- Updated the TrainingUnitSectionsEditor to integrate new CSS classes for the combo planning modal, improving the visual consistency with the exercise preview.
- Added responsive design features to the modal, including max-width and max-height adjustments for better usability on different screen sizes.
- Introduced new toolbar and hint elements to enhance user interaction and provide clearer guidance within the combo planning context.
- Refactored existing modal structure for improved accessibility and user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 14:25:58 +02:00
LarsandClaude Sonnet 4.6 a8942a9e4e feat(version): bump to 0.8.110 and enhance combination exercise features
Test Suite / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Successful in 40s
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 app version to 0.8.110, reflecting recent improvements in combination exercise handling.
- Introduced `load_combination_slots_for_exercise` function to streamline fetching combination slots for exercises.
- Enhanced `TrainingPlanningPage` and `ExercisePeekModal` to utilize the new combination slots functionality, improving user experience.
- Updated changelog to document the latest changes and feature enhancements.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 14:24:55 +02:00
LarsandClaude Sonnet 4.6 5dc93d9a8c feat(training-unit-editor): integrate new summary function and enhance combination exercise display
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `summarizeSlotProfileBrief` utility for concise slot profile summaries, improving the display of combination exercises.
- Updated `CombinationCoachSlots` and `ExercisePeekModal` components to utilize the new summary function for better user experience.
- Enhanced `TrainingUnitSectionsEditor` to manage combination slots more effectively, including improved title handling and display options.
- Adjusted `TrainingPlanningPage` to support additional peek context for combination exercises, streamlining the planning process.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 14:11:53 +02:00
LarsandClaude Sonnet 4.6 805ad3c5a5 feat(training-unit-editor): enhance combination slots handling and UI improvements
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- Added support for `compactPlanningView` and `omitGlobalKeyValueBlock` in the CombinationCoachSlots component to improve display options.
- Updated the TrainingUnitSectionsEditor to fetch and manage combination slots more effectively, including new state management for modal interactions.
- Introduced a new utility function `comboSlotsOutlineForProfileEditor` to streamline the display of combination slots in the editor.
- Enhanced UI elements for better user experience when managing combination exercises and their associated slots.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 09:58:59 +02:00
LarsandClaude Sonnet 4.6 13efce6e36 feat(training-unit-editor): enhance combo planning features and UI updates
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 1m0s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added a new function `compactComboPlanningCaption` to display planning status with archetype labels.
- Introduced state management for a modal to edit combination planning profiles, improving user interaction.
- Updated UI components to enhance the display and interaction of combination exercises, including styling adjustments for better usability.
- Implemented keyboard event handling for modal closure, enhancing user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 09:06:10 +02:00
LarsandClaude Sonnet 4.6 cf9932990e feat(version): bump to 0.8.109 and enhance combination exercise features
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.109, reflecting recent improvements in combination exercise handling.
- Introduced `rep_series_count` for slot profiles, allowing for multiple series in `rep` and `manual` modes, enhancing flexibility in exercise configurations.
- Updated the CombinationMethodProfileEditor and CombinationCoachSlots components to support and display the new series count feature.
- Enhanced ExerciseFormPage to manage series count and intra-series pauses effectively, improving user experience.
- Documented changes in the changelog for better tracking of feature enhancements.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 08:58:41 +02:00
LarsandClaude Sonnet 4.6 38d84ecdf6 feat(version): bump to 0.8.106 and enhance combination exercise features
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 55s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.106, reflecting recent improvements in combination exercise handling.
- Introduced `advance_mode` for slot profiles, allowing for flexible timing options (timed, repetitions, manual) in the CombinationMethodProfileEditor.
- Enhanced the CombinationCoachSlots component to display timing summaries based on the selected advance mode.
- Updated ExerciseFormPage to manage combination slots with new validation and user feedback for exercise selection.
- Documented changes in the changelog for better tracking of feature enhancements.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 08:19:46 +02:00
LarsandClaude Sonnet 4.6 ce63d46cf4 feat(version): bump to 0.8.105 and enhance combination exercise features
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.105, reflecting recent improvements in combination exercise handling.
- Added support for per-slot timing options in the CombinationMethodProfileEditor, allowing for more flexible exercise configurations.
- Enhanced the ExerciseFormPage to manage combination slots more effectively, including new functions for reordering and merging exercises.
- Updated changelog to document the latest changes and improvements.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 07:53:00 +02:00
LarsandClaude Sonnet 4.6 435da7f17a feat(version): bump to 0.8.104 and enhance combination exercise features
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.104, reflecting recent improvements in combination exercise handling.
- Enhanced the CombinationMethodProfileEditor to support structured slot timing profiles without requiring JSON input from trainers.
- Introduced quick ratio presets for circuit and interval training methods, improving user experience in setting up training profiles.
- Updated documentation and changelog to reflect new features and integration details.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 07:38:44 +02:00
LarsandClaude Sonnet 4.6 4e654e50c0 feat(version): bump to 0.8.103 and enhance planning method profile integration
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.103, reflecting recent enhancements in training planning.
- Incremented database schema version to 20260512057, ensuring compatibility with new features.
- Introduced optional `planning_method_profile` for combination exercises, allowing for detailed planning and coaching support.
- Enhanced frontend components to manage and display planning method profiles effectively in the Training Unit Sections Editor and ExerciseFullContent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 07:21:33 +02:00
LarsandClaude Sonnet 4.6 12fd3926b2 feat(combination-exercises): enhance method profile integration and update specifications
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 1m4s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.102, reflecting recent enhancements in combination exercises.
- Introduced structured method profiles for combination exercises, allowing for detailed planning and coaching support.
- Enhanced frontend components to display method profiles in the Exercise and Combination Coach views.
- Updated documentation to include new specifications and implementation details for method archetypes and profiles.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 07:16:58 +02:00
LarsandClaude Sonnet 4.6 919910d52a feat(version): bump to 0.8.101 and update exercise module versions
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.101, reflecting recent enhancements.
- Incremented exercise module version to 2.24.1, improving handling of combination exercises.
- Added changelog entry for new features related to training-coach functionality in combination exercises.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 06:36:50 +02:00
LarsandClaude Sonnet 4.6 3dc4c9c79e feat(exercises): update to version 0.8.100 and enhance combination exercise handling
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Bumped app version to 0.8.100, reflecting recent updates.
- Improved validation logic for combination exercises in the backend, ensuring proper handling of exercise variants.
- Enhanced frontend components, including the ExercisePickerModal, to support filtering and displaying combination exercises.
- Updated API payloads and utility functions to accommodate new exercise types and their properties.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 06:30:53 +02:00
LarsandClaude Sonnet 4.6 8a9f9f960f feat(exercises): introduce combination exercises and enhance exercise management
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.99, reflecting the addition of combination exercises.
- Implemented new data structures and validation for combination slots and archetypes in the backend.
- Enhanced frontend components to support selection and display of combination exercises, including new UI elements for managing slots and archetypes.
- Updated API payload handling to accommodate new exercise types and their associated data.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 06:12:47 +02:00
LarsandClaude Sonnet 4.6 f4f5642c21 feat(profiles): add training planning preferences to user profile
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `training_planning_prefs` field in the ProfileUpdate model to store user-specific UI options for training planning.
- Updated the backend to handle the new preferences during profile updates, ensuring proper validation and storage.
- Enhanced the frontend to allow users to select their preferred display mode for training modules in the Account Settings page.
- Updated version to 0.8.98 and adjusted database schema version accordingly, reflecting the new feature integration.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 22:36:19 +02:00
LarsandClaude Sonnet 4.6 05042ee9ec feat(training-units): add compact legend and module styling in Training Unit Sections Editor
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new CSS styles for compact module display, enhancing the visual structure of training unit sections.
- Implemented functionality to conditionally render module tags and borders based on the selected UX mode.
- Enhanced the section module legend model to aggregate and display module information effectively.
- Improved the rendering logic to support both compact and standard views, ensuring a flexible user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 22:30:55 +02:00
LarsandClaude Sonnet 4.6 e96951728d feat(training-units): enhance training unit sections with new module display and functionality
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 30s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for module display, including a structured layout for exercises and notes within the Training Unit Sections Editor.
- Implemented a function to gather and render module outlines, improving the visibility of exercises and notes associated with training modules.
- Enhanced the TrainingPlanningPage to support module search and preview functionality, allowing users to filter and view module details before applying them.
- Improved state management for module application, ensuring a smoother user experience when inserting modules into training plans.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 22:17:44 +02:00
LarsandClaude Sonnet 4.6 bfaf532ab2 feat(training-units): enhance section editing with insert functionality
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for insert slots and buttons to improve UI for adding items between sections.
- Implemented functionality in the TrainingUnitSectionsEditor to allow users to insert notes and exercises at specified positions within sections.
- Updated the TrainingFrameworkProgramEditPage to support the new insert functionality, ensuring seamless integration with existing features.
- Enhanced state management to handle insert positions effectively, improving user experience during section editing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 22:05:22 +02:00
LarsandClaude Sonnet 4.6 e41908af73 feat(training-planning): enhance training module integration and UI
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function to handle optional source training module IDs, ensuring proper validation and integration.
- Updated the backend to include source training module ID and title in section items, allowing for better tracking of module origins.
- Enhanced the frontend to display module bands in the Training Unit Sections Editor, improving user experience by indicating the source of exercises and notes.
- Added functionality to insert training modules at specified positions within sections, providing users with more control over their training plans.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 21:53:41 +02:00
LarsandClaude Sonnet 4.6 c1243651bb feat(training-modules): implement training module functionality and UI integration
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
- Added new API endpoints for managing training modules, including listing, creating, updating, and deleting modules.
- Implemented the ability to apply training modules to training units, allowing users to copy module content into specific sections.
- Enhanced the frontend with new pages for managing training modules and integrated modal functionality for applying modules within the training planning page.
- Updated version to 0.8.97 and adjusted database schema version accordingly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 21:35:07 +02:00
LarsandClaude Sonnet 4.6 59d53d6154 docs: update project status and add user overview documentation
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 1s
- Updated project status to version 0.8.96 as of 2026-05-12, reflecting recent enhancements and features.
- Added a new section for the user overview in `docs/FACHLICHE_NUTZERFUNKTIONEN.md`, providing a compact perspective for design and product teams.
- Revised references in various documents to include the new user overview and updated project status.
- Enhanced the requirements documentation to link to the user overview for better clarity.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 21:20:36 +02:00
LarsandClaude Sonnet 4.6 98edb282ed chore: bump version to 0.8.96 and enhance legal document features
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.96 with a new build date of 2026-05-12.
- Improved legal documents functionality with a live preview feature alongside the editor.
- Added modal for full document preview and updated CSS styles for better layout.
- Enhanced the AdminLegalDocumentsPage to support rendering previews of legal documents.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:22:01 +02:00
LarsandClaude Sonnet 4.6 81b9e8f601 chore: bump version to 0.8.95 and update legal documents features
Test Suite / build-frontend (push) Successful in 15s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated app version to 0.8.95 with a new build date of 2026-05-12.
- Enhanced legal documents functionality to support section numbering and Markdown formatting in the output.
- Updated dependencies in package.json to include 'marked' and 'react-markdown'.
- Added new CSS styles for legal document presentation.
- Refactored PDF generation logic to incorporate new metadata and improved document structure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 10:52:06 +02:00
Lars 4c974620d8 Merge pull request 'DGSVO Compliance update 1' (#30) from develop into main
Test Suite / build-frontend (push) Successful in 12s
Deploy Production / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #30
2026-05-12 06:34:14 +02:00
LarsandClaude Sonnet 4.6 04663e090a docs: update compliance docs and HANDOVER to reflect P-13 full state (0.8.94)
Test Suite / build-frontend (push) Successful in 10s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 1m3s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 55s
- compliance-implementation.md: expand P-13 section with all extensions
  (0.8.88-0.8.94: audit log, email notifications, club-admin rights,
  workflow bar, archive split, badge, CI fix); update test summary to
  159 passed; add operativ check items 9-13 for P-13 extensions;
  bump app version header to 0.8.94
- compliance-package-register.md: expand P-13 Letzter Stand with full
  extension list through 0.8.94; update Fortschritt version
- compliance-roadmap.md: update app version to 0.8.94; P-13 row in
  Schnellreferenz marked done (was showing as "next recommended");
  Etappe B P-13 hint updated with full feature summary
- HANDOVER.md: update app version header to 0.8.94; §5b P-13 section
  rewritten with complete feature list including all 0.8.88-0.8.94
  additions; §6 next session updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 06:28:35 +02:00
LarsandClaude Sonnet 4.6 56fc6d853d fix(P-13): repair 3 failing CI pytest tests for content_reports
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 59s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 1s
- Add early 403 in set_legal_hold_from_report for plain admin (before DB
  call), fixing test_legal_hold_from_report_requires_superadmin
- Update test_list_inbox_requires_platform_admin to mock DB COUNT query
  (returns cnt=0) so it exercises the club_admin code path correctly
- Extend test_patch_report_under_review mock row with target_type,
  target_id, resolution_note fields now required by the audit-log path

version: 0.8.94
module:  content_reports 1.5.1

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 22:25:23 +02:00
LarsandClaude Sonnet 4.6 5cf61289ec feat(P-13): Club-Admin Bearbeitung + Archiv-Trennung in Inbox
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m3s
Test Suite / pytest-backend (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
Berechtigungen:
- Club-Admins koennen Meldungen zu Vereinsmedien bearbeiten (PATCH + GET-Detail)
- Club-Admins koennen Legal Hold auf Vereinsmedien (visibility != 'official') setzen
- Neue Helfer: _assert_can_manage_report, _assert_can_set_legal_hold_from_report
- set_legal_hold_from_report: Superadmin-Only aufgehoben fuer Vereinsebene

Inbox UI:
- Offene Meldungen (submitted/under_review) im Hauptbereich
- Abgeschlossene Meldungen im kollabierbaren Archiv (standardmaessig zugeklappt)
- Legal-Hold-Button sichtbar fuer Club-Admins bei nicht-offiziellen Medien
- isClubAdmin + isPlatformAdmin aus OrgInboxContext verfuegbar

version: 0.8.93

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 22:15:29 +02:00
LarsandClaude Sonnet 4.6 9af28faa35 fix(P-13): exercises.name -> exercises.title (500 in Inbox und Detail-Endpoint)
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 1m4s
Test Suite / pytest-backend (push) Failing after 36s
Test Suite / lint-backend (push) Successful in 0s
Die Tabelle exercises hat keine Spalte 'name', sondern 'title'.
Alle drei Stellen korrigiert: list_inbox (beide Branches) + get_content_report + Email-Lookup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:37:23 +02:00
LarsandClaude Sonnet 4.6 34e93101f1 feat(P-13): Workflow-Management, Fehleranzeige, Badge-Update, Wieder-öffnen
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Failing after 41s
Test Suite / lint-backend (push) Successful in 0s
- InboxPage: Workflow-Balken (Eingegangen > In Bearbeitung > Abgeschlossen)
- InboxPage: Meldungen können nach Abschluss wieder geöffnet werden (PATCH status=submitted)
- InboxPage: Bearbeitungskommentar separat speicherbar; Reviewer + Datum sichtbar
- InboxPage: Fehler beim Laden von Meldungen wird angezeigt statt leerem Bereich
- OrgInboxContext: contentReportsError State exposed
- ReportContentModal: onSuccess Callback -> Badge in Medienbibliothek sofort aktuell
- content_reports PATCH: Reviewer-Felder werden beim Wieder-öffnen zurückgesetzt
- content_reports PATCH: Kommentar-Änderungen ohne Statuswechsel werden im Audit-Log protokolliert

version: 0.8.92

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:32:44 +02:00
LarsandClaude Sonnet 4.6 bb4d927090 fix(P-13): leserliche Journals, readOnly-Felder, Meldungs-Badge auf Medienkacheln
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Failing after 36s
Test Suite / lint-backend (push) Successful in 0s
- ReportContentModal: Name/E-Mail readOnly fuer eingeloggte Nutzer
- MediaLibraryPage: content_report_filed im Journal leserlich (Meldegrund, Prioritaet, Status DE)
- MediaLibraryPage: Badge auf Medienkacheln zeigt offene Meldungsanzahl (nur Admins)
- media_assets.py: open_report_count Subquery fuer Admin-Sicht in Listendaten
- Inbox-500-Fix: ma.media_kind -> ma.mime_type (alle 3 Stellen)
- PATCH content_reports: Statuswechsel wird in Audit-Log protokolliert
- E-Mails: Dateiname statt Medium-ID, lesbarer Inhalt

version: 0.8.91

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:16:21 +02:00
LarsandClaude Sonnet 4.6 8dd748e7d9 fix(P-13): include legal_hold_set/released in audit log constraint (migration 053)
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 58s
Test Suite / pytest-backend (push) Failing after 34s
Test Suite / lint-backend (push) Successful in 0s
Die CHECK-Constraint auf media_asset_audit_log.event_type schloss
legal_hold_set und legal_hold_released aus, die P-11 bereits in
bestehende Zeilen geschrieben hatte (CREATE TABLE IF NOT EXISTS hatte
die Constraint in Migration 050 nie angewendet).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 19:43:23 +02:00
Lars bacba311ae feat(P-13): implement content reporting enhancements, including email notifications and audit log entries
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 3m41s
Test Suite / pytest-backend (push) Failing after 0s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 19:36:23 +02:00
Lars 24bf3f7035 feat(P-13): update app version to 0.8.89, implement MediaPreviewModal and reporting functionality across media components
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 18:43:05 +02:00
Lars 0dbcd4175c feat: add report button for active media items without legal hold
Test Suite / build-frontend (push) Successful in 11s
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 1s
2026-05-11 18:15:27 +02:00
Lars 2f7e1e50ad feat(P-13): add content reporting functionality with modal and update version to 0.8.88
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 18:08:57 +02:00
Lars 60709df615 feat: Implement Content Reporting Backend
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 58s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Added new API endpoints for content reporting, including submission, retrieval, and status updates.
- Created database migration for `content_reports` table to store report data.
- Integrated content reports into the existing admin inbox for better management.
- Implemented validation for report submissions, including required fields and email format.
- Added tests for content reporting functionality, covering various scenarios and edge cases.
- Updated frontend API utility to include new content report methods.
- Bumped app version to 0.8.87 and updated relevant page versions.
2026-05-11 17:54:53 +02:00
Lars 3c0e63757c feat(compliance): update compliance documents to reflect app version 0.8.86 and finalize P-11 implementation details
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 55s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 13:42:21 +02:00
Lars ee54f8380f feat(P-11): implement legal hold functionality for media assets and update app version to 0.8.86
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 39s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 13:34:41 +02:00
Lars f79f83e8f9 feat(P-11): enhance media asset handling with legal hold attributes and update version to 0.8.85
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 54s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 13:07:52 +02:00
Lars fb8837574e feat(exercise): add support for exercise variants in ExerciseFullContent and related components
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 55s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Updated ExerciseFullContent to accept a new `variantId` prop and display variant-specific information.
- Enhanced TrainingCoachPage to pass `variantId` when rendering ExerciseFullContent.
- Refactored TrainingUnitRunPage to manage exercise context with variant support, including updates to modal handling.
- Improved UI to show variant details, including name, description, and execution changes where applicable.
2026-05-11 12:44:09 +02:00
Lars 1ce6d929ce feat(P-11): Implement Legal Hold functionality for media assets
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 54s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
- Added backend support for Legal Hold with new endpoints to set and release holds on media assets.
- Introduced new database columns for managing Legal Hold status and reasons.
- Updated frontend to include UI elements for setting and releasing Legal Holds, including a confirmation dialog.
- Enhanced Media Library page to display Legal Hold status and actions for superadmins.
- Implemented comprehensive backend tests covering all aspects of Legal Hold functionality.
- Updated documentation to reflect changes in the upload rights specification and interface models.
- Bumped version to 0.8.84 and updated MediaLibraryPage version to 1.6.0.
2026-05-11 12:33:13 +02:00
Lars 1640fe6045 feat(compliance): update compliance documents for app version 0.8.83, including full implementation of P-06 and P-06+ features
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 54s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 12:11:30 +02:00
Lars 61baf26da6 feat(version): update app version to 0.8.83 and fix club_admin check in journal/correction endpoints
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 56s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 11:47:45 +02:00
Lars 0edc86e05a refactor(MediaLibraryPage): remove unused lcLabel function for lifecycle state
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 57s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 11:37:46 +02:00
Lars b2b7bd423d feat(audit-log): implement full audit log for media assets, including visibility, copyright, metadata, and lifecycle changes; add correction declaration functionality
Test Suite / build-frontend (push) Failing after 3s
Deploy Development / deploy (push) Failing after 18s
Test Suite / playwright-tests (push) Successful in 55s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 10:26:50 +02:00
LarsandClaude Sonnet 4.6 56e952f084 fix(p06): declared-Status deckt alle Sichtbarkeiten ab (kein Level-Vergleich mehr)
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Successful in 58s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
- check_rights_coverage: rights_status='declared' gibt immer 'ok' zurück
  (P-06-Erklärung gilt inhaltlich, nicht sichtbarkeitsabhängig)
- assert_rights_for_promotion: 'insufficient'-Pfad entfernt
- Tests: test_declared_private_insufficient_for_club → test_declared_covers_any_visibility

version: 0.8.81
module: media_rights

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:45:06 +02:00
Lars 6586d3b68b feat(version): update app version to 0.8.80 and add changelog entries for recent fixes and enhancements
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 54s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
fix(RightsDeclarationDialog): change cancel button to icon for improved UI
feat(MediaLibraryPage): implement rights dialog for visibility promotions and enhance error handling
fix(version): update MediaLibraryPage version to 1.4.0 reflecting rights dialog changes
2026-05-11 09:39:15 +02:00
Lars fff30b49e1 fix(media-library): update username references to name in media asset queries
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m1s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 09:30:07 +02:00
Lars f544975a6c feat(media-journal): add Superadmin media journal endpoint and UI integration
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Failing after 1m5s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
2026-05-11 09:24:39 +02:00
LarsandClaude Sonnet 4.6 4bc24b4caf feat(p06): Copyright-Feld und Einwilligungskontext in Rechte-Erklaerung
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Failing after 1m2s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Migration 049: 4 optionale TEXT-Spalten in media_asset_rights_declarations
(person_consent_context, parental_consent_context, music_rights_context,
third_party_rights_context) fuer Freitext zum Einwilligungskontext.

Backend:
- media_rights.py: write_rights_declaration speichert 4 Kontextfelder
- media_assets.py: copyright_notice + 4 Kontextfelder in Bulk-Upload,
  RightsDeclarationBody, MediaAssetPatch, MediaBulkPatchBody
- exercises.py: copyright_notice + 4 Kontextfelder in upload_exercise_media,
  wird in INSERT gespeichert

Frontend (alle 3 Formulare):
- RightsDeclarationDialog: Copyright-Eingabefeld (immer sichtbar) +
  Freitext-Textarea bei jeder Ja-Antwort (Personen, Minderjaehrige,
  Musik, Fremdinhalte)
- ExerciseInlineFileMediaModal: gleiche Felder inline im Upload-Tab
- ExerciseInlineEmbedModal: gleiche Felder inline
- api.js: copyright_notice + 4 Kontextfelder in bulkUploadMediaAssets

version: 0.8.77
module: media_rights 1.1.0, media_assets 1.14.0, exercises 2.21.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:06:47 +02:00
LarsandClaude Sonnet 4.6 42aec79ad1 fix(p06): RightsDeclarationDialog als echtes Modal (admin-modal-backdrop)
Test Suite / build-frontend (push) Successful in 10s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m1s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / lint-backend (push) Successful in 1s
modal-overlay/modal-content existierten nicht im CSS und hatten kein
Styling -- daher kein Backdrop, keine Zentrierung. Umgestellt auf
admin-modal-backdrop + admin-modal-sheet wie alle anderen Modals in der App.

version: 0.8.76

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 08:51:56 +02:00
LarsandClaude Sonnet 4.6 9ac8200b41 fix(p06): P-06-Fragen direkt in Exercise-Upload-Modals eingebettet
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 42s
Test Suite / playwright-tests (push) Failing after 1m41s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Kein zweites Dialog-Overlay mehr. Die Rechte-Erklarung ist jetzt
direkt als Formular-Abschnitt im Upload-Tab von
ExerciseInlineFileMediaModal und ExerciseInlineEmbedModal integriert.

- Datei auswaehlen + Titel + Rechte-Erklaerung in einem Schritt
- Validierung beim Klick auf Hochladen (Fehler inline angezeigt)
- RightsDeclarationDialog-Import entfernt
- radio-Namen eindeutig per Praefix (up-/emb-) damit beide Modals
  unabhaengig voneinander funktionieren

version: 0.8.76

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 08:44:37 +02:00
LarsandClaude Sonnet 4.6 000e78e976 fix(p06): RightsDeclarationDialog in Exercise-Upload-Modals integriert
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Failing after 1m19s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
ExerciseInlineFileMediaModal (Upload-Tab) und ExerciseInlineEmbedModal
zeigen jetzt den vollstaendigen P-06-Einwilligungsdialog bevor der
API-Call ausgefuehrt wird. Vorher wurde der Backend-Fehler (400)
als nicht benutzbarer browser alert angezeigt.

- ExerciseInlineFileMediaModal: handleUploadAndInsert oeffnet Dialog,
  doUploadWithDecl haengt die 9 P-06-Felder an FormData an
- ExerciseInlineEmbedModal: submit oeffnet Dialog, doSubmitWithDecl
  haengt P-06-Felder an FormData an
- Backdrop-Click deaktiviert wenn Dialog offen

version: 0.8.76

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 08:25:00 +02:00
LarsandClaude Sonnet 4.6 34235ef46d feat(compliance): P-06 Upload-Einwilligungsdialog v1-conservative
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 1m23s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 1s
Implementiert server-seitige Rechteerklärungspflicht für alle Medien-Uploads
und Sichtbarkeits-Promotions (konservative Erstannahme: alle Uploads).

Backend:
- backend/media_rights.py (NEU): Kernmodul — validate_rights_declaration,
  check_rights_coverage, assert_rights_for_promotion, assert_rights_for_exercise_link,
  write_rights_declaration, update_rights_quick_fields
- backend/migrations/048_media_rights_declarations.sql (NEU): Tabelle
  media_asset_rights_declarations (Append-only Audit-Log), Felder
  rights_status/rights_visibility_level in media_assets
- backend/routers/media_assets.py: P-06-Pflichtprüfung in PATCH (single + bulk),
  POST /api/media-assets/{id}/rights-declarations (Re-Deklaration),
  GET /api/admin/media-rights/legacy-summary|legacy-assets (Admin-Endpoints)
- backend/routers/exercises.py: P-06-Felder in upload_exercise_media,
  assert_rights_for_exercise_link in attach_exercise_media_from_asset
- backend/main.py: admin_rights_router registriert

Frontend:
- frontend/src/components/RightsDeclarationDialog.jsx (NEU): 9-Felder-Dialog
  (konservativ: immer alle Fragen), Client-Validierung, VORLÄUFIG-Hinweis
- frontend/src/pages/MediaLibraryPage.jsx: Dialog-Intercept vor Upload,
  Altbestand-Indikator (legacy_unreviewed)
- frontend/src/utils/api.js: P-06-Felder in bulkUploadMediaAssets weitergeleitet

Tests:
- backend/tests/test_media_rights_declaration.py (NEU): 28 Unit-/Integrationstests
- backend/tests/test_media_assets_archive.py: P-06 fetchone-Slots + Mock ergänzt
- backend/tests/test_media_assets_copyright_promotion.py: check_rights_coverage gemockt
- tests/dev-smoke-test.spec.js: 5 P-06 E2E-Tests ergänzt

Dokumentation:
- docs/compliance-implementation.md: P-06-Abschnitt
- docs/compliance-package-register.md: Status ⚠️ teilweise umgesetzt (KRIT-04 offen)
- docs/compliance-roadmap.md: P-06 im Freigaben-Log

Offen: KRIT-04 (rechtliche Finalisierung Einwilligungsformulierung) — technisch
vollständig, Rechtstext VORLÄUFIG.

version: 0.8.75
module: media_rights 1.0.0, media_assets 1.13.0, exercises 2.20.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 08:12:44 +02:00
LarsandClaude Sonnet 4.6 8cda5c27ec docs(compliance): P-06 fachlich-technische Spezifikation erstellt
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Failing after 53s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
- docs/p06-upload-rights-spec.md (neu): vollständige Spezifikation für
  Upload-Einwilligungsdialog (§22 KUG, §8 DSGVO, Minderjährigenschutz)
  — IST-Analyse, Entscheidungsmatrix, Zielmodell (media_asset_rights_declarations
  + 3 neue Felder in media_assets), 10 Ziel-Flows, Legacy-Konzept,
  12 juristische Klärungspunkte, Umsetzungsplan P-06a–P-06e
- compliance-roadmap.md: Blocker 2 (P-06) mit Spec-Hinweis und
  juristischer Klärungsliste; §6 Freigabe-Empfehlung aktualisiert
- compliance-package-register.md: P-06 Letzter Stand mit Spec-Verweis
  und Zielmodell-Zusammenfassung ergänzt
- compliance-implementation.md: P-06 in Tabelle mit Spec-Hinweis

Keine Code-Umsetzung; Umsetzung erst nach juristischer Klärung.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 22:35:50 +02:00
LarsandClaude Sonnet 4.6 aff3020b13 docs(compliance): Dokumentation auf Stand P-01b und P-01c aktualisiert (0.8.74)
Test Suite / build-frontend (push) Successful in 18s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 58s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
- compliance-implementation.md: P-01c um copy-as-draft (0.8.72) und jsPDF
  + Abschnitts-Sortierung/-Einfuegen (0.8.74) ergaenzt; Testzusammenfassung
  auf 17 Playwright-Tests aktualisiert; Versionheader 0.8.74
- compliance-roadmap.md: App-Version 0.8.74; P-01-Blocker-Beschreibung
  vollstaendig (alle technischen Faehigkeiten); P-01c-Erweiterungen in
  Abschlussliste; Schnellreferenz aktualisiert
- compliance-package-register.md: P-01 Letzter Stand auf 0.8.74; Verweise
  und Hinweise ergaenzt (copy-as-draft, jsPDF, Sortierung); Fortschritt 0.8.74
- compliance-audit.md: Amendment §14.2 und §14.3 mit aktuellem Umsetzungsstand
  P-01/P-01b/P-01c; historische Befunde unveraendert

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 22:17:51 +02:00
LarsandClaude Sonnet 4.6 456ead72b6 feat(legal): echtes PDF-Download via jsPDF + Abschnitts-Sortierung/-Einfuegen
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 50s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
- LegalPage und AdminLegalDocumentsPage: pdf.save() statt window.open/print
- AdminLegalDocumentsPage: Abschnitte per Pfeil-Buttons verschieben
- AdminLegalDocumentsPage: neuen Abschnitt an beliebiger Stelle einfuegen
- npm: jspdf installiert

version: 0.8.74
module: legal_documents 1.2.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 21:29:21 +02:00
Lars 030eb41429 Refactor code structure for improved readability and maintainability
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 49s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
2026-05-10 21:02:53 +02:00
LarsandClaude Sonnet 4.6 5db8f8588c feat(legal): PDF-Export fuer Rechtstexte (Browser-Print)
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 47s
Test Suite / playwright-tests (push) Failing after 49s
Test Suite / pytest-backend (push) Successful in 58s
Test Suite / lint-backend (push) Successful in 0s
printLegalDocument() oeffnet formatiertes Druckfenster mit Titel,
Versionsnummer, Gueltigkeitsdatum und allen Abschnitten.

AdminLegalDocumentsPage: Drucker-Button laedt Volldokument und druckt.
LegalPage: PDF/Drucken-Button neben h1 wenn veroeffentlichtes Dokument geladen.

version: 0.8.73

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 16:47:52 +02:00
LarsandClaude Sonnet 4.6 8992c300f1 feat(legal): Als-Entwurf-kopieren für Rechtstexte
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 51s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
POST /api/admin/legal-documents/{id}/copy-as-draft übernimmt Titel +
Inhalt des Quelldokuments und legt einen neuen Entwurf mit
nächster Versionsnummer an. Funktioniert für alle Status (draft/published/archived).

UI: Copy-Button (⎘) in jeder Dokumentzeile; nach Kopie wird die
Liste automatisch aktualisiert und der neue Entwurf ist sichtbar.

version: 0.8.72
module:  legal_documents 1.1.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 12:25:04 +02:00
LarsandClaude Sonnet 4.6 b9adf6da84 fix(access-layer): legal_documents in EXEMPT_ROUTERS eintragen
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Router hat keinen Vereinsbezug (Plattform-Rechtstexte).
Öffentlicher Endpoint ohne Auth; Admin-Endpoints require_auth + is_superadmin().
ACCESS_LAYER_STRICT schlägt jetzt nicht mehr an.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 12:07:52 +02:00
LarsandClaude Sonnet 4.6 80936b226d feat(compliance): P-01c Admin-konfigurierbare Rechtstexte (0.8.71)
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 46s
Test Suite / playwright-tests (push) Successful in 50s
Test Suite / pytest-backend (push) Failing after 2s
Test Suite / lint-backend (push) Successful in 0s
DB 047: legal_documents (versioniert, draft/published/archived) +
legal_document_audit (Änderungslog); Partial-Unique-Index garantiert
max. ein published-Dokument pro document_type.

Backend: GET /api/legal-documents/{type}/published (kein Auth);
Superadmin-CRUD + Publish/Archive + Audit unter /api/admin/legal-documents.

Frontend: LegalPage lädt aus API mit Platzhalter-Fallback;
AdminLegalDocumentsPage (/admin/legal-documents) mit Tab-Navigation,
Versionsliste, Entwurf-Editor, Publish/Archive-Workflow, Änderungslog.
AdminPageNav: Link „Rechtstexte" ergänzt.

version: 0.8.71 (backend + frontend)
module:  legal_documents 1.0.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 11:53:07 +02:00
LarsandClaude Sonnet 4.6 8bed0199b6 docs(compliance): sync P-01b in compliance documents (v0.8.70)
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 31s
Test Suite / lint-backend (push) Successful in 0s
- compliance-implementation.md: P-01b section added, version to 0.8.70
- compliance-package-register.md: P-01 entry updated with P-01b, version to 0.8.70
- compliance-roadmap.md: P-01b in closed table, Blocker 1 technical stand updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 11:38:57 +02:00
LarsandClaude Sonnet 4.6 cfab5c2d69 fix(tests): stabilize login() helper with waitForURL before navigation
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 37s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
Replace waitForLoadState('networkidle') with waitForURL (not /login) to
ensure React auth processing completes before tests proceed with
page.goto(). Prevents race condition where page.goto() interrupted
in-progress token storage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 11:36:10 +02:00
LarsandClaude Sonnet 4.6 8261fa4420 feat(compliance): P-01b Mobile/PWA-Zugriff auf Rechtstexte via Einstellungen
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 49s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
- SettingsLegalPage.jsx: neue Hub-Seite /settings/legal mit allen 4 Rechtstext-Links
- App.jsx: Route /settings/legal in ProtectedLayout registriert
- AccountSettingsPage.jsx: Link zu /settings/legal unterhalb System-Info
- 3 Playwright-Tests für P-01b (Einstellungen → Rechtliches → Links → Routen)
- Version: 0.8.69 → 0.8.70 (backend + frontend)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 10:51:20 +02:00
LarsandClaude Sonnet 4.6 75d6a40817 docs(compliance): P-01 Dokumentation nach technischer Umsetzung
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 32s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
- compliance-implementation.md: P-01-Abschnitt hinzugefügt (technisch
  teilweise umgesetzt), Testergebnisse, Version 0.8.69
- compliance-package-register.md: P-01 ❌ open → ⚠️ partially
  implemented; Fortschrittsblock aktualisiert; App-Version 0.8.69
- compliance-roadmap.md: P-01 in teilweise umgesetzte Pakete; Blocker 1
  aktualisiert; §6 nächste Freigabe auf P-06 / Etappe B; Anhang

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 09:47:40 +02:00
LarsandClaude Sonnet 4.6 d7ed0c0e9b feat(compliance): P-01 Rechtstextseiten technisch anlegen (0.8.69)
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 32s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
Öffentliche Routen /impressum /datenschutz /nutzungsbedingungen
/medienrichtlinie ohne Auth erreichbar. LegalPage-Komponente mit
deutlichem Platzhalterhinweis und strukturierten Pflichtfeldern je
Rechtstext. Links in LoginPage-Footer und DesktopSidebar-Footer.

KRIT-01 technischer Teil geschlossen. Juristische Inhalte bleiben
offen — Betreiber + Rechtsanwalt erforderlich.

- frontend/src/pages/LegalPage.jsx (neu)
- frontend/src/App.jsx: 4 öffentliche Routen
- frontend/src/pages/LoginPage.jsx: Rechtstext-Links im Footer
- frontend/src/components/DesktopSidebar.jsx: Links im Sidebar-Footer
- tests/dev-smoke-test.spec.js: 5 neue P-01-Tests

version: 0.8.69 (backend + frontend)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 09:41:45 +02:00
LarsandClaude Sonnet 4.6 d73ed13f87 docs(compliance): Dokumentensynchronisierung nach P-12-Abschluss
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 25s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
- compliance-roadmap.md: App-Version 0.8.67→0.8.68 in §2; Etappe A als
  abgeschlossen markiert; §6 nächste Freigabe von P-12 auf P-01 umgestellt;
  Gate 1 P-12-Zeile auf "Bereits erfüllt"; 2× TMG §5 → § 5 DDG;
  Schnellreferenz-Anhang aktualisiert
- compliance-package-register.md: Header App-Version 0.8.67→0.8.68
- compliance-implementation.md: Versionsangaben 0.8.67→0.8.68
- compliance-audit.md: unverändert (historischer Befund)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 09:32:55 +02:00
LarsandClaude Sonnet 4.6 6abc911e94 fix(test): P-12 Playwright-Test akzeptiert confirm()-Dialog beim Logout
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 25s
Test Suite / pytest-backend (push) Successful in 32s
Test Suite / lint-backend (push) Successful in 0s
DesktopSidebar-Logout ruft App.jsx handleLogout() auf, welcher
confirm('Wirklich abmelden?') zeigt. In Playwright headless gibt
confirm() standardmäßig false zurück → Logout wurde nie ausgeführt.
page.once('dialog', dialog => dialog.accept()) behebt das.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 09:17:19 +02:00
LarsandClaude Sonnet 4.6 28ca64b5b4 feat(compliance): P-12 sessionStorage-Bereinigung bei Logout (0.8.68)
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 26s
Test Suite / pytest-backend (push) Successful in 31s
Test Suite / lint-backend (push) Successful in 0s
Sicherheit P-12 (MITT-05): logout() entfernt alle sj_coach_*-Schlüssel
aus sessionStorage gezielt per Präfix-Löschung. Fremde Schlüssel
(Browser-Extensions etc.) bleiben erhalten. Verhindert Datenleak bei
Nutzerwechsel im selben Tab (geteilter Rechner).

- AuthContext.jsx: Präfix-Schleife in logout()
- tests/dev-smoke-test.spec.js: Playwright-Test P-12 (injects/checks 3
  sj_coach_*-Schlüssel + 1 Fremd-Schlüssel; prüft selektive Löschung)

Compliance-Dokumentation:
- docs/compliance-implementation.md: P-12 ✅, Version 0.8.68
- docs/compliance-package-register.md: kanonisches Paketregister (neu)
- docs/compliance-roadmap.md: lebende Steuerungs-Roadmap (neu)
- docs/compliance-audit.md: §20 Paket-ID-Stabilitätsregel

version: 0.8.68 (backend + frontend)
module: auth 1.2.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-10 09:08:28 +02:00
Lars fc33bfbdeb feat(compliance): update retention policy and enhance password reset validation
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
- Adjusted retention policy to align with compliance requirements:
  - Changed HIDDEN_TO_PURGE_DAYS from 90 to 30 days.
- Enhanced password reset functionality to enforce a minimum password length of 8 characters.
- Updated tests to validate new password requirements and retention logic.
- Corrected umlaut in copyright error messages for clarity.
2026-05-10 08:26:15 +02:00
Lars be0385922d Implement compliance report and workspace configuration
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 31s
Test Suite / lint-backend (push) Successful in 0s
- Added compliance implementation report detailing the status of various packages (P-03, P-04, P-05, P-07, P-23, P-24) and their technical changes, tests, and notes.
- Introduced a new workspace configuration file for the project to streamline development setup.
2026-05-09 22:11:33 +02:00
259 changed files with 53126 additions and 8202 deletions

No files matched your search

+25 -14
View File
@@ -1,21 +1,25 @@
# Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-08
**Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260508049` (`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
---
## Executive Summary
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge), plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop mit Auto-Scroll, Vorschau-/Rückweg-UX). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`**, **Papierkorb & Lifecycle**, plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag-and-Drop mit Auto-Scroll). **Governance:** Sichtbarkeit **`official`** nur **Superadmin** (Übungen und Medien). **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert.
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Melde- und Transparenzpfad (P-13, seit 0.8.87 ff.):** **Inhaltsmeldungen** mit Workflow im Posteingang, Club-Admin-Beteiligung für Vereinsmedien, Legal-Hold-Anbindung, Badges in der Medienbibliothek; Folgepakete P-14–P-16 bewusst offen (siehe `docs/HANDOVER.md`).
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
**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).
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
**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)
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-12, für **neue Session**):
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
@@ -23,15 +27,17 @@
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** Abschnitt 11; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
---
**Nächste Schritte (Auszug — Planung/Rahmen):**
**Nächste Schritte (Auszug — Planung/Rahmen & Kombination):**
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. **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`.
---
@@ -87,6 +93,8 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
- [x] **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:**
@@ -96,6 +104,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
**Skills-System:**
- [x] Hierarchisches Schema, Fokusbereich-Zuordnung, Exercise-Skill mit Levels
- [x] **Gewichtetes Fähigkeiten-Profil (Phase 3):** Module, Rahmenprogramme, Regressionspfade; Peer-Kontext getrennt; Listen-Filter + Discovery — **`technical/SKILL_SCORING_SPEC.md`**
**Admin-UI:**
@@ -150,17 +159,19 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
| Dokument | Pfad | Stand | Status |
|----------|------|-------|--------|
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-08 | ✅ Aktualisiert (§12 Medien inkl. Inline 0.8.60–0.8.64) |
| 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-04-27 | ✅ Neu |
| 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-07 | ✅ Abschnitt Medien-Archiv |
| 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-08 | ✅ auf 0.8.64 aktualisiert |
| 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 |
---
@@ -171,4 +182,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
---
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
**Letzte Aktualisierung:** 2026-05-14 (Version 0.8.140, DB 063, Handover Coaching/Breakout)
+46 -10
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo - Fachliches Domänenmodell
**Version:** 0.4.4
**Stand:** 2026-05-08 (Medien-Archiv **`media_assets`** / Bibliothek **`/media`** im Ist; **Inline-Medien** im Fließtext umgesetzt — `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11)
**Version:** 0.4.6
**Stand:** 2026-05-14 (Fachlicher Nutzerüberblick: `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
---
@@ -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 |
@@ -4,11 +4,15 @@ Ausführliche fachliche Inhalte:
| Dokument | Inhalt |
|----------|--------|
| [**Fachliche Nutzerfunktionen (Ist, Überblick)**](../../../docs/FACHLICHE_NUTZERFUNKTIONEN.md) | Kompakte **Nutzer-/Rollen-Perspektive** zur Übergabe an Design & Product (ohne Implementierungsdetail) |
| [shinkan_anforderungsdokument_entwurf.md](./shinkan_anforderungsdokument_entwurf.md) | Gesamtentwurf Anforderungen |
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (§11.2), **Medien-Archiv** (Abschnitt 2026-05) |
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **geplante Inline-Medien §11** |
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (Abschnitt 11.2), **Medien-Archiv** (Abschnitt 2026-05) |
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **Inline-Medien** (Spec Abschnitt 11, umgesetzt) |
| [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan |
| [**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 |
**Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) §12, Repo-Root **`docs/HANDOVER.md`**.
**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`**.
`CLAUDE.md` (Repo-Root) verweist hierher als Einstieg.
@@ -0,0 +1,829 @@
# Trainingsmodule und Kombinationsübungen — fachliche Spezifikation V3
**Status:** fachlicher Spezifikationsentwurf
**Stand:** 2026-05-12 (Anhang A App **0.8.110**; Zeit‑Pfad **`COMBINATION_TIMING_PROFILE_PLAN.md`**) · **Coaching/Archetypen:** § 10.2.1, § 10.4–10.6, **§ 5.4/§ 6.3** Methoden/Archetypen/Zeitschicht · **Anhang A**
**Zweck:** Produkt- und Fachspezifikation für Trainingsmodule, Kombinationsübungen, Trainingsmethodenbezug, Planungsintegration und Coaching-Modus in Shinkan.
**Wichtige Leitlinie dieser Version:**
Diese Spezifikation beschreibt bewusst **keine verbindlichen Tabellen, API-Pfade, Spaltennamen oder konkrete Implementierungsdetails**. Die technische Umsetzung soll durch den Coding Agent auf Basis der bestehenden Codebasis geplant werden. Ziel dieses Dokuments ist es, die fachliche Zielarchitektur, Nutzerlogik, Datenbedeutung und Produktentscheidungen so klar zu beschreiben, dass spätere große Refactorings vermieden werden, ohne die bestehende Anwendung durch zu frühe technische Festlegungen zu destabilisieren.
---
## 1. Ausgangslage
Shinkan ist eine trainerzentrierte App für Übungsverwaltung, Trainingsplanung, Rahmenprogramme und Durchführung. Die bestehende Planung arbeitet fachlich mit Trainingseinheiten, Trainingsabschnitten und Einträgen wie Übungen oder Notizen.
Für die nächste Ausbaustufe werden zwei zusätzliche fachliche Bausteine benötigt:
1. **Kombinationsübungen**
Strukturierte Übungsformen, bei denen mehrere Einzelübungen, Stationen, Rollen oder Schritte methodisch zusammenwirken.
2. **Trainingsmodule**
Wiederverwendbare Planungsbausteine, also gespeicherte Übungsfolgen oder Trainingsblöcke, die in konkrete Trainings oder Rahmenprogramme übernommen werden können.
Zusätzlich muss geklärt werden, wie **Trainingsmethoden**, **Methoden-Archetypen** und **konkrete Ablaufprofile** fachlich voneinander getrennt werden.
---
## 2. Fachliche Grundentscheidungen
### 2.1 Trainingsabschnitte bleiben Makrostruktur
Trainingsabschnitte beschreiben die grobe Struktur einer Trainingseinheit, z. B.:
* Aufwärmen,
* Hauptteil,
* Kumite,
* Kata,
* Selbstschutz,
* Abschluss.
Ein Abschnitt ist damit ein Gliederungselement der gesamten Trainingseinheit.
### 2.2 Kombinationsübungen sind nicht an genau einen Abschnitt gebunden
Eine Kombinationsübung darf nicht fachlich oder technisch auf genau einen Trainingsabschnitt reduziert werden.
Sie kann:
* innerhalb eines Abschnitts verwendet werden,
* einen Abschnitt faktisch ausfüllen,
* zwischen zwei Abschnitten stehen,
* als zentraler Block der Einheit auf Trainingsebene liegen,
* Bestandteil eines Trainingsmoduls sein,
* Bestandteil eines Rahmenprogramms oder Rahmen-Slots sein.
Der Abschnitt kann ein sinnvoller Anzeige- oder Planungskontext sein, ist aber nicht die fachliche Heimat der Kombinationsübung.
### 2.3 Kombinationsübungen gehören fachlich zum Übungsbereich
Eine Kombinationsübung ist eine Sonderform einer Übung. Sie besitzt daher die typischen Eigenschaften einer Übung:
* Titel,
* Ziel,
* Durchführung,
* Trainerhinweise,
* Vorbereitung,
* Hilfsmittel,
* Dauer,
* Zielgruppe,
* Fähigkeiten,
* Methodenbezug,
* Medien,
* Sichtbarkeit,
* Freigabestatus.
Zusätzlich besitzt sie eine interne Struktur:
* Slots,
* Stationen,
* Rollen,
* Schritte,
* Übungspools,
* Methoden-Archetyp,
* Ablaufprofil für Planung und Coaching.
### 2.4 Trainingsmodule gehören fachlich zur Planung
Trainingsmodule sind keine Übungen, sondern wiederverwendbare Planungsbausteine.
Ein Trainingsmodul kann enthalten:
* einzelne Übungen,
* Kombinationsübungen,
* Notizen,
* methodische Hinweise,
* kurze wiederverwendbare Übungsfolgen,
* größere Blöcke innerhalb einer Einheit.
Trainingsmodule sollten deshalb fachlich unter **Planung / Bibliothek / Module** verortet werden.
### 2.5 Einfügen bedeutet Kopie mit Herkunft, nicht Live-Verknüpfung
Wenn ein Trainingsmodul oder eine Kombinationsübung in eine konkrete Trainingseinheit übernommen wird, entsteht eine bearbeitbare Planungsinstanz.
Grundsatz:
> Bibliothek = Vorlage.
> Planung = lokal bearbeitbare Übernahme.
> Durchführung = tatsächliche Nutzung im Training.
Spätere Änderungen an der Vorlage dürfen bereits geplante oder historische Einheiten nicht ungefragt verändern.
---
## 3. Zentrale Begriffe
| Begriff | Fachliche Bedeutung |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Trainingseinheit** | Konkretes geplantes oder durchgeführtes Training. |
| **Trainingsabschnitt** | Makrostruktur der Einheit, z. B. Aufwärmen oder Hauptteil. |
| **Planungsblock** | Zusammenhängender Inhalt innerhalb einer Einheit, z. B. Modul, Kombinationsübung oder manuell gruppierter Block. |
| **Kombinationsübung** | Sonderform einer Übung mit interner Struktur aus Slots, Stationen, Rollen oder Schritten. |
| **Trainingsmodul** | Wiederverwendbarer Planungsbaustein aus Übungen, Kombinationsübungen und Notizen. |
| **Trainingsmethode** | Fachlicher Katalogeintrag, der beschreibt, wie eine Trainingsform didaktisch oder sportmethodisch einzuordnen ist. |
| **Methoden-Archetyp** | Ablaufmuster für Planung und Coaching, z. B. rotierender Zirkel oder lineare Sequenz. |
| **Ablaufprofil** | Konkrete Ausprägung eines Archetyps, z. B. Arbeitszeit, Wechselzeit, Runden oder Erklärphase. |
| **Slot** | Platzhalter innerhalb einer Kombinationsübung, z. B. Station 1, Rolle A oder Schritt 2. |
| **Slot-Pool** | Menge möglicher Übungen für einen Slot, aus denen bei der Planung eine konkrete Auswahl getroffen werden kann. |
---
## 4. Trainingsmethoden: Ablage und Beschreibung
### 4.1 Rolle des Methodenkatalogs
Trainingsmethoden sollen als eigenständige fachliche Katalogobjekte geführt werden.
Sie beschreiben nicht eine konkrete Übung, sondern die methodische Qualität einer Trainingsform.
Beispiele:
* Zirkeltraining,
* Rollenspiel,
* strukturierte Übung,
* Koordinationstraining,
* plyometrisches Training,
* Dauermethode,
* extensive Intervallmethode,
* Partnerübung,
* freie Anwendung,
* Reflexionsformat.
Der Methodenkatalog dient:
* der Übungsbeschreibung,
* der Suche und Filterung,
* der Trainingsplanung,
* der fachlichen Standardisierung im Verein,
* der späteren KI- oder Assistenzunterstützung,
* der Qualitätssicherung bei offiziellen Inhalten.
### 4.2 Abgrenzung: Methode, Archetyp, Ablaufprofil
Die drei Begriffe müssen getrennt bleiben.
| Ebene | Frage | Beispiel |
| --------------------- | ---------------------------------------------- | --------------------------------------------------------- |
| **Trainingsmethode** | Welche fachliche Methode wird verwendet? | Zirkeltraining, Rollenspiel, Intervalltraining. |
| **Methoden-Archetyp** | Nach welchem Ablaufmuster wird gesteuert? | rotierender Zirkel, parallele Stationen, lineare Sequenz. |
| **Ablaufprofil** | Wie ist die konkrete Durchführung eingestellt? | 45 Sekunden Arbeit, 15 Sekunden Wechsel, 3 Runden. |
Wichtig:
> Der Methoden-Archetyp ersetzt nicht die Trainingsmethode. Er ergänzt sie nur dort, wo der Ablauf für Planung oder Coaching maschinenlesbar interpretiert werden muss.
### 4.3 Fachliche Beschreibung einer Trainingsmethode
Eine Trainingsmethode sollte aus Trainersicht so beschrieben werden, dass sie zuverlässig angewendet, gesucht und von anderen Methoden unterschieden werden kann.
Empfohlene fachliche Beschreibungsfelder:
| Feld | Zweck |
| ---------------------------------- | -------------------------------------------------------------------------- |
| **Name** | Eindeutige Bezeichnung der Methode. |
| **Kurzbeschreibung** | Schnelle Orientierung in Listen und Auswahlfeldern. |
| **Langbeschreibung** | Fachliche Erklärung der Methode. |
| **Ziel / Nutzen** | Wofür diese Methode besonders geeignet ist. |
| **Typische Einsatzsituationen** | Wann die Methode sinnvoll eingesetzt wird. |
| **Geeignete Zielgruppen** | Altersgruppen, Leistungsgruppen oder Trainingskontexte. |
| **Organisationsform** | Einzelarbeit, Partnerarbeit, Gruppe, Stationen, Kreis, freie Fläche usw. |
| **Belastungscharakter** | locker, technisch, koordinativ, intensiv, intervallartig, spielerisch usw. |
| **Typische Dauer** | Orientierung für Planung und Zeitmanagement. |
| **Benötigte Rahmenbedingungen** | Platz, Material, Gruppengröße, Sicherheitsabstände. |
| **Trainerhinweise** | Wichtige Hinweise für Anleitung und Steuerung. |
| **Risiken / typische Fehler** | Was bei falscher Anwendung problematisch sein kann. |
| **Geeignete Fähigkeiten** | Fähigkeiten, die mit der Methode häufig adressiert werden. |
| **Verwandte Methoden** | Ähnliche oder kombinierbare Methoden. |
| **Abgrenzung zu anderen Methoden** | Wann eine andere Methode passender wäre. |
| **Optionale Standard-Archetypen** | Falls die Methode häufig mit bestimmten Ablaufmustern genutzt wird. |
| **Status und Sichtbarkeit** | Entwurf, freigegeben, offiziell, vereinsintern usw. |
Diese Felder sind fachliche Anforderungen. Die konkrete technische Ablage soll der Coding Agent anhand der bestehenden Methodendomäne planen.
### 4.4 Haupt- und Nebenmethoden
Eine Übung sollte fachlich mindestens eine Hauptmethode haben können.
Zusätzlich können Nebenmethoden sinnvoll sein, weil eine Übung aus mehreren methodischen Perspektiven beschrieben werden kann.
Beispiel:
* Hauptmethode: Zirkeltraining
* Nebenmethode: plyometrisches Training
* weitere Nebenmethode: Koordinationstraining
Produktentscheidung:
> Übungen und Kombinationsübungen sollen eine Hauptmethode und optional weitere Nebenmethoden unterstützen.
Perspektivisch kann zusätzlich unterschieden werden zwischen:
* sportmethodischer Methode,
* didaktischer Vermittlungsmethode,
* organisatorischer Durchführungsform.
Diese Unterscheidung sollte aber im MVP nicht übermodelliert werden.
### 4.5 Trainingsmethoden in Kombinationsübungen
Bei Kombinationsübungen ist der Methodenbezug besonders wichtig.
Eine Kombinationsübung sollte daher fachlich drei Dinge besitzen:
1. **Methode**
Beispiel: Zirkeltraining.
2. **Archetyp**
Beispiel: rotierender Zeit-Zirkel.
3. **Ablaufprofil**
Beispiel: 6 Stationen, 45 Sekunden Arbeit, 15 Sekunden Wechsel, 3 Runden.
So kann dieselbe Methode unterschiedlich angewendet werden:
| Methode | Archetyp | Beispiel |
| ------------------- | ------------------- | --------------------------------------------------- |
| Zirkeltraining | rotierender Zirkel | Alle Gruppen wechseln gemeinsam weiter. |
| Zirkeltraining | parallele Stationen | Stationen laufen parallel, kein gemeinsamer Umlauf. |
| Intervalltraining | Intervallblock | Gemeinsame Zeitdomäne ohne Stationen. |
| Strukturierte Übung | lineare Sequenz | Schritt 1, Schritt 2, Schritt 3. |
### 4.6 Methoden in Trainingsmodulen
Trainingsmodule können ebenfalls einen Methodenbezug besitzen, aber anders als Übungen.
Ein Modul kann:
* eine dominante Methode haben,
* mehrere Methoden enthalten,
* methodisch neutral sein,
* nur aus einzelnen Übungen bestehen, die selbst Methoden besitzen.
Empfehlung:
> Ein Trainingsmodul darf optional eine primäre methodische Ausrichtung besitzen, sollte aber nicht zwingend eine Methode erzwingen.
Beispiel:
* Modul: „Aktivierung und Reaktion“
* Primäre methodische Ausrichtung: Koordinationstraining
* Enthaltene Übungen: Reaktionsspiel, Sprintsignal, Partneraufgabe
### 4.7 Methoden in der Suche und Planung
Der Methodenkatalog soll in der Nutzung sichtbar werden.
Benötigte Such- und Planungsfunktionen:
* Übungen nach Methode filtern,
* Kombinationsübungen nach Methode und Archetyp filtern,
* Trainingsmodule nach methodischer Ausrichtung filtern,
* in der Planung passende Methoden für ein Trainingsziel finden,
* Methoden als Qualitätsmerkmal offizieller Vereinsinhalte nutzen,
* bei der Auswahl einer Kombinationsübung passende Ablaufmuster vorschlagen.
Beispiel aus Trainersicht:
> „Ich suche eine Übung für Kumite, Jugendliche, Schwerpunkt Beinarbeit, Methode Zirkeltraining oder Koordinationstraining, Dauer maximal 15 Minuten.“
### 4.8 Governance des Methodenkatalogs
Trainingsmethoden sind fachliche Standardobjekte. Daher sollten sie stärker kontrolliert werden als private Trainingsnotizen.
Empfehlung:
* offizielle Methoden werden durch Administratoren oder Inhaltsverantwortliche gepflegt,
* Vereine können eigene Ergänzungen oder Spezialisierungen anlegen,
* Trainer können Vorschläge oder private methodische Hinweise erfassen,
* Änderungen an offiziellen Methoden sollten nicht ungeprüft globale Inhalte verändern.
---
## 5. Methoden-Archetypen für Kombinationsübungen
### 5.1 Zweck
Archetypen beschreiben wiederkehrende Ablaufmuster, die für Planung und Coaching relevant sind.
Sie beantworten nicht die Frage „Welche Methode ist das?“, sondern:
> Wie soll dieser Block im Training durchlaufen oder angezeigt werden?
### 5.2 Empfohlene Start-Archetypen
| Archetyp | Fachliche Bedeutung | Coaching-Idee |
| ------------------------ | -------------------------------------------------------------------- | -------------------------------------------------- |
| **Lineare Sequenz** | Übungen bauen nacheinander aufeinander auf. | Schrittfolge mit optionalem Timer. |
| **Rotierender Zirkel** | Mehrere Stationen, Gruppen wechseln nach Zeit weiter. | Gemeinsamer Timer, Wechselhinweis, Rundenzähler. |
| **Parallele Stationen** | Mehrere Stationen laufen gleichzeitig, aber ohne zwingende Rotation. | Vorher erklären, dann paralleler Betrieb. |
| **Parcours** | Stationen oder Aufgaben entlang eines Wegs oder Ablaufs. | Navigation, Abhaken, flexible Reihenfolge möglich. |
| **Partner-/Paarwechsel** | Rollen oder Aufgaben wechseln gekoppelt. | A/B-Logik, Rollenhinweise, Wechselimpulse. |
| **Intervallblock** | Gemeinsame Zeitdomäne mit wiederholten Belastungsphasen. | Globale Uhr, Intervallanzeige. |
| **Freier Methodenblock** | Methodischer Zusammenhang ohne harte Steuerungslogik. | Kompakte Anzeige, manuelles Abhaken. |
### 5.3 Mindestanforderung an Archetypen
Für jeden Archetyp muss fachlich beschrieben sein:
* wann er verwendet wird,
* welche Informationen der Trainer bei der Planung benötigt,
* welche Informationen im Coaching-Modus angezeigt werden,
* welche Angaben verpflichtend sind,
* welche Angaben optional sind,
* wann ein anderer Archetyp besser geeignet wäre.
Die technische Validierung und konkrete Ablage dieser Angaben soll der Coding Agent planen.
### 5.4 Einordnung: Trainingsformen wie HIIT, Dauer, plyometrisch ↔ Archetypen
**Wichtige Trennung (bleibt fachlich zwingend):**
* **Trainingsmethode im Methodenkatalog** (z. B. HIIT, extensive Intervallmethode, Dauermethode, plyometrisches Training) beschreibt primär den **didaktisch/belastungsmethodischen Kontext („was für eine Trainingsqualität ist das?“)**.
* **`method_archetype`** beschreibt **das Ablaufmuster („wie soll der Trainer den Block strukturieren und im Coach geführt werden?“)** — insbesondere **Parallelität, Rotation, Sequenz, Zeitdomänen**.
Dieselbe Methode kann in der Praxis mit **mehreren** Archetypen sinnvoll kombiniert sein; das ist **kein Widerspruch**.
| Beispiel (Methoden-/Belastungsbegriff) | Typischer Archetyp (Orientierung), nicht Pflicht |
| -------------------------------------- | ---------------------------------------------- |
| **HIIT**, Tabata-ähnlich, Kurzintervalle oft mit hoher Intention | sehr oft **`time_domain_interval`** oder innerhalb eines Zirkels **`circuit_rotate_time`** mit kurzen Arbeitsphasen; Partnerformen zusätzlich **`pair_superset`**. |
| **Klassisches Intervalltraining** (längere Arbeit, definierte Erholung, N Wiederholungen) | überwiegend **`time_domain_interval`** oder **`circuit_rotate_time`**, wenn die „Intervallschicht“ an Stationen gebunden ist. |
| **Dauermethode** (überwiegend durchgehend ohne harte Arbeit-Erholung-Takte) | eher **`free_method_block`** oder **`sequence_linear`** mit optionalen Hinweiten; **weniger** `time_domain_interval`, sofern kein geregeltes Intervallschema gemeint ist. |
| **Plyometrisch**, Explosivblöcke, Technik-Schichtung | häufig **`sequence_linear`** (Progression vor Ort) oder **`circuit_rotate_time`** / **`time_domain_interval`**, wenn klar Zeitfenster oder Wiederholungsblöcke vorgegeben sind. |
| Rein **organisatorisches** Stationslaufen ohne gemeinsamen Intervalltakt | **`circuit_rotate_time`** oder **`station_parcours`**, **`circuit_all_parallel`**, je nach ob rotiert wird oder parallel aktiv ist. |
**Shinkan-Zielrichtung bleibt trainerzentriert:** Es geht **nicht** um individuelle Pulsonomie eines Sportlers, sondern darum, dass der **Trainer Belastungs- und Erholungsphasen, Durchläufe und ggf. Umlauf-/Parallellogik** vorgibt und der **Coach** diese Vorgaben **sichtbar und später steuerbar** macht
(siehe **§ 6.3** zu Phasen jenseits „nur Gesamtminuten auf dem Planungsitem“).
### 5.5 Erweiterbarkeit von Archetypen (aktuell zurückgestellt)
Die Idee einer **von Superadmins zur Laufzeit editierbare Archetyp-Registry**, die den Coaching-Modus **völlig frei parametrierbar** macht, wird **zurückgestellt**. Vorerst reicht die **festgelegte, versionierte Liste** kanonischer Archetyp-IDs (**§ 10.2.1**); **weitere Archetypen** können später **wie bisher durch Produkt-/Release entschieden** ergänzt werden (Code oder kuratierter Import), ohne freies „Beliebig-Neuanlegen“ ohne definierten Coach-Verhaltens-Anker.
---
## 6. Kombinationsübungen
### 6.1 Fachliche Beschreibung
Eine Kombinationsübung ist eine wiederverwendbare Übungsform mit interner Struktur.
Beispiele:
* Kumite-Zirkel mit fünf Stationen,
* Koordinationsparcours,
* Selbstschutz-Parcours,
* Partnerwechselübung,
* methodische Sequenz zur Distanzkontrolle,
* Reaktions- und Explosivitätsblock,
* Aufwärmparcours für Kinder.
### 6.2 Bestandteile
Eine Kombinationsübung sollte fachlich enthalten:
* allgemeine Übungsbeschreibung,
* Ziel,
* Durchführung,
* Trainerhinweise,
* Vorbereitung,
* Hilfsmittel,
* Zielgruppe,
* Fähigkeiten,
* Hauptmethode,
* optionale Nebenmethoden,
* Archetyp,
* Slots / Stationen / Rollen / Schritte,
* mögliche Übungen je Slot,
* strukturierte **Zeitphasen und Belastungs-/Erholungsvorgaben** innerhalb der Kombination (**`method_profile`**, Überblick § 6.3; Details § 10.5) — **zusätzlich** zu allenfalls geplanten **Gesamtminuten am Planungseintrag**,
* optionale klassische Hinweise zu Dauer, Runden oder Wechsel aus der Übung heraus,
* Hinweise für den Coaching-Modus.
### 6.3 Zeitschicht: Phasen innerhalb der Kombination (Bibliothek) und Anpassungen in der Planung
Ein **einzelnes** Feld „Geplante Minuten für diesen Eintrag in der Einheit“ kann die **innenliegende zeitliche Logik** einer Kombinationsübung **nicht** ersetzen. Für Trainersteuerung (und später für Coaching **Stufe C**) soll die Kombination in der Bibliotheksbeschreibung vorsehen können:
**A) Kombinationseinheit („global“ über die Slots)**
* **Arbeits-** und **Erholungszeiten** (Sekunden/Minuten) und **Anzahl der Durchläufe** oder **Intervalle**,
* ggf. **gemeinsamer Takt** für alle Teilnehmenden (z. B. rotierender Zirkel oder eine gemeinsame Intervalluhr),
* **Erklär- oder Aufbauzeit** vor dem eigentlichen Start,
* dort, wo der Archetyp passt: **Runden-/Umlaufzahl** oder vergleichbare Strukturen.
Alle diese Angaben sind **Anweisungen an den Trainer** und **Coach‑Assistenz**, **keine** individuelle Pulssonde oder ähnliche Personenmessung.
**B) Optional pro Slot oder Schritt**
* wenn fachlich sinnvoll: **von Station zu Station variierende Arbeitsphasen** oder Mini‑Sequenzen innerhalb eines Slots — technisch z. B. als strukturierte Liste in `method_profile` mit Bezug zum `slot_index` (Ausarbeitung Coding Agent).
**Nach Einplanung in eine konkrete Trainingseinheit** muss diese Zeitschicht (oder ihr Abgleich mit der Einheitsposition) für den Trainer **bearbeitbar** bleiben, **ohne** die Bibliotheksvorlage still zu überschreiben (kopier-/instanzbasierte Anpassungen — siehe bereits § 2.5 und § 8.3).
**Umsetzung in der App (Stand 0.8.110):** Pro Übungszeile in einer Trainingseinheit kann optional ein **JSON-Snapshot** des Ablaufprofils gespeichert werden (`planning_method_profile` in der DB, Migration **057**). **`null`** oder fehlender Key: für **Anzeige und Editor** wirkt das **Zusammenführen** aus **Katalog** (`exercises.method_profile` bzw. Join `catalog_method_profile`) **+** Snapshot — der Katalog wird **nicht** durch ein leeres Planungsobjekt verworfen; fehlende bzw. JSON-`null`-Werte im Snapshot **überschreiben** keine Katalogfelder; `slot_profiles_v1` wird **je `slot_index`** zusammengeführt (inkl. konsistenter Steuerungslogik Zeit vs. Ziel‑Wdh.). Persistenz: der Snapshot speichert nur die vom Trainer **gesetzten** Planungsdaten (nach STZ-„Runde“ können leere Objekte als `null` normalisiert werden). **Konkrete Logik:** Frontend `effectiveComboMethodProfile` / `merge` in `frontend/src/utils/comboPlanningMethodProfile.js` (Coach, Planungseditor, Druck/Vorschau konsistent). Bearbeitung in der Planungs-UI: Modal **„Ablauf bearbeiten…“** mit `CombinationMethodProfileEditor` + Vorschau `CombinationPlanBracket`.
**Coach:** soll die wirksamen Werte nach **Übernahme** und **Einheitsübersteuerungen** konsistent nachvollziehen (**§ 10.4**).
**Geplantes kanonisches Zeitmodell:** Globale Eckwerte (z. B. Anzahl der Durchläufe / Runden, optionale Gesamt-/Einführungszeit als Ziel oder Rechenhilfe) und **pro Platz (Slot)** die Dimensionen „Belastung“, „wie viele gleiche Übung hintereinander“, „kurze Pause dazwischen“, „Übergangszeit zur nächsten Übung/arbeitstation“ — dokumentiert für die technische Angleichung in **`.claude/docs/working/COMBINATION_TIMING_PROFILE_PLAN.md`** (Felder **`slot_profiles_v1`**, `timing_schema`). Archetypen können **Strukturen und typische Schnellwahlen** vorgeben (z. B. Zirkel: Relation Belastungszeit = Übergangszeit oder Erholungsanteil ≈ 2/3 der Belastung); der Archetyp **Freier Methodenblock** bildet den **Maximal‑Pfad** ohne stärkere stille Annahmen. **Pyramidale/abhängige Pausen** (Pause abhängig von vorheriger Belastung) sind **nicht Teil des aktuellen Umsetzungspfads**, können später als eigener Untertyp ergänzt werden.
**Fortschritt pro Slot (Stand 0.8.109):** optional **`advance_mode`** je Eintrag in **`slot_profiles_v1`**: `timed` — Standard (`load_sec` = geplante Arbeitsdauer für Timer im Coach; fehlende Angabe entspricht `timed` ohne Sekundenfeld), **`rep`** — mengenorientiert (Zielzahl über **`consecutive_reps`**; keine verbindliche Arbeitsuhr), **`manual`** — coachgeführt (Fortschritt bewusst per Schritt später im Coach, optional Richtwert über **`consecutive_reps`**). Optional **`rep_series_count`**: Standard **1** (wird im Formular/API explizit geführt); Ausnahmen nur, wenn der **Methoden‑Archetyp** in `ARCHETYPE_DEFAULT_REP_SERIES_COUNT` eine andere Vorgabe definiert oder der Nutzer eine andere Zahl setzt. ≥ 2 ermöglicht Pause **zwischen Serien** (`intra_rep_rest_sec`). Bei nur **einer** Serie: kein **`intra_rep_rest_sec`** in UI und Payload; **`transition_after_sec`** = Wechsel zur nächsten Station.
### 6.4 Slot- und Pool-Logik
Slots können fest oder variabel sein.
Beispiel fest:
* Station 1 = Seilspringen
* Station 2 = Liegestütz
* Station 3 = Beinarbeit
Beispiel variabel:
* Station 1 = eine Übung aus Pool „Beinarbeit“
* Station 2 = eine Übung aus Pool „Reaktion“
* Station 3 = eine Übung aus Pool „Konter“
Die konkrete Auswahl kann bei der Planung angepasst werden, ohne die Bibliotheksvorlage zu ändern.
---
## 7. Trainingsmodule
### 7.1 Fachliche Beschreibung
Ein Trainingsmodul ist ein wiederverwendbarer Planungsbaustein.
Beispiele:
* Standard-Aufwärmen für Kinder,
* Mobilisation und Aktivierung,
* Kumite-Beinarbeit 20 Minuten,
* SV-Einstieg Wahrnehmung und Distanz,
* Abschlussritual mit Reflexion,
* prüfungsnaher Kihon-Block.
### 7.2 Bestandteile
Ein Trainingsmodul sollte fachlich enthalten:
* Titel,
* Kurzbeschreibung,
* Ziel,
* empfohlene Dauer,
* empfohlene Zielgruppe,
* optional empfohlener Einsatzbereich,
* optionale methodische Ausrichtung,
* enthaltene Übungen,
* enthaltene Kombinationsübungen,
* Notizen oder Trainerhinweise,
* Sichtbarkeit,
* Freigabestatus.
### 7.3 Keine harte Abschnittsbindung
Ein Modul kann für einen Abschnitt empfohlen sein, z. B. „Aufwärmen“, darf aber nicht technisch darauf beschränkt werden.
Ein Modul kann:
* in einen Abschnitt eingefügt werden,
* als eigener Block auf Einheitsebene eingefügt werden,
* zwischen Abschnitten eingefügt werden,
* in ein Rahmenprogramm übernommen werden.
---
## 8. Planungslogik
### 8.1 Planungsblöcke
Für die Produktlogik braucht Shinkan den Begriff des Planungsblocks.
Ein Planungsblock ist ein zusammengehöriger Inhalt in einer Trainingseinheit.
Planungsblöcke können sein:
* eingefügtes Trainingsmodul,
* eingefügte Kombinationsübung,
* manuell gruppierter Block,
* später ggf. weitere Blocktypen.
### 8.2 Verhältnis zu Abschnitten
Ein Planungsblock kann einem Abschnitt zugeordnet sein, muss aber nicht vollständig in einem Abschnitt aufgehen.
Produktregel:
> Abschnitte gliedern die Einheit. Planungsblöcke gliedern den konkreten Trainingsinhalt.
### 8.3 Lokale Anpassbarkeit
Nach dem Einfügen muss ein Planungsblock lokal angepasst werden können:
* Dauer ändern,
* **bei Kombinationsübungen:** Ablaufprofil **optional nur für diese Platzierung** überschreiben (aktuell: Snapshot parallel zum Katalog-`method_profile`, z. B. Arbeit-, Erholungs- und Runden-/Intervallangaben über die gleichen strukturierten Felder wie im Übungskatalog) — zusätzlich zu den **Gepl.-Min.** am Eintrag; **Stations-/Slot-Austausch** am konkreten Vorkommen weiter über die bestehende Übungs-/Planungslogik, nicht gesondert als „Kombi-Programmierung“ je Zeile,
* Übung austauschen,
* Station ergänzen,
* Hinweise anpassen,
* Reihenfolge ändern,
* Block auflösen,
* Block duplizieren,
* Block als neues Modul speichern.
Diese Änderungen betreffen nur die konkrete Einheit oder den konkreten Rahmen-Slot, nicht automatisch das Bibliotheksexemplar.
---
## 9. UX-Anforderungen
### 9.1 Inhalt hinzufügen
Im Planungseditor sollte der Trainer fachlich klar wählen können:
* Übung hinzufügen,
* Kombinationsübung hinzufügen,
* Trainingsmodul hinzufügen,
* Notiz hinzufügen,
* manuellen Block erstellen.
### 9.2 Modul erstellen
Ein Modul sollte auf mehreren Wegen entstehen können:
* leer anlegen,
* aus bestehendem Abschnitt speichern,
* aus markierten Übungen speichern,
* aus einem Teil eines alten Trainings speichern.
### 9.3 Kombinationsübung erstellen
Eine Kombinationsübung sollte geführt angelegt werden:
1. Grunddaten erfassen,
2. Methode wählen,
3. Archetyp wählen,
4. Slots / Stationen / Rollen definieren,
5. Übungen oder Pools zuordnen,
6. Ablaufprofil festlegen,
7. Coaching-Vorschau prüfen,
8. speichern.
### 9.4 Methoden auswählen
Die Methodenauswahl sollte Trainer unterstützen, nicht belasten.
Empfohlene UX:
* Hauptmethode prominent,
* Nebenmethoden optional,
* passende Methoden vorschlagen,
* Methoden kurz erklären,
* bei Kombinationsübungen passende Archetypen vorschlagen,
* keine Pflicht zur Überklassifizierung bei einfachen Übungen.
---
## 10. Coaching- und Assistenzmodus
### 10.1 Ziel
Der Coaching-Modus soll die Durchführung unterstützen, ohne den Trainer zu zwingen, exakt dem Plan zu folgen.
Grundsatz:
> Der Coaching-Modus gibt Orientierung, Zeitstruktur und Ablaufhilfe, bleibt aber in der Praxis flexibel.
### 10.2 Unterschiedliche Anzeige je Archetyp
| Archetyp | Coaching-Anzeige |
| -------------------- | -------------------------------------------- |
| Lineare Sequenz | Schrittfolge mit Weiter/Zurück. |
| Rotierender Zirkel | Stationen, Arbeitszeit, Wechselzeit, Runden. |
| Parallele Stationen | Erst Erklärübersicht, dann Parallelbetrieb. |
| Parcours | Stationen oder Wegpunkte zum Abhaken. |
| Partner-/Paarwechsel | Rollen, Aufgaben und Wechselhinweise. |
| Intervallblock | Globale Zeit, Intervallzähler, Aufgaben. |
| Freier Methodenblock | Kompakte Übersicht und manuelle Steuerung. |
#### 10.2.1 Kanonische Archetyp-IDs (Abgleich Fachbegriff, UI und API)
Damit Produktbeschreibung, Formularfelder (`method_archetype`), Trainingscoach und Backend‑Validierung **dieselben Werte** nutzen und es keinen dokumentationsbedingten Drift gibt, gelten diese **festen Schlüssel** (Maschinen‑IDs):
| Archetyp (fachlicher Name in § 5.2) | Schlüssel `method_archetype` (`exercises.method_archetype`) |
| ----------------------------------- | ----------------------------------------------------------- |
| Lineare Sequenz | `sequence_linear` |
| Rotierender Zirkel (Zeit) | `circuit_rotate_time` |
| Parallele Stationen | `circuit_all_parallel` |
| Parcours | `station_parcour` |
| Partner- / Paarwechsel | `pair_superset` |
| Intervallblock (Zeitdomäne) | `time_domain_interval` |
| Freier Methodenblock | `free_method_block` |
Änderungen an dieser Zuordnung nur **gemeinsam** (Produkt, Backend‑Enum und UI‑Konstanten); siehe Implementierungsanhang weiter unten.
### 10.3 Durchführungsdokumentation
Perspektivisch sollte dokumentierbar sein:
* was durchgeführt wurde,
* was übersprungen wurde,
* was verändert wurde,
* tatsächliche Dauer,
* Trainerhinweise,
* Reflexion,
* Vorschläge zur Verbesserung einer Übung oder eines Moduls.
Die konkrete technische Umsetzung wird nicht in dieser Spezifikation festgelegt.
### 10.4 Coaching-Reifegrade (Normierung ohne technisches Pflichtenheft)
Archetyp-spezifisches Coaching soll **nicht** als ein einziges UX-„Monolith“ gebaut werden, sondern in **nachvollziehbaren Stufen**, damit frühere Umsetzungen nicht überschrieben wirken und der Fortschritt in Doku/Umsetzungsplan nachverfolgt werden kann:
| Stufe | Bezeichnung (Arbeitstitel) | Inhalt aus Trainersicht | Abgrenzung |
| ----- | ---------------------------- | ------------------------ | ----------- |
| **A** | **Informations-/Struktursicht** | Pro Kombinationsübung: Kopf‑Kontext aus Katalog **plus** strukturierte Darstellung der **Slots** und der **einzelnen Kandidatenübungen** (Titel, Kurztext, Detail aufklappbar); **ein zeitlicher Schritt im Coach** entspricht weiter **einem** Planungseintrag (ein Item in der Einheit). | Kein eigener Rundenzähler, kein eigener Stations‑Timer‑State pro Archetyp. |
| **B** | **Archetyp-Steuerung in der bestehenden Zeitleiste** | Optionale Aufspaltung: z. B. bei **`sequence_linear`** pro Slot **ein Coach‑Schritt** (Weiter/Zurück pro Station), ohne die Datenbank-Semantik der Einheit zu zerstückeln (Virtuelle Schritte oder materialisierte Hilfs‑Einträge – technische Variante dokumentieren). | Bewusste Produkt-/Architekturentscheidung nötig, damit IST‑Zeiten und Abschluss‑PUT konsistent bleiben. |
| **C** | **Interaktive Assistenz je Archetyp** | Gemeinschafts-/Stations‑Timer, Wechselimpulse (**`circuit_rotate_time`**), Vorab‑„Erklärphase“‑Flag (**`circuit_all_parallel`**), Abhaken (**`station_parcour`**), gekoppelte A/B‑Ansicht (**`pair_superset`**), globale Intervalluhr (**`time_domain_interval`**) — jeweils an Parameter aus **`method_profile`** angebunden, wo diese in Stufe A/B bereits sichtbar gepflegt werden. | Keine verpflichtende KI‑Steuerung; Trainer kann überspringen (Grundsatz § 10.1). |
**Aktuelle Zielrichtung:** Stufe **A** soll für **alle** in § 10.2.1 genannten Archetypen **inhaltsgleich** die Slot‑ und Kandidateninformation liefern; **unterschiedliche Kopf-/Hilfstexte und UI-Mikrolayouts** nach Archetyp sind Teil von A und sollten gemeinsam mit Stufe B/C wachsen (kein „still“ abweichendes Verhalten ohne Doku‑Update).
### 10.5 Fachliche Mindestinfos im **Ablaufprofil** (`method_profile`) pro Archetyp
`method_profile` ist das **konkretisierende** JSON (o. ä.) zum gewählten Archetyp: Zeiten, Runden, Schalter. Technische Pflichtfelder und Validierung regelt die technische Umsetzung — **fachlich** gilt folgende Minimal-Erwartung, damit Stufe B/C sinnvoll nutzbar ist:
| Archetyp-Schlüssel | Mindest-Parameter (fachlich sinnvoll; Benennung in der Umsetzung kanonisch festlegen). Typische Zuordnung methodischer Überbegriffe: **§ 5.4** |
| ------------------ | ------------------------------------------------------------------------------------- |
| `sequence_linear` | Orientierungs-Arbeits-/Pausenhinweise je Schritt oder global; Reihenfolge = Slotreihenfolge — u. a. für **Skillschichtungen**, Aufwärmserien ohne festen Rotationstakt oder **Ausdauer-/Technikketten ohne Intervalltakt**. |
| `circuit_rotate_time` | **Arbeit** je Station oder Umlauf, **optional Wechsel/Transition**, **optional Erholung zwischen Runden**, **optional Rundenanzahl**; Kern für rotierenden Zirkel inkl. vieler HIIT-/Zirkelmischformen über Stationen hinweg (**§ 5.4**). |
| `circuit_all_parallel` | „Erst gemeinsame Erklärung, dann gleichzeitiger Betrieb aller Stationen“; Zeitfenster Vorab‑Erklärung optional — z. B. wenn keine Rotation, aber gemeinsamer Startzeitpunkt gewünscht ist. |
| `station_parcour` | Fokus Stationsbeschreibung; optional freie Besuchsreihenfolge (Profil/Archetyp); weniger zentral **feste Arbeit/Erholung-Takte**, mehr Navigation/Abhaken (später Stufe C). |
| `pair_superset` | Arbeit und Wechsel bei **gekoppelten** Rollen; typisch wenn zwei Linien oder Partnerblöcke im Takt gewechselt werden. |
| `time_domain_interval` | Klare Zeitdomäne: **Belastungs-, Erholungsblöcke** und **Anzahl Wiederholungen** der Domäne bzw. **Gesamtblockbegrenzung** — zentrale Schicht für viele Formen aus **„Intervall/HIIT/Zeitschachtelungs“‑**Methodenkatalog ohne individuelle Messung (**§ 5.4**). |
| `free_method_block` | Keine zusätzlichen Pflichtparameter; **unterstützt** etwa **reibungsarmere Dauer- oder Spielformen**, wo der Trainer keine starke Taktuhr braucht, aber Stationsideen strukturiert bündeln will. |
#### 10.5.1 Mehrschichtiges Planen (Überblick)
| Ebene | Inhalt zeitlicher Art |
| ----- | --------------------- |
| **Einheit / Planungsitem** | z. B. geplante **Gesamtminuten** dieser Platzierung („der Block soll heute etwa 25 Min einnehmen“). |
| **Kombinationsübung (Bibliothek)** | strukturierte **Phasen in `method_profile`** (arbeiten, pausieren, Runden…) — § 6.3. |
| **Einheitliche Planungsinstanz** | optionale Abweiche vom Bibliotheksprofil **nur für dieses Training** (§ 8.3). |
| **Coach** | liest wirksamen Stand (Bibliothek + Overrides) zur **Orientierung**, später automatisierte Taktassistenz (**§ 10.4**). |
Solange diese Mindestinfos in der Datenpflege noch **nicht** validiert oder nicht geführt erfasst werden, bleibt Coaching bei **Informations-Schicht und manuellen Timern des bestehenden Coach-Dialogs** die fachlich ehrliche Darstellung (siehe Anhang A).
### 10.6 Offene und geplante Erweiterungen (Produkt-Backlog, Stand 2026-05-12)
Die folgenden Punkte stammen aus **Session-/Chat-Arbeit** an Planung, Klammerdarstellung und Coach **Stufe A**; sie sind **noch nicht** als vollständige Produktfunktion abgeschlossen bzw. bewusst zurückgestellt:
| Thema | Kurzbeschreibung | Status |
| ----- | ---------------- | ------ |
| **Coaching Stufe B/C (individuelle Archetyp-Steuerung)** | Über **Stufe A** (lesend: Slots, Zeiten, Archetyp-Hinweis, Kandidaten-Texte) hinaus: **pro Archetyp** gesteuerte Durchführung (z. B. Substeps bei Sequenz, Stations-/Rotations-Timer beim Zirkel, Erklärphase bei parallelen Stationen, Abhaken Parcours, Intervalluhr). § 10.4 Stufe **B** (Zeitleiste) und **C** (Assistenz). | **Offen** — aktuell nur informativ/Orientierung; kein archetypspezifischer Zustand im Coach. |
| **Administrierbarkeit der Archetypen** | Archetypen sind **fest** im Code (`COMBINATION_ARCHETYPE_IDS` Backend, `COMBINATION_ARCHETYPE_OPTIONS` Frontend); **keine** DB-/Admin-Oberfläche für Labels, Defaults, Sichtbarkeit oder club-spezifische Erweiterungen. | **Offen** — Änderungen nur per Release/Code-Review. |
| **Einfache Vorbelegung aller Zeit- und Anzahlfelder** | Teilweise: Schnellwahlen (**Zirkel**, **Intervall**), Serien-Default **1**, Archetyp-Map `ARCHETYPE_DEFAULT_REP_SERIES_COUNT`. **Fehlt:** ein Klick „alle Stationen aus globalen Eckwerten / Archetyp-Muster füllen“, Profil-weite **Reset/Übernehmen**-Presets über alle Slots. | **Teilweise** — Ausbau siehe `COMBINATION_TIMING_PROFILE_PLAN.md` § 1 („Archetyp = Struktur + Defaults“). |
| **Archetypbedingte Restriktionen & Server-Validierung** | Client führt geführte Felder; **keine** verbindliche Backend-Prüfung „Profil passt zu Archetyp“ (Pflichtschlüssel, Wertebereiche, unzulässige Slot-Kombinationen). | **Offen** — erhöht Datenqualität und Coach-Verlässlichkeit vor Stufe C. |
| **Governance Archetyp ↔ offizielle Inhalte** | Noch keine getrennte Policy „nur Superadmin darf neue Archetyp-IDs einführen“ (derzeit ohnehin nur Code). | **Offen** — relevant sobald Archetypen konfigurierbar werden. |
**Hinweis:** § 13.1 nennt Stufe **A** als MVP-Pflicht und **B/C** als Ausbauschritte — die Tabelle oben präzisiert die **noch offenen** Arbeitspakete aus der Umsetzungspraxis.
---
## 11. Rahmenprogramm-Integration
Trainingsmodule und Kombinationsübungen müssen auch in Rahmenprogrammen nutzbar sein.
Regel:
> Was in einer konkreten Trainingseinheit geplant werden kann, sollte grundsätzlich auch in einem Rahmenprogramm oder Rahmen-Slot vorbereitet werden können, sofern es keine echte Durchführung voraussetzt.
Das betrifft insbesondere:
* Modul einfügen,
* Kombinationsübung einfügen,
* methodische Ausrichtung übernehmen,
* Slot-Pools vorbelegen,
* Dauer anpassen,
* später konkrete Einheit daraus ableiten.
Nicht in den Rahmen gehört:
* echte Durchführung,
* tatsächliche Dauer,
* spontane Trainingsnotizen,
* Nachbereitungsreflexion.
---
## 12. Governance
Für Methoden, Übungen, Kombinationsübungen und Module gelten abgestufte Sichtbarkeiten und Verantwortlichkeiten.
Empfohlene fachliche Ebenen:
* privat,
* Verein,
* offiziell,
* archiviert,
* Entwurf,
* freigegeben.
Normale Trainer sollen Inhalte nutzen und lokal anpassen können. Offizielle oder vereinsweite Vorlagen sollen nicht ungeprüft überschrieben werden.
Für Methoden ist eine besondere Qualitätskontrolle sinnvoll, weil sie als fachlicher Katalog für viele Übungen und Planungen wirken.
---
## 13. MVP-Empfehlung
### 13.1 Muss enthalten sein
* Trainingsmodule anlegen und wiederverwenden,
* Kombinationsübungen als fachliche Sonderform von Übungen,
* Methodenbezug mit Hauptmethode und optionalen Nebenmethoden,
* klare Trennung zwischen Methode, Archetyp und Ablaufprofil,
* mindestens folgende Archetypen:
* lineare Sequenz,
* rotierender Zirkel,
* freier Methodenblock,
* Planungsblöcke als fachliches Konzept,
* lokale Anpassbarkeit nach Einfügen,
* Coaching: mindestens **Stufe A** nach § 10.4 für alle Archetypen aus § 10.2.1 (strukturierte Slot-/Kombi-Darstellung; Archetyp-Hilfstexte); **zeitliche/mechanische Archetyp-Steuerung (Stufen B/C)** ausdrücklich als Ausbauschritte.
### 13.2 Sollte vorbereitet werden
* parallele Stationen,
* Parcours,
* Partner-/Paarwechsel,
* Intervallblock,
* Durchführungsdokumentation,
* Rückfluss von Erfahrungswissen,
* Offline-/PWA-Nutzung,
* stärkere Suche nach Methoden und Archetypen.
### 13.3 Nicht im MVP
* vollständige technische Event-Historie jeder Planänderung,
* automatische Synchronisation alter Einheiten bei Vorlagenänderung,
* komplexe Verschachtelung von Modulen in Modulen,
* individuelles Athleten-Tracking,
* KI-generierte Trainingsplanung,
* verbindliche technische Tabellen- oder API-Architektur.
---
## 14. Arbeitsauftrag an den Coding Agent — fachliche Leitplanken
Der Coding Agent soll die bestehende Codebasis prüfen und auf dieser Grundlage eine technische Umsetzungsplanung erstellen.
Dabei soll er ausdrücklich:
1. bestehende Strukturen wiederverwenden, soweit sinnvoll,
2. keine unnötigen Refactorings auslösen,
3. bestehende Trainingsplanung nicht destabilisieren,
4. Migrationen schrittweise und rückwärtskompatibel planen,
5. vorhandene Methodendomäne berücksichtigen,
6. die Trennung zwischen Trainingsmethode, Archetyp und Ablaufprofil fachlich erhalten,
7. technische Alternativen mit Vor- und Nachteilen darstellen,
8. erst danach konkrete Tabellen, APIs und UI-Komponenten vorschlagen.
Die Spezifikation ist daher kein technisches Pflichtenheft, sondern ein fachlicher Rahmen.
---
## 15. Zusammenfassung der verbindlichen Produktlogik
1. Trainingsabschnitte sind die Makrostruktur der Einheit.
2. Kombinationsübungen sind keine Abschnitte.
3. Kombinationsübungen sind Sonderformen von Übungen.
4. Trainingsmodule sind Planungsbausteine.
5. Trainingsmethoden sind eigenständige fachliche Katalogobjekte.
6. Eine Übung hat eine Hauptmethode und optional Nebenmethoden.
7. Methoden-Archetypen beschreiben Ablaufmuster, nicht die Methode selbst.
8. Ablaufprofile konkretisieren den Archetyp für Planung und Coaching (siehe § 10.5).
9. Einfügen aus Bibliotheken erzeugt lokal bearbeitbare Planungsinhalte.
10. Vorlagenänderungen verändern historische oder konkrete Planungen nicht automatisch.
11. Rahmenprogramme sollen dieselbe Planungslogik nutzen wie konkrete Einheiten.
12. Der Coding Agent entscheidet die technische Umsetzung anhand der bestehenden Codebasis.
13. Archetyp-IDs und Coaching-Stufen (§ 10.2.1, § 10.4) sind die **Referenz gegen Code-Drift**; Änderungen nur mit Anhang A und technischer Doku.
14. **Zeitliche Phasen** einer Kombination liegen vorrangig in **`method_profile`** und **Gesamtzeit am Planungseintrag**; **Übersteuerungen nur in der Planungsinstanz**, nicht still in der Bibliothek (§ 6.3, § 8.3, § 10.5.1).
---
## Anhang A — Implementierungsabgleich (Stand Code: App **0.8.110**)
Zweck: dieselbe Tabelle für **Produkt / Architekt / Agent** beim nächsten Schritt; verhindert „wir haben X gebaut, die Spec sagt aber Y“ ohne dass es dokumentiert wird.
| Thema (fachliche Headline aus dieser Spez) | Kurz beschrieben | Stand Code / UX (Referenz nur) | Lücke / nächste sinnvolle Schritte |
|--------------------------------------------|-----------------|---------------------------------|-------------------------------------|
| **Trainingsmodule (Bibliothek)** | Wiederverwendbare Blöcke, Kopier-Einfügen in Einheit | Bibliothek, API, Übernahme-Modal, Lineage-Spalte | **Phase 3** des Umsetzungsplans: erweiterter Übernahmemodus |
| **Kombinationsübung im Katalog** | `exercise_kind=combination`, Slots, Pools (Kandidaten) | Migration 056, CRUD Übung mit `combination_slots`, GET liefert Slots + Kandidatentitel | Fachbezug Haupt-/Nebenmethoden aus § 4/§ 6 dort umsetzen, wo die Domäne es noch nicht abdeckt |
| **Archetyp + Ablaufprofil am Katalogobjekt** | `method_archetype`, JSON `method_profile` + **`slot_profiles_v1`** | Geführtes Profil (`CombinationMethodProfileEditor`), `advance_mode` je Slot (Zeit / Ziel‑Wdh. / Coach), API-Build aus `ExerciseFormPage` | **Admin-UI für Archetypen** fehlt (nur Code-Konstanten); **serverseitige Validierung** Profil↔Archetyp offen; **volle Vorbelegung** aller Slots aus Preset/Archetyp nur teilweise (Schnellwahl) |
| **Einplanbarkeit (normale Planung)** | Kombi in Sektionen; Overrides § 8.3 | `planning_method_profile` JSONB; Modal **„Ablauf bearbeiten“**; **Merge** Katalog+Planung im Frontend (`effectiveComboMethodProfile`); Payload-Sanitisierung; Backend `Json()` beim Insert | Planungsblöcke Phase 3; **serverseitige** Zusammenführung/Validierung optional (aktuell Merge nur Client) |
| **Darstellung Planung / Lauf / Druck** | Konsistente Zeiten & Wdh. | `CombinationPlanBracket`, `effectiveStationTimingSummary`, Belastungs-Badge je Station; kompakte Kombi-Zeile in `TrainingUnitSectionsEditor` | Feintuning nach Nutzerfeedback |
| **Zeitphasen (global / pro Slot)** | § 6.3 | `slot_profiles_v1`, globale Archetyp-Felder, `inferAdvanceModeFromStoredSlotRow` für Legacy-Zeilen | `timing_schema`-Konvergenz laut `COMBINATION_TIMING_PROFILE_PLAN.md` |
| **Coaching Stufe A** | Slots + Kandidaten, Archetyp, Profil lesbar | `ExerciseFullContent` + `CombinationCoachSlots`: Merge Katalog+Planung; **globale Eckdaten mit fachlichen Labels** (`describeGlobalComboProfile`); Stationstexte inkl. „Wdh. ohne Wechsel zur nächsten Station“ / Pausen-Hinweis | Stufe **B/C** weiterhin **offen** (§ 10.6) |
| **Coaching Stufe B** | Zeitleiste archetypnah | **Nein** — ein Coach‑Schritt = ein Planungsitem | Designentscheid: virtuelle Substeps vs. DB‑Materialisierung; Auswirkung auf Ist‑Zeit pro Item |
| **Coaching Stufe C** | Timer/Wechsel/Abhaken nach Archetyp | Nur **generischer** Minuten-/Ist-Input pro Item; **kein** Stations-Timer-State | Pro Archetyp UI + `method_profile` — Haupt-Backlog |
| **Rahmenprogramm** | Gleiche Inhalte wie Einheit | Slot‑Blueprint, `from-framework-slot` | Modul-/Kombi‑UX in Rahmen wie in Einheit konsolidieren (Phase 5) |
| **Coaching-Vorschau im Editor** | § 9.3 Schritt 7 | **Peek** / Run nutzen `CombinationPlanBracket`; kein eigener „Coach-Sim“-Modus im Übungseditor | Optional: eingebettete read-only Coach-Ansicht |
**Pflege:** Bei jeder relevanten Codeänderung diese Tabelle **in demselben PR / derselben Session** anpassen (kein stiller Drift).
@@ -1,7 +1,7 @@
# Gelieferte Features & technische Basis (Q2 2026)
**Stand:** 2026-05-08
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.64**, **DB_SCHEMA_VERSION** siehe dort
**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/`.
@@ -123,7 +123,16 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
---
## 12. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
## 12. Trainingsplan: Phasen & parallele Streams (DB **063**, App **0.8.137–0.8.140**)
- **063:** `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` / `parallel_stream_id`; Default-Ganzgruppenphase für Bestand.
- **API:** `GET /api/training-units/:id` mit **`phases`** + **`sections`**; `PUT`/`POST` mit **`phases`** für Breakout-Einheiten (**0.8.138**); Rahmen-Slot-Materialisierung kopiert Phasen (**0.8.138**).
- **Frontend:** Planung Breakout-Panel (**0.8.139–0.8.140**); **`trainingPlanUtils.js`** — `sectionsWithPlanLocForDisplay`, `flattenPlanTimeline`, `buildCoachSavePlanPayload`, Split-Rejoin (`coachShouldPromptSplitRejoinTransition`); **`TrainingCoachPage`**, **`TrainingUnitRunPage`**.
- **Doku:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`, `docs/HANDOVER.md` §3, Arbeitspaket „offen“.
---
## 13. Medien-Archiv & Medienbibliothek (Migration **045** ff., App ca. **0.8.41–0.8.64**)
Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick geliefert:
@@ -150,7 +159,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
---
## 13. Nächste sinnvolle Schritte (nicht Lieferstand)
## 14. Nächste sinnvolle Schritte (nicht Lieferstand)
- Trainingsplanung: Kalender‑UI‑Anbindung **„aus Rahmen übernehmen“**; Visibility/Policies für geteilte Rahmen (**CURR‑004** später).
- Progressions-Serien als **Blöcke** (angekündigt; Voraussetzung: `prerequisite_variant_id` / `progression_level` vorhanden).
@@ -160,14 +169,41 @@ 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. 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` |
@@ -0,0 +1,178 @@
# KI-gestützte Trainingsplanung – Zentrales Konzept
**Version:** 0.1
**Datum:** 2026-05-16
**Status:** Arbeitsdokument (Verfeinerung durch fachliche Konzept-Agentur vorgesehen)
**Ziel:** Einheitlicher Rahmen für **stufenweise** KI-Unterstützung bei der Planung (Abschnitte, Einheiten, später mehrtägig/Rahmen) – ohne vollständigen Katalog im Prompt zu spiegeln.
**Verwandte Dokumente:**
`functional/DOMAIN_MODEL.md` · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (u. a. CURR-003 zu Progressions-/KI-Automatik) · `technical/TRAINING_FRAMEWORK_SPEC.md` · `technical/KI_FEATURES_SPEC.md` · `technical/AI_PROMPT_SYSTEM_SPEC.md` · `docs/FACHLICHE_NUTZERFUNKTIONEN.md` · `docs/HANDOVER.md`
---
## 1. Produktliche Leitlinien
- **Nutzer:** Trainer/Vereinskontext, **Gruppenplanung** – keine Pflicht zur individuellen Sportler-Verfolgung; Kontext soll primär aus **Gruppe**, **bereits geplanten/durchgeführten Einheiten**, **Rahmen-/Zielen** und **berechtigtem Übungskorpus** bestehen.
- **Human-in-the-loop:** KI liefert **Vorschläge** (Liste, Reihenfolge, Begründung); schreibende Übernahme in Pläne nur nach **Trainer-Bestätigung** oder expliziter Aktion (analog „Manual First“ in `KI_FEATURES_SPEC.md`).
- **Governance-first:** Nur Übungen, die die API bereits für den Mandanten/Kontext **sichtbar** freigibt, dürfen in Kandidatenlisten landen – **vor** Retrieval und **vor** jedem Prompt.
---
## 2. Kernproblem: Skalierung des Kontextes
Aus einer **großen Übungssammlung** („>1000 Übungen“) können weder alle **Felder** (Ziele, Ablauf, Skills, Varianten …) noch alle **Zeilen** sinnvoll in einen LLM-Prompt.
**Festlegung:** Der LLM-Prompt erhält immer nur ein **begrenztes Kontext-Paket** mit:
| Paketteil | Zweck |
|-----------|--------|
| **Auftrag** | z. B. Sektionstyp, Dauerbudget, Schwierigkeit, erlaubte Phasen/Streams |
| **Hard Constraints** | Gruppe, Termin/Zeitraum, Governance-Filter bereits angewendet |
| **Komprimierte Historie** | Letzte *N* Einheiten als **Liste von Übungs-IDs + Kurzlabels** (+ optional Haupt-Skills), keine vollen Fließtexte |
| **Ziele / Rahmen** | Kurztexte aus Rahmen-Slot/Zielblöcken oder Trainer-Prompt |
| **Kandidaten-Top‑K** | z. B. 30–120 Übungen, **je Zeile gekürzt** (Titel, `summary`, 2–5 Skill-Namen/Stufen); **nie** der gesamte Katalog |
| **Strukturierte Kanten optional** | Kleine Mengen Kanten aus Progressionsgraph: „Nachbarn von zuletzt genutzten Übungen“ |
**Zahlen‑Richtwerte (überarbeitungsfähig):**
Kandidaten **vor** dem LLM typischerweise **50–150** Einträge; im Prompt durch Token-Limit weiter **truncate** oder **zweistufig** (grober Ranking-Schritt ohne LLM, dann finer mit LLM auf Top‑40).
---
## 3. Pipeline: „Selektion vor dem Prompt“
Die **„optimale“** Auswahl entsteht **nicht**, indem das Modell den Katalog „im Kopf“ hält, sondern über eine **mehrstufige Pipeline**:
### Stufe 1 – Harte Filter (deterministisch, DB)
Synchron zur bestehenden Suche/List-API-Logik, z. B.:
- Sichtbarkeit / Verein / `official`‑Regeln
- Aktivitäts-/Archiv-Status der Übung
- Fokusbereich, Stil, Zielgruppe (wenn Trainings-/Gruppenkontext das vorgibt)
- Ausschluss bereits in **dieser Einheit** fester Übernutzung (optional)
Ergebnis: Menge \(M\) – kann noch sehr groß sein.
### Stufe 2 – Kontext-Verankerung (deterministisch + Graph)
- **Historie:** aus letzten *N* Gruppeneinheiten extrahierte `exercise_id`s (optional Variant).
- **Progressionsgraph:** ausgehend davon Nachbarn (eingehend/ausgehend begrenzte Tiefe) – bereits im Produkt als **unterstützend** modelliert (**CURR‑013**).
- **Rahmen/Slot-Ziele:** Überlapp mit Skill-Tags oder Stichwortliste (falls formalisiert).
- **Variantenketten:** `prerequisite_variant_id` / `progression_level` nur innerhalb bereits gewählter Übung prüfen oder als Hint an den LLM-Block durchreichen.
Ergebnis: **„Anker‑Menge“** + **„Graph‑Nachbarschaft“** → priorisierte Kandidaten.
### Stufe 3 – Weiches Ranking / Retrieval (halb-strukturiert)
Mindestens **eine** der folgenden Optionen – kombinierbar:
1. **Skill-/Facet-Overlap:** Punktezahl, wenn Übungs-Skills mit Ziel-/Matrix-Schwerpunkten übereinstimmen (bereits Daten in `exercise_skills`).
2. **Diversitäts-/Wiederholungsstrafe:** häufig in letzten Wochen geübte Übungen abwerten.
3. **Textsuche:** PostgreSQL **`tsvector`/Volltext** auf `title`, `summary`, ggf. gekürzte `goal` – für Trainer-Stichwort „Koordination Sprung“.
4. **Semantische Suche:** Embeddings + **Ähnlichkeitsuche** auf Kurztexte (siehe §5).
Ergebnis: sortierte Liste, **Top‑K** für den Prompt.
### Stufe 4 – LLM (optional zweistufig)
- **Optional 1:** LLM nur **sortiert/rankted** bereits vorgegebene IDs (Ranking mit kurzer Begründung).
- **Optional 2:** Zwei Calls: erst „welche drei Schwerpunkte“ / „Welche Constraints habe ich übersehen?“, zweiter Call nur mit gekürztem Top‑K – nur wenn UX den Mehraufwand rechtfertigt.
**Ausgabe-Contract:** Zurückkommen dürfen **nur gültige `exercise_id`s** aus der übergebenen Kandidatenliste (Server validiert gegen Set); **Halluzinationsrisiko damit entschärft**.
---
## 4. Antwort auf die konkrete Frage: „Alle Übungen in den Prompt?“
**Nein.** Workflow:
1. **DB + Regeln + Graph + Historie** reduzieren auf **einige Hundert bis wenige tausend** Rohzeilen höchstens **intern** – aber
2. in den **LLM-Prompt** gehen nur **Top‑K kompakte Artefakte** (siehe §2).
Das LLM löst dann **Ranking, Reihenfolge, Timing-Hinweise, Trainer-sprachliche Kurzkommentare** – nicht die Frage „gibt es diese Übung überhaupt im System?“.
---
## 5. Vector DB (z. B. Qdrant) – wann nötig, wann nicht?
### 5.1 Ziel embeddings
Semantic Retrieval: „wie springt Coordinative Belastung ohne das Wort ‚Koordination‘ im Titel zu stehen.“ Das ist **über** reine Filtersuche und oft **über** stumpfe Volltextsuche erreichbar.
### 5.2 Option A – ohne separate Vector DB
- **PostgreSQL + `pgvector`** (Extension): Embeddings-Spalte an `exercises` (oder an „Search Document“-Zeilen), Indices, Abfrage zusammen mit SQL-Filtern in **einer Transaktions-DB**.
- **Größenordnung** einige 10 k–100 k Zeilen für Übungen: für Shinkan **oft ausreichend**.
- Vorteile: ein Betriebspfad, Mandanten-/Governance weiter in SQL lösen; Backup wie heute.
### 5.3 Option B – Qdrant (oder anderer Dediz-Vektorstore)
Sinnvoller zeitlicher Punkt oder technische Auslöser:
- sehr hohe Latenz-Anforderung mit **Hybrid-Filter** über viele kombinierte Metadaten in nahezu Echtzeit,
- Entkopplung: Embedding-Pipeline läuft asynchron und soll die **Operational DB** nicht beschweren,
- später **mehrsprachig** oder **mehrere Embedding-Versionen**/Re-Index ohne großen Migrationstress,
- Team bevorzugt **Dedicated** Vector-Ops gegenüber Postgres-Ops.
### 5.4 Empfehlung für diese Codebasis (überarbeitungsfähig)
1. **Phase 1:** Harte Filter + Graph + Historie + **PostgreSQL-Volltext** + Top‑K; LLM erst auf komprimierten Kandidaten → hoher Nutzen ohne neuen Infrastructure-Typen.
2. **Phase 2:** Bei nachweisbaren „Recall-Lücken“ (Trainer findet nichts Passendes trotz großem Korpus) **`pgvector` in Postgres** evaluieren – **vor** zusätzlicher Infrastruktur wie Qdrant.
3. **Phase 3:** Qdrant (o. ä.) wenn Größenordnung, Betrieb oder Produkt-Anforderungen **pgvector** sprengen oder klar eine **embedding-first** Produktstraße geplant wird.
**Fazit:** Eine dedizierte **Vector DB ist nicht zwingende Voraussetzung** für vernünftige Selektion; sie ist eine **Ausbaustufe**, wenn **semantische Lücke** und Skalierung es rechtfertigen. **Selektion** ist immer **„Filter + Ranking + kleines Top‑K“**, unabhängig vom Speicherort der Vektoren.
---
## 6. Datenpflege für gutes Retrieval (fachlicher Hebel)
Retrieval‑Qualität hängt stärker an **Metadaten** als an der Embedding-Technologie allein:
- verlässliche **Skills** (`exercise_skills`, ggf. KI-geholfen bereits laut Spez beim Übungs-Anlegen);
- sinnvolle **`summary`**-Felder für Karten/Liste/KI-Pack;
- **Progressionsgraph** dort, wo pädagogische Ketten gefestigt sind;
- konsistente **Fokusbereich/Stil**-Zuordnung.
Das fachliche Konzept sollte entscheiden: **wie viel automatische Pflege vs. Trainer-Pflichtfelder**.
---
## 7. Produkt-/Release-Stufen (Anknüpfung)
| Stufe | Nutzen | Technik-Schwerpunkt |
|-------|--------|---------------------|
| A | Backend-KI-Service + Prompt-Slugs unter `technical/AI_PROMPT_SYSTEM_SPEC.md` | OpenRouter, Timeouts, 503 ohne Key |
| B | „Übungen für Abschnitt vorschlagen“ | Pipeline §3 Stufen 1–3 + Prompt mit Top‑K |
| C | Reihenfolge / Zeitslots innerhalb bestehender Sektion | Graph + LLM Ranking |
| D | Ganze Einheit (inkl. Phasen/Streams vereinfacht) | strukturiertere JSON-Ausgabe, strikte Schema-Validation |
| E | Mehreinheiten / Rahmen‑Alignment | Ziele aus Rahmenprogramm, Serie von Slots |
Die **Selektions‑Pipeline §3 bleibt** über alle Stufen konsistent und wird nur parametrierbar erweitert.
---
## 8. Compliance & Datenschutz (Kurzhinweis)
- Datenminimierung: **keine Teilnehmerliste** ohne expliziten Scope; Kontext über **Einheiten-Metadaten** und Übungen.
- **OpenRouter**/Modellwahl: Organisation intern klären (AV/Verarbeitungsvertrag, Datenflüsse außerhalb EU – siehe Repo-Compliance-Dokumente).
- **Logging:** Prompts keine unnötigen personenbezogenen Daten; wenn Debug: Retention definieren.
---
## 9. Offene Punkte für die fachliche Verfeinerung
- Gewichtung „**Wiederholung** vs. **Progression** vs. **Motivation**“ (domänenspezifisch).
- Umgang mit **Kombinationsübungen** und **Coach-Stufen B/C** in der Datenübergabe.
- Soll das System **„Lücken“** aus der **Matrix-Auflösung** aktiv quantifizieren oder nur Narrative verwenden?
- Akzeptierte **Übersetzungen**: nur Deutsch oder mehrsprachige Embeddings erforderlich?
---
## 10. Glossar
| Begriff | Bedeutung |
|---------|-----------|
| **Top‑K** | Feste kleine Obergrenze Übungen pro LLM-Anfrage |
| **Hard filter** | Deterministische SQL-/Policy-Einschränkung vor KI |
| **Kontext-Paket** | Zusammengesetztes, tokenlimitiertes Eingabeobjekt für den Prompt |
| **Retrieval** | algorithmischer Schritt ohne Generierung („wer kommt überhaupt in Frage“) |
@@ -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).
@@ -0,0 +1,205 @@
# Trainingsmodule und Kombinationsübungen — Spezifikation (Entwurf)
**Status:** Entwurf zur fachlichen und technischen Abstimmung · **Stand:** 2026-05-12 (Code **0.8.110**, siehe `backend/version.py`)
**Zweck:** Rahmen für Umsetzung, Integration in Planung/Rahmenprogramm und Durchführung im assistierten Training (Coaching-Modus). Dieses Dokument ist **nicht** implementierungsbindend, bis die markierten **offenen Entscheidungen** geschlossen und der Status angehoben wurde.
**Abgleich mit Code (Drift vermeiden):**
- **Kanonische Archetyp-IDs:** fest in `backend/routers/exercises.py` (`COMBINATION_ARCHETYPE_IDS`); fachliche Tabelle und UI-Labels in `frontend/src/constants/combinationArchetypes.js` — die **fachliche Master-Zuordnung** Name↔ID steht in `functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` § 10.2.1. **Administrierbare Archetypen** (DB/UI) gibt es **nicht**; Erweiterungen nur per Code-Release — Fachspez **§ 10.6**.
- **Planungs-Override:** `planning_method_profile` (Migration **057**) speichert einen **Snapshot**; **Merge** mit Katalogprofil erfolgt im Frontend (`frontend/src/utils/comboPlanningMethodProfile.js` — `effectiveComboMethodProfile`), nicht als serverseitiger Join. Payload-Sanitisierung vor PUT; Backend speichert JSONB zuverlässig (`Json()`).
- **Coaching:** Stufe **A** — Slots, Kandidaten, Archetyp-Hilfstext, **Label** für globale Eckdaten (`describeGlobalComboProfile` in `combinationMethodProfileUi.js`), visuelle Klammer (`CombinationPlanBracket`) in Peek/Run; Stufen **B/C** (archetypgesteuerte Zeitleiste/Takt) **offen** — Fachspez § 10.4, **§ 10.6**, **Anhang A**.
- **Umsetzungsplan:** `working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Phase 2/4 „teilweise“; Pakete **4e–4g** für Admin, Vorbelegung, Validierung).
**Verwandte Dokumente:**
| 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 |
| `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` | Sichtbarkeit, Mandant, Rollen bei neuen Bibliotheks-Entitäten |
---
## 1. Zielbild und Abgrenzung
### 1.1 Problem
Die Trainingsplanung unterstützt Einheiten mit Sektionen und einzelnen Übungen (inkl. Notizen) sowie Rahmenprogramme mit Blueprint-Einheiten pro Slot. Es fehlen:
- **Wiederverwendbare Übungsfolgen** („Trainingsmodule“), die sich wie Bausteine in eine Einheit einfügen lassen (ganze Sektion oder Block innerhalb einer Sektion), inkl. kopierbasierter Integration analog zum Rahmen.
- **Strukturierte Kombinationsformen** (z. B. Zirkel mit Stationstausch, Parcour), bei denen **mehrere Einzelübungen** Slots oder Rollen einnehmen und die **Trainingsmethode** den Ablauf (Rotation, parallele Stationen, Zeitmodell) bestimmt.
- Ein durchgängiges Konzept für den **Coaching- bzw. Assistenzmodus**, in dem derselbe Plan je nach Archetyp **unterschiedlich gesteuert** wird (Beispiel Zirkel: Erklärphase vs. parallele Nutzung aller Stationen).
### 1.2 Nicht-Ziele (für erste Ausbaustufe)
- **Individuelles Athleten-Tracking** oder Leistungsmessung pro Person (außerhalb Shinkan-MVP, siehe Produktabgrenzung).
- Automatische **Synchronisation** zwischen Bibliotheksexemplar und bereits geplanten historischen Einheiten (bewusst: **Kopie** statt Live-Spiegel, konsistent mit Rahmen-Konzept).
### 1.3 Zwei Bausteine (fachliche Trennung)
| Baustein | Kurzname | Einordnung | Kurzbeschreibung |
|----------|-----------|------------|------------------|
| **Typ 1** | **Kombinationsübung** | Übungskatalog (Sonderform einer **Übung**) | Eine logische Übung mit **1–n Slots**; Slots können einzelne Übungen oder **Pools** auswählbarer Übungen tragen; **Methodenprofil / Archetyp** steuert später den Durchlauf. |
| **Typ 2** | **Trainingsmodul** | Planung / Bibliothek | Gespeicherte, wiederverwendbare **Sequenz** von Elementen (Einzelübungen, optional Kombinationsübungen, Notizen); Einbindung per **Kopie** in konkrete `training_units` oder in Rahmen-Slot-Blueprints. |
**Abgrenzung Rahmenprogramm:** Das Rahmenprogramm strukturiert **mehrere Einheiten** (Slots) auf Programm-Ebene. Ein Trainingsmodul strukturiert typischerweise **Inhalt einer Einheit** oder eines Teils davon, nicht den Wochen-/Periodenrahmen.
---
## 2. Begriffe
| Begriff | Definition |
|---------|------------|
| **Bibliotheksexemplar** | Gespeicherte Vorlage (Modul oder Kombinationsübung-Definition) mit Governance (z. B. global, Verein, privat). |
| **Instanz in der Planung** | In `training_unit_section_items` (und ggf. ergänzende Tabellen) materialisierter Ablauf für einen **konkreten Termin** bzw. eine **geplante Einheit**. |
| **Slot (Typ 1)** | Position innerhalb einer Kombinationsübung; kann genau eine gewählte Übung oder einen **Pool** (mehrere Kandidaten) referenzieren. |
| **Methodenprofil / Archetyp** | Maschinenlesbare Semantik **wie** trainiert wird (Zeit, Rotation, Parallelität), ergänzend zum bestehenden Katalog `training_methods` (Beschreibung **was** für eine Didaktik/Kondition gilt). |
| **Coaching-Modus** | UI- und Zustandslogik zur Durchführung einer geplanten Einheit (Timer, Phasen, Stationen). |
---
## 3. Trainingsmethoden und Archetypen (Typ 1)
### 3.1 Bestehende Basis
Der Katalog `training_methods` (Migration 003) enthält u. a. **Zirkeltraining** (`category` u. a. `zirkel`, `kondition`). Er beschreibt die Methode **inhaltlich**, nicht aber Parameter wie Wechselintervalle oder parallele vs. rotierende Nutzung.
### 3.2 Erweiterung: Archetyp
Jede Kombinationsübung (und optional der Methodendatensatz als Default) erhält ein Feld **`method_archetype`** (Enum/Wertliste). Der Archetyp legt fest, welche **Parameter** am Methodenprofil relevant sind und wie der **Coaching-Modus** den Ablauf interpretiert.
**Vorschlagsliste (erweiterbar, zu verbindlich machen):**
| Archetyp-ID (Vorschlag) | Beschreibung Planungslogik | Coaching (Intent) |
|-------------------------|----------------------------|---------------------|
| `circuit_rotate_time` | n Stationen; Wechsel nach Ablaufzeit, optional globale Rundenanzahl | Rotierender oder gemeinsamer Takt; Umlauf zur nächsten Station |
| `circuit_all_parallel` | n Stationen; **kein** Umlauf als fachlicher Kern, alle Stationen gleichzeitig aktiv | Erklärphase (alle Inhalte vorher), dann **parallel** alle Stationen |
| `sequence_linear` | feste Reihenfolge; Aufbau, keine Kreisrotation | Schrittliste / Timer optional pro Schritt |
| `station_parcour` | Stationsbezogener Pfad, Reihenfolge kann variieren | Navigation / Abhaken eher als ein globaler Umlauf-Takt |
| `pair_superset` | zwei (oder wenige) Blöcke im Wechsel | Partnerlogik, gekoppelte Timer |
| `time_domain_interval` | AMRAP/EMOM-ähnliche Zeitdomäne | Globale Uhr, Runden-/Intervallzähler |
### 3.3 Parameter des Methodenprofils
Zu präzisieren (JSON-Dokument vs. normalisierte Spalten):
- Zeit: `work_seconds`, `rest_seconds`, `transition_seconds`, `rounds`
- Organisation: `station_count`, `rotation_direction`, Flags `explain_all_before_start`, `stations_operate_simultaneously`
- ggf. `intensity_profile` (skalar oder Enum), nur wenn für MVP nötig
**Offen:** Welche Parameter sind **Pflicht pro Archetyp** (Validierung).
---
## 4. Datenmodell (Zielarchitektur, Entwurf)
### 4.1 Typ 2 — Trainingsmodule
**Entwurfstabellen (Namen können bei Implementierung angeglichen werden):**
- `training_modules` — Kopf: Titel, Beschreibung, Metadaten, `visibility`, `club_id`, `created_by`, Timestamps
- optional `training_module_sections` — falls ein Modul mehrere semantische Blöcke abbilden soll
- `training_module_items` — Reihenfolge, Verweis auf:
- Einzelübung (`exercise_id`, `exercise_variant_id`)
- Kombinationsübung (`combination_exercise_id` / `exercise_id` mit `kind=combination`)
- Freitext-Notiz (analog `note` bei Einheiten)
Semantik: **Bibliotheksbaum**, keine Bindung an Kalender oder Gruppe.
### 4.2 Typ 1 — Kombinationsübungen
**Option A (Embedding in `exercises`):** Spalte `exercise_kind` = `simple` | `combination` und Kindtabellen für Slots/Pools.
**Option B (Separate Kopf-Tabelle):** 1:1-Beziehung zwischen `exercises` und `combination_exercises`.
**Slot-Pools:** mindestens M:N **Pool-Kandidat** pro Slot; die **konkret geplante Auswahl** gehört zur **Instanz** (geplante Einheit), nicht zwingend zum Bibliotheksexemplar.
### 4.3 Integration in geplante Einheiten
Heute: `training_unit_section_items` mit `item_type` in (`exercise`, `note`).
**Erweiterungsoptionen (Entscheidung offen):**
1. **Expansion beim Einfügen:** Modul wird in Items „aufgeklappt“; optional `source_module_id` an Items für Herkunft (Lineage-Light).
2. **Block-Item:** neuer `item_type` `module_reference` oder `combination` mit ID und eingebetteter Bearbeitungssemantik (komplexer, aber „Modul als Einheit“ editierbar).
Empfehlung zur Abstimmung: MVP oft mit **Expansion** + optionaler Markierung; später Block-Knoten.
**Rahmenprogramm:** Blueprint-`training_units` pro Slot nutzen dieselbe Sektions-/Item-Struktur — Module müssen **dort** ebenfalls einfügbar sein, wenn Rahmen und konkrete Planung konsistent bleiben sollen.
---
## 5. API (Skizze)
Verbindliche Pfade und Payloads folgen nach Freigabe dieses Dokuments.
| Richtung | Beispielpfad / Funktion | Zweck |
|----------|-------------------------|--------|
| CRUD | `GET/POST/PUT/DELETE …/training-modules` | Bibliothek Trainingsmodule |
| Anwendung | `POST …/training-units/{id}/apply-module` | Modulinhalt in Sektion kopieren (tiefe Kopie) |
| Übungen | Erweiterung `GET/POST/PUT …/exercises` oder Unterressource `…/exercises/{id}/combination` | Kombinationsübung inkl. Slots |
| optional | `POST …/training-units/from-module` | Neue Einheit aus Modul (falls produktrelevant) |
**AuthZ:** analog andere Bibliotheks- und Planungsobjekte; Abgleich mit `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` und Endpoint-Audit.
---
## 6. Frontend
- **Bibliothek:** Verwaltung Trainingsmodule (Liste, Editor, Sortierung, Vorschau).
- **Übungsbereich:** Editor für Kombinationsübungen (Slots, Pools, Methodenprofil/Archetyp).
- **Planungs-UI:** Aktion „Modul einfügen“, Ziel-Sektion und Position; Hinweis **Kopie** und Editierbarkeit pro Termin.
---
## 7. Coaching- / Assistenzmodus (Durchlauf)
### 7.1 Phasenmodell (konzeptionell)
- **Briefing / Erklärung:** insbesondere für `circuit_all_parallel` und Varianten mit `explain_all_before_start`
- **Arbeitsphase(n):** timer- und stationsgetrieben
- **Übergänge:** Pausen, Wechsel, Rundenzähler
### 7.2 Persistenz während Durchführung
**Offen:** Ob ein **`training_session_run`** (Snapshot der aufgelösten Einheit zum Startzeitpunkt) für Nachvollziehbarkeit und Offline-Fähigkeit nötig ist.
### 7.3 Ausbaustufen
1. Read-only **Durchführungsansicht** (Archetyp + Zeiten, keine komplexe State Machine)
2. **Aktiver Modus** mit State Machine und Archetyp-spezifischer UI
3. Optional: Offline/PWA-Verhalten
---
## 8. Umsetzungsphasen (Vorschlag)
| Phase | Inhalt |
|-------|--------|
| **A** | Dieses Dokument verbindlich machen; Archetypen und Parameter final; Governance-Regeln |
| **B** | Typ 2: `training_modules` + API + „Modul in Einheit einfügen“ (Expansion) |
| **C** | Typ 1: Kombinationsübung im Katalog + Slots/Pools + Methodenprofil |
| **D** | Einbindung in Rahmen-Slot-Blueprints (Editor-Flow) |
| **E** | Coaching-Modus gemäß Archetyp |
---
## 9. Offene Entscheidungen (Checkliste)
- [ ] Modul-Einfügung: nur **Expansion** vs. **Block-Knoten** vs. beides
- [ ] Normalisierung vs. JSON für **Methodenprofil-Parameter**
- [ ] Globale vs. vereinsbezogene vs. private **Trainingsmodule** (Governance-Matrix)
- [ ] Pflichtbinding: muss jede Kombinationsübung einen **Default-Archetyp** aus `training_methods` erben dürfen?
- [ ] Coaching: Mindestumfang MVP (nur Ansicht vs. interaktive Timer)
- [ ] Verweise in `DOMAIN_MODEL.md` und `DATABASE_SCHEMA.md` nach Implementierung pflegen
---
## 10. Changelog
| Datum | Änderung |
|-------|----------|
| 2026-05-12 | Erstversion (Entwurf) angelegt |
@@ -15,6 +15,8 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
| 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` |
| platform_media_storage | `GET/PUT /api/admin/platform-media-storage` | Plattform | `require_auth` | GET: `is_platform_admin`; PUT: nur `superadmin` | Relativer Pfad unter `MEDIA_ROOT`; keine Secrets; EXEMPT wie admin_users |
@@ -36,12 +38,13 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
**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-07 — Upload-Dedupe Papierkorb 409 + `reactivate`; DELETE …/media nur Verknüpfung.
Letzte Änderung: 2026-05-13 — `GET /api/dashboard/kpis` (Kurzüberblick-Aggregat).
---
### Changelog (Fortführung)
- **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,106 @@
# Kombinations‑Ablaufprofil — Zeitmodell, Archetyp‑Vorgaben, Umsetzung
**Zweck:** Fach-/Technik-Brücke zwischen Wunschbild („kein Nutzer‑JSON“, globale und slotbezogene Eckwerte, Archetyp‑Strukturen) und bestehendem Speicher **`method_profile` (JSON)** + **`planning_method_profile`** auf Planungszeilen.
**Bezüge:** `.claude/docs/functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md` (§ 6.3 / § 8.3); Frontend `CombinationMethodProfileEditor`, `combinationMethodProfileUi.js`; Archetyp‑IDs siehe Backend `COMBINATION_ARCHETYPE_IDS` / Frontend `COMBINATION_ARCHETYPE_OPTIONS`.
---
## 1. Grundprinzipien
| Prinzip | Beschreibung |
|--------|--------------|
| **Kein Pflicht‑JSON für Trainer** | Alle trainertypischen Pflegepfade nur über geführte Felder + Archetyp‑Vorschlagsknöpfe. |
| **JSON bleibt Transport** | Persistenz geschieht weiter in `method_profile` / Kopie in `planning_method_profile`; **kanonische Schlüssel** werden hier und in Codekommentaren festgehalten. |
| **Archetyp = Struktur + Defaults** | Wechsel des Archetyps soll (optional/togglebar) Grundwerte oder typische Relationen vorbelegen können — keine stillen Überschreibungen ohne Hinweis. |
| **`free_method_block` = Maximale Freiheit** | Entspricht „maximaler Konfiguration“: alle relevanten Timing‑Dimensionen über UI, insbesondere **pro Slot**; keine impliziten stationären Constraints. |
---
## 2. Kanonisches Zeit‑Schema (`timing_schema`)
**Empfohlene Versionierung im Objekt:**
- **`timing_schema: 1`** — sobald neue globale/strukturierte Felder aktiv genutzt werden (Pilot; UI kann ohne Migration starten durch parallele Schlüssel).
### 2.1 Globalebene (`method_profile`)
| Feld (Pilot) | Semantik |
|----------------|----------|
| `timing_schema` | `1` wenn Block unten aktiv |
| `intro_sec` oder bestehend `block_intro_sec` | einmalige Einführung/Demo am Block |
| `rounds` (bzw. bei Intervallen `interval_rounds` — Angleich später) | komplette Durchläufe des Musters |
| *Planned totals* nur **berechnete Anzeige** in UI, optional persistiert z. B. `planned_total_duration_min_hint` später |
Relationen **Zwischen Arbeit und Pause** können als Schnellwahl gesetzt werden (kein eigener Persist‑Erzwing‑Typ nötig), indem konkrete Sekunden geschrieben werden.
### 2.2 Slots (`slot_profiles_v1`)
Array synchron zu `slot_index`; fehlende Einträge = „nicht gefüllt / aus globalen Eckdaten ableiten wo sinnvoll“.
Objekt‑Shape (Sekunden, ganze Zahlen ≥ 0):
```json
{
"slot_index": 0,
"load_sec": 40,
"consecutive_reps": 1,
"intra_rep_rest_sec": 10,
"transition_after_sec": 15
}
```
| Feld | Bedeutung |
|------|------------|
| `load_sec` | Belastungsdauer „an der Station“. |
| `consecutive_reps` | Wiederholungen pro „Serie“ bzw. ohne Wechsel zu **neuem** Stationsinhalt (oft 1). |
| `rep_series_count` | Anzahl Serien à `consecutive_reps` bei rep/manual; Standard **1**, Archetyp‑Vorgabe möglich (**`ARCHETYPE_DEFAULT_REP_SERIES_COUNT`**). Persistiert für rep/manual ab 1. |
| `intra_rep_rest_sec` | Pause zwischen den Folge‑Wiederholungen bzw. **zwischen Serien** (nur sinnvoll, wenn `rep_series_count` ≥ 2 im Modus `rep`/`manual`; sonst Wechselzeit `transition_after_sec` nutzen). |
| `transition_after_sec` | Pause / Wechsel **zur nächsten** Station oder zum nächsten logischen Block. |
**Hinweis:** Bestehende Archetyp‑„flachen“ Schlüssel (`work_seconds`, `transition_seconds`, …) werden schrittweise **nicht zerstört**, sondern Slots ergänzen; Konvergenz (eine Darstellung zu v1) kann Phase 4 sein.
---
## 3. Archetyp → typische Schnellwahl (Überblicks‑Matrix)
| Archetyp | Globale Schnellwahl (Beispiele) | Slots |
|----------|---------------------------------|-------|
| `circuit_rotate_time` | Arbeit; Rotation „≈ Arbeit“ oder „Pause 2/3 Arbeit“ bezogen auf Rund‑Pausen/Rotation wo im UI dokumentiert | sinnvoll ab **timing_schema** geführt |
| `time_domain_interval` | Pause = Arbeit; Pause = 2/3 Arbeit (auf `rest_seconds`↔`work_seconds`) | optional |
| `sequence_linear` | Einführung + grobe Sek./Station | **slot_profiles_v1** priorisiert |
| `circuit_all_parallel` | Erklärzeit, gemeinsamer Start | Slots optional |
| `pair_superset` | Wechsel A↔B, Arbeit je Seite (+ später erweiterbar) | 2‑Slot‑Fokus |
| `free_method_block` | alle globalen Slots optional | **Pfad für maximale Flex** |
| `station_parcour` | Reihenfolge frei‑Flag bestehend | pro Station Verweilen sinnvoll |
**Pyramidal (später):** neue Archetyp‑ID **`pyramid_interval`** o. ä. oder Flag `pyramid_recovery_rule` mit Regelwerk „Pause abhängig von letzter Belastung“ — **explizit out of scope** bis Regeln feststehen.
---
## 4. UX‑Normen
- **Trainingsplanung** (`plannerMode`): **keine** Roh‑JSON‑Oberfläche.
- **Übungsformular**: Roh‑JSON nur wenn `allowExpertJson === true` (Default false; später z. B. Superadmin/Dev).
- **Coaching‑Ansicht**: nur **wirksame** Zahlen aus Snapshot/Katalog (Merge wie in `comboPlanningMethodProfile.js`); **globale** Profilwerte mit **fachlichen Labels** (`describeGlobalComboProfile`), nicht nur Rohschlüsseln.
### 4.1 Stand Umsetzung (App **0.8.110**, Kurz)
- **`slot_profiles_v1`** und Schnellwahlen Zirkel/Intervall im geführten Editor umgesetzt; **`advance_mode`** je Slot (Zeit / Ziel‑Wdh. / Coach).
- **Phase 2** dieses Plans (Modal „Archetyp‑Vorlage anwenden?“, nicht‑destruktives Merge über alle Slots) — **noch offen** (Fachspez § 10.6, Umsetzungsplan Paket **4f**).
---
## 5. Phasen (Implementierung)
| Phase | Inhalt |
|-------|--------|
| **1 (jetzt)** | Slot‑Zeilen‑UI über `slot_profiles_v1`; Schnellwahl‑Ratios für `circuit_rotate_time` + `time_domain_interval`; `plannerMode` ohne JSON; `allowExpertJson` default false |
| **2** | Beim Archetypwechsel **optionales** Modal „Archetyp‑Vorlage anwenden?“ mit nicht‑destruktivem Merge |
| **3** | Geplante **Gesamtzeit** konsistent rechnerisch (Summe Slots × Runden + Global) mit Transparenz in UI |
| **4** | Konsolidierung flacher Schlüssel → **`timing_schema`** v1‑only im Editor |
| **5** | Pyramide / adaptive Recovery |
---
**Pflege:** Änderungen an Schlüsseln oder Phasen hier und in Anhang A der Fachspez mitziehen.
@@ -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).
```
@@ -0,0 +1,43 @@
# Umsetzungsplan: Trainingsmodule & Kombinationsübungen
**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-20 (Abgleich mit Code, siehe `backend/version.py`)
## Ziele
Umsetzung der MVP-Punkte aus der Fachspezifikation ohne die bestehende Planung zu destabilisieren: schrittweise Migrationen, bestehende Sektions-/Item-Struktur (`training_unit_sections`, `training_unit_section_items`) beibehalten, Kopiersemantik bei Übernahmen.
## Phasenüberblick
| 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“; **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) |
| **5** | Rahmenprogramm: Modulübernahme UX in Slot-Blueprint-Editor konsolidieren | geplant |
## Coaching — verbindliche Arbeitspakete (gegen Spec-Drift)
| Paket | Spec-Referenz | Kurzinhalt |
|-------|----------------|-----------|
| **4a (Ist/Ziel)** | § 10.2.1 | Archetyp-Schlüssel bleiben identisch zu `backend/routers/exercises.py` (`COMBINATION_ARCHETYPE_IDS`) und `frontend/src/constants/combinationArchetypes.js`. |
| **4b** | § 10.4 Stufe A | **Erreicht (0.8.110):** Slots + Kandidaten; Archetyp-Hilfstext; wirksames Profil lesend mit **fachlichen Labels**; Klammerdarstellung konsistent (`CombinationPlanBracket`, `comboPlanningMethodProfile.js`). |
| **4c** | § 10.4 Stufe B | Entscheidung: virtuelle Substeps vs. persistierte Items; Konsistenz `sectionsToPutPayload`/Ist-Zeit. |
| **4d** | § 10.4 Stufe C | Archetyp-spezifische Timer/Wechsel/Abhaken an `method_profile` — nach 4c. |
| **4e** | § 10.6 | **Archetyp-Verwaltung:** DB/UI oder Konfiguration statt nur Release — Labels, Defaults, ggf. Vereins-/Rollen-Sichtbarkeit. |
| **4f** | § 10.6 · `COMBINATION_TIMING_PROFILE_PLAN.md` | **Massen-Vorbelegung:** ein Klick alle Slot-Zeiten/Anzahlen aus Archetyp/Global; Modal „Archetyp-Vorlage anwenden?“ (Phase 2 des Timing-Plans). |
| **4g** | § 10.6 | **Backend-Validierung:** Pflichtfelder/Wertebereiche je `method_archetype`; optional serverseitiger Merge mit Katalog (aktuell nur Client). |
## Phase 1 (technische Notizen)
- **Governance:** `visibility`/`club_id`/`created_by` analog `training_plan_templates`; Listenfilter `library_content_visibility_sql`.
- **Übernahme:** Keine Live-Verknüpfung; Items werden kopiert; `source_training_module_id` dokumentiert Herkunft.
- **Schnittstelle Übernahme:** `section_order_index` entspricht der Reihenfolge der Abschnitte in der gespeicherten Einheit (0-basiert), konsistent zur Planungs-API.
## Pflege nach Merge
- `DATABASE_SCHEMA.md` bei größeren Schema-Erweiterungen ergänzen.
- `ACCESS_LAYER_ENDPOINT_AUDIT.md` bei neuen mandantenbezogenen Endpunkten fortpflegen.
- **Nach jeder Kombi-/Coach-Änderung:** `functional/… Spezifikation V2.md` **Anhang A** und diese Tabelle Phasen 2/4 abstimmen.
+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,7 +12,11 @@
> | 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`** |
## Projekt-Übersicht
@@ -83,10 +87,11 @@ frontend/src/
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
Kurz (Stand 2026-05-08): App **0.8.64**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll), Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (§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`.
+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,
+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
+10 -3
View File
@@ -82,8 +82,8 @@ app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "X-Auth-Token", "X-Active-Club-Id"],
)
@@ -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_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, skill_profiles, training_planning, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin, legal_documents, content_reports
app.include_router(auth.router)
app.include_router(profiles.router)
@@ -205,14 +205,21 @@ app.include_router(club_join_requests.router)
app.include_router(admin_users.router)
app.include_router(platform_media_storage.router)
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(import_wiki.router)
app.include_router(import_wiki_admin.router)
app.include_router(legal_documents.router)
app.include_router(content_reports.router)
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
+247
View File
@@ -0,0 +1,247 @@
"""P-11: Legal-Hold-Services fuer Medien-Assets.
Sofortsperrung bei Rechtsverletzungen (Compliance-Paket P-11).
Klare Trennung:
- P-06: Rechteerklaerungs-/Deklarationsstatus (rights_status='declared'/'legacy_unreviewed')
- P-11: Legal-Hold-Sperre (legal_hold_active + Metadaten)
- P-03: Normaler Papierkorb-Lifecycle (lifecycle_state)
- P-13: Meldeverfahren (spaeter; nutzt denselben set_legal_hold-Service)
Berechtigungen:
- Setzen und Aufheben: ausschliesslich Superadmin.
- Lesezugriff auf Legal-Hold-Status: Superadmin und Plattform-Admin.
"""
from __future__ import annotations
from typing import Any, Optional
from fastapi import HTTPException
from club_tenancy import is_superadmin
from media_rights import write_audit_log_entry
LEGAL_HOLD_REASON_CODES = {
"rights_dispute",
"consent_withdrawn",
"privacy_complaint",
"copyright_complaint",
"youth_protection",
"illegal_content",
"other",
}
def assert_superadmin_for_legal_hold(role: Optional[str]) -> None:
if not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Legal-Hold-Aktionen sind nur fuer Superadmins verfuegbar.",
)
def is_media_available_for_normal_use(asset: dict) -> bool:
"""True wenn das Medium fuer normale Nutzerpfade verfuegbar ist.
Ein Medium ist NICHT verfuegbar wenn legal_hold_active = True,
unabhaengig vom lifecycle_state.
"""
return not bool(asset.get("legal_hold_active"))
def assert_not_under_legal_hold(asset: dict) -> None:
"""Wirft HTTPException 403 wenn das Medium unter Legal Hold steht."""
if bool(asset.get("legal_hold_active")):
raise HTTPException(
status_code=403,
detail={
"code": "LEGAL_HOLD_ACTIVE",
"message": (
"Dieses Medium ist durch einen Administrator sofort gesperrt und "
"kann nicht verwendet werden."
),
"asset_id": asset.get("id"),
},
)
def set_legal_hold(
cur: Any,
conn: Any,
asset_id: int,
acting_profile_id: int,
reason_code: str,
reason_note: Optional[str],
) -> dict:
"""Setzt Legal Hold auf ein Medium. Nur Superadmin.
Wirkung:
- legal_hold_active = TRUE
- legal_hold_reason_code, legal_hold_reason_note, legal_hold_set_by_profile_id, legal_hold_set_at
- rights_status = 'blocked' (Spiegel fuer schnelle Checks)
- Audit-Log-Eintrag 'legal_hold_set'
Gibt das aktualisierte Asset-Dict zurueck.
"""
if reason_code not in LEGAL_HOLD_REASON_CODES:
raise HTTPException(
status_code=400,
detail=f"Ungueltiger reason_code. Erlaubt: {sorted(LEGAL_HOLD_REASON_CODES)}",
)
if not reason_note or not reason_note.strip():
raise HTTPException(
status_code=400,
detail="reason_note (Begruendung) ist Pflicht beim Setzen eines Legal Holds.",
)
cur.execute(
"""SELECT id, legal_hold_active, rights_status, lifecycle_state, visibility
FROM media_assets WHERE id = %s""",
(asset_id,),
)
from db import r2d
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(row)
if bool(asset.get("legal_hold_active")):
raise HTTPException(
status_code=409,
detail="Dieses Medium befindet sich bereits unter Legal Hold.",
)
old_rights_status = asset.get("rights_status") or "legacy_unreviewed"
cur.execute(
"""UPDATE media_assets
SET legal_hold_active = TRUE,
legal_hold_reason_code = %s,
legal_hold_reason_note = %s,
legal_hold_set_by_profile_id = %s,
legal_hold_set_at = NOW(),
legal_hold_released_by_profile_id = NULL,
legal_hold_released_at = NULL,
legal_hold_release_note = NULL,
rights_status = 'blocked',
updated_at = NOW()
WHERE id = %s
RETURNING id, legal_hold_active, legal_hold_reason_code, legal_hold_reason_note,
legal_hold_set_by_profile_id, legal_hold_set_at, rights_status,
lifecycle_state, visibility""",
(reason_code, reason_note.strip()[:2000], acting_profile_id, asset_id),
)
updated_row = cur.fetchone()
updated = r2d(updated_row)
write_audit_log_entry(
cur,
asset_id=asset_id,
acting_profile_id=acting_profile_id,
event_type="legal_hold_set",
old_values={"rights_status": old_rights_status, "legal_hold_active": False},
new_values={
"rights_status": "blocked",
"legal_hold_active": True,
"reason_code": reason_code,
"reason_note": reason_note.strip()[:2000] if reason_note else None,
},
)
conn.commit()
return updated
def release_legal_hold(
cur: Any,
conn: Any,
asset_id: int,
acting_profile_id: int,
release_note: Optional[str],
) -> dict:
"""Hebt Legal Hold auf. Nur Superadmin.
Wirkung:
- legal_hold_active = FALSE
- legal_hold_released_by_profile_id, legal_hold_released_at, legal_hold_release_note
- rights_status: zurueck auf 'declared' wenn vorher declared war, sonst 'legacy_unreviewed'
(Entscheidungslogik: war vor dem Hold ein Deklarations-Eintrag vorhanden?)
- Audit-Log-Eintrag 'legal_hold_released'
Gibt das aktualisierte Asset-Dict zurueck.
"""
if not release_note or not release_note.strip():
raise HTTPException(
status_code=400,
detail="release_note (Freigabe-Begruendung) ist Pflicht.",
)
cur.execute(
"""SELECT id, legal_hold_active, rights_status, lifecycle_state, visibility,
legal_hold_reason_code, legal_hold_reason_note
FROM media_assets WHERE id = %s""",
(asset_id,),
)
from db import r2d
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(row)
if not bool(asset.get("legal_hold_active")):
raise HTTPException(
status_code=409,
detail="Dieses Medium befindet sich nicht unter Legal Hold.",
)
# Bestimme den rights_status nach Freigabe:
# Gibt es eine gueltige Deklaration? → 'declared', sonst 'legacy_unreviewed'
cur.execute(
"""SELECT COUNT(*) AS cnt FROM media_asset_rights_declarations
WHERE media_asset_id = %s
AND action_type NOT IN ('correction')
AND rights_holder_confirmed = TRUE""",
(asset_id,),
)
decl_row = cur.fetchone()
decl_count = int(decl_row[0] if not hasattr(decl_row, "keys") else decl_row["cnt"])
restored_rights_status = "declared" if decl_count > 0 else "legacy_unreviewed"
cur.execute(
"""UPDATE media_assets
SET legal_hold_active = FALSE,
legal_hold_released_by_profile_id = %s,
legal_hold_released_at = NOW(),
legal_hold_release_note = %s,
rights_status = %s,
updated_at = NOW()
WHERE id = %s
RETURNING id, legal_hold_active, rights_status, lifecycle_state, visibility,
legal_hold_reason_code, legal_hold_reason_note,
legal_hold_set_by_profile_id, legal_hold_set_at,
legal_hold_released_by_profile_id, legal_hold_released_at,
legal_hold_release_note""",
(acting_profile_id, release_note.strip()[:2000], restored_rights_status, asset_id),
)
updated_row = cur.fetchone()
updated = r2d(updated_row)
write_audit_log_entry(
cur,
asset_id=asset_id,
acting_profile_id=acting_profile_id,
event_type="legal_hold_released",
old_values={
"rights_status": "blocked",
"legal_hold_active": True,
"reason_code": asset.get("legal_hold_reason_code"),
},
new_values={
"rights_status": restored_rights_status,
"legal_hold_active": False,
"release_note": release_note.strip()[:2000] if release_note else None,
},
)
conn.commit()
return updated
+9 -2
View File
@@ -21,7 +21,8 @@ LC_TRASH_SOFT = "trash_soft"
LC_TRASH_HIDDEN = "trash_hidden"
SOFT_TO_HIDDEN_DAYS = max(1, int(os.getenv("MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS", "30")))
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "90")))
# P-03b: Default gemaess fachlichem Loeschkonzept (Audit 2026-05-09): 30+30 Tage.
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "30")))
def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None:
@@ -278,6 +279,10 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
"""
Automatik: trash_soft älter als SOFT_TO_HIDDEN_DAYS → trash_hidden;
trash_hidden mit purge_after_at in der Vergangenheit → purge.
P-11: Medien unter aktivem Legal Hold werden NICHT gerpurged (legal_hold_active = TRUE).
Die Retention verschiebt sie auch nicht automatisch von trash_soft nach trash_hidden —
Legal-Hold-Status hat Vorrang vor dem Papierkorb-Lifecycle.
"""
cutoff_soft = datetime.now(timezone.utc) - timedelta(days=SOFT_TO_HIDDEN_DAYS)
cur.execute(
@@ -285,6 +290,7 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
SET lifecycle_state = %s, trash_hidden_at = NOW(), updated_at = NOW(),
purge_after_at = NOW() + (%s * INTERVAL '1 day')
WHERE lifecycle_state = %s AND trash_soft_at IS NOT NULL AND trash_soft_at <= %s
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)
RETURNING id""",
(LC_TRASH_HIDDEN, HIDDEN_TO_PURGE_DAYS, LC_TRASH_SOFT, cutoff_soft),
)
@@ -293,7 +299,8 @@ def run_retention_pass(cur: Any, conn: Any) -> dict:
cur.execute(
"""SELECT id FROM media_assets
WHERE lifecycle_state = %s AND purge_after_at IS NOT NULL AND purge_after_at <= NOW()""",
WHERE lifecycle_state = %s AND purge_after_at IS NOT NULL AND purge_after_at <= NOW()
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)""",
(LC_TRASH_HIDDEN,),
)
purge_ids = [r2d(r)["id"] for r in cur.fetchall()]
+412
View File
@@ -0,0 +1,412 @@
"""P-06: Zentrale Rechte-Policy fuer Medien-Uploads und Promotionen.
Konservative Erstannahmen (p06-v1-conservative):
- Alle Uploads (inkl. private) erfordern vollstaendige Erklaerung
- Personenfragen bei allen Sichtbarkeiten Pflicht zu beantworten
- Promotion zu hoeherem Niveau erfordert neue Erklaerung
- Altmedien ('legacy_unreviewed') duerfen nicht promoted werden
VORLAEUTIG: Juristische Validierung der Felder und Texte steht aus.
"""
from __future__ import annotations
import json as _json
from typing import Any, Optional
from fastapi import HTTPException
DECLARATION_VERSION = "p06-v1-conservative"
# Sichtbarkeits-Hierarchie: private(1) < club(2) < official(3)
VISIBILITY_LEVELS: dict[str, int] = {
"private": 1,
"club": 2,
"official": 3,
}
def visibility_level(vis: str) -> int:
return VISIBILITY_LEVELS.get((vis or "").strip().lower(), 0)
def rights_covers_target(declared_for: Optional[str], target_vis: str) -> bool:
"""True wenn die vorhandene Erklaerung die Ziel-Sichtbarkeit abdeckt."""
if not declared_for:
return False
return visibility_level(declared_for) >= visibility_level(target_vis)
# --------------------------------------------------------------------------
# Validierung einer eingehenden Erklaerung
# --------------------------------------------------------------------------
def validate_rights_declaration(decl: dict[str, Any], target_visibility: str) -> None:
"""Pruefen ob alle Pflichtfelder der konservativen Erstannahme vorliegen.
Wirft HTTPException 400 mit maschinenlesbarem code bei Verstoss.
Gilt fuer alle Sichtbarkeiten (private/club/official) identisch.
"""
# 1. rights_holder_confirmed ist immer Pflicht
if not decl.get("rights_holder_confirmed"):
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": (
"Bitte bestaetigen, dass du die erforderlichen Rechte an diesem Medium besitzt."
),
},
)
# 2. contains_identifiable_persons muss explizit beantwortet sein
if decl.get("contains_identifiable_persons") is None:
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": "Bitte angeben, ob erkennbare Personen abgebildet sind.",
},
)
# 3. Wenn Personen vorhanden: Einwilligung Pflicht
if decl.get("contains_identifiable_persons") is True:
if not decl.get("person_consent_confirmed"):
raise HTTPException(
status_code=400,
detail={
"code": "PERSON_CONSENT_REQUIRED",
"message": (
"Bitte bestaetigen, dass die Einwilligungen aller erkennbaren Personen vorliegen."
),
},
)
# 4. contains_minors muss explizit beantwortet sein
if decl.get("contains_minors") is None:
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": "Bitte angeben, ob Minderjaehrige abgebildet sind.",
},
)
# 5. Wenn Minderjaehrige: Elterneinwilligung Pflicht
if decl.get("contains_minors") is True:
if not decl.get("parental_consent_confirmed"):
raise HTTPException(
status_code=400,
detail={
"code": "PARENTAL_CONSENT_REQUIRED",
"message": (
"Bitte bestaetigen, dass die Einwilligungen der Sorgeberechtigten vorliegen."
),
},
)
# 6. contains_music muss explizit beantwortet sein
if decl.get("contains_music") is None:
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": "Bitte angeben, ob das Medium Musik enthaelt.",
},
)
# 7. Wenn Musik: Musikrechte Pflicht
if decl.get("contains_music") is True:
if not decl.get("music_rights_confirmed"):
raise HTTPException(
status_code=400,
detail={
"code": "MUSIC_RIGHTS_REQUIRED",
"message": (
"Bitte bestaetigen, dass die erforderlichen Musikrechte vorliegen."
),
},
)
# 8. contains_third_party_content muss explizit beantwortet sein
if decl.get("contains_third_party_content") is None:
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": "Bitte angeben, ob fremde geschuetzte Inhalte (Logos, Grafiken etc.) enthalten sind.",
},
)
# 9. Wenn Fremdmaterial: Rechte Pflicht
if decl.get("contains_third_party_content") is True:
if not decl.get("third_party_rights_confirmed"):
raise HTTPException(
status_code=400,
detail={
"code": "THIRD_PARTY_RIGHTS_REQUIRED",
"message": (
"Bitte bestaetigen, dass die Rechte an allen enthaltenen Fremdmaterialien vorliegen."
),
},
)
# --------------------------------------------------------------------------
# Pruefen ob vorhandene Erklaerung Zielsichtbarkeit abdeckt
# --------------------------------------------------------------------------
def check_rights_coverage(cur: Any, asset_id: int, target_visibility: str) -> str:
"""Status der Rechteabdeckung fuer ein Asset und eine Zielsichtbarkeit.
Returns:
'ok' - vorhandene Erklaerung reicht aus
'legacy' - Altmedium ohne Erklaerung (legacy_unreviewed)
'blocked' - durch Admin gesperrt
'no_declaration' - neues Medium ohne Erklaerung (sollte nicht vorkommen)
Hinweis: Eine P-06-Erklaerung beschreibt den Inhalt (Rechteinhaber, Personen, Musik etc.)
und ist sichtbarkeitsunabhaengig. rights_status='declared' gilt daher fuer alle
Sichtbarkeits-Stufen ohne Levelvergleich.
"""
cur.execute(
"SELECT rights_status FROM media_assets WHERE id = %s",
(asset_id,),
)
row = cur.fetchone()
if not row:
return "no_declaration"
rs = (row[0] if not hasattr(row, "keys") else row["rights_status"] or "").strip().lower()
if rs == "blocked":
return "blocked"
if rs == "legacy_unreviewed":
return "legacy"
if rs == "declared":
return "ok"
return "no_declaration"
def assert_rights_for_promotion(cur: Any, asset_id: int, target_visibility: str) -> None:
"""Wirft HTTPException wenn das Asset keine gueltige Erklaerung fuer target_visibility hat."""
status = check_rights_coverage(cur, asset_id, target_visibility)
if status == "ok":
return
if status == "legacy":
raise HTTPException(
status_code=400,
detail={
"code": "LEGACY_REDECLARATION_REQUIRED",
"message": (
"Dieses Medium wurde vor Einfuehrung der Einwilligungspflicht hochgeladen. "
"Bitte eine Rechterklaerung nachreichen, bevor die Sichtbarkeit erhoeht wird."
),
"asset_id": asset_id,
},
)
if status == "blocked":
raise HTTPException(
status_code=403,
detail={
"code": "RIGHTS_BLOCKED",
"message": "Dieses Medium ist durch einen Administrator gesperrt.",
"asset_id": asset_id,
},
)
# no_declaration (neues Medium ohne Erklaerung)
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_DECLARATION_REQUIRED",
"message": "Fuer dieses Medium liegt keine Rechterklaerung vor.",
"asset_id": asset_id,
},
)
def assert_rights_for_exercise_link(cur: Any, asset_id: int, exercise_visibility: str) -> None:
"""Pruefen ob das Asset in eine Uebung mit dieser Sichtbarkeit eingebunden werden darf."""
status = check_rights_coverage(cur, asset_id, exercise_visibility)
if status == "ok":
return
if status == "legacy" and exercise_visibility == "private":
# Altmedien duerfen in private Uebungen eingebunden bleiben (kein Upgrade-Risiko)
return
if status == "legacy":
raise HTTPException(
status_code=400,
detail={
"code": "LEGACY_REDECLARATION_REQUIRED",
"message": (
"Das gewahlte Archiv-Medium hat noch keine Rechterklaerung nach neuem Standard. "
"Bitte zuerst eine Erklaerung fuer dieses Medium abgeben."
),
"asset_id": asset_id,
},
)
if status == "insufficient":
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_SCOPE_INSUFFICIENT",
"message": (
f"Das Archiv-Medium hat keine Erklaerung fuer Sichtbarkeit '{exercise_visibility}'. "
"Bitte zuerst eine neue Erklaerung fuer dieses Medium abgeben."
),
"asset_id": asset_id,
},
)
if status == "blocked":
raise HTTPException(
status_code=403,
detail={
"code": "RIGHTS_BLOCKED",
"message": "Dieses Medium ist gesperrt und kann nicht verwendet werden.",
"asset_id": asset_id,
},
)
# --------------------------------------------------------------------------
# Declaration-Log schreiben + Schnellfelder aktualisieren
# --------------------------------------------------------------------------
def _clean_context(val: Any) -> Optional[str]:
"""Leere Strings → None, sonst auf 2000 Zeichen kuerzen."""
s = (val or "").strip()
return s[:2000] if s else None
def write_rights_declaration(
cur: Any,
asset_id: int,
profile_id: int,
action_type: str,
target_visibility: str,
decl: dict[str, Any],
) -> int:
"""Schreibt einen neuen Eintrag in media_asset_rights_declarations (append-only).
Returns: id des neuen Eintrags
"""
cur.execute(
"""INSERT INTO media_asset_rights_declarations (
media_asset_id, declared_by_profile_id, action_type, target_visibility,
declaration_version,
rights_holder_confirmed,
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
contains_minors, parental_consent_confirmed, parental_consent_context,
contains_music, music_rights_confirmed, music_rights_context,
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id""",
(
asset_id,
profile_id,
action_type,
target_visibility,
DECLARATION_VERSION,
bool(decl.get("rights_holder_confirmed")),
decl.get("contains_identifiable_persons"),
decl.get("person_consent_confirmed"),
_clean_context(decl.get("person_consent_context")),
decl.get("contains_minors"),
decl.get("parental_consent_confirmed"),
_clean_context(decl.get("parental_consent_context")),
decl.get("contains_music"),
decl.get("music_rights_confirmed"),
_clean_context(decl.get("music_rights_context")),
decl.get("contains_third_party_content"),
decl.get("third_party_rights_confirmed"),
_clean_context(decl.get("third_party_rights_context")),
),
)
row = cur.fetchone()
if hasattr(row, "keys"):
return int(row["id"])
return int(row[0])
def write_audit_log_entry(
cur: Any,
asset_id: int,
acting_profile_id: Optional[int],
event_type: str,
old_values: dict,
new_values: dict,
) -> None:
"""Schreibt einen Eintrag in media_asset_audit_log (append-only)."""
cur.execute(
"""INSERT INTO media_asset_audit_log
(media_asset_id, acting_profile_id, event_type, old_values, new_values)
VALUES (%s, %s, %s, %s, %s)""",
(
asset_id,
acting_profile_id,
event_type,
_json.dumps(old_values, default=str),
_json.dumps(new_values, default=str),
),
)
def write_rights_correction_declaration(
cur: Any,
asset_id: int,
profile_id: int,
target_visibility: str,
decl: dict[str, Any],
correction_note: Optional[str],
) -> int:
"""Schreibt eine Korrektur-Deklaration (action_type='correction', append-only)."""
cur.execute(
"""INSERT INTO media_asset_rights_declarations (
media_asset_id, declared_by_profile_id, action_type, target_visibility,
declaration_version,
rights_holder_confirmed,
contains_identifiable_persons, person_consent_confirmed, person_consent_context,
contains_minors, parental_consent_confirmed, parental_consent_context,
contains_music, music_rights_confirmed, music_rights_context,
contains_third_party_content, third_party_rights_confirmed, third_party_rights_context,
correction_note
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id""",
(
asset_id,
profile_id,
"correction",
target_visibility,
DECLARATION_VERSION,
bool(decl.get("rights_holder_confirmed")),
decl.get("contains_identifiable_persons"),
decl.get("person_consent_confirmed"),
_clean_context(decl.get("person_consent_context")),
decl.get("contains_minors"),
decl.get("parental_consent_confirmed"),
_clean_context(decl.get("parental_consent_context")),
decl.get("contains_music"),
decl.get("music_rights_confirmed"),
_clean_context(decl.get("music_rights_context")),
decl.get("contains_third_party_content"),
decl.get("third_party_rights_confirmed"),
_clean_context(decl.get("third_party_rights_context")),
_clean_context(correction_note),
),
)
row = cur.fetchone()
if hasattr(row, "keys"):
return int(row["id"])
return int(row[0])
def update_rights_quick_fields(cur: Any, asset_id: int, target_visibility: str) -> None:
"""Setzt die Schnellfelder in media_assets nach erfolgreicher Deklaration."""
cur.execute(
"""UPDATE media_assets
SET rights_status = 'declared',
rights_declared_for_visibility = %s,
rights_declared_at = NOW(),
updated_at = NOW()
WHERE id = %s""",
(target_visibility, asset_id),
)
@@ -0,0 +1,37 @@
-- Migration 047: Admin-konfigurierbare Rechtstexte
-- Tabellen: legal_documents (versioniert), legal_document_audit (Änderungslog)
-- document_type: impressum | privacy_policy | terms_of_use | media_policy
-- status: draft | published | archived
-- Partial unique index: nur genau ein published-Dokument pro document_type erlaubt.
CREATE TABLE IF NOT EXISTS legal_documents (
id SERIAL PRIMARY KEY,
document_type VARCHAR(50) NOT NULL
CHECK (document_type IN ('impressum', 'privacy_policy', 'terms_of_use', 'media_policy')),
version INT NOT NULL DEFAULT 1,
title VARCHAR(255) NOT NULL,
content_sections JSONB NOT NULL DEFAULT '[]',
status VARCHAR(20) NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'published', 'archived')),
change_note TEXT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
created_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
published_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
published_at TIMESTAMP
);
-- Sicherstellt: pro document_type maximal ein published-Datensatz
CREATE UNIQUE INDEX IF NOT EXISTS legal_documents_unique_published
ON legal_documents (document_type)
WHERE status = 'published';
CREATE TABLE IF NOT EXISTS legal_document_audit (
id SERIAL PRIMARY KEY,
legal_document_id INT NOT NULL REFERENCES legal_documents(id) ON DELETE CASCADE,
action VARCHAR(50) NOT NULL,
changed_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
change_note TEXT,
previous_status VARCHAR(20),
created_at TIMESTAMP DEFAULT NOW()
);
@@ -0,0 +1,75 @@
-- Migration 048: P-06 Upload-Einwilligungsdialog
-- Append-only Deklarations-Log + Schnellfelder in media_assets
-- Alle bestehenden Medien erhalten rights_status = 'legacy_unreviewed'
-- Deklarations-Log (append-only, wird nie geaendert oder geloescht)
CREATE TABLE IF NOT EXISTS media_asset_rights_declarations (
id SERIAL PRIMARY KEY,
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
declared_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
declared_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Kontext der Erklaerung
action_type VARCHAR(50) NOT NULL
CHECK (action_type IN (
'upload', -- Erstupload
'promote_club', -- Promotion zu club
'promote_official', -- Promotion zu official
're_declaration', -- Freiwillige Nacherklaerung
'legacy_re_declaration' -- Altmedium: erste Erklaerung nachgereicht
)),
target_visibility VARCHAR(32) NOT NULL
CHECK (target_visibility IN ('private', 'club', 'official')),
-- Textversion der Erklaerung; 'p06-v1-conservative' = konservative Erstannahmen
-- VORLAEUTIG: Texte noch nicht juristisch geprueft
declaration_version VARCHAR(40) NOT NULL DEFAULT 'p06-v1-conservative',
-- Pflichtfeld (alle Sichtbarkeiten, alle Aktionen)
rights_holder_confirmed BOOLEAN NOT NULL,
-- Personen (konservative Annahme: immer abgefragt, auch bei 'private')
contains_identifiable_persons BOOLEAN,
person_consent_confirmed BOOLEAN, -- Pflicht wenn contains_identifiable_persons = true
-- Minderjaehrige
contains_minors BOOLEAN,
parental_consent_confirmed BOOLEAN, -- Pflicht wenn contains_minors = true
-- Drittmaterial
contains_music BOOLEAN,
music_rights_confirmed BOOLEAN, -- Pflicht wenn contains_music = true
contains_third_party_content BOOLEAN,
third_party_rights_confirmed BOOLEAN, -- Pflicht wenn contains_third_party_content = true
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_mard_asset
ON media_asset_rights_declarations (media_asset_id);
CREATE INDEX IF NOT EXISTS idx_mard_profile
ON media_asset_rights_declarations (declared_by_profile_id);
CREATE INDEX IF NOT EXISTS idx_mard_action_type
ON media_asset_rights_declarations (action_type);
-- Schnellfelder in media_assets (kein Ersatz fuer den Log, nur fuer effiziente Abfragen)
ALTER TABLE media_assets
ADD COLUMN IF NOT EXISTS rights_status VARCHAR(32)
NOT NULL DEFAULT 'legacy_unreviewed'
CHECK (rights_status IN ('legacy_unreviewed', 'declared', 'blocked')),
ADD COLUMN IF NOT EXISTS rights_declared_for_visibility VARCHAR(32)
CHECK (rights_declared_for_visibility IN ('private', 'club', 'official')),
ADD COLUMN IF NOT EXISTS rights_declared_at TIMESTAMPTZ;
-- Bestehende Medien: explicit legacy_unreviewed setzen (redundant zum DEFAULT, zur Klarheit)
UPDATE media_assets
SET rights_status = 'legacy_unreviewed'
WHERE rights_status = 'legacy_unreviewed'; -- no-op, setzt Default explizit
COMMENT ON TABLE media_asset_rights_declarations IS
'P-06: Append-only Erklaerungslog fuer Upload-Einwilligungen. '
'Eintraege werden nie geaendert. Juristische Validierung der Felder und Texte steht aus.';
COMMENT ON COLUMN media_assets.rights_status IS
'P-06: legacy_unreviewed = Altbestand ohne P-06-Erklaerung; '
'declared = gueltige Erklaerung fuer rights_declared_for_visibility; '
'blocked = durch Admin gesperrt (P-11-Schnittstelle).';
@@ -0,0 +1,18 @@
-- Migration 049: P-06 Erweiterung – Einwilligungskontext-Felder und Copyright im Upload-Dialog
-- Optionale Freitextfelder fuer den Kontext der Einwilligung (z.B. "Schriftliche Einwilligung
-- vom 2026-05-01 liegt vor") sowie copyright_notice direkt beim Upload erfassbar.
ALTER TABLE media_asset_rights_declarations
ADD COLUMN IF NOT EXISTS person_consent_context TEXT,
ADD COLUMN IF NOT EXISTS parental_consent_context TEXT,
ADD COLUMN IF NOT EXISTS music_rights_context TEXT,
ADD COLUMN IF NOT EXISTS third_party_rights_context TEXT;
COMMENT ON COLUMN media_asset_rights_declarations.person_consent_context IS
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der abgebildeten Personen vor?';
COMMENT ON COLUMN media_asset_rights_declarations.parental_consent_context IS
'Optionaler Freitext: In welchem Zusammenhang liegt die Einwilligung der Sorgeberechtigten vor?';
COMMENT ON COLUMN media_asset_rights_declarations.music_rights_context IS
'Optionaler Freitext: Welche Lizenz / GEMA-Regelung liegt fuer die Musik vor?';
COMMENT ON COLUMN media_asset_rights_declarations.third_party_rights_context IS
'Optionaler Freitext: Auf welcher Grundlage duerfen die enthaltenen Fremdinhalte verwendet werden?';
@@ -0,0 +1,47 @@
-- Migration 050: Medien-Volljournal – Audit-Log für alle Änderungen + Korrektur-Deklarationen
-- Vollständiger Audit-Log: Sichtbarkeitsänderungen, Copyright, Metadaten, Lifecycle
CREATE TABLE IF NOT EXISTS media_asset_audit_log (
id SERIAL PRIMARY KEY,
media_asset_id INT NOT NULL REFERENCES media_assets(id) ON DELETE CASCADE,
acting_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
event_type VARCHAR(50) NOT NULL
CHECK (event_type IN (
'visibility_change',
'copyright_change',
'metadata_change',
'lifecycle_change'
)),
old_values JSONB,
new_values JSONB
);
CREATE INDEX IF NOT EXISTS idx_maal_asset ON media_asset_audit_log (media_asset_id);
CREATE INDEX IF NOT EXISTS idx_maal_asset_occurred ON media_asset_audit_log (media_asset_id, occurred_at);
COMMENT ON TABLE media_asset_audit_log IS
'Append-only Protokoll aller Aenderungen an Medien-Assets (Sichtbarkeit, Copyright, Metadaten, Lifecycle). '
'Wird nie aktualisiert oder geloescht (ausser ON DELETE CASCADE des Assets).';
-- Korrektur-Notiz für nachtraegliche Deklarations-Korrekturen
ALTER TABLE media_asset_rights_declarations
ADD COLUMN IF NOT EXISTS correction_note TEXT;
COMMENT ON COLUMN media_asset_rights_declarations.correction_note IS
'Optionale Begruendung fuer action_type=correction: Warum wurde die Erklaerung korrigiert?';
-- ''correction'' action_type hinzufuegen (bestehende CHECK-Constraint ersetzen)
ALTER TABLE media_asset_rights_declarations
DROP CONSTRAINT IF EXISTS media_asset_rights_declarations_action_type_check;
ALTER TABLE media_asset_rights_declarations
ADD CONSTRAINT media_asset_rights_declarations_action_type_check
CHECK (action_type IN (
'upload',
'promote_club',
'promote_official',
're_declaration',
'legacy_re_declaration',
'correction'
));
+73
View File
@@ -0,0 +1,73 @@
-- Migration 051: P-11 Legal-Hold Lifecycle-Status
-- Sofortsperrung fuer rechtlich problematische Medien (Compliance-Paket P-11)
--
-- Architekturentscheidung:
-- rights_status='blocked' bleibt als Spiegel-Schnellstatus (P-06-Kompatibilitaet).
-- Primaere Wahrheit: legal_hold_active + dedizierte Metadaten-Felder in media_assets.
-- Dies ermoeglicht klare Trennung: P-06 Deklarationsstatus / P-11 Legal Hold / P-03 Lifecycle.
-- P-13 kann spaeter denselben set_legal_hold-Service nutzen.
ALTER TABLE media_assets
ADD COLUMN IF NOT EXISTS legal_hold_active BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS legal_hold_reason_code VARCHAR(50)
CHECK (legal_hold_reason_code IN (
'rights_dispute',
'consent_withdrawn',
'privacy_complaint',
'copyright_complaint',
'youth_protection',
'illegal_content',
'other'
)),
ADD COLUMN IF NOT EXISTS legal_hold_reason_note TEXT,
ADD COLUMN IF NOT EXISTS legal_hold_set_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS legal_hold_set_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS legal_hold_released_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS legal_hold_released_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS legal_hold_release_note TEXT;
COMMENT ON COLUMN media_assets.legal_hold_active IS
'P-11: TRUE = Medium unter Legal Hold; sofortige Sperrung fuer alle normalen Nutzerpfade. '
'Retention-Job darf dieses Medium nicht purgen. '
'rights_status wird bei Aktivierung auf ''blocked'' gespiegelt.';
COMMENT ON COLUMN media_assets.legal_hold_reason_code IS
'P-11: Kategorie des Legal Holds. Pflicht beim Setzen.';
COMMENT ON COLUMN media_assets.legal_hold_reason_note IS
'P-11: Freitext-Begruendung fuer den Legal Hold.';
COMMENT ON COLUMN media_assets.legal_hold_set_by_profile_id IS
'P-11: Profil das den Legal Hold gesetzt hat (Superadmin).';
COMMENT ON COLUMN media_assets.legal_hold_set_at IS
'P-11: Zeitpunkt der Legal-Hold-Aktivierung.';
COMMENT ON COLUMN media_assets.legal_hold_released_by_profile_id IS
'P-11: Profil das den Legal Hold aufgehoben hat.';
COMMENT ON COLUMN media_assets.legal_hold_released_at IS
'P-11: Zeitpunkt der Legal-Hold-Freigabe.';
COMMENT ON COLUMN media_assets.legal_hold_release_note IS
'P-11: Begruendung fuer die Aufhebung des Legal Holds.';
-- Index fuer Admin-Liste aktiver Legal Holds
CREATE INDEX IF NOT EXISTS idx_media_assets_legal_hold_active
ON media_assets (legal_hold_active)
WHERE legal_hold_active = TRUE;
-- Neue event_types fuer media_asset_audit_log
ALTER TABLE media_asset_audit_log
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
ALTER TABLE media_asset_audit_log
ADD CONSTRAINT media_asset_audit_log_event_type_check
CHECK (event_type IN (
'visibility_change',
'copyright_change',
'metadata_change',
'lifecycle_change',
'legal_hold_set',
'legal_hold_released'
));
@@ -0,0 +1,73 @@
-- P-13: Content-Melde-Backend
-- Meldungen rechtswidriger Inhalte (DSA-konformes Meldeverfahren, KRIT-03)
--
-- Architektur: Diese Tabelle traegt alle fachlichen Report-Daten.
-- Die bestehende Admin-Inbox (InboxPage.jsx, GET /api/me/inbox/join-requests)
-- wird um einen zweiten Abschnitt erweitert, der Content-Reports anzeigt.
-- Keine separate Admin-Queue, keine generische inbox_items-Tabelle.
CREATE TABLE IF NOT EXISTS content_reports (
id SERIAL PRIMARY KEY,
-- Ziel der Meldung (erweiterbar auf weitere Typen)
target_type VARCHAR(20) NOT NULL DEFAULT 'media_asset'
CHECK (target_type IN ('media_asset', 'exercise')),
target_id INTEGER NOT NULL,
-- Meldungsinhalt
report_reason VARCHAR(50) NOT NULL
CHECK (report_reason IN (
'copyright',
'image_rights',
'privacy',
'minors',
'illegal_content',
'youth_protection',
'offensive_content',
'other'
)),
report_description TEXT NOT NULL,
-- Meldende Person (Name + E-Mail Pflicht; Profil optional bei eingeloggten Nutzern)
reporter_name VARCHAR(200) NOT NULL,
reporter_email VARCHAR(200) NOT NULL,
reporter_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
-- Gutglaubenserklärung (Pflicht)
good_faith_confirmed BOOLEAN NOT NULL DEFAULT FALSE,
-- Automatische Priorisierung (high fuer minors/youth_protection/illegal_content)
priority VARCHAR(20) NOT NULL DEFAULT 'normal'
CHECK (priority IN ('high', 'normal')),
-- Workflow-Status
status VARCHAR(30) NOT NULL DEFAULT 'submitted'
CHECK (status IN (
'submitted',
'under_review',
'resolved_no_action',
'resolved_legal_hold',
'rejected_invalid'
)),
-- Bearbeitung
assigned_to_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
reviewed_by_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
reviewed_at TIMESTAMP,
resolution_note TEXT,
-- Zeitstempel
submitted_at TIMESTAMP DEFAULT NOW(),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Indices fuer Admin-Liste
CREATE INDEX IF NOT EXISTS idx_content_reports_status_created
ON content_reports (status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_content_reports_target
ON content_reports (target_type, target_id);
CREATE INDEX IF NOT EXISTS idx_content_reports_priority
ON content_reports (priority, status, created_at DESC);
@@ -0,0 +1,21 @@
-- Migration 053: Audit-Log event_type-Constraint korrigieren + 'content_report_filed' hinzufuegen
--
-- Hintergrund: Die Tabelle media_asset_audit_log wurde per CREATE TABLE IF NOT EXISTS angelegt.
-- Da die Tabelle bereits existierte, wurde die CHECK-Constraint aus Migration 050 nie angewendet.
-- In der DB existieren Zeilen mit legal_hold_set und legal_hold_released (aus P-11).
-- Diese Migration setzt die Constraint erstmalig mit allen gueltigen Werten.
ALTER TABLE media_asset_audit_log
DROP CONSTRAINT IF EXISTS media_asset_audit_log_event_type_check;
ALTER TABLE media_asset_audit_log
ADD CONSTRAINT media_asset_audit_log_event_type_check
CHECK (event_type IN (
'visibility_change',
'copyright_change',
'metadata_change',
'lifecycle_change',
'legal_hold_set',
'legal_hold_released',
'content_report_filed'
));
@@ -0,0 +1,60 @@
-- Migration 054: Trainingsmodule (Bibliothek / Planung) — Phase 1 MVP
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md
CREATE TABLE IF NOT EXISTS training_modules (
id SERIAL PRIMARY KEY,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
title VARCHAR(200) NOT NULL,
summary TEXT,
goal TEXT,
recommended_duration_min INT,
target_group_notes TEXT,
deployment_context_notes TEXT,
primary_method_id INT REFERENCES training_methods(id) ON DELETE SET NULL,
visibility VARCHAR(50) NOT NULL DEFAULT 'club'
CHECK (visibility IN ('private', 'club', 'official')),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_training_modules_club ON training_modules(club_id);
CREATE INDEX IF NOT EXISTS idx_training_modules_creator ON training_modules(created_by);
CREATE INDEX IF NOT EXISTS idx_training_modules_visibility ON training_modules(visibility);
CREATE INDEX IF NOT EXISTS idx_training_modules_method ON training_modules(primary_method_id)
WHERE primary_method_id IS NOT NULL;
DROP TRIGGER IF EXISTS training_modules_update ON training_modules;
CREATE TRIGGER training_modules_update
BEFORE UPDATE ON training_modules
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
CREATE TABLE IF NOT EXISTS training_module_items (
id SERIAL PRIMARY KEY,
module_id INT NOT NULL REFERENCES training_modules(id) ON DELETE CASCADE,
order_index INT NOT NULL,
item_type VARCHAR(20) NOT NULL CHECK (item_type IN ('exercise', 'note')),
exercise_id INT REFERENCES exercises(id) ON DELETE SET NULL,
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
planned_duration_min INT,
notes TEXT,
note_body TEXT,
UNIQUE (module_id, order_index),
CHECK (
(item_type = 'exercise' AND exercise_id IS NOT NULL AND note_body IS NULL)
OR
(item_type = 'note' AND exercise_id IS NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_training_module_items_module ON training_module_items(module_id);
CREATE INDEX IF NOT EXISTS idx_training_module_items_exercise ON training_module_items(exercise_id)
WHERE exercise_id IS NOT NULL;
-- Herkunft bei Übernahme aus Modul-Bibliothek (Kopie, keine Live-Verknüpfung)
ALTER TABLE training_unit_section_items
ADD COLUMN IF NOT EXISTS source_training_module_id INT REFERENCES training_modules(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_training_unit_section_items_source_module
ON training_unit_section_items(source_training_module_id)
WHERE source_training_module_id IS NOT NULL;
@@ -0,0 +1,3 @@
-- Persönliche Planungs-UI-Präferenzen (JSONB, selbst vom Nutzer setzbar)
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS training_planning_prefs JSONB NOT NULL DEFAULT '{}'::jsonb;
@@ -0,0 +1,33 @@
-- Migration 056: Kombinationsübungen (Phase 2 MVP) — Slots + Pool-Kandidaten
-- Fachgrundlage: functional/Shinkan Trainingsmodule Kombinationsuebungen Spezifikation V2.md §6
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS exercise_kind VARCHAR(20) NOT NULL DEFAULT 'simple'
CHECK (exercise_kind IN ('simple', 'combination')),
ADD COLUMN IF NOT EXISTS method_archetype VARCHAR(80),
ADD COLUMN IF NOT EXISTS method_profile JSONB NOT NULL DEFAULT '{}'::jsonb;
CREATE INDEX IF NOT EXISTS idx_exercises_exercise_kind ON exercises(exercise_kind);
CREATE INDEX IF NOT EXISTS idx_exercises_method_archetype ON exercises(method_archetype)
WHERE method_archetype IS NOT NULL;
CREATE TABLE IF NOT EXISTS combination_exercise_slots (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
slot_index INT NOT NULL,
title VARCHAR(200),
UNIQUE (exercise_id, slot_index)
);
CREATE INDEX IF NOT EXISTS idx_combination_exercise_slots_exercise ON combination_exercise_slots(exercise_id);
CREATE TABLE IF NOT EXISTS combination_slot_candidates (
id SERIAL PRIMARY KEY,
slot_id INT NOT NULL REFERENCES combination_exercise_slots(id) ON DELETE CASCADE,
candidate_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
sort_order INT NOT NULL DEFAULT 0,
UNIQUE (slot_id, candidate_exercise_id)
);
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_slot ON combination_slot_candidates(slot_id);
CREATE INDEX IF NOT EXISTS idx_combination_slot_candidates_exercise ON combination_slot_candidates(candidate_exercise_id);
@@ -0,0 +1,8 @@
-- 057: Terminspezifisches Ablaufprofil fuer Kombinationsuebungen in der Planung
-- NULL = method_profile vom Katalog (exercises) verwenden; sonst dieser JSONB-Stand gilt fuer diese Platzierung.
ALTER TABLE training_unit_section_items
ADD COLUMN IF NOT EXISTS planning_method_profile JSONB NULL;
COMMENT ON COLUMN training_unit_section_items.planning_method_profile IS
'Snapshots des Ablaufprofils fuer diese Einheit/Zeile; NULL = exercises.method_profile.';
@@ -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;
+9 -1
View File
@@ -26,7 +26,7 @@ class PasswordResetRequest(BaseModel):
class PasswordResetConfirm(BaseModel):
token: str
new_password: str
new_password: str = Field(min_length=8, max_length=128)
class ProfileCreate(BaseModel):
"""Nur für POST /api/profiles (Plattform-Admin): neues Nutzerprofil ohne Self-Registration."""
@@ -47,6 +47,10 @@ class ProfileUpdate(BaseModel):
default=None,
description="JSON: gespeicherte Standardfilter für die Übungsliste",
)
training_planning_prefs: Optional[Dict[str, Any]] = Field(
default=None,
description="JSON: UI-Optionen Trainingsplanung (z.B. Darstellung kopierter Module)",
)
class ProfileResponse(BaseModel):
id: int
@@ -113,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
@@ -121,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
+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).
+2 -2
View File
@@ -98,8 +98,8 @@ def change_pin(req: dict, session: dict=Depends(require_auth)):
"""Change PIN/password for current user."""
pid = session['profile_id']
new_pin = req.get('pin', '')
if len(new_pin) < 4:
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
if len(new_pin) < 8:
raise HTTPException(400, "Passwort muss mind. 8 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn:
+931
View File
@@ -0,0 +1,931 @@
"""
P-13: Content-Melde-Backend
Meldeverfahren fuer moeglicherweise rechtswidrige Inhalte (DSA-Grundlage, KRIT-03).
Architektur:
- Fachliche Daten in 'content_reports' Tabelle (Migration 052)
- Integration in bestehende Admin-Inbox (GET /api/me/inbox/content-reports)
- Keine separate Admin-Queue; die InboxPage.jsx zeigt beide Vorgangstypen
- P-11-Anschluss: Superadmin kann aus Meldung heraus Legal Hold setzen
Berechtigungen:
- Meldung einreichen: optional Auth (ohne Auth nur fuer official-Medien erlaubt)
- Liste/Detail: Plattform-Admin (alle Meldungen) oder Club-Admin (nur eigene Vereinsmedien)
- Status-Bearbeitung: Plattform-Admin
- Legal Hold aus Meldung: ausschliesslich Superadmin
E-Mail-Benachrichtigungen:
- Nach Eingang: Bestaetigung an Melder
- Nach Eingang: Benachrichtigung aller Plattform-Admins (best-effort, kein Fehler wenn SMTP fehlt)
Audit-Log (Migration 053):
- Bei media_asset-Meldungen: Eintrag in media_asset_audit_log (event_type='content_report_filed')
"""
from __future__ import annotations
import os
import re
from typing import Optional
from fastapi import APIRouter, Depends, Header, HTTPException
from pydantic import BaseModel, Field, field_validator
from club_tenancy import is_platform_admin, is_superadmin
from db import get_db, get_cursor, r2d
from media_legal_hold import (
LEGAL_HOLD_REASON_CODES,
assert_superadmin_for_legal_hold,
set_legal_hold,
)
from media_rights import write_audit_log_entry
from tenant_context import TenantContext, get_tenant_context
router = APIRouter(prefix="/api", tags=["content_reports"])
# Erlaubte Meldungsgruende
REPORT_REASONS = frozenset({
"copyright",
"image_rights",
"privacy",
"minors",
"illegal_content",
"youth_protection",
"offensive_content",
"other",
})
REASON_LABELS_DE = {
"copyright": "Urheberrecht",
"image_rights": "Bildrechte",
"privacy": "Datenschutz / Persönlichkeitsrecht",
"minors": "Minderjährige",
"illegal_content": "Rechtswidriger Inhalt",
"youth_protection": "Jugendschutz",
"offensive_content": "Beleidigender Inhalt",
"other": "Sonstiges",
}
# Gruende mit hoher Prioritaet (illegal, Minderjaehrigenschutz)
HIGH_PRIORITY_REASONS = frozenset({
"minors",
"illegal_content",
"youth_protection",
})
# Mapping: report_reason -> legal_hold reason_code
_REASON_TO_HOLD_CODE = {
"copyright": "copyright_complaint",
"image_rights": "rights_dispute",
"privacy": "privacy_complaint",
"minors": "youth_protection",
"illegal_content": "illegal_content",
"youth_protection": "youth_protection",
"offensive_content": "illegal_content",
"other": "other",
}
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
# ─── Pydantic-Modelle ────────────────────────────────────────────────────────
class ContentReportCreate(BaseModel):
target_type: str = Field(default="media_asset")
target_id: int = Field(..., ge=1)
report_reason: str
report_description: str = Field(..., min_length=10, max_length=8000)
reporter_name: str = Field(..., min_length=1, max_length=200)
reporter_email: str = Field(..., min_length=5, max_length=200)
good_faith_confirmed: bool
@field_validator("target_type")
@classmethod
def validate_target_type(cls, v: str) -> str:
if v not in ("media_asset", "exercise"):
raise ValueError("target_type muss 'media_asset' oder 'exercise' sein")
return v
@field_validator("report_reason")
@classmethod
def validate_reason(cls, v: str) -> str:
if v not in REPORT_REASONS:
raise ValueError(f"Ungueltiger report_reason. Erlaubt: {sorted(REPORT_REASONS)}")
return v
@field_validator("reporter_email")
@classmethod
def validate_email(cls, v: str) -> str:
if not _EMAIL_RE.match(v.strip()):
raise ValueError("Ungueltige E-Mail-Adresse")
return v.strip().lower()
@field_validator("reporter_name")
@classmethod
def validate_name(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("Name darf nicht leer sein")
return v
class ContentReportPatch(BaseModel):
status: Optional[str] = None
resolution_note: Optional[str] = Field(None, max_length=4000)
assigned_to_profile_id: Optional[int] = None
@field_validator("status")
@classmethod
def validate_status(cls, v: Optional[str]) -> Optional[str]:
if v is None:
return v
allowed = {"submitted", "under_review", "resolved_no_action",
"resolved_legal_hold", "rejected_invalid"}
if v not in allowed:
raise ValueError(f"Ungueltiger status. Erlaubt: {sorted(allowed)}")
return v
class ContentReportLegalHoldBody(BaseModel):
reason_note: str = Field(..., min_length=5, max_length=2000)
# ─── Hilfsfunktionen ────────────────────────────────────────────────────────
def _assert_can_manage_report(cur, role: Optional[str], pid: int, report: dict) -> None:
"""Platform-Admins: jede Meldung. Club-Admin: nur Meldungen zu Medien ihres Vereins."""
if is_platform_admin(role):
return
if report.get("target_type") != "media_asset":
raise HTTPException(status_code=403, detail="Nur Plattform-Admins können Meldungen zu Übungen bearbeiten")
cur.execute("SELECT club_id FROM media_assets WHERE id = %s", (int(report["target_id"]),))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
club_id = r2d(row).get("club_id")
if not club_id:
raise HTTPException(status_code=403, detail="Kein Zugriff – Medium ohne Vereinszugehörigkeit")
cur.execute(
"""
SELECT 1 FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.club_id = %s
AND cm.status = 'active' AND r.role_code = 'club_admin'
""",
(pid, club_id),
)
if cur.fetchone() is None:
raise HTTPException(status_code=403, detail="Kein Zugriff auf diese Meldung")
def _assert_can_set_legal_hold_from_report(cur, role: Optional[str], pid: int, asset_id: int) -> None:
"""Superadmin: immer. Club-Admin: nur für Vereinsmedien mit visibility != 'official'."""
if is_superadmin(role):
return
cur.execute("SELECT club_id, visibility FROM media_assets WHERE id = %s", (asset_id,))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(row)
if asset.get("visibility") == "official":
raise HTTPException(
status_code=403,
detail="Legal Hold auf offiziellen Medien erfordert Superadmin-Rechte",
)
club_id = asset.get("club_id")
if not club_id:
raise HTTPException(status_code=403, detail="Legal Hold erfordert Superadmin-Rechte für Medien ohne Vereinszugehörigkeit")
cur.execute(
"""
SELECT 1 FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.club_id = %s
AND cm.status = 'active' AND r.role_code = 'club_admin'
""",
(pid, club_id),
)
if cur.fetchone() is None:
raise HTTPException(status_code=403, detail="Kein Zugriff – Superadmin oder Vereinsadmin des Vereins erforderlich")
def _is_media_asset_visible_anonymous(cur, asset_id: int) -> bool:
"""True wenn das Medium als 'official' und aktiv gilt (fuer anonyme Meldung zugaenglich)."""
cur.execute(
"""
SELECT 1 FROM media_assets
WHERE id = %s
AND visibility = 'official'
AND lifecycle_state = 'active'
AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)
""",
(asset_id,),
)
return cur.fetchone() is not None
def _is_media_asset_visible_to_profile(cur, asset_id: int, profile_id: int, global_role: Optional[str]) -> bool:
"""Prueft ob ein eingeloggter Nutzer das Medium sehen darf."""
if is_platform_admin(global_role):
cur.execute("SELECT 1 FROM media_assets WHERE id = %s", (asset_id,))
return cur.fetchone() is not None
cur.execute(
"""
SELECT ma.id, ma.visibility, ma.club_id, ma.uploaded_by_profile_id
FROM media_assets ma
WHERE ma.id = %s
AND ma.lifecycle_state = 'active'
AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL)
""",
(asset_id,),
)
row = cur.fetchone()
if not row:
return False
asset = r2d(row)
visibility = asset.get("visibility")
if visibility == "official":
return True
if visibility == "club":
club_id = asset.get("club_id")
if not club_id:
return False
cur.execute(
"""
SELECT 1 FROM club_members
WHERE profile_id = %s AND club_id = %s AND status = 'active'
""",
(profile_id, club_id),
)
return cur.fetchone() is not None
if visibility == "private":
if asset.get("uploaded_by_profile_id") == profile_id:
return True
club_id = asset.get("club_id")
if club_id:
cur.execute(
"""
SELECT 1 FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.club_id = %s AND cm.status = 'active'
AND r.role_code = 'club_admin'
""",
(profile_id, club_id),
)
return cur.fetchone() is not None
return False
def _is_exercise_visible_to_profile(cur, exercise_id: int, profile_id: Optional[int], global_role: Optional[str]) -> bool:
"""Vereinfachte Sichtbarkeitspruefung fuer Uebungen (fuer Meldungen)."""
if profile_id and is_platform_admin(global_role):
cur.execute("SELECT 1 FROM exercises WHERE id = %s AND status != 'deleted'", (exercise_id,))
return cur.fetchone() is not None
if profile_id is None:
cur.execute(
"SELECT 1 FROM exercises WHERE id = %s AND visibility = 'official' AND status = 'active'",
(exercise_id,),
)
return cur.fetchone() is not None
cur.execute(
"""
SELECT e.visibility, e.club_id, e.created_by_profile_id
FROM exercises e WHERE e.id = %s AND e.status != 'deleted'
""",
(exercise_id,),
)
row = cur.fetchone()
if not row:
return False
ex = r2d(row)
if ex.get("visibility") == "official":
return True
if ex.get("visibility") == "club":
club_id = ex.get("club_id")
if not club_id:
return False
cur.execute(
"SELECT 1 FROM club_members WHERE profile_id = %s AND club_id = %s AND status = 'active'",
(profile_id, club_id),
)
return cur.fetchone() is not None
if ex.get("visibility") == "private":
return ex.get("created_by_profile_id") == profile_id
return False
def _resolve_optional_auth(cur, x_auth_token: Optional[str]) -> tuple[Optional[int], Optional[str]]:
"""Gibt (profile_id, global_role) zurueck wenn Token gueltig, sonst (None, None)."""
if not x_auth_token:
return None, None
cur.execute(
"""
SELECT p.id AS profile_id, p.role
FROM sessions s
INNER JOIN profiles p ON p.id = s.profile_id
WHERE s.token = %s
AND (s.expires_at IS NULL OR s.expires_at > NOW())
""",
(x_auth_token,),
)
row = cur.fetchone()
if not row:
return None, None
d = r2d(row)
return d.get("profile_id"), d.get("role")
def _get_platform_admin_emails(cur) -> list[str]:
"""Gibt E-Mail-Adressen aller aktiven Plattform-Admins zurueck."""
cur.execute(
"""
SELECT email FROM profiles
WHERE role IN ('admin', 'superadmin')
AND email IS NOT NULL AND email <> ''
"""
)
return [r2d(row)["email"] for row in cur.fetchall()]
def _send_email(to: str, subject: str, body: str) -> None:
"""SMTP-Versand (best-effort, ignoriert Fehler und nicht konfiguriertes SMTP)."""
try:
import smtplib, ssl
from email.mime.text import MIMEText
smtp_host = (os.getenv("SMTP_HOST") or "").strip()
smtp_user = (os.getenv("SMTP_USER") or "").strip()
smtp_pass = os.getenv("SMTP_PASS") or ""
if not smtp_host or not smtp_user or not smtp_pass:
return
smtp_port = int(os.getenv("SMTP_PORT") or "587")
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
force_ssl = (os.getenv("SMTP_SSL", "").strip().lower() in ("1", "true", "yes")) or smtp_port == 465
use_tls = os.getenv("SMTP_STARTTLS", "true").strip().lower() not in ("0", "false", "no")
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = smtp_from
msg["To"] = to
ctx = ssl.create_default_context()
if force_ssl:
with smtplib.SMTP_SSL(smtp_host, smtp_port, context=ctx, timeout=30) as srv:
srv.login(smtp_user, smtp_pass)
srv.send_message(msg)
else:
with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as srv:
srv.ehlo()
if use_tls:
srv.starttls(context=ctx)
srv.ehlo()
srv.login(smtp_user, smtp_pass)
srv.send_message(msg)
except Exception as exc:
print(f"[SMTP content_reports] Fehler: {exc}")
def _notify_report_submitted(
*,
report_id: int,
reporter_name: str,
reporter_email: str,
reason: str,
priority: str,
target_type: str,
target_id: int,
target_label: str,
admin_emails: list[str],
) -> None:
"""Sendet Bestaetigungs-Mail an Melder + Benachrichtigung an alle Plattform-Admins (best-effort)."""
app_url = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
reason_label = REASON_LABELS_DE.get(reason, reason)
prio_label = "DRINGEND" if priority == "high" else "normal"
# Bestaetigungs-Mail an Melder
confirmation_body = (
f"Hallo {reporter_name},\n\n"
f"Ihre Meldung (#{report_id}) wurde entgegengenommen.\n\n"
f"Meldegrund: {reason_label}\n"
f"Gemeldeter Inhalt: {target_label}\n\n"
f"Ein Administrator wird Ihre Meldung zeitnah prüfen. Sie müssen nichts weiter tun.\n\n"
f"Shinkan Jinkendo\n"
f"{app_url}"
)
_send_email(reporter_email, f"Meldung #{report_id} eingegangen – Shinkan Jinkendo", confirmation_body)
# Admin-Benachrichtigung
admin_body = (
f"Neue Inhaltsmeldung #{report_id} [{prio_label}]\n\n"
f"Meldegrund: {reason_label}\n"
f"Gemeldeter Inhalt: {target_label}\n"
f"Gemeldet von: {reporter_name} <{reporter_email}>\n\n"
f"Posteingang öffnen: {app_url}/inbox\n"
)
subject = f"Inhaltsmeldung #{report_id} [{prio_label}] – Shinkan Jinkendo"
for email in admin_emails:
_send_email(email, subject, admin_body)
def _report_row_to_dict(row) -> dict:
return r2d(row)
# ─── Endpoints ──────────────────────────────────────────────────────────────
@router.post("/content-reports", status_code=201)
def submit_content_report(
body: ContentReportCreate,
x_auth_token: Optional[str] = Header(default=None),
):
"""
Meldung einreichen (optionale Authentifizierung).
- Ohne Login: nur fuer 'official'-Medien erlaubt (öffentlich erreichbare Inhalte)
- Mit Login: fuer alle Inhalte, die der Nutzer laut Sichtbarkeitslogik sehen darf
- Gutglaubenserklärung (good_faith_confirmed=true) ist Pflicht
- Journaleintrag im Medien-Audit-Log (wenn target_type=media_asset)
- E-Mail-Bestaetigung an Melder + Benachrichtigung an Plattform-Admins (best-effort)
"""
if not body.good_faith_confirmed:
raise HTTPException(
status_code=400,
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
)
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
report_id: int
admin_emails: list[str] = []
with get_db() as conn:
cur = get_cursor(conn)
# Optionale Auth aufloesen
profile_id, global_role = _resolve_optional_auth(cur, x_auth_token)
# Sichtbarkeit pruefen
if body.target_type == "media_asset":
if profile_id:
visible = _is_media_asset_visible_to_profile(cur, body.target_id, profile_id, global_role)
else:
visible = _is_media_asset_visible_anonymous(cur, body.target_id)
if not visible:
raise HTTPException(
status_code=404,
detail="Das gemeldete Medium existiert nicht oder ist nicht zugänglich.",
)
elif body.target_type == "exercise":
visible = _is_exercise_visible_to_profile(cur, body.target_id, profile_id, global_role)
if not visible:
raise HTTPException(
status_code=404,
detail="Die gemeldete Übung existiert nicht oder ist nicht zugänglich.",
)
cur.execute(
"""
INSERT INTO content_reports (
target_type, target_id, report_reason, report_description,
reporter_name, reporter_email, reporter_profile_id,
good_faith_confirmed, priority, status,
submitted_at, created_at, updated_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'submitted', NOW(), NOW(), NOW())
RETURNING id, status, priority, submitted_at
""",
(
body.target_type,
body.target_id,
body.report_reason,
body.report_description.strip(),
body.reporter_name,
body.reporter_email,
profile_id,
body.good_faith_confirmed,
priority,
),
)
row = cur.fetchone()
result = r2d(row)
report_id = int(result["id"])
# Dateinamen / Zielbezeichnung fuer E-Mail abfragen
target_label_for_email = f"{'Medium' if body.target_type == 'media_asset' else 'Übung'} #{body.target_id}"
if body.target_type == "media_asset":
cur.execute("SELECT original_filename FROM media_assets WHERE id = %s", (body.target_id,))
fn_row = cur.fetchone()
if fn_row:
fn = r2d(fn_row).get("original_filename") or ""
if fn:
target_label_for_email = f"{fn} (Medium #{body.target_id})"
elif body.target_type == "exercise":
cur.execute("SELECT title FROM exercises WHERE id = %s", (body.target_id,))
ex_row = cur.fetchone()
if ex_row:
ex_name = r2d(ex_row).get("title") or ""
if ex_name:
target_label_for_email = f"{ex_name} (Übung #{body.target_id})"
# Audit-Log-Eintrag (nur fuer media_asset-Meldungen)
if body.target_type == "media_asset":
write_audit_log_entry(
cur,
body.target_id,
profile_id,
"content_report_filed",
{},
{
"content_report_id": report_id,
"report_reason": REASON_LABELS_DE.get(body.report_reason, body.report_reason),
"priority": "hoch" if priority == "high" else "normal",
},
)
# Admin-E-Mails vor Commit abfragen (Verbindung noch offen)
admin_emails = _get_platform_admin_emails(cur)
conn.commit()
# E-Mails nach Commit senden (best-effort, kein Rollback-Risiko)
_notify_report_submitted(
report_id=report_id,
reporter_name=body.reporter_name,
reporter_email=body.reporter_email,
reason=body.report_reason,
priority=priority,
target_type=body.target_type,
target_id=body.target_id,
target_label=target_label_for_email,
admin_emails=admin_emails,
)
return {
"id": report_id,
"status": result["status"],
"priority": result["priority"],
"submitted_at": str(result["submitted_at"]),
"message": "Ihre Meldung wurde entgegengenommen. Ein Administrator wird sie prüfen.",
}
@router.get("/me/inbox/content-reports")
def list_inbox_content_reports(
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Meldungen fuer die Inbox.
- Plattform-Admins (admin/superadmin): alle Meldungen
- Club-Admins: nur Meldungen ueber Medien ihres Vereins
"""
pid = tenant.profile_id
role = tenant.global_role
is_padmin = is_platform_admin(role)
with get_db() as conn:
cur = get_cursor(conn)
if is_padmin:
# Plattform-Admin: alle Meldungen
cur.execute(
"""
SELECT
cr.id,
cr.target_type,
cr.target_id,
cr.report_reason,
cr.report_description,
cr.reporter_name,
cr.reporter_email,
cr.reporter_profile_id,
cr.priority,
cr.status,
cr.assigned_to_profile_id,
cr.reviewed_by_profile_id,
cr.reviewed_at,
cr.resolution_note,
cr.submitted_at,
cr.created_at,
cr.updated_at,
ma.original_filename AS target_filename,
ma.visibility AS target_visibility,
ma.mime_type AS target_mime_type,
ma.legal_hold_active AS target_legal_hold_active,
ex.title AS target_exercise_name,
rev.name AS reviewed_by_name,
asgn.name AS assigned_to_name
FROM content_reports cr
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
ORDER BY
CASE WHEN cr.status = 'submitted' THEN 0
WHEN cr.status = 'under_review' THEN 1
ELSE 2 END ASC,
cr.priority DESC,
cr.created_at ASC
LIMIT 500
""",
)
else:
# Club-Admin: Meldungen ueber Medien der eigenen Vereine
# Zuerst pruefen ob ueberhaupt Club-Admin-Rolle vorhanden
cur.execute(
"""
SELECT COUNT(*) AS cnt
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
""",
(pid,),
)
cnt_row = r2d(cur.fetchone())
if int(cnt_row.get("cnt", 0)) == 0:
raise HTTPException(status_code=403, detail="Kein Zugriff auf Inhaltsmeldungen")
cur.execute(
"""
SELECT
cr.id,
cr.target_type,
cr.target_id,
cr.report_reason,
cr.report_description,
cr.reporter_name,
cr.reporter_email,
cr.reporter_profile_id,
cr.priority,
cr.status,
cr.assigned_to_profile_id,
cr.reviewed_by_profile_id,
cr.reviewed_at,
cr.resolution_note,
cr.submitted_at,
cr.created_at,
cr.updated_at,
ma.original_filename AS target_filename,
ma.visibility AS target_visibility,
ma.mime_type AS target_mime_type,
ma.legal_hold_active AS target_legal_hold_active,
ex.title AS target_exercise_name,
rev.name AS reviewed_by_name,
asgn.name AS assigned_to_name
FROM content_reports cr
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
WHERE cr.target_type = 'media_asset'
AND ma.club_id IN (
SELECT cm.club_id
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.status = 'active' AND r.role_code = 'club_admin'
)
ORDER BY
CASE WHEN cr.status = 'submitted' THEN 0
WHEN cr.status = 'under_review' THEN 1
ELSE 2 END ASC,
cr.priority DESC,
cr.created_at ASC
LIMIT 200
""",
(pid,),
)
return [_report_row_to_dict(row) for row in cur.fetchall()]
@router.get("/content-reports/{report_id}")
def get_content_report(
report_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Detail-Ansicht einer Meldung fuer Plattform-Admins und zustaendige Club-Admins."""
pid = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT
cr.*,
ma.original_filename AS target_filename,
ma.visibility AS target_visibility,
ma.mime_type AS target_mime_type,
ma.legal_hold_active AS target_legal_hold_active,
ma.legal_hold_reason_code AS target_legal_hold_reason_code,
ex.title AS target_exercise_name,
ex.visibility AS target_exercise_visibility,
rev.name AS reviewed_by_name,
asgn.name AS assigned_to_name,
rep.name AS reporter_profile_name
FROM content_reports cr
LEFT JOIN media_assets ma ON ma.id = cr.target_id AND cr.target_type = 'media_asset'
LEFT JOIN exercises ex ON ex.id = cr.target_id AND cr.target_type = 'exercise'
LEFT JOIN profiles rev ON rev.id = cr.reviewed_by_profile_id
LEFT JOIN profiles asgn ON asgn.id = cr.assigned_to_profile_id
LEFT JOIN profiles rep ON rep.id = cr.reporter_profile_id
WHERE cr.id = %s
""",
(report_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
report_dict = _report_row_to_dict(row)
_assert_can_manage_report(cur, role, pid, report_dict)
return report_dict
@router.patch("/content-reports/{report_id}")
def patch_content_report(
report_id: int,
body: ContentReportPatch,
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Status und Bearbeitungsnotiz einer Meldung aktualisieren.
Abschluss ohne Massnahme (resolved_no_action, rejected_invalid) erfordert resolution_note.
Plattform-Admins: jede Meldung. Club-Admins: nur Meldungen zu Medien ihres Vereins.
"""
pid = tenant.profile_id
role = tenant.global_role
if body.status in ("resolved_no_action", "rejected_invalid") and not (body.resolution_note or "").strip():
raise HTTPException(
status_code=400,
detail="Bei Abschluss ohne Massnahme ist eine Begründung (resolution_note) Pflicht.",
)
STATUS_LABELS_DE = {
"submitted": "Eingegangen",
"under_review": "In Bearbeitung",
"resolved_no_action": "Abgeschlossen (kein Handlungsbedarf)",
"resolved_legal_hold": "Abgeschlossen (Legal Hold)",
"rejected_invalid": "Abgewiesen (ungültig)",
}
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, status, resolution_note, target_type, target_id FROM content_reports WHERE id = %s",
(report_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
old_report = r2d(row)
_assert_can_manage_report(cur, role, pid, old_report)
old_status = old_report["status"]
old_note = (old_report.get("resolution_note") or "").strip()
updates = ["updated_at = NOW()"]
params = []
if body.status is not None:
updates.append("status = %s")
params.append(body.status)
if body.status in ("resolved_no_action", "resolved_legal_hold", "rejected_invalid"):
updates.append("reviewed_by_profile_id = %s")
updates.append("reviewed_at = NOW()")
params.append(pid)
elif body.status == "submitted":
# Wieder öffnen: Prüferfelder zurücksetzen
updates.append("reviewed_by_profile_id = NULL")
updates.append("reviewed_at = NULL")
if body.resolution_note is not None:
updates.append("resolution_note = %s")
params.append(body.resolution_note.strip() or None)
if body.assigned_to_profile_id is not None:
updates.append("assigned_to_profile_id = %s")
params.append(body.assigned_to_profile_id)
if len(updates) == 1:
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren angegeben")
params.append(report_id)
cur.execute(
f"UPDATE content_reports SET {', '.join(updates)} WHERE id = %s RETURNING id, status",
params,
)
updated = r2d(cur.fetchone())
new_status = updated["status"]
is_media = old_report["target_type"] == "media_asset"
if is_media:
new_note = (body.resolution_note or "").strip() if body.resolution_note is not None else old_note
# Audit-Log: Statuswechsel
if body.status is not None and old_status != new_status:
write_audit_log_entry(
cur,
int(old_report["target_id"]),
pid,
"content_report_filed",
{"status": STATUS_LABELS_DE.get(old_status, old_status)},
{
"content_report_id": report_id,
"status": STATUS_LABELS_DE.get(new_status, new_status),
**({"begründung": new_note} if new_note else {}),
},
)
# Audit-Log: reine Notizänderung (ohne Statuswechsel)
elif body.resolution_note is not None and new_note != old_note:
write_audit_log_entry(
cur,
int(old_report["target_id"]),
pid,
"content_report_filed",
{"content_report_id": report_id, "begründung": old_note or None},
{"content_report_id": report_id, "begründung": new_note or None},
)
conn.commit()
return {"ok": True, "id": updated["id"], "status": updated["status"]}
@router.post("/content-reports/{report_id}/legal-hold")
def set_legal_hold_from_report(
report_id: int,
body: ContentReportLegalHoldBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Legal Hold (P-11) aus einer Meldung heraus setzen.
Superadmin: immer. Club-Admin: nur fuer Vereinsmedien (visibility != 'official').
Nur fuer Meldungen mit target_type='media_asset'.
Der Reason-Code wird automatisch aus dem report_reason der Meldung abgeleitet.
Nach dem Setzen wird der Report-Status auf 'resolved_legal_hold' gesetzt.
"""
pid = tenant.profile_id
role = tenant.global_role
# Plattform-Admin ohne Superadmin hat keine Legal-Hold-Rechte (fruehzeitig ablehnen)
if is_platform_admin(role) and not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Legal Hold erfordert Superadmin oder Vereinsadmin-Rechte",
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, target_type, target_id, report_reason, status FROM content_reports WHERE id = %s",
(report_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Meldung nicht gefunden")
report = r2d(row)
if report["target_type"] != "media_asset":
raise HTTPException(
status_code=400,
detail="Legal Hold ist nur fuer Meldungen mit target_type='media_asset' verfügbar.",
)
asset_id = int(report["target_id"])
_assert_can_set_legal_hold_from_report(cur, role, pid, asset_id)
reason_code = _REASON_TO_HOLD_CODE.get(report["report_reason"], "other")
# P-11-Service aufrufen
set_legal_hold(
cur=cur,
conn=conn,
asset_id=asset_id,
acting_profile_id=pid,
reason_code=reason_code,
reason_note=f"[P-13 Meldung #{report_id}] {body.reason_note.strip()}",
)
# set_legal_hold committed bereits — neue Transaktion fuer Report-Update
cur.execute(
"""
UPDATE content_reports
SET status = 'resolved_legal_hold',
reviewed_by_profile_id = %s,
reviewed_at = NOW(),
resolution_note = %s,
updated_at = NOW()
WHERE id = %s
RETURNING id, status
""",
(pid, f"Legal Hold gesetzt auf Asset #{asset_id} (reason_code: {reason_code})", report_id),
)
updated = r2d(cur.fetchone())
conn.commit()
return {
"ok": True,
"report_id": updated["id"],
"report_status": updated["status"],
"asset_id": asset_id,
"legal_hold_reason_code": reason_code,
}
+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}
+567 -16
View File
@@ -9,13 +9,17 @@ import json
import logging
import os
import re
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple
from urllib.parse import quote
from fastapi import APIRouter, HTTPException, Depends, Query, Request, UploadFile, File, Form
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 (
@@ -29,6 +33,8 @@ from club_tenancy import (
)
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
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 exercise_rich_text import (
RICH_HTML_EXERCISE_FIELDS,
assert_no_inline_media_references_on_create,
@@ -93,6 +99,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]:
@@ -106,6 +113,25 @@ def normalize_exercise_skill_level(value) -> Optional[str]:
return s
return _LEGACY_SKILL_LEVEL_SLUG.get(s)
_ALLOWED_SKILL_INTENSITY = frozenset({"niedrig", "mittel", "hoch"})
def normalize_exercise_skill_intensity(value) -> str:
"""Kanonische Nutzeneinschätzung; leer/ungültig → mittel (kein leerer Wert)."""
if value is None:
return "mittel"
key = str(value).strip().lower()
if key in ("low",):
return "niedrig"
if key in ("medium",):
return "mittel"
if key in ("high",):
return "hoch"
if key in _ALLOWED_SKILL_INTENSITY:
return key
return "mittel"
MEDIA_ROOT = Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent.parent / "media")))
MAX_EXERCISE_MEDIA = 10
# Upload-Limits (Übungs-Medien): Trainer wie bisher kleiner; Admin/Superadmin höheres Limit für große Videos
@@ -196,6 +222,26 @@ def _upload_limit_bytes(tenant: TenantContext) -> int:
# Pydantic Models
# ============================================================================
# Archetyp-IDs (Maschinenlesbare Ablaufmuster) — konsistent zur technischen Entwurfsspezifikation
COMBINATION_ARCHETYPE_IDS = frozenset(
{
"circuit_rotate_time",
"circuit_all_parallel",
"sequence_linear",
"station_parcour",
"pair_superset",
"time_domain_interval",
"free_method_block",
}
)
class CombinationSlotIn(BaseModel):
slot_index: int = Field(ge=0, le=99)
title: Optional[str] = Field(None, max_length=200)
candidate_exercise_ids: list[int] = Field(default_factory=list)
class ExerciseCreate(BaseModel):
# Basis-Felder (goal/execution: DB-Constraint mind. eines; Wiki oft nur eines)
title: str = Field(..., min_length=3, max_length=300)
@@ -229,6 +275,12 @@ class ExerciseCreate(BaseModel):
status: str = "draft"
club_id: Optional[int] = None
# Kombinationsübung (Phase 2)
exercise_kind: Literal["simple", "combination"] = "simple"
method_archetype: Optional[str] = Field(None, max_length=80)
method_profile: Dict[str, Any] = Field(default_factory=dict)
combination_slots: list[CombinationSlotIn] = Field(default_factory=list)
@model_validator(mode="after")
def normalize_goal_execution(self):
g = (self.goal or "").strip() or None
@@ -268,6 +320,11 @@ class ExerciseUpdate(BaseModel):
# Vereins-Übung: fehlende Copyrights an Datei-Assets nach Prompt-Text setzen (PUT-Retry)
default_club_media_copyright: Optional[str] = Field(default=None, max_length=2000)
exercise_kind: Optional[Literal["simple", "combination"]] = None
method_archetype: Optional[str] = Field(None, max_length=80)
method_profile: Optional[Dict[str, Any]] = None
combination_slots: Optional[list[CombinationSlotIn]] = None
@model_validator(mode="after")
def normalize_goal_execution(self):
if self.goal is not None:
@@ -809,6 +866,174 @@ def _resolve_local_media_file(
return path_under_media_root(media_root, asset_storage_key)
return _abs_media_path(file_path_db or "", media_root) if file_path_db else None
def _normalize_method_profile_store(raw: Any) -> Dict[str, Any]:
if raw is None:
return {}
if isinstance(raw, dict):
return raw
raise HTTPException(status_code=400, detail="method_profile muss ein JSON-Objekt sein")
def _validate_archetype_for_kind(kind: str, archetype: Optional[str]) -> None:
if kind != "combination":
return
if archetype is None or not str(archetype).strip():
return
a = str(archetype).strip()
if a not in COMBINATION_ARCHETYPE_IDS:
raise HTTPException(
status_code=400,
detail=(
"Unbekannter method_archetype. Erlaubt: "
+ ", ".join(sorted(COMBINATION_ARCHETYPE_IDS))
),
)
def _assert_candidate_exercises_for_combination(cur, tenant: TenantContext, ids: List[int]) -> None:
if not ids:
return
seen: set[int] = set()
for cid_raw in ids:
cid = int(cid_raw)
if cid in seen:
continue
seen.add(cid)
cur.execute(
"""SELECT id, exercise_kind, visibility, club_id, created_by
FROM exercises WHERE id = %s""",
(cid,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=400, detail=f"Slot-Verweis: Übung #{cid} nicht gefunden")
rd = r2d(row)
k = str(rd.get("exercise_kind") or "simple").strip().lower()
if k != "simple":
raise HTTPException(
status_code=400,
detail=f"Slot-Verweis: Übung #{cid} ist eine Kombinationsübung — nur Einzelübungen erlaubt",
)
if not library_content_visible_to_profile(
cur,
tenant.profile_id,
rd.get("visibility"),
rd.get("club_id"),
rd.get("created_by"),
tenant.global_role,
):
raise HTTPException(status_code=403, detail=f"Slot-Verweis: keine Leserechte für Übung #{cid}")
def _validate_and_normalize_combination_slots_payload(
cur,
tenant: TenantContext,
slots: Optional[List[CombinationSlotIn]],
) -> List[Tuple[int, Optional[str], List[int]]]:
if slots is None:
return []
normalized: Dict[int, Tuple[Optional[str], List[int]]] = {}
for s in sorted(slots, key=lambda x: x.slot_index):
cid_list_raw = list(s.candidate_exercise_ids or [])
cid_list: List[int] = []
for x in cid_list_raw:
cid_list.append(int(x))
title = ((s.title or "").strip()) or None
normalized[int(s.slot_index)] = (title, cid_list)
out: List[Tuple[int, Optional[str], List[int]]] = []
for idx in sorted(normalized.keys()):
title, cands = normalized[idx]
if not cands:
raise HTTPException(
status_code=400,
detail=f"Station (Index {idx}): mindestens eine Einzelübung (Pool) ist erforderlich",
)
out.append((idx, title, cands))
return out
def replace_combination_slots(
cur,
tenant: TenantContext,
exercise_id: int,
slots_norm: List[Tuple[int, Optional[str], List[int]]],
) -> None:
flat_ids = [cid for _, __, xs in slots_norm for cid in xs]
_assert_candidate_exercises_for_combination(cur, tenant, flat_ids)
cur.execute("DELETE FROM combination_exercise_slots WHERE exercise_id = %s", (exercise_id,))
for slot_index, title, cand_ids in slots_norm:
cur.execute(
"""INSERT INTO combination_exercise_slots (exercise_id, slot_index, title)
VALUES (%s, %s, %s) RETURNING id""",
(exercise_id, slot_index, title),
)
row = cur.fetchone()
sid = row["id"] if isinstance(row, dict) else row[0]
for so, cid in enumerate(cand_ids):
cur.execute(
"""INSERT INTO combination_slot_candidates (slot_id, candidate_exercise_id, sort_order)
VALUES (%s, %s, %s)""",
(sid, int(cid), int(so)),
)
def wipe_combination_structure(cur, exercise_id: int) -> None:
cur.execute("DELETE FROM combination_exercise_slots WHERE exercise_id = %s", (exercise_id,))
def assert_exercise_not_combination(cur, exercise_id: int) -> None:
cur.execute(
"SELECT COALESCE(exercise_kind, 'simple') AS exercise_kind FROM exercises WHERE id = %s",
(exercise_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
if str(r2d(row).get("exercise_kind") or "simple").strip().lower() == "combination":
raise HTTPException(
status_code=400,
detail="Kombinationsübungen unterstützen keine Varianten.",
)
def load_combination_slots_for_exercise(cur, exercise_id: int) -> List[dict]:
"""Stationsliste einer Kombinationsübung (gleiches Format wie GET /api/exercises/:id)."""
cur.execute(
"""SELECT id, slot_index, title FROM combination_exercise_slots
WHERE exercise_id = %s ORDER BY slot_index ASC, id ASC""",
(exercise_id,),
)
slot_rows = [r2d(r) for r in cur.fetchall()]
slots_out: List[dict] = []
for sr in slot_rows:
slot_pk = sr["id"]
cur.execute(
"""SELECT candidate_exercise_id FROM combination_slot_candidates
WHERE slot_id = %s ORDER BY sort_order ASC, id ASC""",
(slot_pk,),
)
crows = cur.fetchall()
cids = [int(r2d(c)["candidate_exercise_id"]) for c in crows]
cand_meta: Dict[int, Optional[str]] = {}
if cids:
ph = ",".join(["%s"] * len(cids))
cur.execute(
f"SELECT id, title FROM exercises WHERE id IN ({ph})",
tuple(cids),
)
cand_meta = {int(r2d(x)["id"]): r2d(x).get("title") for x in cur.fetchall()}
slots_out.append(
{
"slot_index": sr["slot_index"],
"title": sr.get("title"),
"candidate_exercise_ids": cids,
"candidates": [{"exercise_id": cid, "title": cand_meta.get(cid)} for cid in cids],
}
)
return slots_out
def enrich_exercise_detail(exercise_id: int, cur) -> dict:
"""
Lädt alle M:N Relations für eine Übung und gibt ein vollständiges
@@ -896,13 +1121,15 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
FROM exercise_skills es
JOIN skills s ON es.skill_id = s.id
WHERE es.exercise_id = %s
ORDER BY es.is_primary DESC, s.name""",
ORDER BY s.name""",
(exercise_id,)
)
exercise["skills"] = [r2d(r) for r in cur.fetchall()]
for sk in exercise["skills"]:
sk["required_level"] = normalize_exercise_skill_level(sk.get("required_level"))
sk["target_level"] = normalize_exercise_skill_level(sk.get("target_level"))
sk["intensity"] = normalize_exercise_skill_intensity(sk.get("intensity"))
sk["is_primary"] = False
# Variants (1:N) - mit Progression (Reihenfolge: sequence_order, dann progression_level)
cur.execute(
@@ -921,7 +1148,8 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
"""SELECT em.id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context,
em.media_asset_id, ma.copyright_notice AS asset_copyright_notice,
ma.lifecycle_state AS asset_lifecycle_state
ma.lifecycle_state AS asset_lifecycle_state,
ma.legal_hold_active AS asset_legal_hold_active
FROM exercise_media em
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
WHERE em.exercise_id = %s
@@ -930,6 +1158,14 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
)
exercise["media"] = [r2d(r) for r in cur.fetchall()]
mp_raw = exercise.get("method_profile")
exercise["method_profile"] = mp_raw if isinstance(mp_raw, dict) else {}
exercise["exercise_kind"] = str(exercise.get("exercise_kind") or "simple").strip().lower()
exercise["combination_slots"] = []
if exercise["exercise_kind"] == "combination":
exercise["combination_slots"] = load_combination_slots_for_exercise(cur, exercise_id)
return exercise
@@ -1008,8 +1244,8 @@ def assign_exercise_relations(
(
exercise_id,
skill["skill_id"],
skill.get("is_primary", False),
skill.get("intensity"),
False,
normalize_exercise_skill_intensity(skill.get("intensity")),
normalize_exercise_skill_level(skill.get("required_level")),
normalize_exercise_skill_level(skill.get("target_level")),
skill.get("ai_suggested", False),
@@ -1442,6 +1678,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"),
@@ -1467,6 +1717,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",
@@ -1525,15 +1784,41 @@ def list_exercises(
default=False,
description="Nur Übungen, die vom aktuellen Profil angelegt wurden (created_by = Profil)",
),
exercise_kind_any: list[str] = Query(
default=[],
description="ODER: mind. einer dieser Übungsarten — simple oder combination",
),
tenant: TenantContext = Depends(get_tenant_context),
):
"""
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)
@@ -1555,6 +1840,21 @@ def list_exercises(
where.append("e.created_by = %s")
params.append(profile_id)
ek_filtered: List[str] = []
if exercise_kind_any:
for raw in exercise_kind_any:
s = str(raw or "").strip().lower()
if not s:
continue
if s not in ("simple", "combination"):
raise HTTPException(status_code=400, detail="exercise_kind_any: nur simple oder combination")
if s not in ek_filtered:
ek_filtered.append(s)
if ek_filtered:
ph = ",".join(["%s"] * len(ek_filtered))
where.append(f"(LOWER(TRIM(COALESCE(e.exercise_kind::text,''))) IN ({ph}))")
params.extend(ek_filtered)
vis_list = _merge_str_any(visibility_any, visibility)
if vis_list:
ph = ",".join(["%s"] * len(vis_list))
@@ -1751,6 +2051,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 = """,
@@ -1773,6 +2079,7 @@ def list_exercises(
# Query (primary_focus_name für Listen-Ansicht gemäß Spec-Beispiel „focus_area“-Label)
query = f"""
SELECT e.id, e.title, e.summary, e.visibility, e.status,
e.exercise_kind, e.method_archetype,
e.created_by, p.name as creator_name,
e.club_id, c.name as club_name,
e.created_at, e.updated_at,
@@ -1809,16 +2116,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()
@@ -1826,11 +2143,14 @@ def list_exercises(
out = []
for r in rows:
d = r2d(r)
d["exercise_kind"] = str(d.get("exercise_kind") or "simple").strip().lower()
pfn = d.get("primary_focus_name")
d["focus_area"] = pfn
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):
@@ -1844,6 +2164,58 @@ 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,
)
@router.get("/exercises/{exercise_id}")
def get_exercise(
exercise_id: int,
@@ -1910,16 +2282,39 @@ def create_exercise(
cur, profile_id, tenant.global_role, body.visibility, club_id
)
kind_clean = str(body.exercise_kind or "simple").strip().lower()
if kind_clean not in ("simple", "combination"):
raise HTTPException(status_code=400, detail="exercise_kind: simple oder combination")
prof_dict = _normalize_method_profile_store(body.method_profile)
arch_raw = body.method_archetype
arch_val = (arch_raw.strip() if isinstance(arch_raw, str) and arch_raw.strip() else None)
_validate_archetype_for_kind(kind_clean, arch_val)
slots_norm: List[Tuple[int, Optional[str], List[int]]] = []
if kind_clean == "combination":
slots_norm = _validate_and_normalize_combination_slots_payload(
cur, tenant, body.combination_slots or []
)
if not slots_norm:
raise HTTPException(
status_code=400,
detail="Kombinationsübung: mindestens eine Station mit Übungen nötig",
)
mp_json = Json(prof_dict if kind_clean == "combination" else {})
arch_db = arch_val if kind_clean == "combination" else None
# Equipment als JSONB
equipment_json = json.dumps(body.equipment) if body.equipment else None
# INSERT
cur.execute(
"""INSERT INTO exercises
(title, summary, goal, execution, preparation, trainer_notes,
duration_min, duration_max, group_size_min, group_size_max,
equipment, visibility, status, created_by, club_id)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
equipment, visibility, status, created_by, club_id,
exercise_kind, method_archetype, method_profile)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
RETURNING id""",
(
body.title, body.summary, body.goal, body.execution,
@@ -1928,11 +2323,15 @@ def create_exercise(
body.group_size_min, body.group_size_max,
equipment_json,
body.visibility, body.status, profile_id, club_id,
)
kind_clean, arch_db, mp_json,
),
)
row = cur.fetchone()
exercise_id = row['id'] if isinstance(row, dict) else row[0]
if kind_clean == "combination":
replace_combination_slots(cur, tenant, exercise_id, slots_norm)
data = body.dict()
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
if (body.visibility or "").strip().lower() == "club":
@@ -1960,7 +2359,7 @@ def update_exercise(
cur = get_cursor(conn)
cur.execute(
f"""SELECT created_by, visibility, club_id,
f"""SELECT created_by, visibility, club_id, exercise_kind, method_archetype, method_profile,
{", ".join(sorted(RICH_HTML_EXERCISE_FIELDS))}
FROM exercises WHERE id = %s""",
(exercise_id,),
@@ -1990,6 +2389,84 @@ def update_exercise(
default_official_copy = data.pop("default_official_media_copyright", None)
default_club_copy = data.pop("default_club_media_copyright", None)
combo_slots_provided = "combination_slots" in data
combo_slots_payload = data.pop("combination_slots", None)
ec_kind_was = str(rd_full.get("exercise_kind") or "simple").strip().lower()
ek_provided = "exercise_kind" in data
next_kind = ec_kind_was
if ek_provided:
next_kind = str(data.pop("exercise_kind") or "simple").strip().lower()
arche_provided = "method_archetype" in data
meth_prof_provided = "method_profile" in data
next_ma_db = rd_full.get("method_archetype")
if isinstance(next_ma_db, str):
next_ma_db = next_ma_db.strip() or None
else:
next_ma_db = None
mp_row = rd_full.get("method_profile")
next_mp_db = mp_row if isinstance(mp_row, dict) else {}
if ek_provided and next_kind not in ("simple", "combination"):
raise HTTPException(status_code=400, detail="exercise_kind: simple oder combination")
if arche_provided:
va = data.pop("method_archetype")
if va is None or (isinstance(va, str) and not va.strip()):
next_ma_db = None
elif isinstance(va, str):
next_ma_db = va.strip() or None
else:
next_ma_db = None
if meth_prof_provided:
next_mp_db = _normalize_method_profile_store(data.pop("method_profile"))
if next_kind == "simple":
next_ma_db = None
next_mp_db = {}
_validate_archetype_for_kind(next_kind, next_ma_db)
if ec_kind_was == "simple" and next_kind == "combination":
if not combo_slots_provided:
raise HTTPException(
status_code=400,
detail='Umschalten auf Kombinationsübung: Feld "combination_slots" ist erforderlich',
)
combo_slots_normalized: Optional[List[Tuple[int, Optional[str], List[int]]]] = None
if combo_slots_provided:
if next_kind != "combination":
raise HTTPException(
status_code=400,
detail="combination_slots nur bei exercise_kind=combination erlaubt",
)
slots_in_raw = combo_slots_payload if combo_slots_payload is not None else []
slots_in: List[CombinationSlotIn] = []
for s in slots_in_raw:
if isinstance(s, CombinationSlotIn):
slots_in.append(s)
elif isinstance(s, dict):
slots_in.append(CombinationSlotIn(**s))
else:
raise HTTPException(status_code=400, detail="Ungültige combination_slots Payload-Struktur")
combo_slots_normalized = _validate_and_normalize_combination_slots_payload(
cur, tenant, slots_in
)
if not combo_slots_normalized:
raise HTTPException(status_code=400, detail="Kombinationsübung: mindestens eine Station mit Übungen")
update_combo_cols = (
ek_provided
or arche_provided
or meth_prof_provided
or (next_kind == "simple" and ec_kind_was != "simple")
)
merged_rich = {fld: rich_row.get(fld) for fld in RICH_HTML_EXERCISE_FIELDS}
for fld in RICH_HTML_EXERCISE_FIELDS:
if fld not in data:
@@ -2061,11 +2538,27 @@ def update_exercise(
fields.append("equipment = %s")
params.append(json.dumps(data["equipment"]) if data["equipment"] else None)
if update_combo_cols:
if ek_provided:
fields.append("exercise_kind = %s")
params.append(next_kind)
fields.append("method_archetype = %s")
params.append(next_ma_db)
fields.append("method_profile = %s")
params.append(Json(next_mp_db))
if fields:
fields.append("updated_at = NOW()")
params.append(exercise_id)
query = f"UPDATE exercises SET {', '.join(fields)} WHERE id = %s"
cur.execute(query, params)
elif combo_slots_normalized is not None:
cur.execute("UPDATE exercises SET updated_at = NOW() WHERE id = %s", (exercise_id,))
if combo_slots_normalized is not None:
replace_combination_slots(cur, tenant, exercise_id, combo_slots_normalized)
elif ec_kind_was == "combination" and next_kind == "simple":
wipe_combination_structure(cur, exercise_id)
assign_exercise_relations(cur, conn, exercise_id, data, do_commit=False)
try:
@@ -2141,6 +2634,7 @@ def reorder_exercise_variants(
with get_db() as conn:
cur = get_cursor(conn)
_assert_can_edit_exercise(cur, exercise_id, tenant)
assert_exercise_not_combination(cur, exercise_id)
cur.execute(
"SELECT id FROM exercise_variants WHERE exercise_id = %s",
@@ -2175,6 +2669,7 @@ def create_exercise_variant(
with get_db() as conn:
cur = get_cursor(conn)
_assert_can_edit_exercise(cur, exercise_id, tenant)
assert_exercise_not_combination(cur, exercise_id)
_validate_variant_prerequisite(cur, exercise_id, body.prerequisite_variant_id)
eq_json = _variant_equipment_json(body.equipment_changes)
@@ -2239,6 +2734,7 @@ def update_exercise_variant(
with get_db() as conn:
cur = get_cursor(conn)
_assert_can_edit_exercise(cur, exercise_id, tenant)
assert_exercise_not_combination(cur, exercise_id)
old = _fetch_variant_row(cur, exercise_id, variant_id)
if "variant_name" in data and data["variant_name"] is not None:
@@ -2320,6 +2816,7 @@ def delete_exercise_variant(
with get_db() as conn:
cur = get_cursor(conn)
_assert_can_edit_exercise(cur, exercise_id, tenant)
assert_exercise_not_combination(cur, exercise_id)
_fetch_variant_row(cur, exercise_id, variant_id)
cur.execute(
@@ -2464,7 +2961,8 @@ def _fetch_media_row(cur, exercise_id: int, media_id: int) -> Optional[dict]:
"""SELECT em.id, em.exercise_id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context, em.created_at,
em.media_asset_id, ma.storage_key AS asset_storage_key,
ma.lifecycle_state AS asset_lifecycle_state
ma.lifecycle_state AS asset_lifecycle_state,
ma.legal_hold_active AS asset_legal_hold_active
FROM exercise_media em
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
WHERE em.id = %s AND em.exercise_id = %s""",
@@ -2494,6 +2992,12 @@ def download_exercise_media_file(
if (media.get("embed_url") or "").strip():
raise HTTPException(status_code=400, detail="Embed-Medien haben keine Datei-URL")
if bool(media.get("asset_legal_hold_active")):
raise HTTPException(
status_code=451,
detail={"code": "LEGAL_HOLD_ACTIVE", "message": "Dieses Medium ist gesperrt und steht nicht zur Verfügung."}
)
lc = (media.get("asset_lifecycle_state") or "active").strip().lower()
if lc == "trash_hidden":
_assert_can_edit_exercise(cur, exercise_id, tenant)
@@ -2526,6 +3030,21 @@ async def upload_exercise_media(
description: str = Form(""),
context: str = Form("ablauf"),
is_primary: bool = Form(False),
copyright_notice: Optional[str] = Form(None),
# P-06: Rechte-Erklaerung (Pflicht bei Datei-Upload mit neuem media_asset)
rights_holder_confirmed: Optional[bool] = Form(None),
contains_identifiable_persons: Optional[bool] = Form(None),
person_consent_confirmed: Optional[bool] = Form(None),
person_consent_context: Optional[str] = Form(None),
contains_minors: Optional[bool] = Form(None),
parental_consent_confirmed: Optional[bool] = Form(None),
parental_consent_context: Optional[str] = Form(None),
contains_music: Optional[bool] = Form(None),
music_rights_confirmed: Optional[bool] = Form(None),
music_rights_context: Optional[str] = Form(None),
contains_third_party_content: Optional[bool] = Form(None),
third_party_rights_confirmed: Optional[bool] = Form(None),
third_party_rights_context: Optional[str] = Form(None),
):
profile_id = tenant.profile_id
if media_type not in ("image", "video", "document", "sketch"):
@@ -2764,11 +3283,12 @@ async def upload_exercise_media(
if not dest_path.is_file():
dest_path.write_bytes(raw)
clean_cr = (copyright_notice or "").strip() or None
cur.execute(
"""INSERT INTO media_assets (
mime_type, byte_size, sha256, original_filename, visibility, club_id,
uploaded_by_profile_id, copyright_notice, storage_backend, storage_key, lifecycle_state
) VALUES (%s, %s, %s, %s, %s, %s, %s, NULL, 'local', %s, 'active')
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'local', %s, 'active')
RETURNING id""",
(
mime,
@@ -2778,11 +3298,31 @@ async def upload_exercise_media(
ex_vis,
dedupe_club,
profile_id,
clean_cr,
storage_key,
),
)
ar = cur.fetchone()
aid = r2d(ar)["id"]
# P-06: Rechterklaerung fuer neues Media-Asset validieren und schreiben
p06_decl = {
"rights_holder_confirmed": rights_holder_confirmed,
"contains_identifiable_persons": contains_identifiable_persons,
"person_consent_confirmed": person_consent_confirmed,
"person_consent_context": person_consent_context,
"contains_minors": contains_minors,
"parental_consent_confirmed": parental_consent_confirmed,
"parental_consent_context": parental_consent_context,
"contains_music": contains_music,
"music_rights_confirmed": music_rights_confirmed,
"music_rights_context": music_rights_context,
"contains_third_party_content": contains_third_party_content,
"third_party_rights_confirmed": third_party_rights_confirmed,
"third_party_rights_context": third_party_rights_context,
}
validate_rights_declaration(p06_decl, ex_vis)
write_rights_declaration(cur, aid, profile_id, "upload", ex_vis, p06_decl)
update_rights_quick_fields(cur, aid, ex_vis)
db_path = f"/media/{storage_key}"
cur.execute(
f"""INSERT INTO exercise_media (
@@ -2843,7 +3383,7 @@ def attach_exercise_media_from_asset(
cur.execute(
"""SELECT id, mime_type, byte_size, original_filename, visibility, club_id,
uploaded_by_profile_id, storage_key, lifecycle_state
uploaded_by_profile_id, storage_key, lifecycle_state, legal_hold_active
FROM media_assets WHERE id = %s""",
(body.media_asset_id,),
)
@@ -2856,6 +3396,8 @@ def attach_exercise_media_from_asset(
status_code=400,
detail="Nur aktive Archiv-Medien können verknüpft werden",
)
# P-11: Legal Hold verhindert neue Einbindung in Übungen
assert_not_under_legal_hold(asset)
if not library_content_visible_to_profile(
cur,
@@ -2867,6 +3409,15 @@ def attach_exercise_media_from_asset(
):
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Archiv-Medium")
# P-06: Rechtspruefung — Asset muss Einwilligung fuer Sichtbarkeit der Uebung haben
cur.execute(
"SELECT visibility FROM exercises WHERE id = %s",
(exercise_id,),
)
ex_row = cur.fetchone()
ex_vis = (r2d(ex_row).get("visibility") or "private").strip().lower() if ex_row else "private"
assert_rights_for_exercise_link(cur, body.media_asset_id, ex_vis)
cur.execute(
"SELECT 1 FROM exercise_media WHERE exercise_id = %s AND media_asset_id = %s",
(exercise_id, body.media_asset_id),
+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
+475
View File
@@ -0,0 +1,475 @@
"""
Rechtstexte (Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie).
Öffentlich (kein Auth):
GET /api/legal-documents/{document_type}/published
Superadmin only:
GET /api/admin/legal-documents – Liste aller Versionen
POST /api/admin/legal-documents – Neuen Entwurf anlegen
GET /api/admin/legal-documents/{id} – Einzelnes Dokument
PUT /api/admin/legal-documents/{id} – Entwurf bearbeiten
POST /api/admin/legal-documents/{id}/publish – Veröffentlichen
POST /api/admin/legal-documents/{id}/archive – Archivieren
GET /api/admin/legal-documents/{id}/audit – Änderungslog
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from auth import require_auth
from club_tenancy import is_superadmin
from db import get_db, get_cursor, r2d
# ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug.
# Öffentlicher GET-Endpoint ohne jegliche Auth; Admin-Endpoints nutzen require_auth + is_superadmin().
# Eingetragen in backend/scripts/check_access_layer_hints.py EXEMPT_ROUTERS.
router = APIRouter(tags=["legal_documents"])
VALID_TYPES = {"impressum", "privacy_policy", "terms_of_use", "media_policy"}
def _require_superadmin(session: dict):
role = (session.get("role") or "").lower()
if not is_superadmin(role):
raise HTTPException(status_code=403, detail="Nur Superadmins")
return session
class LegalDocumentCreate(BaseModel):
document_type: str
title: str
content_sections: List[Dict[str, Any]] = []
change_note: Optional[str] = None
class LegalDocumentUpdate(BaseModel):
title: Optional[str] = None
content_sections: Optional[List[Dict[str, Any]]] = None
change_note: Optional[str] = None
class PublishRequest(BaseModel):
change_note: Optional[str] = None
# ─── Public endpoint ────────────────────────────────────────────────────────
@router.get("/api/legal-documents/{document_type}/published")
def get_published_legal_document(document_type: str):
"""Liefert das aktuell veröffentlichte Dokument oder null. Kein Auth erforderlich."""
if document_type not in VALID_TYPES:
raise HTTPException(status_code=404, detail="Unbekannter Dokumententyp")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, document_type, version, title, content_sections,
status, change_note, published_at, updated_at
FROM legal_documents
WHERE document_type = %s AND status = 'published'
LIMIT 1
""",
(document_type,),
)
row = cur.fetchone()
if not row:
return None
doc = r2d(row)
return doc
# ─── Superadmin endpoints ────────────────────────────────────────────────────
@router.get("/api/admin/legal-documents")
def list_legal_documents(
document_type: Optional[str] = None,
session: dict = Depends(require_auth),
):
"""Alle Versionen aller Rechtstexte (oder gefiltert nach document_type)."""
_require_superadmin(session)
with get_db() as conn:
cur = get_cursor(conn)
if document_type:
cur.execute(
"""
SELECT d.id, d.document_type, d.version, d.title, d.status,
d.change_note, d.created_at, d.updated_at, d.published_at,
p.name AS created_by_name
FROM legal_documents d
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
WHERE d.document_type = %s
ORDER BY d.document_type, d.version DESC
""",
(document_type,),
)
else:
cur.execute(
"""
SELECT d.id, d.document_type, d.version, d.title, d.status,
d.change_note, d.created_at, d.updated_at, d.published_at,
p.name AS created_by_name
FROM legal_documents d
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
ORDER BY d.document_type, d.version DESC
"""
)
rows = cur.fetchall()
return [r2d(r) for r in rows]
@router.post("/api/admin/legal-documents", status_code=201)
def create_legal_document(
body: LegalDocumentCreate,
session: dict = Depends(require_auth),
):
"""Neuen Entwurf anlegen. Versionsnummer = max(vorherige) + 1."""
_require_superadmin(session)
if body.document_type not in VALID_TYPES:
raise HTTPException(status_code=422, detail="Ungültiger document_type")
profile_id = session["profile_id"]
import json as _json
sections_json = _json.dumps(body.content_sections, ensure_ascii=False)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT COALESCE(MAX(version), 0) FROM legal_documents WHERE document_type = %s",
(body.document_type,),
)
row = cur.fetchone()
next_version = list(row.values())[0] + 1
cur.execute(
"""
INSERT INTO legal_documents
(document_type, version, title, content_sections, status, change_note, created_by_profile_id)
VALUES (%s, %s, %s, %s::jsonb, 'draft', %s, %s)
RETURNING id, document_type, version, title, content_sections,
status, change_note, created_at, updated_at
""",
(body.document_type, next_version, body.title, sections_json, body.change_note, profile_id),
)
new_row = cur.fetchone()
new_id = list(new_row.values())[0]
cur.execute(
"""
INSERT INTO legal_document_audit (legal_document_id, action, changed_by_profile_id, change_note)
VALUES (%s, 'created', %s, %s)
""",
(new_id, profile_id, body.change_note),
)
conn.commit()
return r2d(new_row)
@router.get("/api/admin/legal-documents/{doc_id}")
def get_legal_document(doc_id: int, session: dict = Depends(require_auth)):
"""Einzelnes Dokument (alle Felder inkl. content_sections)."""
_require_superadmin(session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT d.id, d.document_type, d.version, d.title, d.content_sections,
d.status, d.change_note, d.created_at, d.updated_at,
d.published_at, d.created_by_profile_id,
p.name AS created_by_name,
pb.name AS published_by_name
FROM legal_documents d
LEFT JOIN profiles p ON p.id = d.created_by_profile_id
LEFT JOIN profiles pb ON pb.id = d.published_by_profile_id
WHERE d.id = %s
""",
(doc_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
return r2d(row)
@router.put("/api/admin/legal-documents/{doc_id}")
def update_legal_document(
doc_id: int,
body: LegalDocumentUpdate,
session: dict = Depends(require_auth),
):
"""Entwurf bearbeiten. Nur status='draft' kann bearbeitet werden."""
_require_superadmin(session)
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, status, title, content_sections, change_note FROM legal_documents WHERE id = %s",
(doc_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
doc = r2d(row)
if doc["status"] != "draft":
raise HTTPException(status_code=409, detail="Nur Entwürfe können bearbeitet werden")
import json as _json
new_title = body.title if body.title is not None else doc["title"]
new_sections = body.content_sections if body.content_sections is not None else doc["content_sections"]
new_note = body.change_note if body.change_note is not None else doc["change_note"]
sections_json = _json.dumps(new_sections, ensure_ascii=False)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
UPDATE legal_documents
SET title = %s, content_sections = %s::jsonb, change_note = %s, updated_at = NOW()
WHERE id = %s
RETURNING id, document_type, version, title, content_sections,
status, change_note, created_at, updated_at
""",
(new_title, sections_json, new_note, doc_id),
)
updated = cur.fetchone()
cur.execute(
"""
INSERT INTO legal_document_audit (legal_document_id, action, changed_by_profile_id, change_note)
VALUES (%s, 'updated', %s, %s)
""",
(doc_id, profile_id, new_note),
)
conn.commit()
return r2d(updated)
@router.post("/api/admin/legal-documents/{doc_id}/publish")
def publish_legal_document(
doc_id: int,
body: PublishRequest = PublishRequest(),
session: dict = Depends(require_auth),
):
"""
Veröffentlicht dieses Dokument. Ein bisher veröffentlichtes Dokument desselben
Typs wird automatisch auf 'archived' gesetzt (partial unique index erzwingt dies).
"""
_require_superadmin(session)
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, document_type, status FROM legal_documents WHERE id = %s",
(doc_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
doc = r2d(row)
if doc["status"] == "published":
raise HTTPException(status_code=409, detail="Dokument ist bereits veröffentlicht")
if doc["status"] == "archived":
raise HTTPException(status_code=409, detail="Archivierte Dokumente können nicht veröffentlicht werden")
with get_db() as conn:
cur = get_cursor(conn)
# Vorheriges published-Dokument desselben Typs archivieren
cur.execute(
"""
UPDATE legal_documents
SET status = 'archived', updated_at = NOW()
WHERE document_type = %s AND status = 'published' AND id != %s
""",
(doc["document_type"], doc_id),
)
# Dieses Dokument veröffentlichen
cur.execute(
"""
UPDATE legal_documents
SET status = 'published', published_at = NOW(),
published_by_profile_id = %s, updated_at = NOW()
WHERE id = %s
RETURNING id, document_type, version, title, content_sections,
status, change_note, published_at, updated_at
""",
(profile_id, doc_id),
)
updated = cur.fetchone()
cur.execute(
"""
INSERT INTO legal_document_audit
(legal_document_id, action, changed_by_profile_id, change_note, previous_status)
VALUES (%s, 'published', %s, %s, %s)
""",
(doc_id, profile_id, body.change_note, doc["status"]),
)
conn.commit()
return r2d(updated)
@router.post("/api/admin/legal-documents/{doc_id}/archive")
def archive_legal_document(
doc_id: int,
session: dict = Depends(require_auth),
):
"""Archiviert ein Dokument. Veröffentlichte Dokumente dürfen nur archiviert werden wenn kein anderes published ist."""
_require_superadmin(session)
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, status FROM legal_documents WHERE id = %s",
(doc_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
doc = r2d(row)
if doc["status"] == "archived":
raise HTTPException(status_code=409, detail="Dokument ist bereits archiviert")
prev_status = doc["status"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
UPDATE legal_documents
SET status = 'archived', updated_at = NOW()
WHERE id = %s
RETURNING id, document_type, version, title, status, updated_at
""",
(doc_id,),
)
updated = cur.fetchone()
cur.execute(
"""
INSERT INTO legal_document_audit
(legal_document_id, action, changed_by_profile_id, previous_status)
VALUES (%s, 'archived', %s, %s)
""",
(doc_id, profile_id, prev_status),
)
conn.commit()
return r2d(updated)
@router.post("/api/admin/legal-documents/{doc_id}/copy-as-draft", status_code=201)
def copy_legal_document_as_draft(
doc_id: int,
session: dict = Depends(require_auth),
):
"""
Kopiert ein beliebiges Dokument (egal welcher Status) als neuen Entwurf mit
nächster Versionsnummer. Inhalt und Titel werden übernommen.
"""
_require_superadmin(session)
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, document_type, title, content_sections FROM legal_documents WHERE id = %s",
(doc_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
src = r2d(row)
import json as _json
sections_json = _json.dumps(src["content_sections"], ensure_ascii=False)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT COALESCE(MAX(version), 0) FROM legal_documents WHERE document_type = %s",
(src["document_type"],),
)
row2 = cur.fetchone()
next_version = list(row2.values())[0] + 1
cur.execute(
"""
INSERT INTO legal_documents
(document_type, version, title, content_sections, status, change_note, created_by_profile_id)
VALUES (%s, %s, %s, %s::jsonb, 'draft', NULL, %s)
RETURNING id, document_type, version, title, content_sections,
status, change_note, created_at, updated_at
""",
(src["document_type"], next_version, src["title"], sections_json, profile_id),
)
new_row = cur.fetchone()
new_id = list(new_row.values())[0]
cur.execute(
"""
INSERT INTO legal_document_audit
(legal_document_id, action, changed_by_profile_id, change_note)
VALUES (%s, 'created', %s, %s)
""",
(new_id, profile_id, f"Kopie von Version {src.get('version', '?')} (ID {doc_id})"),
)
conn.commit()
return r2d(new_row)
@router.get("/api/admin/legal-documents/{doc_id}/audit")
def get_legal_document_audit(doc_id: int, session: dict = Depends(require_auth)):
"""Änderungslog für ein Dokument."""
_require_superadmin(session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM legal_documents WHERE id = %s", (doc_id,))
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Dokument nicht gefunden")
cur.execute(
"""
SELECT a.id, a.action, a.change_note, a.previous_status, a.created_at,
p.name AS changed_by_name
FROM legal_document_audit a
LEFT JOIN profiles p ON p.id = a.changed_by_profile_id
WHERE a.legal_document_id = %s
ORDER BY a.created_at DESC
""",
(doc_id,),
)
rows = cur.fetchall()
return [r2d(r) for r in rows]
+797 -15
View File
@@ -13,6 +13,7 @@ from club_tenancy import (
assert_club_member,
assert_valid_governance_visibility,
club_ids_for_profile_with_roles,
has_club_role,
is_platform_admin,
is_superadmin,
library_content_visible_to_profile,
@@ -37,6 +38,24 @@ from media_lifecycle import (
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root, relocate_local_media_file
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible
from media_rights import (
assert_rights_for_promotion,
update_rights_quick_fields,
validate_rights_declaration,
write_rights_declaration,
write_audit_log_entry,
write_rights_correction_declaration,
check_rights_coverage,
VISIBILITY_LEVELS,
)
from media_legal_hold import (
LEGAL_HOLD_REASON_CODES,
assert_not_under_legal_hold,
assert_superadmin_for_legal_hold,
is_media_available_for_normal_use,
set_legal_hold,
release_legal_hold,
)
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
router = APIRouter(prefix="/api/media-assets", tags=["media-assets"])
@@ -70,6 +89,57 @@ class MediaAssetPatch(BaseModel):
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
club_id: Optional[int] = None
tags: Optional[list[str]] = None
# P-06: optionale Rechte-Erklaerung (wird Pflicht wenn Promotion zu hoeherer Sichtbarkeit)
rights_holder_confirmed: Optional[bool] = None
contains_identifiable_persons: Optional[bool] = None
person_consent_confirmed: Optional[bool] = None
person_consent_context: Optional[str] = Field(None, max_length=2000)
contains_minors: Optional[bool] = None
parental_consent_confirmed: Optional[bool] = None
parental_consent_context: Optional[str] = Field(None, max_length=2000)
contains_music: Optional[bool] = None
music_rights_confirmed: Optional[bool] = None
music_rights_context: Optional[str] = Field(None, max_length=2000)
contains_third_party_content: Optional[bool] = None
third_party_rights_confirmed: Optional[bool] = None
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
class RightsDeclarationBody(BaseModel):
"""P-06: Explizite Re-Deklaration / Nachdeklaration fuer ein bestehendes Medium."""
target_visibility: str = Field(..., pattern="^(private|club|official)$")
rights_holder_confirmed: bool
contains_identifiable_persons: bool
person_consent_confirmed: Optional[bool] = None
person_consent_context: Optional[str] = Field(None, max_length=2000)
contains_minors: bool
parental_consent_confirmed: Optional[bool] = None
parental_consent_context: Optional[str] = Field(None, max_length=2000)
contains_music: bool
music_rights_confirmed: Optional[bool] = None
music_rights_context: Optional[str] = Field(None, max_length=2000)
contains_third_party_content: bool
third_party_rights_confirmed: Optional[bool] = None
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
class RightsCorrectionBody(BaseModel):
"""P-06: Nachtraegliche Korrektur einer Erklaerung (append-only, neueste gilt)."""
target_visibility: str = Field(..., pattern="^(private|club|official)$")
rights_holder_confirmed: bool
contains_identifiable_persons: bool
person_consent_confirmed: Optional[bool] = None
person_consent_context: Optional[str] = Field(None, max_length=2000)
contains_minors: bool
parental_consent_confirmed: Optional[bool] = None
parental_consent_context: Optional[str] = Field(None, max_length=2000)
contains_music: bool
music_rights_confirmed: Optional[bool] = None
music_rights_context: Optional[str] = Field(None, max_length=2000)
contains_third_party_content: bool
third_party_rights_confirmed: Optional[bool] = None
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
correction_note: Optional[str] = Field(None, max_length=2000)
class MediaBulkLifecycleBody(BaseModel):
@@ -100,7 +170,22 @@ class MediaBulkPatchBody(BaseModel):
original_filename: Optional[str] = Field(None, max_length=300)
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
club_id: Optional[int] = None
# P-06 Kontext (bei Promotion)
person_consent_context: Optional[str] = Field(None, max_length=2000)
parental_consent_context: Optional[str] = Field(None, max_length=2000)
music_rights_context: Optional[str] = Field(None, max_length=2000)
third_party_rights_context: Optional[str] = Field(None, max_length=2000)
tags: Optional[list[str]] = None
# P-06: Rechterklaerung (gilt fuer alle Assets des Batches bei Promotion)
rights_holder_confirmed: Optional[bool] = None
contains_identifiable_persons: Optional[bool] = None
person_consent_confirmed: Optional[bool] = None
contains_minors: Optional[bool] = None
parental_consent_confirmed: Optional[bool] = None
contains_music: Optional[bool] = None
music_rights_confirmed: Optional[bool] = None
contains_third_party_content: Optional[bool] = None
third_party_rights_confirmed: Optional[bool] = None
_LIFECYCLE_LIST_FILTERS = frozenset({"active", "trash_soft", "trash_hidden", "all"})
@@ -379,8 +464,16 @@ def _relocate_asset_file_if_governance_changed(
def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str, list[Any]]:
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL."""
def _list_active_visibility_clause(
is_plat: bool,
profile_id: int,
include_legal_hold: bool = False,
) -> tuple[str, list[Any]]:
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL.
P-11: Legal-Hold-Medien sind für normale Nutzer nicht sichtbar.
is_plat/is_sup können include_legal_hold=True übergeben, um sie weiterhin zu sehen.
"""
parts = ["lower(trim(ma.visibility)) = 'official'"]
vals: list[Any] = []
@@ -414,8 +507,13 @@ def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str,
)
vals.append(profile_id)
sql = "(" + " OR ".join(parts) + ")"
return sql, vals
vis_sql = "(" + " OR ".join(parts) + ")"
# P-11: Legal-Hold-Medien für normale Nutzer ausblenden
if not include_legal_hold:
vis_sql = f"({vis_sql} AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL))"
return vis_sql, vals
def _list_trash_visibility_clause(
@@ -453,12 +551,15 @@ def _list_main_visibility_where(
) -> tuple[str, list[Any]]:
"""
Kombiniert lifecycle mit Leserechten. Papierkorb-Stufen für normale Nutzer stark eingeschränkt.
P-11: Plattform-Admins und Superadmins sehen Legal-Hold-Medien in der aktiven Liste.
"""
lc = (lifecycle or "active").strip().lower()
if lc not in _LIFECYCLE_LIST_FILTERS:
raise HTTPException(status_code=400, detail="Ungültiger lifecycle-Filter")
active_sql, active_params = _list_active_visibility_clause(is_plat, profile_id)
active_sql, active_params = _list_active_visibility_clause(
is_plat, profile_id, include_legal_hold=is_sup
)
trash_sql, trash_params = _list_trash_visibility_clause(
is_plat, is_sup, profile_id, admin_club_ids
)
@@ -572,6 +673,7 @@ def _apply_lifecycle_action(
action = body.action
role_raw = tenant.global_role
old_lc = (asset.get("lifecycle_state") or LC_ACTIVE).strip()
if action == "superadmin_hard_delete":
if not is_superadmin(role_raw):
@@ -586,7 +688,13 @@ def _apply_lifecycle_action(
raise HTTPException(status_code=403, detail="Nur Superadmin")
tl = body.target_lifecycle or "active"
mp = {"active": LC_ACTIVE, "trash_soft": LC_TRASH_SOFT, "trash_hidden": LC_TRASH_HIDDEN}
return superadmin_force_lifecycle_state(cur, conn, asset_id, mp[tl])
new_lc = mp[tl]
result = superadmin_force_lifecycle_state(cur, conn, asset_id, new_lc)
if old_lc != new_lc:
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
{"lifecycle_state": old_lc}, {"lifecycle_state": new_lc})
conn.commit()
return result
if action == "purge":
if not is_superadmin(role_raw):
@@ -603,16 +711,32 @@ def _apply_lifecycle_action(
if action == "trash_soft":
assert_can_trash_soft(cur, tenant, asset)
return transition_to_trash_soft(cur, conn, asset_id)
result = transition_to_trash_soft(cur, conn, asset_id)
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_SOFT})
conn.commit()
return result
if action == "trash_hidden":
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
return transition_to_trash_hidden(cur, conn, asset_id)
result = transition_to_trash_hidden(cur, conn, asset_id)
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_HIDDEN})
conn.commit()
return result
if action == "recover":
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
return transition_recover_from_hidden(cur, conn, asset_id)
result = transition_recover_from_hidden(cur, conn, asset_id)
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_TRASH_SOFT})
conn.commit()
return result
if action == "reactivate":
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
return reactivate_media_asset_from_trash(cur, conn, asset_id)
result = reactivate_media_asset_from_trash(cur, conn, asset_id)
write_audit_log_entry(cur, asset_id, tenant.profile_id, "lifecycle_change",
{"lifecycle_state": old_lc}, {"lifecycle_state": LC_ACTIVE})
conn.commit()
return result
raise HTTPException(status_code=500, detail="Interner Fehler: lifecycle action")
@@ -628,8 +752,14 @@ def _ingest_library_media_file(
content_type: Optional[str],
visibility: str,
club_id_form: Optional[int],
decl: Optional[dict] = None,
copyright_notice: Optional[str] = None,
) -> dict:
"""Neues Archiv-Medium oder aktiver Dedupe-Treffer (sha256 + Sichtbarkeit + Verein). Kein exercise_media."""
"""Neues Archiv-Medium oder aktiver Dedupe-Treffer (sha256 + Sichtbarkeit + Verein). Kein exercise_media.
decl: P-06 Rechterklaerung (bereits validiert). Bei Dedupe-Treffer wird eine neue Erklaerung
fuer die aktuelle Aktion geschrieben falls decl uebergeben wird.
"""
profile_id = tenant.profile_id
role = tenant.global_role or ""
vis = (visibility or "private").strip().lower()
@@ -762,11 +892,12 @@ def _ingest_library_media_file(
if not dest_path.is_file():
dest_path.write_bytes(raw)
clean_cr = (copyright_notice or "").strip() or None
cur.execute(
"""INSERT INTO media_assets (
mime_type, byte_size, sha256, original_filename, visibility, club_id,
uploaded_by_profile_id, copyright_notice, storage_backend, storage_key, lifecycle_state
) VALUES (%s, %s, %s, %s, %s, %s, %s, NULL, 'local', %s, 'active')
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'local', %s, 'active')
RETURNING id""",
(
mime,
@@ -776,11 +907,16 @@ def _ingest_library_media_file(
vis,
next_cid,
profile_id,
clean_cr,
storage_key,
),
)
ar = cur.fetchone()
aid = int(r2d(ar)["id"])
# P-06: Erklaerung schreiben und Schnellfelder setzen
if decl is not None:
write_rights_declaration(cur, aid, tenant.profile_id, "upload", vis, decl)
update_rights_quick_fields(cur, aid, vis)
return {"status": "created", "media_asset_id": aid, "original_filename": filename or storage_key}
@@ -790,8 +926,27 @@ async def bulk_upload_media_assets(
files: list[UploadFile] = File(..., description="Mehrere Dateien (jpeg, png, gif, mp4, pdf)"),
visibility: str = Form("private"),
club_id: Optional[int] = Form(None),
copyright_notice: Optional[str] = Form(None),
# P-06 Rechterklaerung (gilt fuer alle Dateien des Batches)
rights_holder_confirmed: bool = Form(...),
contains_identifiable_persons: bool = Form(...),
person_consent_confirmed: Optional[bool] = Form(None),
person_consent_context: Optional[str] = Form(None),
contains_minors: bool = Form(...),
parental_consent_confirmed: Optional[bool] = Form(None),
parental_consent_context: Optional[str] = Form(None),
contains_music: bool = Form(...),
music_rights_confirmed: Optional[bool] = Form(None),
music_rights_context: Optional[str] = Form(None),
contains_third_party_content: bool = Form(...),
third_party_rights_confirmed: Optional[bool] = Form(None),
third_party_rights_context: Optional[str] = Form(None),
):
"""Mehrere Dateien ins Archiv; Dedupe wie Übungs-Upload. Pro Datei eigene DB-Transaktion."""
"""Mehrere Dateien ins Archiv; Dedupe wie Übungs-Upload. Pro Datei eigene DB-Transaktion.
P-06: Eine Rechterklaerung gilt fuer alle Dateien des Batches.
VORLAEUTIG: Texte und Pflichtfelder noch nicht juristisch geprueft (p06-v1-conservative).
"""
if not files:
raise HTTPException(status_code=400, detail="Keine Dateien übermittelt")
if len(files) > _MAX_BULK_LIBRARY_FILES:
@@ -800,6 +955,24 @@ async def bulk_upload_media_assets(
detail=f"Maximal {_MAX_BULK_LIBRARY_FILES} Dateien pro Anfrage",
)
decl = {
"rights_holder_confirmed": rights_holder_confirmed,
"contains_identifiable_persons": contains_identifiable_persons,
"person_consent_confirmed": person_consent_confirmed,
"person_consent_context": person_consent_context,
"contains_minors": contains_minors,
"parental_consent_confirmed": parental_consent_confirmed,
"parental_consent_context": parental_consent_context,
"contains_music": contains_music,
"music_rights_confirmed": music_rights_confirmed,
"music_rights_context": music_rights_context,
"contains_third_party_content": contains_third_party_content,
"third_party_rights_confirmed": third_party_rights_confirmed,
"third_party_rights_context": third_party_rights_context,
}
target_vis = (visibility or "private").strip().lower()
validate_rights_declaration(decl, target_vis)
results: list[dict[str, Any]] = []
created = duplicate = failed = 0
@@ -821,7 +994,10 @@ async def bulk_upload_media_assets(
uf.content_type,
visibility,
club_id,
decl=decl,
copyright_notice=copyright_notice,
)
conn.commit()
results.append({"filename": fn, "ok": True, **r})
if r["status"] == "created":
created += 1
@@ -969,7 +1145,10 @@ def list_media_assets(
cur.execute(
f"""SELECT ma.id, ma.mime_type, ma.byte_size, ma.original_filename, ma.visibility, ma.club_id,
ma.uploaded_by_profile_id, ma.lifecycle_state, ma.created_at, ma.sha256,
ma.copyright_notice, ma.storage_key, {tags_select}
ma.copyright_notice, ma.storage_key, ma.rights_status,
ma.legal_hold_active, ma.legal_hold_reason_code, ma.legal_hold_reason_note,
ma.legal_hold_set_at, ma.legal_hold_set_by_profile_id,
{tags_select}
pr.name AS uploader_name,
pr.email AS uploader_email,
cl.name AS club_name
@@ -989,10 +1168,26 @@ def list_media_assets(
show_club = sup or is_adm or bool(admin_club_ids)
asset_ids = [int(r["id"]) for r in rows]
usage_map = _usage_for_media_assets(cur, asset_ids)
# open_report_count: nur für Admins relevant; immer befüllen (0 für normale Nutzer ok)
report_count_map: dict[int, int] = {}
if asset_ids and (is_adm or bool(admin_club_ids)):
cur.execute(
"""SELECT target_id, COUNT(*) AS cnt
FROM content_reports
WHERE target_type = 'media_asset'
AND target_id = ANY(%s)
AND status IN ('submitted', 'under_review')
GROUP BY target_id""",
(asset_ids,),
)
for row in cur.fetchall():
rd = r2d(row)
report_count_map[int(rd["target_id"])] = int(rd["cnt"])
for r in rows:
r["permissions"] = _item_permissions(r, tenant, admin_club_ids)
tid = int(r["id"])
r["usage"] = usage_map.get(tid, {"exercises": [], "training_units": []})
r["open_report_count"] = report_count_map.get(tid, 0)
tags_val = r.get("tags")
if tags_val is None:
r["tags"] = []
@@ -1035,9 +1230,30 @@ def download_media_asset_file(
with get_db() as conn:
cur = get_cursor(conn)
asset = _fetch_asset_file_row(cur, asset_id)
# _fetch_asset_file_row wird erweitert um legal_hold_active
cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
storage_key, mime_type, original_filename, legal_hold_active
FROM media_assets WHERE id = %s""",
(asset_id,),
)
row = cur.fetchone()
asset = r2d(row) if row else None
if not asset:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
# P-11: Legal Hold blockiert normalen Dateizugriff (nicht für Superadmin)
if bool(asset.get("legal_hold_active")):
role = tenant.global_role if hasattr(tenant, "global_role") else None
if not is_superadmin(role):
raise HTTPException(
status_code=403,
detail={
"code": "LEGAL_HOLD_ACTIVE",
"message": "Dieses Medium ist sofort gesperrt und nicht verfügbar.",
},
)
lc = (asset.get("lifecycle_state") or "").strip().lower()
if lc == "active":
_assert_can_view_archive_asset(cur, tenant, asset)
@@ -1158,6 +1374,56 @@ def bulk_media_patch(
)
continue
if next_vis in ("club", "official"):
effective_copyright = (
patch_fields.get("copyright_notice") or asset.get("copyright_notice") or ""
)
if not str(effective_copyright).strip():
failed.append(
{
"id": asset_id,
"detail": (
"Für Vereins- oder offizielle Medien ist eine "
"Urheberrechtsangabe (copyright_notice) Pflicht."
),
}
)
continue
# P-06: Rechteprüfung bei Promotion
cur_vis = (asset.get("visibility") or "private").strip().lower()
bulk_p06_decl: Optional[dict] = None
bulk_p06_action: Optional[str] = None
if VISIBILITY_LEVELS.get(next_vis, 0) > VISIBILITY_LEVELS.get(cur_vis, 0):
coverage = check_rights_coverage(cur, asset_id, next_vis)
if coverage != "ok":
p06_fields = {
"rights_holder_confirmed": patch_fields.get("rights_holder_confirmed"),
"contains_identifiable_persons": patch_fields.get("contains_identifiable_persons"),
"person_consent_confirmed": patch_fields.get("person_consent_confirmed"),
"contains_minors": patch_fields.get("contains_minors"),
"parental_consent_confirmed": patch_fields.get("parental_consent_confirmed"),
"contains_music": patch_fields.get("contains_music"),
"music_rights_confirmed": patch_fields.get("music_rights_confirmed"),
"contains_third_party_content": patch_fields.get("contains_third_party_content"),
"third_party_rights_confirmed": patch_fields.get("third_party_rights_confirmed"),
}
if p06_fields.get("rights_holder_confirmed") is None:
code = "LEGACY_REDECLARATION_REQUIRED" if coverage == "legacy" else "RIGHTS_SCOPE_INSUFFICIENT"
failed.append({
"id": asset_id,
"detail": f"{code}: Rechterklaerung fuer '{next_vis}' erforderlich.",
})
continue
try:
validate_rights_declaration(p06_fields, next_vis)
except HTTPException as p06e:
d = p06e.detail
failed.append({"id": asset_id, "detail": d.get("message") if isinstance(d, dict) else str(d)})
continue
bulk_p06_decl = p06_fields
bulk_p06_action = "legacy_re_declaration" if coverage == "legacy" else "promote_club" if next_vis == "club" else "promote_official"
new_sk: Optional[str] = None
if "visibility" in patch_fields or "club_id" in patch_fields:
next_club_param: Optional[int] = None
@@ -1196,6 +1462,12 @@ def bulk_media_patch(
f"UPDATE media_assets SET {', '.join(sets)} WHERE id = %s",
tuple(vals),
)
# P-06: Declaration-Log schreiben wenn neue Erklaerung bei Promotion
if bulk_p06_decl is not None and bulk_p06_action is not None:
write_rights_declaration(
cur, asset_id, profile_id, bulk_p06_action, next_vis, bulk_p06_decl
)
update_rights_quick_fields(cur, asset_id, next_vis)
conn.commit()
updated.append(asset_id)
except HTTPException as he:
@@ -1239,6 +1511,8 @@ def patch_media_asset(
eff = _effective_media_patch_fields(data, asset)
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
next_cid = eff.get("club_id", asset.get("club_id"))
_p06_pending_decl: Optional[dict] = None
_p06_action: Optional[str] = None
if "visibility" in data or "club_id" in data:
assert_valid_governance_visibility(
cur,
@@ -1256,6 +1530,75 @@ def patch_media_asset(
),
)
if next_vis in ("club", "official"):
effective_copyright = (
data.get("copyright_notice") or asset.get("copyright_notice") or ""
)
if not str(effective_copyright).strip():
raise HTTPException(
status_code=400,
detail=(
"Für Vereins- oder offizielle Medien ist eine Urheberrechtsangabe "
"(copyright_notice) Pflicht. Bitte vor oder zusammen mit der "
"Freigabe angeben."
),
)
# P-06: Rechteprüfung bei Sichtbarkeits-Promotion
cur_vis = (asset.get("visibility") or "private").strip().lower()
if VISIBILITY_LEVELS.get(next_vis, 0) > VISIBILITY_LEVELS.get(cur_vis, 0):
coverage = check_rights_coverage(cur, asset_id, next_vis)
if coverage != "ok":
# Neue Erklaerung muss im Body mitgeliefert werden
p06_fields = {
"rights_holder_confirmed": data.get("rights_holder_confirmed"),
"contains_identifiable_persons": data.get("contains_identifiable_persons"),
"person_consent_confirmed": data.get("person_consent_confirmed"),
"contains_minors": data.get("contains_minors"),
"parental_consent_confirmed": data.get("parental_consent_confirmed"),
"contains_music": data.get("contains_music"),
"music_rights_confirmed": data.get("music_rights_confirmed"),
"contains_third_party_content": data.get("contains_third_party_content"),
"third_party_rights_confirmed": data.get("third_party_rights_confirmed"),
}
if coverage == "legacy":
if p06_fields.get("rights_holder_confirmed") is None:
raise HTTPException(
status_code=400,
detail={
"code": "LEGACY_REDECLARATION_REQUIRED",
"message": (
"Dieses Medium wurde vor Einfuehrung der Einwilligungspflicht "
"hochgeladen. Bitte eine vollstaendige Rechterklaerung (P-06-Felder) "
"zusammen mit dem PATCH uebergeben."
),
"asset_id": asset_id,
},
)
else:
if p06_fields.get("rights_holder_confirmed") is None:
raise HTTPException(
status_code=400,
detail={
"code": "RIGHTS_SCOPE_INSUFFICIENT",
"message": (
f"Die vorhandene Erklaerung deckt '{next_vis}' nicht ab. "
"Bitte eine neue Erklaerung (P-06-Felder) mitschicken."
),
"asset_id": asset_id,
"target_visibility": next_vis,
},
)
validate_rights_declaration(p06_fields, next_vis)
_p06_pending_decl = p06_fields
_p06_action = "legacy_re_declaration" if coverage == "legacy" else "promote_club" if next_vis == "club" else "promote_official"
else:
_p06_pending_decl = None
_p06_action = None
else:
_p06_pending_decl = None
_p06_action = None
new_sk: Optional[str] = None
if "visibility" in data or "club_id" in data:
next_club_param: Optional[int] = None
@@ -1292,6 +1635,38 @@ def patch_media_asset(
f"UPDATE media_assets SET {', '.join(sets)} WHERE id = %s",
tuple(vals),
)
# P-06: Declaration-Log schreiben wenn neue Erklaerung bei Promotion
if _p06_pending_decl is not None and _p06_action is not None:
write_rights_declaration(
cur, asset_id, profile_id, _p06_action, next_vis, _p06_pending_decl
)
update_rights_quick_fields(cur, asset_id, next_vis)
# Audit-Log: Änderungen protokollieren (gleiche Transaktion)
if "visibility" in data or "club_id" in data:
_old_vis = (asset.get("visibility") or "").strip()
_old_cid = asset.get("club_id")
if next_vis != _old_vis or next_cid != _old_cid:
write_audit_log_entry(
cur, asset_id, profile_id, "visibility_change",
{"visibility": _old_vis, "club_id": _old_cid},
{"visibility": next_vis, "club_id": next_cid},
)
if "copyright_notice" in data:
_old_cr = (asset.get("copyright_notice") or "").strip()
_new_cr = (data.get("copyright_notice") or "").strip()
if _new_cr != _old_cr:
write_audit_log_entry(
cur, asset_id, profile_id, "copyright_change",
{"copyright_notice": asset.get("copyright_notice")},
{"copyright_notice": data["copyright_notice"]},
)
_meta_old: dict = {}
_meta_new: dict = {}
if "original_filename" in data:
_meta_old["original_filename"] = asset.get("original_filename")
_meta_new["original_filename"] = data["original_filename"]
if _meta_new:
write_audit_log_entry(cur, asset_id, profile_id, "metadata_change", _meta_old, _meta_new)
conn.commit()
has_tags = _media_assets_tags_column_present(cur)
if has_tags:
@@ -1312,3 +1687,410 @@ def patch_media_asset(
if not has_tags:
out["tags"] = []
return out
# ---------------------------------------------------------------------------
# P-06: Re-Deklaration / Nachdeklaration
# ---------------------------------------------------------------------------
@router.post("/{asset_id}/rights-declarations")
def create_rights_declaration(
asset_id: int,
body: RightsDeclarationBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-06: Explizite Rechte-Erklaerung fuer ein bestehendes Medium.
Verwendung:
- Altmedium ('legacy_unreviewed'): Erste Erklaerung nach P-06 (action_type='legacy_re_declaration')
- Medium mit Erklaerung fuer niedrigere Sichtbarkeit: Neue Erklaerung fuer Zielsichtbarkeit
(action_type='re_declaration')
Die Erklaerung aendert NICHT die Sichtbarkeit des Mediums; dafuer PATCH verwenden.
"""
profile_id = tenant.profile_id
decl = body.model_dump() if hasattr(body, "model_dump") else body.dict()
target_vis = decl.pop("target_visibility")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, uploaded_by_profile_id, lifecycle_state, rights_status FROM media_assets WHERE id = %s",
(asset_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(row)
assert_can_edit_media_asset_metadata(cur, tenant, asset)
validate_rights_declaration(decl, target_vis)
rs = (asset.get("rights_status") or "legacy_unreviewed").strip().lower()
action_type = "legacy_re_declaration" if rs == "legacy_unreviewed" else "re_declaration"
decl_id = write_rights_declaration(cur, asset_id, profile_id, action_type, target_vis, decl)
update_rights_quick_fields(cur, asset_id, target_vis)
conn.commit()
return {
"declaration_id": decl_id,
"asset_id": asset_id,
"action_type": action_type,
"target_visibility": target_vis,
"rights_status": "declared",
}
# ---------------------------------------------------------------------------
# P-06: Admin – Legacy-Übersicht
# ---------------------------------------------------------------------------
admin_rights_router = APIRouter(prefix="/api/admin/media-rights", tags=["admin", "media-rights"])
@admin_rights_router.get("/legacy-summary")
def get_legacy_rights_summary(
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-06 Admin: Zusammenfassung wie viele Medien noch im legacy_unreviewed-Status sind."""
role = tenant.global_role
if not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung (Plattform-Admin erforderlich)")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT rights_status, COUNT(*) AS cnt
FROM media_assets
WHERE lifecycle_state = 'active'
GROUP BY rights_status
ORDER BY rights_status
"""
)
rows = [r2d(r) for r in cur.fetchall()]
totals = {r["rights_status"]: int(r["cnt"]) for r in rows}
total_active = sum(totals.values())
cur.execute(
"SELECT COUNT(*) AS cnt FROM media_asset_rights_declarations"
)
decl_count_row = cur.fetchone()
total_declarations = int(r2d(decl_count_row)["cnt"]) if decl_count_row else 0
return {
"total_active_assets": total_active,
"legacy_unreviewed": totals.get("legacy_unreviewed", 0),
"declared": totals.get("declared", 0),
"blocked": totals.get("blocked", 0),
"total_declarations_logged": total_declarations,
}
@admin_rights_router.get("/legacy-assets")
def get_legacy_rights_assets(
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
visibility: Optional[str] = Query(None, pattern="^(private|club|official)$"),
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-06 Admin: Liste der Medien mit rights_status = 'legacy_unreviewed' oder 'blocked'."""
role = tenant.global_role
if not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung (Plattform-Admin erforderlich)")
with get_db() as conn:
cur = get_cursor(conn)
conditions = ["ma.lifecycle_state = 'active'", "ma.rights_status != 'declared'"]
params: list[Any] = []
if visibility:
conditions.append("ma.visibility = %s")
params.append(visibility)
where = " AND ".join(conditions)
cur.execute(
f"""
SELECT ma.id, ma.original_filename, ma.visibility, ma.rights_status,
ma.created_at, ma.uploaded_by_profile_id,
p.name AS uploader_name
FROM media_assets ma
LEFT JOIN profiles p ON p.id = ma.uploaded_by_profile_id
WHERE {where}
ORDER BY ma.created_at DESC
LIMIT %s OFFSET %s
""",
(*params, limit, offset),
)
assets = [r2d(r) for r in cur.fetchall()]
cur.execute(
f"""
SELECT COUNT(*) AS cnt
FROM media_assets ma
WHERE {where}
""",
tuple(params),
)
total_row = cur.fetchone()
total = int(r2d(total_row)["cnt"]) if total_row else 0
return {"total": total, "limit": limit, "offset": offset, "assets": assets}
@admin_rights_router.get("/assets/{asset_id}/journal")
def get_media_asset_journal(
asset_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Vollständiges Medien-Journal: Einwilligungen + alle Änderungen chronologisch.
Zugriff: Superadmin, ursprünglicher Uploader oder Vereins-Admin des betreffenden Mediums.
"""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, original_filename, visibility, club_id, rights_status,
rights_declared_for_visibility, rights_declared_at,
copyright_notice, mime_type, lifecycle_state,
uploaded_by_profile_id, created_at
FROM media_assets
WHERE id = %s
""",
(asset_id,),
)
asset_row = cur.fetchone()
if not asset_row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(asset_row)
is_sup = is_superadmin(role)
is_uploader = asset.get("uploaded_by_profile_id") == profile_id
is_club_adm = False
if asset.get("club_id"):
is_club_adm = has_club_role(cur, profile_id, asset["club_id"], "club_admin")
if not (is_sup or is_uploader or is_club_adm):
raise HTTPException(status_code=403, detail="Keine Berechtigung (Superadmin, Uploader oder Vereinsadmin)")
can_correct = is_sup or is_uploader or is_club_adm
cur.execute(
"""
SELECT d.id, d.declared_at, d.action_type, d.target_visibility,
d.declaration_version,
d.rights_holder_confirmed,
d.contains_identifiable_persons, d.person_consent_confirmed,
d.person_consent_context,
d.contains_minors, d.parental_consent_confirmed,
d.parental_consent_context,
d.contains_music, d.music_rights_confirmed,
d.music_rights_context,
d.contains_third_party_content, d.third_party_rights_confirmed,
d.third_party_rights_context,
d.declared_by_profile_id, d.correction_note,
p.name AS declared_by_name,
p.email AS declared_by_email
FROM media_asset_rights_declarations d
LEFT JOIN profiles p ON p.id = d.declared_by_profile_id
WHERE d.media_asset_id = %s
ORDER BY d.declared_at ASC
""",
(asset_id,),
)
events: list[dict] = []
for r in cur.fetchall():
d = r2d(r)
d["kind"] = "declaration"
d["at"] = str(d.get("declared_at", ""))
events.append(d)
# Audit-Log (Migration 050 – Tabelle darf noch nicht existieren)
try:
cur.execute(
"""
SELECT a.id, a.occurred_at, a.event_type, a.old_values, a.new_values,
a.acting_profile_id,
p.name AS acting_name,
p.email AS acting_email
FROM media_asset_audit_log a
LEFT JOIN profiles p ON p.id = a.acting_profile_id
WHERE a.media_asset_id = %s
ORDER BY a.occurred_at ASC
""",
(asset_id,),
)
for r in cur.fetchall():
a = r2d(r)
a["kind"] = "audit"
a["at"] = str(a.get("occurred_at", ""))
events.append(a)
except Exception:
pass # Tabelle noch nicht migriert
events.sort(key=lambda e: e.get("at", ""))
return {"asset": asset, "events": events, "can_correct": can_correct}
@admin_rights_router.post("/assets/{asset_id}/correction")
def add_rights_correction(
asset_id: int,
body: RightsCorrectionBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Nachträgliche Korrektur einer P-06-Einwilligungserklärung (append-only, neueste gilt).
Zugriff: Superadmin, ursprünglicher Uploader oder Vereins-Admin.
"""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, uploaded_by_profile_id, club_id, rights_status, lifecycle_state FROM media_assets WHERE id = %s",
(asset_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
asset = r2d(row)
is_sup = is_superadmin(role)
is_uploader = asset.get("uploaded_by_profile_id") == profile_id
is_club_adm = False
if asset.get("club_id"):
is_club_adm = has_club_role(cur, profile_id, asset["club_id"], "club_admin")
if not (is_sup or is_uploader or is_club_adm):
raise HTTPException(
status_code=403,
detail="Keine Berechtigung (Superadmin, ursprünglicher Uploader oder Vereinsadmin erforderlich)",
)
decl = body.model_dump(exclude_unset=False) if hasattr(body, "model_dump") else body.dict()
target_vis = decl.pop("target_visibility")
correction_note = decl.pop("correction_note", None)
validate_rights_declaration(decl, target_vis)
write_rights_correction_declaration(cur, asset_id, profile_id, target_vis, decl, correction_note)
update_rights_quick_fields(cur, asset_id, target_vis)
conn.commit()
return {"ok": True, "asset_id": asset_id}
# ---------------------------------------------------------------------------
# P-11: Legal-Hold-Endpoints (Superadmin only)
# ---------------------------------------------------------------------------
admin_legal_hold_router = APIRouter(prefix="/api/admin/media-assets", tags=["admin", "legal-hold"])
class LegalHoldSetBody(BaseModel):
reason_code: str = Field(..., description="Kategorie des Legal Holds")
reason_note: str = Field(..., min_length=5, max_length=2000, description="Pflichtbegründung")
class LegalHoldReleaseBody(BaseModel):
release_note: str = Field(..., min_length=5, max_length=2000, description="Freigabe-Begründung")
@admin_legal_hold_router.post("/{asset_id}/legal-hold")
def post_legal_hold_set(
asset_id: int,
body: LegalHoldSetBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Legal Hold auf ein Medium setzen. Nur Superadmin.
Wirkung: Sofortige Unsichtbarkeit in normalen Nutzerpfaden, rights_status='blocked',
Audit-Log-Eintrag. Keine automatische physische Löschung. Keine Löschfristen.
"""
assert_superadmin_for_legal_hold(tenant.global_role)
with get_db() as conn:
cur = get_cursor(conn)
result = set_legal_hold(
cur, conn,
asset_id=asset_id,
acting_profile_id=int(tenant.profile_id),
reason_code=body.reason_code,
reason_note=body.reason_note,
)
return {
"ok": True,
"asset_id": asset_id,
"legal_hold_active": result.get("legal_hold_active"),
"rights_status": result.get("rights_status"),
"legal_hold_reason_code": result.get("legal_hold_reason_code"),
"legal_hold_set_at": str(result.get("legal_hold_set_at", "")),
}
@admin_legal_hold_router.post("/{asset_id}/legal-hold/release")
def post_legal_hold_release(
asset_id: int,
body: LegalHoldReleaseBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Legal Hold aufheben. Nur Superadmin.
Wirkung: legal_hold_active=FALSE, rights_status wiederhergestellt,
Audit-Log-Eintrag. Vorheriger Lifecycle-Zustand bleibt erhalten.
"""
assert_superadmin_for_legal_hold(tenant.global_role)
with get_db() as conn:
cur = get_cursor(conn)
result = release_legal_hold(
cur, conn,
asset_id=asset_id,
acting_profile_id=int(tenant.profile_id),
release_note=body.release_note,
)
return {
"ok": True,
"asset_id": asset_id,
"legal_hold_active": result.get("legal_hold_active"),
"rights_status": result.get("rights_status"),
"legal_hold_released_at": str(result.get("legal_hold_released_at", "")),
}
@admin_legal_hold_router.get("/legal-hold")
def list_legal_hold_assets(
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Admin-Liste aller Medien unter aktivem Legal Hold. Superadmin oder Plattform-Admin."""
if not is_platform_admin(tenant.global_role):
raise HTTPException(
status_code=403,
detail="Keine Berechtigung (Plattform-Admin oder Superadmin erforderlich)",
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT ma.id, ma.original_filename, ma.visibility, ma.club_id,
ma.lifecycle_state, ma.rights_status,
ma.legal_hold_active, ma.legal_hold_reason_code,
ma.legal_hold_reason_note, ma.legal_hold_set_at,
ma.legal_hold_set_by_profile_id,
p_set.name AS set_by_name,
ma.uploaded_by_profile_id,
p_upl.name AS uploader_name,
cl.name AS club_name,
ma.created_at
FROM media_assets ma
LEFT JOIN profiles p_set ON p_set.id = ma.legal_hold_set_by_profile_id
LEFT JOIN profiles p_upl ON p_upl.id = ma.uploaded_by_profile_id
LEFT JOIN clubs cl ON cl.id = ma.club_id
WHERE ma.legal_hold_active = TRUE
ORDER BY ma.legal_hold_set_at DESC NULLS LAST, ma.id DESC
LIMIT %s OFFSET %s
""",
(limit, offset),
)
assets = [r2d(r) for r in cur.fetchall()]
cur.execute(
"SELECT COUNT(*) AS cnt FROM media_assets WHERE legal_hold_active = TRUE"
)
total_row = cur.fetchone()
total = int(r2d(total_row)["cnt"]) if total_row else 0
return {"total": total, "limit": limit, "offset": offset, "assets": assets}
+9
View File
@@ -384,6 +384,15 @@ def _run_profile_update(pid: str, p: ProfileUpdate, tenant: TenantContext) -> di
else:
raise HTTPException(400, "exercise_list_prefs muss ein JSON-Objekt sein")
if "training_planning_prefs" in patch:
tp = patch.pop("training_planning_prefs")
if tp is None:
data["training_planning_prefs"] = Json({})
elif isinstance(tp, dict):
data["training_planning_prefs"] = Json(tp)
else:
raise HTTPException(400, "training_planning_prefs muss ein JSON-Objekt sein")
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
for k, v in patch.items():
if k == "email":
+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,),
+381
View File
@@ -0,0 +1,381 @@
"""
Trainingsmodule — wiederverwendbare Planungsbausteine (Bibliothek).
Governance wie Trainings‑Mikrovorlagen (`training_plan_templates`):
Liste/Detail über `library_content_visibility_sql`; Bearbeiten/Löschen wie Übungen (s. club_tenancy).
Siehe `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.
"""
from typing import Any, Dict, List, Optional, Tuple
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,
)
router = APIRouter(prefix="/api", tags=["training_modules"])
def _has_planning_role(role: Optional[str]) -> bool:
return role in ("admin", "superadmin", "trainer", "user")
def _fetch_training_module_row(cur, mid: int) -> Dict[str, Any]:
cur.execute("SELECT * FROM training_modules WHERE id = %s", (mid,))
r = cur.fetchone()
if not r:
raise HTTPException(status_code=404, detail="Trainingsmodul nicht gefunden")
return r2d(r)
def _module_assert_readable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
if is_platform_admin(role):
return
if not library_content_visible_to_profile(
cur,
profile_id,
row.get("visibility") or "club",
row.get("club_id"),
row.get("created_by"),
role,
):
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Modul")
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)
return row
def _validate_variant_for_exercise(cur, exercise_id: Optional[int], variant_id: Optional[int]):
if not variant_id:
return
if not exercise_id:
raise HTTPException(
status_code=400, detail="exercise_variant_id nur zusammen mit exercise_id erlaubt"
)
cur.execute(
"SELECT 1 FROM exercise_variants WHERE id = %s AND exercise_id = %s",
(variant_id, exercise_id),
)
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Variante passt nicht zur gewählten Übung")
def _optional_positive_int(val, field_name: str) -> Optional[int]:
if val is None or val == "":
return None
try:
i = int(val)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"Ungültige {field_name}")
if i < 1:
raise HTTPException(status_code=400, detail=f"Ungültige {field_name}")
return i
def _replace_module_items(cur, module_id: int, items_in: Optional[List[Any]]) -> None:
cur.execute("DELETE FROM training_module_items WHERE module_id = %s", (module_id,))
items_in = items_in or []
for i, raw in enumerate(items_in):
itype = raw.get("item_type")
if not itype:
itype = "exercise" if raw.get("exercise_id") else "note"
order_ix = raw.get("order_index")
if order_ix is None:
order_ix = i
order_ix = int(order_ix)
if itype == "note":
body = raw.get("note_body")
if body is None:
body = ""
cur.execute(
"""
INSERT INTO training_module_items (
module_id, order_index, item_type,
exercise_id, exercise_variant_id,
planned_duration_min, notes, note_body
) VALUES (%s, %s, 'note',
NULL, NULL, NULL, NULL, %s)
""",
(module_id, order_ix, body),
)
continue
eid = raw.get("exercise_id")
if not eid:
continue
eid = int(eid)
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
_validate_variant_for_exercise(cur, eid, vid)
cur.execute(
"""
INSERT INTO training_module_items (
module_id, order_index, item_type,
exercise_id, exercise_variant_id,
planned_duration_min, notes, note_body
) VALUES (%s, %s, 'exercise',
%s, %s, %s, %s, NULL)
""",
(
module_id,
order_ix,
eid,
vid,
raw.get("planned_duration_min"),
raw.get("notes"),
),
)
def load_training_module_for_apply(
cur, module_id: int, profile_id: int, role: Optional[str]
) -> Tuple[List[Dict[str, Any]], int]:
"""
Liest Modul inkl. Items für Übernahme in eine Trainingseinheit.
Returns (items_ordered, module_id).
Raises HTTPException bei 403/404.
"""
row = _fetch_training_module_row(cur, module_id)
_module_assert_readable(cur, row, profile_id, role or "")
cur.execute(
"""
SELECT item_type, exercise_id, exercise_variant_id,
planned_duration_min, notes, note_body
FROM training_module_items
WHERE module_id = %s
ORDER BY order_index ASC
""",
(module_id,),
)
raw_items = [r2d(x) for x in cur.fetchall()]
items: List[Dict[str, Any]] = []
for r in raw_items:
items.append(dict(r))
return items, int(module_id)
@router.get("/training-modules")
def list_training_modules(tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
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.*,
(SELECT COUNT(*) FROM training_module_items i WHERE i.module_id = m.id)
AS items_count
FROM training_modules m
WHERE ({vis_clause})
ORDER BY m.updated_at DESC NULLS LAST, m.title
""",
vis_params,
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/training-modules/{module_id}")
def get_training_module(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)
cur.execute(
"""
SELECT *
FROM training_module_items
WHERE module_id = %s
ORDER BY order_index ASC
""",
(module_id,),
)
row["items"] = [r2d(r) for r in cur.fetchall()]
return row
@router.post("/training-modules")
def create_training_module(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
role = tenant.global_role
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Trainingsmodule anlegen")
title = (data.get("title") or "").strip()
if not title:
raise HTTPException(status_code=400, detail="title ist Pflicht")
vis_raw = data.get("visibility")
visibility = (vis_raw if isinstance(vis_raw, str) else "club").strip() or "club"
club_id = data.get("club_id")
if club_id in ("", []):
club_id = None
if visibility == "club" and club_id is None:
club_id = tenant.effective_club_id
primary_method_id = data.get("primary_method_id")
if primary_method_id in ("", []):
primary_method_id = None
if primary_method_id is not None:
primary_method_id = int(primary_method_id)
items_in = data.get("items") or []
with get_db() as conn:
cur = get_cursor(conn)
assert_valid_governance_visibility(cur, profile_id, role, visibility, club_id)
if primary_method_id is not None:
cur.execute("SELECT 1 FROM training_methods WHERE id = %s", (primary_method_id,))
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Trainingsmethode nicht gefunden")
cur.execute(
"""
INSERT INTO training_modules (
club_id, created_by, title, summary, goal,
recommended_duration_min, target_group_notes, deployment_context_notes,
primary_method_id, visibility
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
club_id,
profile_id,
title,
(data.get("summary") or "").strip() or None,
data.get("goal"),
data.get("recommended_duration_min"),
data.get("target_group_notes"),
data.get("deployment_context_notes"),
primary_method_id,
visibility,
),
)
mid = cur.fetchone()["id"]
_replace_module_items(cur, mid, items_in if isinstance(items_in, list) else [])
conn.commit()
return get_training_module(mid, tenant)
@router.put("/training-modules/{module_id}")
def update_training_module(
module_id: int, data: dict, 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_prev = _fetch_training_module_row(cur, module_id)
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")
if "visibility" in data:
v_in = data.get("visibility")
if not isinstance(v_in, str) or v_in not in ("private", "club", "official"):
raise HTTPException(status_code=400, detail="visibility ungültig")
merged_vis = v_in
if "club_id" in data:
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] = []
params: List[Any] = []
if "title" in data:
t = data.get("title")
t = t.strip() if isinstance(t, str) else ""
if not t:
raise HTTPException(status_code=400, detail="title ist Pflicht")
fields.append("title = %s")
params.append(t)
for col in ("summary", "goal", "target_group_notes", "deployment_context_notes"):
if col in data:
fields.append(f"{col} = %s")
v = data.get(col)
if col == "summary" and isinstance(v, str):
v = v.strip() or None
params.append(v)
if "recommended_duration_min" in data:
fields.append("recommended_duration_min = %s")
params.append(data.get("recommended_duration_min"))
if "primary_method_id" in data:
pm = data.get("primary_method_id")
if pm in ("", [], None):
fields.append("primary_method_id = %s")
params.append(None)
else:
pm = int(pm)
cur.execute("SELECT 1 FROM training_methods WHERE id = %s", (pm,))
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Trainingsmethode nicht gefunden")
fields.append("primary_method_id = %s")
params.append(pm)
if "club_id" in data:
fields.append("club_id = %s")
params.append(merged_club)
if "visibility" in data:
fields.append("visibility = %s")
params.append(merged_vis)
if fields:
fields.append("updated_at = NOW()")
params.append(module_id)
cur.execute(
f"UPDATE training_modules SET {', '.join(fields)} WHERE id = %s",
tuple(params),
)
if "items" in data:
items_in = data["items"]
_replace_module_items(cur, module_id, items_in if isinstance(items_in, list) else [])
conn.commit()
return get_training_module(module_id, tenant)
@router.delete("/training-modules/{module_id}")
def delete_training_module(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_del = _fetch_training_module_row(cur, module_id)
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
@@ -22,6 +22,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
"auth.py",
"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()
"catalogs.py",
"skills.py",
"maturity_models.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
@@ -0,0 +1,100 @@
"""
P-05b: POST /api/auth/reset-password muss Passwoerter unter 8 Zeichen ablehnen.
Prueft Pydantic-Validierung (HTTP 422) BEVOR die DB befragt wird.
"""
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 main import app
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
def _mock_db_valid_token() -> MagicMock:
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {"profile_id": 1}
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
return mock_cm, mock_cur
# ── Mindestlaenge-Grenzwerte ──────────────────────────────────────────────────
@pytest.mark.parametrize("short_pw", ["", "a", "1234567"])
def test_reset_password_too_short_rejected(client: TestClient, short_pw: str) -> None:
"""Passwort < 8 Zeichen muss mit 422 abgelehnt werden (Pydantic-Validierung)."""
r = client.post(
"/api/auth/reset-password",
json={"token": "sometoken", "new_password": short_pw},
)
assert r.status_code == 422, (
f"Erwartet 422 fuer Passwort {short_pw!r} ({len(short_pw)} Zeichen), "
f"erhalten {r.status_code}"
)
def test_reset_password_exactly_8_chars_accepted(client: TestClient) -> None:
"""Passwort mit genau 8 Zeichen muss die Validierung passieren."""
mock_cm, mock_cur = _mock_db_valid_token()
with patch("routers.auth.get_db", return_value=mock_cm), patch(
"routers.auth.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/auth/reset-password",
json={"token": "sometoken", "new_password": "12345678"},
)
assert r.status_code == 200
assert r.json().get("ok") is True
def test_reset_password_long_password_accepted(client: TestClient) -> None:
"""Langes Passwort (>= 8 Zeichen) muss akzeptiert werden."""
mock_cm, mock_cur = _mock_db_valid_token()
with patch("routers.auth.get_db", return_value=mock_cm), patch(
"routers.auth.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/auth/reset-password",
json={"token": "sometoken", "new_password": "sicheresPasswort123!"},
)
assert r.status_code == 200
def test_reset_password_missing_field_rejected(client: TestClient) -> None:
"""Fehlendes new_password-Feld muss mit 422 abgelehnt werden."""
r = client.post(
"/api/auth/reset-password",
json={"token": "sometoken"},
)
assert r.status_code == 422
def test_reset_password_invalid_token_returns_400(client: TestClient) -> None:
"""Gueltiges Passwort aber ungueltiger Token muss 400 liefern."""
mock_cur = MagicMock()
mock_cur.fetchone.return_value = None
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
with patch("routers.auth.get_db", return_value=mock_cm), patch(
"routers.auth.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/auth/reset-password",
json={"token": "ungueltig", "new_password": "validesPw123"},
)
assert r.status_code == 400
+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
+13 -11
View File
@@ -130,8 +130,8 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"c": 0},
{"created_by": 1, "visibility": "private", "club_id": None}, # _assert_can_edit_exercise
{"c": 0}, # _count_exercise_media
{
"id": 5,
"mime_type": "image/jpeg",
@@ -142,14 +142,15 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"storage_key": _SK_OFF_A,
},
{"id": 1},
}, # asset lookup
{"visibility": "private"}, # P-06: exercise visibility
{"id": 1}, # duplicate check -> 400
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
), patch("routers.exercises.assert_rights_for_exercise_link"):
r = client.post(
"/api/exercises/3/media/from-asset",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
@@ -196,8 +197,8 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
}
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"c": 0},
{"created_by": 1, "visibility": "private", "club_id": None}, # _assert_can_edit_exercise
{"c": 0}, # _count_exercise_media
{
"id": 5,
"mime_type": "image/jpeg",
@@ -208,15 +209,16 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"storage_key": _SK_OFF_B,
},
None,
inserted,
}, # asset lookup
{"visibility": "private"}, # P-06: exercise visibility
None, # duplicate check -> None (no duplicate)
inserted, # INSERT RETURNING
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
), patch("routers.exercises.assert_rights_for_exercise_link"):
r = client.post(
"/api/exercises/3/media/from-asset",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
@@ -0,0 +1,258 @@
"""
P-04: Copyright-Pflicht bei Promotion auf club/official.
PATCH /api/media-assets/{id} und POST /api/media-assets/bulk-patch
lehnen eine Sichtbarkeits-Promotion auf club oder official ab,
wenn keine copyright_notice vorhanden ist.
"""
from __future__ import annotations
import os
from contextlib import ExitStack
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from main import app
from tenant_context import TenantContext, get_tenant_context
_SUPERADMIN_TENANT = TenantContext(
profile_id=1,
global_role="superadmin",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
_PRIVATE_ASSET: dict = {
"id": 42,
"visibility": "private",
"club_id": 7,
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"copyright_notice": None,
"original_filename": "foto.jpg",
"sha256": "a" * 64,
"storage_key": f"library/verein-7/image/{'a' * 64}.jpg",
"storage_backend": "local",
"mime_type": "image/jpeg",
"byte_size": 1024,
"created_at": None,
"tags": [],
}
_ASSET_WITH_COPYRIGHT: dict = {**_PRIVATE_ASSET, "copyright_notice": "Verein 2026"}
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides():
yield
app.dependency_overrides.pop(get_tenant_context, None)
def _make_db_mocks(asset: dict) -> tuple[MagicMock, MagicMock]:
mock_cur = MagicMock()
mock_cur.fetchone.return_value = asset
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
return mock_cm, mock_cur
_PERMISSION_PATCHES = [
("routers.media_assets.assert_can_edit_media_asset_metadata", {}),
("routers.media_assets.assert_valid_governance_visibility", {}),
("routers.media_assets._media_assets_tags_column_present", {"return_value": False}),
("routers.media_assets.get_effective_media_root", {"return_value": "/tmp/media"}),
("routers.media_assets._relocate_asset_file_if_governance_changed", {"return_value": None}),
# P-06: bestehende Tests testen Copyright, nicht Rechteerklaerung – "ok" mocken
("routers.media_assets.check_rights_coverage", {"return_value": "ok"}),
]
def _enter_permission_patches(stack: ExitStack) -> None:
for target, kwargs in _PERMISSION_PATCHES:
stack.enter_context(patch(target, **kwargs))
# ── Single PATCH ─────────────────────────────────────────────────────────────
def test_patch_promote_to_club_without_copyright_returns_400(client: TestClient) -> None:
"""Promotion private -> club ohne copyright_notice muss 400 liefern."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"visibility": "club", "club_id": 7},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 400
detail = r.json()["detail"].lower()
assert "copyright" in detail or "urheberrecht" in detail
def test_patch_promote_to_official_without_copyright_returns_400(client: TestClient) -> None:
"""Promotion private -> official ohne copyright_notice muss 400 liefern."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"visibility": "official"},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 400
detail = r.json()["detail"].lower()
assert "copyright" in detail or "urheberrecht" in detail
def test_patch_promote_to_club_with_copyright_in_body_allowed(client: TestClient) -> None:
"""Promotion private -> club MIT copyright_notice im Body muss 200 liefern."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
updated_asset = {**_PRIVATE_ASSET, "visibility": "club", "copyright_notice": "Verein 2026"}
mock_cur.fetchone.side_effect = [_PRIVATE_ASSET, updated_asset]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"visibility": "club", "club_id": 7, "copyright_notice": "Verein 2026"},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
body = r.json()
assert body["id"] == 42
assert body["visibility"] == "club"
assert body["copyright_notice"] == "Verein 2026"
def test_patch_promote_to_club_existing_copyright_allowed(client: TestClient) -> None:
"""Asset hat bereits copyright_notice -> Promotion ohne Body-Copyright muss 200 liefern."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
promoted_asset = {**_ASSET_WITH_COPYRIGHT, "visibility": "club"}
mock_cm, mock_cur = _make_db_mocks(_ASSET_WITH_COPYRIGHT)
mock_cur.fetchone.side_effect = [_ASSET_WITH_COPYRIGHT, promoted_asset]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"visibility": "club", "club_id": 7},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
body = r.json()
assert body["id"] == 42
assert body["visibility"] == "club"
assert body["copyright_notice"] == "Verein 2026"
def test_patch_filename_only_no_copyright_check(client: TestClient) -> None:
"""Kein Visibility-Wechsel -> keine Copyright-Prufung."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
mock_cur.fetchone.side_effect = [
_PRIVATE_ASSET,
{**_PRIVATE_ASSET, "original_filename": "neu.jpg"},
]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"original_filename": "neu.jpg"},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
# ── Bulk PATCH ────────────────────────────────────────────────────────────────
def test_bulk_patch_promote_to_club_without_copyright_in_failed(client: TestClient) -> None:
"""Bulk-Promotion ohne copyright_notice -> Asset in failed-Liste."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cur = MagicMock()
mock_cur.fetchone.return_value = _PRIVATE_ASSET
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.post(
"/api/media-assets/bulk-patch",
json={"media_asset_ids": [42], "visibility": "club", "club_id": 7},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
body = r.json()
assert body["updated_count"] == 0
assert body["failed_count"] == 1
detail = body["failed"][0]["detail"].lower()
assert "copyright" in detail or "urheberrecht" in detail
def test_bulk_patch_promote_to_club_with_copyright_in_updated(client: TestClient) -> None:
"""Bulk-Promotion MIT copyright_notice -> Asset in updated-Liste."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cur = MagicMock()
mock_cur.fetchone.return_value = _PRIVATE_ASSET
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.post(
"/api/media-assets/bulk-patch",
json={
"media_asset_ids": [42],
"visibility": "club",
"club_id": 7,
"copyright_notice": "Verein 2026",
},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
body = r.json()
assert 42 in body["updated"]
assert body["updated_count"] == 1
@@ -0,0 +1,430 @@
"""
P-06: Rechte-Erklaerung – Backend-Tests.
Abgedeckt:
1. validate_rights_declaration – alle Pflichtfelder
2. check_rights_coverage – ok / insufficient / legacy / blocked
3. assert_rights_for_promotion – richtiges Fehlermuster
4. PATCH /api/media-assets/{id} – Promotion mit und ohne P-06
5. POST /api/media-assets/{id}/rights-declarations – Re-Deklaration
6. POST /api/media-assets/bulk-patch – P-06-Pfad im Bulk
"""
from __future__ import annotations
import os
from contextlib import ExitStack
from unittest.mock import MagicMock, patch, call
import pytest
from fastapi.testclient import TestClient
from fastapi import HTTPException
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from main import app
from media_rights import (
validate_rights_declaration,
check_rights_coverage,
assert_rights_for_promotion,
rights_covers_target,
visibility_level,
)
from tenant_context import TenantContext, get_tenant_context
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
_SUPERADMIN_TENANT = TenantContext(
profile_id=1,
global_role="superadmin",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
_FULL_DECL = {
"rights_holder_confirmed": True,
"contains_identifiable_persons": False,
"person_consent_confirmed": None,
"contains_minors": False,
"parental_consent_confirmed": None,
"contains_music": False,
"music_rights_confirmed": None,
"contains_third_party_content": False,
"third_party_rights_confirmed": None,
}
_PRIVATE_ASSET = {
"id": 42,
"visibility": "private",
"club_id": 7,
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"copyright_notice": "Rechteinhaber 2026",
"original_filename": "foto.jpg",
"sha256": "a" * 64,
"storage_key": f"library/verein-7/image/{'a' * 64}.jpg",
"storage_backend": "local",
"mime_type": "image/jpeg",
"byte_size": 1024,
"created_at": None,
"tags": [],
"rights_status": "legacy_unreviewed",
"rights_declared_for_visibility": None,
}
_DECLARED_ASSET = {**_PRIVATE_ASSET, "rights_status": "declared", "rights_declared_for_visibility": "private"}
_BLOCKED_ASSET = {**_PRIVATE_ASSET, "rights_status": "blocked", "rights_declared_for_visibility": None}
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides():
yield
app.dependency_overrides.pop(get_tenant_context, None)
def _make_db_mocks(asset: dict) -> tuple[MagicMock, MagicMock]:
mock_cur = MagicMock()
mock_cur.fetchone.return_value = asset
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
return mock_cm, mock_cur
_PERMISSION_PATCHES = [
("routers.media_assets.assert_can_edit_media_asset_metadata", {}),
("routers.media_assets.assert_valid_governance_visibility", {}),
("routers.media_assets._media_assets_tags_column_present", {"return_value": False}),
("routers.media_assets.get_effective_media_root", {"return_value": "/tmp/media"}),
("routers.media_assets._relocate_asset_file_if_governance_changed", {"return_value": None}),
]
def _enter_permission_patches(stack: ExitStack) -> None:
for target, kwargs in _PERMISSION_PATCHES:
stack.enter_context(patch(target, **kwargs))
# ===========================================================================
# 1. validate_rights_declaration – Unit-Tests (kein HTTP)
# ===========================================================================
class TestValidateRightsDeclaration:
def test_missing_rights_holder_raises(self):
decl = {**_FULL_DECL, "rights_holder_confirmed": False}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.status_code == 400
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
def test_identifiable_persons_none_raises(self):
decl = {**_FULL_DECL, "contains_identifiable_persons": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.status_code == 400
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
def test_person_consent_required_when_persons_present(self):
decl = {**_FULL_DECL, "contains_identifiable_persons": True, "person_consent_confirmed": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "club")
assert exc.value.detail["code"] == "PERSON_CONSENT_REQUIRED"
def test_minors_none_raises(self):
decl = {**_FULL_DECL, "contains_minors": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
def test_parental_consent_required_when_minors_present(self):
decl = {**_FULL_DECL, "contains_minors": True, "parental_consent_confirmed": False}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "official")
assert exc.value.detail["code"] == "PARENTAL_CONSENT_REQUIRED"
def test_music_none_raises(self):
decl = {**_FULL_DECL, "contains_music": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
def test_music_rights_required_when_music_present(self):
decl = {**_FULL_DECL, "contains_music": True, "music_rights_confirmed": False}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.detail["code"] == "MUSIC_RIGHTS_REQUIRED"
def test_third_party_none_raises(self):
decl = {**_FULL_DECL, "contains_third_party_content": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "private")
assert exc.value.detail["code"] == "RIGHTS_DECLARATION_REQUIRED"
def test_third_party_rights_required_when_content_present(self):
decl = {**_FULL_DECL, "contains_third_party_content": True, "third_party_rights_confirmed": None}
with pytest.raises(HTTPException) as exc:
validate_rights_declaration(decl, "official")
assert exc.value.detail["code"] == "THIRD_PARTY_RIGHTS_REQUIRED"
def test_full_clean_decl_passes(self):
validate_rights_declaration(_FULL_DECL, "official")
def test_full_decl_with_all_true_passes(self):
decl = {
"rights_holder_confirmed": True,
"contains_identifiable_persons": True,
"person_consent_confirmed": True,
"contains_minors": True,
"parental_consent_confirmed": True,
"contains_music": True,
"music_rights_confirmed": True,
"contains_third_party_content": True,
"third_party_rights_confirmed": True,
}
validate_rights_declaration(decl, "official")
def test_private_also_requires_full_declaration(self):
"""Konservative Erstannahme: private erfordert dieselbe Erklaerung wie official."""
decl = {**_FULL_DECL, "contains_identifiable_persons": None}
with pytest.raises(HTTPException):
validate_rights_declaration(decl, "private")
# ===========================================================================
# 2. check_rights_coverage – Unit-Tests mit Mock-Cursor
# ===========================================================================
class TestCheckRightsCoverage:
def _cur(self, row):
cur = MagicMock()
cur.fetchone.return_value = row
return cur
def test_no_asset_returns_no_declaration(self):
cur = self._cur(None)
assert check_rights_coverage(cur, 1, "private") == "no_declaration"
def test_blocked_returns_blocked(self):
cur = self._cur({"rights_status": "blocked"})
assert check_rights_coverage(cur, 1, "private") == "blocked"
def test_legacy_returns_legacy(self):
cur = self._cur({"rights_status": "legacy_unreviewed"})
assert check_rights_coverage(cur, 1, "club") == "legacy"
def test_declared_covers_any_visibility(self):
# Eine bestehende Erklaerung gilt sichtbarkeitsunabhaengig
for target in ("private", "club", "official"):
cur = self._cur({"rights_status": "declared"})
assert check_rights_coverage(cur, 1, target) == "ok", f"failed for target={target}"
# ===========================================================================
# 3. assert_rights_for_promotion – Fehlermuster
# ===========================================================================
class TestAssertRightsForPromotion:
def _cur(self, row):
cur = MagicMock()
cur.fetchone.return_value = row
return cur
def test_ok_passes_for_any_target(self):
for target in ("private", "club", "official"):
cur = self._cur({"rights_status": "declared"})
assert_rights_for_promotion(cur, 1, target) # no raise
def test_legacy_raises_legacy_code(self):
cur = self._cur({"rights_status": "legacy_unreviewed"})
with pytest.raises(HTTPException) as exc:
assert_rights_for_promotion(cur, 1, "club")
assert exc.value.status_code == 400
assert exc.value.detail["code"] == "LEGACY_REDECLARATION_REQUIRED"
def test_blocked_raises_403(self):
cur = self._cur({"rights_status": "blocked"})
with pytest.raises(HTTPException) as exc:
assert_rights_for_promotion(cur, 1, "official")
assert exc.value.status_code == 403
assert exc.value.detail["code"] == "RIGHTS_BLOCKED"
# ===========================================================================
# 4. PATCH /api/media-assets/{id} – P-06-Promotion via HTTP
# ===========================================================================
class TestPatchP06Promotion:
def test_promote_legacy_without_decl_returns_400(self, client):
"""PATCH private->club ohne P-06-Felder muss LEGACY_REDECLARATION_REQUIRED liefern."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
mock_cur.fetchone.side_effect = [_PRIVATE_ASSET, {"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None}]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
r = client.patch(
"/api/media-assets/42",
json={"visibility": "club", "club_id": 7, "copyright_notice": "Rechteinhaber 2026"},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 400
d = r.json()["detail"]
assert d["code"] == "LEGACY_REDECLARATION_REQUIRED"
def test_promote_legacy_with_full_decl_calls_write_declaration(self, client):
"""PATCH private->club mit vollstaendiger P-06-Erklaerung schreibt Declaration-Log."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
updated_asset = {**_PRIVATE_ASSET, "visibility": "club"}
mock_cur.fetchone.side_effect = [
_PRIVATE_ASSET,
{"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None},
updated_asset,
]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
_enter_permission_patches(stack)
wr = stack.enter_context(patch("routers.media_assets.write_rights_declaration", return_value=1))
uq = stack.enter_context(patch("routers.media_assets.update_rights_quick_fields"))
r = client.patch(
"/api/media-assets/42",
json={
"visibility": "club",
"club_id": 7,
"copyright_notice": "Rechteinhaber 2026",
**_FULL_DECL,
},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
assert wr.called
call_args = wr.call_args
assert call_args.args[3] == "legacy_re_declaration"
assert call_args.args[4] == "club"
assert uq.called
# ===========================================================================
# 5. POST /api/media-assets/{id}/rights-declarations – Re-Deklaration
# ===========================================================================
class TestPostRightsDeclaration:
def test_redeclaration_for_legacy_asset_succeeds(self, client):
"""Nachdeklaration fuer Altmedium setzt action_type='legacy_re_declaration'."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
mock_cur.fetchone.return_value = _PRIVATE_ASSET
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
wr = stack.enter_context(patch("routers.media_assets.write_rights_declaration", return_value=99))
stack.enter_context(patch("routers.media_assets.update_rights_quick_fields"))
r = client.post(
"/api/media-assets/42/rights-declarations",
json={"target_visibility": "club", **_FULL_DECL},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
data = r.json()
assert data["action_type"] == "legacy_re_declaration"
assert data["declaration_id"] == 99
assert wr.called
def test_redeclaration_incomplete_decl_returns_400_or_422(self, client):
"""Fehlende Erklaerungsfelder fuehren zu 400 (business logic) oder 422 (Pydantic)."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
r = client.post(
"/api/media-assets/42/rights-declarations",
# Fehlende Pflichtfelder (contains_identifiable_persons etc.) -> Pydantic 422 ODER
# validate_rights_declaration 400 je nach welche Felder fehlen
json={"target_visibility": "private", "rights_holder_confirmed": True},
headers={"X-Auth-Token": "t"},
)
assert r.status_code in (400, 422)
def test_redeclaration_asset_not_found_returns_404(self, client):
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(None)
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
r = client.post(
"/api/media-assets/999/rights-declarations",
json={"target_visibility": "private", **_FULL_DECL},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 404
# ===========================================================================
# 6. Bulk-Patch – P-06-Promotion im Batch
# ===========================================================================
class TestBulkPatchP06:
def test_bulk_promote_legacy_without_decl_reports_failure(self, client):
"""Bulk-Patch: Legacy-Asset ohne P-06-Felder landet in 'failed', nicht 422."""
app.dependency_overrides[get_tenant_context] = lambda: _SUPERADMIN_TENANT
mock_cm, mock_cur = _make_db_mocks(_PRIVATE_ASSET)
mock_cur.fetchone.side_effect = [
_PRIVATE_ASSET,
{"rights_status": "legacy_unreviewed", "rights_declared_for_visibility": None},
]
with ExitStack() as stack:
stack.enter_context(patch("routers.media_assets.get_db", return_value=mock_cm))
stack.enter_context(patch("routers.media_assets.get_cursor", return_value=mock_cur))
stack.enter_context(patch("routers.media_assets.assert_can_edit_media_asset_metadata"))
stack.enter_context(patch("routers.media_assets.assert_valid_governance_visibility"))
stack.enter_context(patch("routers.media_assets._media_assets_tags_column_present", return_value=False))
stack.enter_context(patch("routers.media_assets.get_effective_media_root", return_value="/tmp"))
stack.enter_context(patch("routers.media_assets._relocate_asset_file_if_governance_changed", return_value=None))
r = client.post(
"/api/media-assets/bulk-patch",
json={
"media_asset_ids": [42],
"visibility": "club",
"club_id": 7,
"copyright_notice": "Rechteinhaber 2026",
},
headers={"X-Auth-Token": "t"},
)
assert r.status_code == 200
data = r.json()
assert data["failed_count"] == 1
assert data["updated_count"] == 0
assert "LEGACY_REDECLARATION_REQUIRED" in data["failed"][0]["detail"] or \
"RIGHTS_SCOPE_INSUFFICIENT" in data["failed"][0]["detail"]
+281
View File
@@ -0,0 +1,281 @@
"""
P-11: Legal-Hold – Backend-Tests.
Abgedeckt (15 Faelle):
1. assert_superadmin_for_legal_hold – Superadmin darf
2. assert_superadmin_for_legal_hold – Nicht-Superadmin wird geblockt
3. is_media_available_for_normal_use – ohne Hold True
4. is_media_available_for_normal_use – mit Hold False
5. assert_not_under_legal_hold – ohne Hold passiert nichts
6. assert_not_under_legal_hold – mit Hold wirft 403 LEGAL_HOLD_ACTIVE
7. set_legal_hold – ungueltige reason_code → 400
8. set_legal_hold – leere reason_note → 400
9. set_legal_hold – Asset bereits unter Hold → 409
10. set_legal_hold – Erfolgspfad: DB-Update + Audit-Log
11. release_legal_hold – leere release_note → 400
12. release_legal_hold – Asset nicht unter Hold → 409
13. release_legal_hold – Erfolgspfad ohne Deklaration → legacy_unreviewed
14. release_legal_hold – Erfolgspfad mit Deklaration → declared
15. Retention-Job ueberspringt Legal-Hold-Assets (run_retention_pass query)
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch, call
import pytest
from fastapi import HTTPException
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from media_legal_hold import (
LEGAL_HOLD_REASON_CODES,
assert_not_under_legal_hold,
assert_superadmin_for_legal_hold,
is_media_available_for_normal_use,
release_legal_hold,
set_legal_hold,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _asset(legal_hold_active=False, rights_status="legacy_unreviewed", **kw) -> dict:
base = {
"id": 99,
"visibility": "private",
"lifecycle_state": "active",
"rights_status": rights_status,
"legal_hold_active": legal_hold_active,
"legal_hold_reason_code": None,
"legal_hold_reason_note": None,
}
base.update(kw)
return base
def _make_cur(fetchone_val, fetchone_seq=None):
"""Erstellt einen Mock-Cursor.
fetchone_seq: wenn angegeben, wird fetchone() sequenziell diese Werte liefern.
"""
cur = MagicMock()
if fetchone_seq is not None:
cur.fetchone.side_effect = fetchone_seq
else:
cur.fetchone.return_value = fetchone_val
return cur
def _dict_row(d: dict):
"""Simuliert ein psycopg2-DictRow-Objekt (keys() + Subscript)."""
m = MagicMock()
m.keys.return_value = list(d.keys())
m.__getitem__ = lambda self, k: d[k]
m.__iter__ = lambda self: iter(d.values())
return m
# ---------------------------------------------------------------------------
# 1–2: assert_superadmin_for_legal_hold
# ---------------------------------------------------------------------------
class TestAssertSuperadmin:
def test_superadmin_passes(self):
# kein Fehler
assert_superadmin_for_legal_hold("superadmin")
def test_non_superadmin_raises_403(self):
for role in ("admin", "user", "club_admin", None, ""):
with pytest.raises(HTTPException) as exc:
assert_superadmin_for_legal_hold(role)
assert exc.value.status_code == 403
# ---------------------------------------------------------------------------
# 3–4: is_media_available_for_normal_use
# ---------------------------------------------------------------------------
class TestIsMediaAvailable:
def test_no_hold_is_available(self):
assert is_media_available_for_normal_use(_asset(legal_hold_active=False)) is True
def test_hold_active_is_not_available(self):
assert is_media_available_for_normal_use(_asset(legal_hold_active=True)) is False
# ---------------------------------------------------------------------------
# 5–6: assert_not_under_legal_hold
# ---------------------------------------------------------------------------
class TestAssertNotUnderLegalHold:
def test_no_hold_does_not_raise(self):
assert_not_under_legal_hold(_asset(legal_hold_active=False))
def test_hold_active_raises_403_with_code(self):
with pytest.raises(HTTPException) as exc:
assert_not_under_legal_hold(_asset(legal_hold_active=True, id=55))
assert exc.value.status_code == 403
detail = exc.value.detail
assert isinstance(detail, dict)
assert detail["code"] == "LEGAL_HOLD_ACTIVE"
assert detail["asset_id"] == 55
# ---------------------------------------------------------------------------
# 7–10: set_legal_hold
# ---------------------------------------------------------------------------
class TestSetLegalHold:
def test_invalid_reason_code_raises_400(self):
cur = MagicMock()
conn = MagicMock()
with pytest.raises(HTTPException) as exc:
set_legal_hold(cur, conn, asset_id=1, acting_profile_id=1,
reason_code="totally_made_up", reason_note="some reason")
assert exc.value.status_code == 400
def test_empty_reason_note_raises_400(self):
cur = MagicMock()
conn = MagicMock()
with pytest.raises(HTTPException) as exc:
set_legal_hold(cur, conn, asset_id=1, acting_profile_id=1,
reason_code="rights_dispute", reason_note="")
assert exc.value.status_code == 400
def test_already_under_hold_raises_409(self):
asset = _asset(legal_hold_active=True)
cur = _make_cur(_dict_row(asset))
conn = MagicMock()
with patch("db.r2d", return_value=asset), \
patch("media_legal_hold.write_audit_log_entry"):
with pytest.raises(HTTPException) as exc:
set_legal_hold(cur, conn, asset_id=99, acting_profile_id=1,
reason_code="rights_dispute", reason_note="Verletzung bestätigt")
assert exc.value.status_code == 409
def test_success_sets_hold_and_writes_audit(self):
asset_before = _asset(legal_hold_active=False, rights_status="declared")
asset_after = {
**asset_before,
"legal_hold_active": True,
"legal_hold_reason_code": "copyright_complaint",
"legal_hold_reason_note": "Urheberrechtsverletzung gemeldet",
"legal_hold_set_by_profile_id": 1,
"legal_hold_set_at": "2026-05-11T12:00:00Z",
"rights_status": "blocked",
}
cur = _make_cur(None)
cur.fetchone.side_effect = [_dict_row(asset_before), _dict_row(asset_after)]
conn = MagicMock()
with patch("db.r2d", side_effect=[asset_before, asset_after]), \
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
result = set_legal_hold(
cur, conn,
asset_id=99,
acting_profile_id=1,
reason_code="copyright_complaint",
reason_note="Urheberrechtsverletzung gemeldet",
)
assert result["legal_hold_active"] is True
assert result["rights_status"] == "blocked"
conn.commit.assert_called_once()
mock_audit.assert_called_once()
audit_call_kwargs = mock_audit.call_args
assert audit_call_kwargs[1]["event_type"] == "legal_hold_set"
assert audit_call_kwargs[1]["new_values"]["legal_hold_active"] is True
assert audit_call_kwargs[1]["new_values"]["reason_code"] == "copyright_complaint"
# ---------------------------------------------------------------------------
# 11–14: release_legal_hold
# ---------------------------------------------------------------------------
class TestReleaseLegalHold:
def test_empty_release_note_raises_400(self):
cur = MagicMock()
conn = MagicMock()
with pytest.raises(HTTPException) as exc:
release_legal_hold(cur, conn, asset_id=99, acting_profile_id=1, release_note="")
assert exc.value.status_code == 400
def test_not_under_hold_raises_409(self):
asset = _asset(legal_hold_active=False)
cur = _make_cur(_dict_row(asset))
conn = MagicMock()
with patch("db.r2d", return_value=asset):
with pytest.raises(HTTPException) as exc:
release_legal_hold(cur, conn, asset_id=99, acting_profile_id=1,
release_note="Falschmeldung")
assert exc.value.status_code == 409
def test_release_without_declaration_restores_legacy_unreviewed(self):
asset = _asset(legal_hold_active=True, rights_status="blocked")
asset_after = {**asset, "legal_hold_active": False, "rights_status": "legacy_unreviewed",
"legal_hold_released_by_profile_id": 1, "legal_hold_release_note": "Klaerung abgeschlossen"}
cur = _make_cur(None)
# fetchone-Sequenz: 1) Asset (fuer r2d), 2) decl count row, 3) updated asset row (fuer r2d)
decl_cnt_row = type("Row", (), {"__getitem__": staticmethod(lambda k: 0), "__iter__": staticmethod(lambda: iter([0]))})()
cur.fetchone.side_effect = [_dict_row(asset), decl_cnt_row, _dict_row(asset_after)]
conn = MagicMock()
with patch("db.r2d", side_effect=[asset, asset_after]), \
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
result = release_legal_hold(
cur, conn, asset_id=99, acting_profile_id=1,
release_note="Klaerung abgeschlossen",
)
assert result["legal_hold_active"] is False
assert result["rights_status"] == "legacy_unreviewed"
conn.commit.assert_called_once()
mock_audit.assert_called_once()
assert mock_audit.call_args[1]["event_type"] == "legal_hold_released"
def test_release_with_declaration_restores_declared(self):
asset = _asset(legal_hold_active=True, rights_status="blocked")
asset_after = {**asset, "legal_hold_active": False, "rights_status": "declared",
"legal_hold_released_by_profile_id": 1, "legal_hold_release_note": "Einigung erzielt"}
cur = _make_cur(None)
decl_cnt_row = type("Row", (), {"__getitem__": staticmethod(lambda k: 1), "__iter__": staticmethod(lambda: iter([1]))})()
cur.fetchone.side_effect = [_dict_row(asset), decl_cnt_row, _dict_row(asset_after)]
conn = MagicMock()
with patch("db.r2d", side_effect=[asset, asset_after]), \
patch("media_legal_hold.write_audit_log_entry") as mock_audit:
result = release_legal_hold(
cur, conn, asset_id=99, acting_profile_id=1,
release_note="Einigung erzielt",
)
assert result["legal_hold_active"] is False
assert result["rights_status"] == "declared"
mock_audit.assert_called_once()
assert mock_audit.call_args[1]["new_values"]["rights_status"] == "declared"
# ---------------------------------------------------------------------------
# 15: Retention-Job ueberspringt Legal-Hold-Assets
# ---------------------------------------------------------------------------
class TestRetentionJobSkipsLegalHold:
def test_retention_queries_exclude_legal_hold(self):
"""Prueft dass run_retention_pass keine Legal-Hold-Assets anfasst."""
import inspect
import media_lifecycle
source = inspect.getsource(media_lifecycle.run_retention_pass)
# Beide Queries (trash_soft→trash_hidden und trash_hidden→purge)
# muessen den Legal-Hold-Filter enthalten
assert "legal_hold_active" in source, (
"run_retention_pass muss legal_hold_active in den Retention-Queries filtern"
)
# Sicherstellen, dass der Filter korrekt lautet (FALSE oder IS NULL)
assert "legal_hold_active = FALSE" in source or "legal_hold_active IS NULL" in source, (
"Filter muss 'legal_hold_active = FALSE' oder 'IS NULL' enthalten"
)
+344
View File
@@ -0,0 +1,344 @@
"""
P-13: Content-Melde-Backend – Backend-Tests.
Abgedeckt (15 Faelle):
1. submit_report ohne good_faith_confirmed=False → 400
2. submit_report mit leerem report_description → 422
3. submit_report mit fehlender reporter_email → 422
4. submit_report ohne Login fuer official-Medium – Erfolgspfad
5. submit_report ohne Login fuer nicht-official-Medium → 404
6. submit_report mit Login fuer sichtbares club-Medium – Erfolgspfad
7. submit_report mit Login fuer nicht-sichtbares fremdes Medium → 404
8. Prioritaet high fuer illegal_content/minors/youth_protection
9. Prioritaet normal fuer copyright/other
10. list_inbox als Nicht-Admin → 403
11. list_inbox als Plattform-Admin – gibt Liste zurueck
12. patch_report status 'under_review' – Erfolgspfad
13. patch_report 'resolved_no_action' ohne resolution_note → 400
14. set_legal_hold_from_report als Nicht-Superadmin → 403
15. set_legal_hold_from_report als Superadmin – Erfolgspfad (reason_code-Mapping)
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi import HTTPException
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from routers.content_reports import (
HIGH_PRIORITY_REASONS,
_REASON_TO_HOLD_CODE,
_is_media_asset_visible_anonymous,
_is_media_asset_visible_to_profile,
REPORT_REASONS,
ContentReportCreate,
ContentReportPatch,
)
# ---------------------------------------------------------------------------
# Hilfsfunktionen
# ---------------------------------------------------------------------------
def _make_cur(fetchone_val=None):
cur = MagicMock()
cur.fetchone.return_value = fetchone_val
cur.fetchall.return_value = []
return cur
def _row(data: dict):
"""Simuliert eine psycopg2-DictRow."""
m = MagicMock()
m.__getitem__ = lambda self, k: data[k]
m.keys = lambda: data.keys()
return m
# ---------------------------------------------------------------------------
# 1. good_faith_confirmed=False → 400
# ---------------------------------------------------------------------------
def test_submit_requires_good_faith():
body = ContentReportCreate(
target_type="media_asset",
target_id=1,
report_reason="copyright",
report_description="A" * 20,
reporter_name="Max",
reporter_email="max@example.com",
good_faith_confirmed=False,
)
from routers.content_reports import submit_content_report
with pytest.raises(HTTPException) as exc:
submit_content_report(body)
assert exc.value.status_code == 400
assert "Gutglauben" in exc.value.detail
# ---------------------------------------------------------------------------
# 2. Leere report_description → 422 (Pydantic)
# ---------------------------------------------------------------------------
def test_submit_requires_description():
with pytest.raises(Exception):
ContentReportCreate(
target_type="media_asset",
target_id=1,
report_reason="copyright",
report_description="ab", # unter min_length=10
reporter_name="Max",
reporter_email="max@example.com",
good_faith_confirmed=True,
)
# ---------------------------------------------------------------------------
# 3. Ungueltige E-Mail → 422 (Pydantic Validator)
# ---------------------------------------------------------------------------
def test_submit_requires_valid_email():
with pytest.raises(Exception):
ContentReportCreate(
target_type="media_asset",
target_id=1,
report_reason="copyright",
report_description="A" * 20,
reporter_name="Max",
reporter_email="kein-at-zeichen",
good_faith_confirmed=True,
)
# ---------------------------------------------------------------------------
# 4. Anonym – official-Medium → sichtbar
# ---------------------------------------------------------------------------
def test_anonymous_official_medium_visible():
cur = _make_cur(fetchone_val={"1": 1})
cur.fetchone.return_value = MagicMock()
result = _is_media_asset_visible_anonymous(cur, asset_id=42)
assert result is True
# ---------------------------------------------------------------------------
# 5. Anonym – nicht-official-Medium → nicht sichtbar
# ---------------------------------------------------------------------------
def test_anonymous_non_official_medium_not_visible():
cur = _make_cur(fetchone_val=None)
result = _is_media_asset_visible_anonymous(cur, asset_id=99)
assert result is False
# ---------------------------------------------------------------------------
# 6. Eingeloggter Nutzer – sichtbares club-Medium → True
# ---------------------------------------------------------------------------
def test_logged_in_club_member_can_see_club_media():
asset_row = MagicMock()
asset_row.keys = lambda: ["id", "visibility", "club_id", "uploaded_by_profile_id"]
asset_row.__getitem__ = lambda s, k: {
"id": 7,
"visibility": "club",
"club_id": 3,
"uploaded_by_profile_id": 99,
}[k]
member_row = MagicMock() # Mitgliedschaft gefunden
cur = MagicMock()
cur.fetchone.side_effect = [asset_row, member_row]
result = _is_media_asset_visible_to_profile(cur, asset_id=7, profile_id=1, global_role="trainer")
assert result is True
# ---------------------------------------------------------------------------
# 7. Eingeloggter Nutzer – fremdes Medium → False
# ---------------------------------------------------------------------------
def test_logged_in_non_member_cannot_see_club_media():
asset_row = MagicMock()
asset_row.keys = lambda: ["id", "visibility", "club_id", "uploaded_by_profile_id"]
asset_row.__getitem__ = lambda s, k: {
"id": 7,
"visibility": "club",
"club_id": 3,
"uploaded_by_profile_id": 99,
}[k]
cur = MagicMock()
# Erster fetchone: Asset-Zeile, zweiter: kein Mitglied
cur.fetchone.side_effect = [asset_row, None]
result = _is_media_asset_visible_to_profile(cur, asset_id=7, profile_id=5, global_role="trainer")
assert result is False
# ---------------------------------------------------------------------------
# 8. Prioritaet high fuer kritische Gruende
# ---------------------------------------------------------------------------
def test_high_priority_reasons():
assert "illegal_content" in HIGH_PRIORITY_REASONS
assert "minors" in HIGH_PRIORITY_REASONS
assert "youth_protection" in HIGH_PRIORITY_REASONS
# ---------------------------------------------------------------------------
# 9. Prioritaet normal fuer andere Gruende
# ---------------------------------------------------------------------------
def test_normal_priority_reasons():
normal_reasons = REPORT_REASONS - HIGH_PRIORITY_REASONS
assert "copyright" in normal_reasons
assert "other" in normal_reasons
assert "privacy" in normal_reasons
# ---------------------------------------------------------------------------
# 10. list_inbox als Nicht-Admin → 403
# ---------------------------------------------------------------------------
def test_list_inbox_requires_platform_admin():
from routers.content_reports import list_inbox_content_reports
tenant = MagicMock()
tenant.global_role = "trainer"
tenant.profile_id = 99
# COUNT-Abfrage fuer Club-Admin-Rollen → 0 → 403
cnt_row = _row({"cnt": 0})
mock_cur = MagicMock()
mock_cur.fetchone.return_value = cnt_row
mock_conn = MagicMock()
mock_conn_ctx = MagicMock()
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
patch("routers.content_reports.get_cursor", return_value=mock_cur):
with pytest.raises(HTTPException) as exc:
list_inbox_content_reports(tenant=tenant)
assert exc.value.status_code == 403
# ---------------------------------------------------------------------------
# 11. list_inbox als Plattform-Admin – gibt Liste zurueck
# ---------------------------------------------------------------------------
def test_list_inbox_as_admin_returns_list():
from routers.content_reports import list_inbox_content_reports
tenant = MagicMock()
tenant.global_role = "admin"
mock_conn = MagicMock()
mock_cur = MagicMock()
mock_cur.fetchall.return_value = []
mock_conn.__enter__ = MagicMock(return_value=mock_conn)
mock_conn.__exit__ = MagicMock(return_value=False)
mock_conn_ctx = MagicMock()
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
patch("routers.content_reports.get_cursor", return_value=mock_cur):
result = list_inbox_content_reports(tenant=tenant)
assert isinstance(result, list)
# ---------------------------------------------------------------------------
# 12. patch_report status 'under_review' – Erfolgspfad
# ---------------------------------------------------------------------------
def test_patch_report_under_review():
from routers.content_reports import patch_content_report
tenant = MagicMock()
tenant.global_role = "admin"
tenant.profile_id = 1
body = ContentReportPatch(status="under_review")
existing_row = MagicMock()
existing_row.__getitem__ = lambda s, k: {
"id": 5, "status": "submitted",
"target_type": "media_asset", "target_id": 42, "resolution_note": None,
}[k]
existing_row.keys = lambda: ["id", "status", "target_type", "target_id", "resolution_note"]
updated_row = MagicMock()
updated_row.__getitem__ = lambda s, k: {"id": 5, "status": "under_review"}[k]
updated_row.keys = lambda: ["id", "status"]
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [existing_row, updated_row]
mock_conn = MagicMock()
mock_conn_ctx = MagicMock()
mock_conn_ctx.__enter__ = MagicMock(return_value=mock_conn)
mock_conn_ctx.__exit__ = MagicMock(return_value=False)
with patch("routers.content_reports.get_db", return_value=mock_conn_ctx), \
patch("routers.content_reports.get_cursor", return_value=mock_cur):
result = patch_content_report(5, body, tenant=tenant)
assert result["ok"] is True
assert result["status"] == "under_review"
# ---------------------------------------------------------------------------
# 13. patch_report 'resolved_no_action' ohne resolution_note → 400
# ---------------------------------------------------------------------------
def test_patch_resolved_no_action_requires_note():
from routers.content_reports import patch_content_report
tenant = MagicMock()
tenant.global_role = "admin"
tenant.profile_id = 1
body = ContentReportPatch(status="resolved_no_action", resolution_note=None)
with pytest.raises(HTTPException) as exc:
patch_content_report(99, body, tenant=tenant)
assert exc.value.status_code == 400
assert "Begründung" in exc.value.detail
# ---------------------------------------------------------------------------
# 14. set_legal_hold_from_report als Nicht-Superadmin → 403
# ---------------------------------------------------------------------------
def test_legal_hold_from_report_requires_superadmin():
from routers.content_reports import set_legal_hold_from_report, ContentReportLegalHoldBody
tenant = MagicMock()
tenant.global_role = "admin" # nur admin, nicht superadmin
body = ContentReportLegalHoldBody(reason_note="Test-Begruendung")
with pytest.raises(HTTPException) as exc:
set_legal_hold_from_report(1, body, tenant=tenant)
assert exc.value.status_code == 403
# ---------------------------------------------------------------------------
# 15. Reason-Code-Mapping: copyright → copyright_complaint
# ---------------------------------------------------------------------------
def test_reason_code_mapping():
assert _REASON_TO_HOLD_CODE["copyright"] == "copyright_complaint"
assert _REASON_TO_HOLD_CODE["minors"] == "youth_protection"
assert _REASON_TO_HOLD_CODE["illegal_content"] == "illegal_content"
assert _REASON_TO_HOLD_CODE["privacy"] == "privacy_complaint"
assert _REASON_TO_HOLD_CODE["image_rights"] == "rights_dispute"
assert _REASON_TO_HOLD_CODE["other"] == "other"
# Alle Reason-Codes muessen gemappt sein
for reason in REPORT_REASONS:
assert reason in _REASON_TO_HOLD_CODE, f"{reason} fehlt im Mapping"
+24
View File
@@ -124,3 +124,27 @@ def test_api_attachments_x_content_type_options_nosniff(client: TestClient) -> N
r2 = client.get("/api/version")
assert r2.status_code == 200
assert r2.headers.get("x-content-type-options") == "nosniff"
def test_public_media_static_not_mounted_by_default() -> None:
"""/media/-StaticFiles-Mount darf ohne ALLOW_PUBLIC_MEDIA_STATIC nicht aktiv sein."""
snippet = """
from main import app
mounted = [getattr(r, 'path', '') for r in app.routes]
assert not any(p == '/media' for p in mounted), (
"ALLOW_PUBLIC_MEDIA_STATIC aktiv – /media oeffentlich erreichbar. Vor Deploy entfernen."
)
"""
proc = _run_fresh_import_int(snippet, {"ENVIRONMENT": "production"})
assert proc.returncode == 0, proc.stderr + proc.stdout
def test_allow_public_media_static_activates_media_mount() -> None:
"""Dokumentiert: ALLOW_PUBLIC_MEDIA_STATIC=1 aktiviert /media ohne Authentifizierung."""
snippet = """
from main import app
mounted = [getattr(r, 'path', '') for r in app.routes]
assert any(p == '/media' for p in mounted), "/media-Mount wurde nicht aktiviert"
"""
proc = _run_fresh_import_int(snippet, {"ALLOW_PUBLIC_MEDIA_STATIC": "1"})
assert proc.returncode == 0, proc.stderr + proc.stdout
+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
+673 -11
View File
@@ -1,34 +1,696 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.65"
BUILD_DATE = "2026-05-08"
DB_SCHEMA_VERSION = "20260508049"
APP_VERSION = "0.8.151"
BUILD_DATE = "2026-05-20"
DB_SCHEMA_VERSION = "20260520066"
MODULE_VERSIONS = {
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
"auth": "1.2.3", # P-05b: reset-password min_length=8 via Pydantic PasswordResetConfirm
"profiles": "1.8.0", # training_planning_prefs JSONB (Planungs-UI); Patch via ProfileUpdate + Json(), Migration 055
"tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
"club_memberships": "1.0.1", # Depends(get_tenant_context)
"club_join_requests": "1.0.1", # Depends(get_tenant_context)
"admin_users": "1.0.0", # GET /api/admin/users
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
"media_assets": "1.12.1", # official: nur Superadmin Lifecycle/PATCH; UI Lesemodus; Superadmin Upload-Verein = aktiv
"media_rights": "1.3.1", # acting_profile_id in write_audit_log_entry auf Optional[int] (P-13 anonyme Meldungen)
"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
"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.19.1", # Verein: PUT default_club_media_copyright + Prompt beim Speichern (fehlende File-Asset-Copyrights)
"training_units": "0.2.0",
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
"training_programs": "0.1.0",
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
"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)
"maturity_models": "1.4.0", # matrix_stack_bundle: vollständiger Katalog+Modelle+Bindings Export/Import
"content_reports": "1.5.1", # P-13: Fruehzeitige 403 fuer plain Admin in set_legal_hold_from_report (CI-Fix)
}
CHANGELOG = [
{
"version": "0.8.151",
"date": "2026-05-20",
"changes": [
"Phase 3 Fähigkeiten-Scoring: skill_scoring.py (Dauer × Vorkommen × Primär/Intensität/Beitrag)",
"GET skill-profile für Rahmenprogramm (gesamt + pro Slot), Trainingsmodul, Progressionsgraph",
"GET /api/skill-discovery/suggestions nach skill_ids",
],
},
{
"version": "0.8.149",
"date": "2026-05-19",
"changes": [
"Trainingsplanung: Einheiten-Editor als Vollseite (/planning/units/new|/:id/edit); Hub ohne Modal; Legacy ?unit= Redirect",
"Drift-Schutz: planningUnitRoutes.js, trainingUnitEditorCore.js, Vitest; Playwright 14–15",
],
},
{
"version": "0.8.148",
"date": "2026-05-19",
"changes": [
"Planung Vorlagen: Strukturvorschau (Split-Sessions), Kurzbeschreibung, Bearbeitungsseite; Liste liefert sections[] mit",
],
},
{
"version": "0.8.147",
"date": "2026-05-19",
"changes": [
"Planung: Liste – Rahmen-Session & Übungen→Modul; Dialog Modul aus Einheit; klarere Rahmen-Unit-ID aus Liste",
],
},
{
"version": "0.8.146",
"date": "2026-05-19",
"changes": [
"Planung: Trainingseinheit → Rahmenprogramm (Session-Slot) speichern; API POST /api/training-units/{id}/publish-to-framework",
],
},
{
"version": "0.8.145",
"date": "2026-05-16",
"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",
"changes": [
"GET /api/training-units/:id: Bei Kombinationsübungen werden `combination_slots` inkl. Kandidaten-Titel mitgeliefert (für Plan & Ablauf / Druck).",
"Hilfsfunktion `load_combination_slots_for_exercise` im exercises-Router; GET Übung nutzt dieselbe Ladelogik.",
],
},
{
"version": "0.8.109",
"date": "2026-05-12",
"changes": [
"Kombination: „Serien“ standardmäßig 1 (Formular/API); Archetyp kann via `ARCHETYPE_DEFAULT_REP_SERIES_COUNT` andere Vorgaben setzen; Profil‑Editor zeigt Fallback.",
],
},
{
"version": "0.8.108",
"date": "2026-05-12",
"changes": [
"Kombination rep/manual: Feld „Pause zw. Serien“ nur ab 2 Serien sichtbar und speicherbar; Hinweis unterscheidet Wechsel zur nächsten Station; API verwirft intra_rep_rest_sec bei nur einer Serie.",
],
},
{
"version": "0.8.107",
"date": "2026-05-12",
"changes": [
"Kombination Wiederholungsziel: `rep_series_count` in `slot_profiles_v1` (mehrere Serien à Ziel‑Wdh.); Formular‑ und Profil‑Editor‑Felder; Pause als „zwischen Serien“ beschriftet; Coach‑Zusammenfassung angepasst.",
],
},
{
"version": "0.8.106",
"date": "2026-05-12",
"changes": [
"Kombinationsübung: Stationssteuerung `advance_mode` in `slot_profiles_v1` (zeitlich / Ziel‑Wiederholungen / Coach ohne Arbeitsuhr); Übungsformular + Planungs‑Profil‑Editor; API‑Payload verwirft Arbeit‑Sekunden außer bei Zeitmodus; Coach zeigt verkürzte Planzeile je Station.",
],
},
{
"version": "0.8.105",
"date": "2026-05-12",
"changes": [
"Übungsbearbeitung Kombi: Stationen mit Pool per Modal (nur Einzelübungen), Zeiten pro Station in derselben Karte, Drag&Drop + Pfeile statt Index; API schreibt slot_index aus Reihenfolge; Gesamtdurchläufe bei Zirkel/Sequenz/Parcours/Parallel klar beschriftet.",
],
},
{
"version": "0.8.104",
"date": "2026-05-12",
"changes": [
"Kombinations‑Ablaufprofil UX: Stationszeilen (slot_profiles_v1); Schnellwahlen Arbeit↔Pause (Zirkel + Intervall); Planungs‑Override ohne JSON; Übungsformular: Reihenfolge Stationen dann Ablaufprofil.",
"Arbeitspapier: `.claude/docs/working/COMBINATION_TIMING_PROFILE_PLAN.md`.",
],
},
{
"version": "0.8.103",
"date": "2026-05-12",
"changes": [
"Trainingsplanung: bei Kombinationszeilen optionales `planning_method_profile` (Migration 057); Planungs-Editor mit Ablaufprofil-Details, „wie Katalog“ / „aus Katalog kopieren“; Payload/Coach-PUT übernehmen Snapshot.",
],
},
{
"version": "0.8.102",
"date": "2026-05-12",
"changes": [
"Kombinationsübung beim Anlegen/Bearbeiten: archetypbezogenes Ablaufprofil (geführt) + eingeklappt Roh-JSON (`CombinationMethodProfileEditor`); Schlüsselmanifest `combinationMethodProfileUi.js`. Coach: angelegtes method_profile unter Stationenliste lesbar.",
],
},
{
"version": "0.8.101",
"date": "2026-05-12",
"changes": [
"Training-Coach bei Kombinationsübungen: Stationen/Kandidaten mit geladenem Katalog (Kurzbeschreibung, aufklappbar Ablauf/Trainerhinweise); Archetyp-spezifischer Coach-Hilfstext; Archetyp-Labels aus `combinationArchetypes.js`.",
],
},
{
"version": "0.8.100",
"date": "2026-05-12",
"changes": [
"Planungs-API/UI: Kombinationsübungen in Trainingsseinheiten (exercise_kind in Sektions-Responses; PATCH verbietet exercise_variant_id für combination); ExercisePicker ohne simple-only Filter, Badge Kombination.",
],
},
{
"version": "0.8.99",
"date": "2026-05-12",
"changes": [
"exercises Phase 2 (Kombinationsübungen): Migration 056 (`exercise_kind`, `method_archetype`, `method_profile`; Tabellen Slots/Kandidaten); CRUD über POST/PUT/GET Übung mit `combination_slots`; Liste-Filter `exercise_kind_any`; Varianten-Endpoints verbieten `exercise_kind=combination`.",
],
},
{
"version": "0.8.98",
"date": "2026-05-12",
"changes": [
"profiles: `training_planning_prefs` JSONB (Migration 055), Patch via PUT Profil — z.B. Darstellung kopierter Trainingsmodule in der Planungs-UI (nutzerspezifisch).",
],
},
{
"version": "0.8.97",
"date": "2026-05-12",
"changes": [
"Trainingsmodule (Phase 1): Bibliothek `training_modules` + `training_module_items` (Migration 054); REST `/api/training-modules`; Übernahme in Einheiten per `POST /api/training-units/{id}/apply-training-module`; Herkunft `source_training_module_id` auf kopierten Sektions-Items; UI unter /planning/training-modules und Übernahme-Dialog in der Trainingsplanung.",
"Umsetzungsplan: `.claude/docs/working/TRAINING_MODULES_IMPLEMENTATION_PLAN.md`.",
],
},
{
"version": "0.8.96",
"date": "2026-05-12",
"changes": [
"P-01 Admin Rechtstexte: Live-Vorschau je Abschnitt (Markdown) neben dem Editor; modale „Vollständige Vorschau“ aus dem Formular; Augen-Symbol in der Dokumentenliste für die gerenderte Ansicht (API-Laden).",
],
},
{
"version": "0.8.95",
"date": "2026-05-12",
"changes": [
"P-01 Rechtstexte: Abschnitte in der Ausgabe mit fortlaufender §1, §2, … (nur Darstellung/PDF, nicht in der DB); Fließtext mit Markdown (react-markdown) inkl. PDF-Rendering (fett/kursiv, Listen, Links, Codeblöcke).",
],
},
{
"version": "0.8.94",
"date": "2026-05-11",
"changes": [
"Fix P-13: set_legal_hold_from_report wirft 403 fuer plain Admin vor DB-Zugriff (CI-Testkonsistenz).",
"Fix P-13: Tests test_list_inbox_requires_platform_admin und test_patch_report_under_review repariert.",
],
},
{
"version": "0.8.93",
"date": "2026-05-11",
"changes": [
"Fix P-13: Club-Admins können Inhaltsmeldungen zu Vereinsmedien bearbeiten (PATCH, GET-Detail).",
"Fix P-13: Club-Admins können Legal Hold auf Vereinsmedien (nicht 'official') aus Meldung heraus setzen.",
"Fix P-13: Abgeschlossene Meldungen in der Inbox in kollabierbare Archiv-Sektion verschoben.",
"Fix P-13: isClubAdmin + isPlatformAdmin im OrgInboxContext exponiert.",
],
},
{
"version": "0.8.92",
"date": "2026-05-11",
"changes": [
"Fix P-13: Badge in Medienbibliothek aktualisiert sich sofort nach Einreichen einer Meldung.",
"Fix P-13: Inbox zeigt Fehlermeldung statt leerem Bereich wenn Backend-Fehler auftritt.",
"Fix P-13: Meldungen lassen sich nach Abschluss wieder öffnen (Wieder-öffnen-Button).",
"Fix P-13: Bearbeitungskommentare werden separat im Audit-Log protokolliert.",
"Fix P-13: Reviewer-Felder werden beim Wieder-öffnen einer Meldung zurückgesetzt.",
"Fix P-13: Workflow-Balken im Meldungs-Detail zeigt aktuellen Bearbeitungsstand.",
],
},
{
"version": "0.8.91",
"date": "2026-05-11",
"changes": [
"Fix P-13: Name- und E-Mail-Felder im Melde-Dialog fuer eingeloggte Nutzer nicht mehr bearbeitbar (readOnly).",
"Fix P-13: Journaleintraege fuer content_report_filed leserlich (Meldegrund, Prioritaet, Status auf Deutsch).",
"Fix P-13: Badge auf Medienkacheln zeigt Anzahl offener Meldungen (nur fuer Admins).",
"Fix P-13: Statuswechsel an Meldungen werden im Journal des Mediums protokolliert.",
],
},
{
"version": "0.8.90",
"date": "2026-05-11",
"changes": [
"Fix P-13: Club-Admins sehen jetzt Inhaltsmeldungen ihrer Vereinsmedien in der Inbox (Backend-Filter + Frontend canSeeContentReports).",
"Fix P-13: Journaleintrag (content_report_filed) in media_asset_audit_log beim Einreichen einer Meldung (Migration 053).",
"Fix P-13: E-Mail-Benachrichtigung an alle Plattform-Admins bei neuer Meldung (best-effort).",
"Fix P-13: Bestätigungs-E-Mail an Melder beim Einreichen (best-effort).",
"Fix P-13: Medienname (target_filename/target_exercise_name) korrekt in Inbox-Liste angezeigt.",
],
},
{
"version": "0.8.89",
"date": "2026-05-11",
"changes": [
"Feat P-13: MediaPreviewModal — geteilter Medienvorschau-Dialog für alle Kontexte (Bibliothek, Übungsbearbeitung, angehängte Medien); optionale Melden- und Bearbeiten-Buttons im Header.",
"Feat P-13: Melde-Button im ExerciseFormPage-Viewer (verlinktes Medium → Vorschau → Melden).",
"Refactor: Inline-Vorschau-Blöcke in MediaLibraryPage, ExerciseFormPage und ExerciseAttachmentMediaStrip durch MediaPreviewModal ersetzt.",
],
},
{
"version": "0.8.88",
"date": "2026-05-11",
"changes": [
"Feat P-13: Melde-Button in Medienbibliothek (Grid + Liste) — öffnet ReportContentModal; nur aktive Medien ohne Legal Hold.",
"Feat P-13: Melde-Link an jedem Medium in ExerciseAttachmentMediaStrip (Lesemodus Übung).",
"Feat P-13: ReportContentModal — wiederverwendbares Formular (Grund, Beschreibung, Name, E-Mail, Gutglaubenserklärung); Vorausfüllung für eingeloggte Nutzer.",
],
},
{
"version": "0.8.87",
"date": "2026-05-11",
"changes": [
"Feat P-13: Content-Melde-Backend (DSA/KRIT-03) — Migration 052 content_reports; POST /api/content-reports (optionale Auth, official+aktive Medien ohne Login meldbar); GET /api/me/inbox/content-reports (Plattform-Admin); PATCH /api/content-reports/{id}; POST /api/content-reports/{id}/legal-hold (Superadmin, P-11 Integration).",
"Feat P-13: Automatische Priorisierung high fuer minors/illegal_content/youth_protection.",
"Feat P-13: Inbox-Integration — zweiter Abschnitt 'Inhaltsmeldungen' in InboxPage.jsx; OrgInboxContext liefert contentReports + contentReportCount.",
"Feat P-13: P-11 Legal-Hold via set_legal_hold() aus report heraus (reason_code-Mapping); keine separate Moderations-Queue.",
"Tests: 15 Backend-Unit-Tests test_p13_content_reports.py.",
],
},
{
"version": "0.8.86",
"date": "2026-05-11",
"changes": [
"Fix P-11: download_exercise_media_file gibt 451 zurück für Legal-Hold-Assets (Datei nicht mehr auslieferbar).",
"Fix P-11: enrich_exercise_detail liefert asset_legal_hold_active im Media-Array (Frontend-Komponenten koennen Hold erkennen).",
"Fix P-11: ExerciseMediaEmbed + ExerciseMediaThumbTile zeigen 'Medium nicht verfügbar / Gesperrt' statt Datei laden.",
"Fix P-11: ExerciseFormPage Vorschau-Modal zeigt Hinweis statt Datei bei Legal-Hold.",
"Fix P-11: Media-Bibliothek-Liste (list_media_assets) schliesst Legal-Hold fuer Plattform-Admins aus — nur Superadmin sieht sie.",
],
},
{
"version": "0.8.85",
"date": "2026-05-11",
"changes": [
"Fix P-11: Listquery fehlte legal_hold_active/reason_code/reason_note/set_at — Badge und 'Sperre aufheben' im Modal waren nie sichtbar.",
"Fix P-11: submitLegalHold rief loadMedia() statt loadItems() auf ('loadMedia is not a function').",
"Fix P-11: Journal-Renderpfad verwendete nw.legal_hold_reason_code/note statt nw.reason_code/note (Keys aus dem Audit-Log).",
"Fix P-11: Archiv-Picker (ExerciseFormPage, ExerciseInlineFileMediaModal) filtert Legal-Hold-Assets auch fuer Superadmins heraus.",
],
},
{
"version": "0.8.84",
"date": "2026-05-11",
"changes": [
"Feat P-11: Legal-Hold-Sofortsperre — Migration 051 (legal_hold_active + Metadaten in media_assets; audit_log um legal_hold_set/released erweitert).",
"Feat P-11: media_legal_hold.py — zentrale Services set_legal_hold, release_legal_hold, assert_not_under_legal_hold.",
"Feat P-11: Retention-Job ueberspringt Assets mit legal_hold_active=TRUE (keine automatische Loeschung unter Hold).",
"Feat P-11: Neue Admin-Endpoints POST /api/admin/media-assets/{id}/legal-hold, POST …/legal-hold/release, GET …/legal-hold (nur Superadmin).",
"Feat P-11: Sichtbarkeitsfilter erweitert — normale Nutzer sehen Legal-Hold-Assets nicht; Superadmin/Plattform-Admin sehen sie.",
"Feat P-11: exercises from-asset prueft Legal-Hold (LEGAL_HOLD_ACTIVE 403) vor Verknuepfung.",
"Feat P-11: Frontend MediaLibraryPage — Legal-Hold-Badge, Superadmin-Aktionen, Bestaetigungs-Dialog, Journal-Renderpfad fuer legal_hold_set/released.",
"Tests: 15 Backend-Unit-Tests test_p11_legal_hold.py.",
],
},
{
"version": "0.8.83",
"date": "2026-05-11",
"changes": [
"Fix: Journal + Korrektur-Endpoint: club_admin-Pruefung nutzte falsches Schema (role-Spalte nicht in club_members, sondern in club_member_roles via has_club_role); lieferte immer 500.",
],
},
{
"version": "0.8.82",
"date": "2026-05-11",
"changes": [
"Feat P-06: Volljournal fuer Medien (Migration 050) — media_asset_audit_log protokolliert Sichtbarkeits-, Copyright-, Metadaten- und Lifecycle-Aenderungen automatisch.",
"Feat P-06: Korrektur-Deklaration (action_type='correction') via POST /api/admin/media-rights/assets/{id}/correction — zugaenglich fuer Superadmin, Uploader, Vereinsadmin.",
"Feat P-06: Journal-Endpoint gibt jetzt events[] (Deklarationen + Auditlog chronologisch gemischt) und can_correct zurueck; Zugriff fuer Superadmin + Uploader + Vereinsadmin.",
],
},
{
"version": "0.8.81",
"date": "2026-05-11",
"changes": [
"Fix P-06: check_rights_coverage gibt bei rights_status='declared' immer 'ok' zurueck — Erklaerung gilt sichtbarkeitsunabhaengig (Inhalt aendert sich nicht durch Sichtbarkeits-Promotion). 'insufficient'-Pfad entfernt. Tests angepasst.",
],
},
{
"version": "0.8.80",
"date": "2026-05-11",
"changes": [
"Fix P-06: Bei Sichtbarkeits-Promotion (private→club, club→official) oeffnet das Frontend bei RIGHTS_SCOPE_INSUFFICIENT / LEGACY_REDECLARATION_REQUIRED automatisch den Einwilligungsdialog (promotion/redeclaration-Modus) statt eines alert()-Fehlers; PATCH wird nach Bestaetigung mit P-06-Feldern wiederholt.",
],
},
{
"version": "0.8.79",
"date": "2026-05-11",
"changes": [
"Fix: profiles.username -> profiles.name in Journal-Endpoint (500er behoben); RightsDeclarationDialog: doppelter Abbrechen-Button entfernt (Header-X statt Text); Playwright P-01: Platzhalter-Pruefung optional (echtes Impressum deployed); Playwright P-06c: Selector-Konflikt durch UI-Fix beseitigt.",
],
},
{
"version": "0.8.78",
"date": "2026-05-11",
"changes": [
"P-06 Superadmin Medienjournal: GET /api/admin/media-rights/assets/{id}/journal liefert vollstaendiges Deklarations-Log pro Medium; Frontend: Journal-Button im Bearbeitungs-Modal (nur Superadmin), scrollbare Timeline aller Einwilligungserklaerungen mit Kontext-Feldern.",
],
},
{
"version": "0.8.77",
"date": "2026-05-11",
"changes": [
"P-06 Erweiterung: Migration 049 — 4 optionale Freitext-Kontextfelder in media_asset_rights_declarations (person_consent_context, parental_consent_context, music_rights_context, third_party_rights_context); copyright_notice direkt im Upload-Dialog erfassbar; alle drei Dialoge (RightsDeclarationDialog, ExerciseInlineFileMediaModal, ExerciseInlineEmbedModal) und alle Backend-Endpoints aktualisiert.",
],
},
{
"version": "0.8.76",
"date": "2026-05-11",
"changes": [
"Fix P-06: RightsDeclarationDialog in ExerciseInlineFileMediaModal (Upload-Tab) und ExerciseInlineEmbedModal integriert; vor jedem Exercise-Media-Upload oeffnet sich der vollstaendige Einwilligungsdialog statt eines nicht-benutzbaren alert()",
],
},
{
"version": "0.8.75",
"date": "2026-05-11",
"changes": [
"P-06 (Upload-Einwilligungsdialog) technisch umgesetzt unter konservativen Erstannahmen (p06-v1-conservative): Migration 048 (media_asset_rights_declarations + rights_status/rights_declared_for_visibility/rights_declared_at in media_assets); zentrales Policy-Modul media_rights.py; Bulk-Upload und PATCH/Bulk-Patch mit P-06-Enforcement; Re-Deklarations-Endpoint (POST /api/media-assets/{id}/rights-declarations); Admin-Legacy-Summary (GET /api/admin/media-rights/legacy-summary+/legacy-assets); exercises.py: P-06 bei upload_exercise_media und from-asset; Frontend: RightsDeclarationDialog + Altbestand-Indikator in Medienbibliothek. KRIT-04 bleibt offen bis juristische Validierung.",
],
},
{
"version": "0.8.74",
"date": "2026-05-10",
"changes": [
"Rechtstexte: echtes PDF-Download via jsPDF (pdf.save) statt Browser-Print-Dialog; LegalPage und AdminLegalDocumentsPage",
"Rechtstexte Admin: Abschnitts-Reihenfolge per Pfeil-Buttons aendern; neuen Abschnitt an beliebiger Stelle einfuegen",
],
},
{
"version": "0.8.73",
"date": "2026-05-10",
"changes": [
"Rechtstexte: PDF-Export via Browser-Print (kein neues Paket); Drucker-Button in AdminLegalDocumentsPage (laedt Volldokument) und auf LegalPage (nur bei veroeffentlichtem Inhalt); Dokument enthaelt Versionsnummer und Gueltigkeitsdatum",
],
},
{
"version": "0.8.72",
"date": "2026-05-10",
"changes": [
"Rechtstexte: Als-Entwurf-kopieren — POST /api/admin/legal-documents/{id}/copy-as-draft; Inhalt und Titel werden uebernommen, Versionsnummer inkrementiert",
],
},
{
"version": "0.8.71",
"date": "2026-05-10",
"changes": [
"Compliance P-01c: Admin-konfigurierbare Rechtstexte — DB 047 (legal_documents + legal_document_audit); Superadmin CRUD + Publish/Archive-Workflow; LegalPage laedt aus API mit Platzhalter-Fallback; AdminLegalDocumentsPage unter /admin/legal-documents",
],
},
{
"version": "0.8.70",
"date": "2026-05-10",
"changes": [
"Compliance P-01b: Einstellungen/Rechtliches (/settings/legal) fuer mobile/PWA-Darstellung; Hub mit Links zu Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie",
],
},
{
"version": "0.8.69",
"date": "2026-05-10",
"changes": [
"Compliance P-01 (KRIT-01) technischer Teil: Rechtstextseiten /impressum, /datenschutz, /nutzungsbedingungen, /medienrichtlinie als oeffentliche Routen angelegt (Platzhalter, kein Auth erforderlich)",
"Login-Seite und Desktop-Sidebar enthalten Links zu allen vier Rechtstextseiten",
],
},
{
"version": "0.8.68",
"date": "2026-05-10",
"changes": [
"Sicherheit P-12 (MITT-05): logout() bereinigt alle sj_coach_*-Schlüssel aus sessionStorage; Präfix-gezielte Löschung, keine fremden Schlüssel betroffen",
],
},
{
"version": "0.8.67",
"date": "2026-05-10",
"changes": [
"Sicherheit P-05b: PasswordResetConfirm.new_password min_length=8 (POST /auth/reset-password)",
"Sicherheit P-03b: Retention-Default HIDDEN_TO_PURGE 90->30 Tage (gemaess Loeschkonzept 30+30)",
"Sicherheit P-04: Positive Promotion-Tests haerten (explizit 200 + Payload); Umlaut in Fehlermeldung",
],
},
{
"version": "0.8.66",
"date": "2026-05-09",
"changes": [
"Sicherheit P-03: Papierkorb-Retention-Job (media_retention_job.py) als Docker-Service retention-cron aktiviert (lauft taglich um 03:00 Uhr)",
"Sicherheit P-04: Copyright-Pflicht bei Sichtbarkeits-Promotion auf club/official in PATCH und bulk-patch (media_assets)",
"Sicherheit P-05: Passwort-Mindestlange PUT /auth/pin von 4 auf 8 Zeichen angehoben",
"Sicherheit P-07: Release-Test fur ALLOW_PUBLIC_MEDIA_STATIC in test_security_release.py ergaenzt",
"Sicherheit P-23: LoginPage minLength 6 auf 8 angehoben; hartcodierter Versionsstring entfernt",
"Sicherheit P-24: CORS allow_methods und allow_headers auf benotigte Werte eingeschrankt",
],
},
{
"version": "0.8.65",
"date": "2026-05-08",
+38
View File
@@ -81,6 +81,44 @@ services:
networks:
- shinkan-network
retention-cron:
build:
context: ./backend
dockerfile: Dockerfile
container_name: shinkan-retention-cron
command: >
python -c "
import time, subprocess, sys, os, datetime
def next_3am():
now = datetime.datetime.now()
target = now.replace(hour=3, minute=0, second=0, microsecond=0)
if target <= now:
target += datetime.timedelta(days=1)
return (target - now).total_seconds()
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
while True:
time.sleep(next_3am())
subprocess.run([sys.executable, 'scripts/media_retention_job.py'], check=False)
"
working_dir: /app
environment:
DB_HOST: postgres
DB_PORT: 5432
DB_NAME: shinkan
DB_USER: shinkan_user
DB_PASSWORD: ${DB_PASSWORD}
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
# Loeschkonzept (Audit P-03b): 30 Tage Soft-Trash, dann 30 Tage Hidden, dann Purge (gesamt 60 Tage).
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS: "${MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS:-30}"
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS: "${MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS:-30}"
volumes:
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
depends_on:
- postgres
restart: unless-stopped
networks:
- shinkan-network
volumes:
shinkan-db-data:
+139
View File
@@ -0,0 +1,139 @@
# Shinkan Jinkendo – Fachliche Nutzerfunktionen (Ist-Stand)
**Zweck:** Überblick über die **wesentlichen, produktiv nutzbaren Funktionen** aus Nutzer- und Fachperspektive – zur Weitergabe an Design, Product Discovery oder externe Fachplanung.
**Technischer Detailstand:** App-Version (`APP_VERSION`) und Datenbankschema (`DB_SCHEMA_VERSION`) siehe **`backend/version.py`** — dort ist der autoritative Stand.
**Vertiefung:** Domänenmodell `.claude/docs/functional/DOMAIN_MODEL.md`, Lieferdetal `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md`, Projektstatus `.claude/docs/PROJECT_STATUS.md`, Entwickler-Handover `docs/HANDOVER.md`.
---
## 1. Produktauftrag und Zielgruppe
**Shinkan Jinkendo** ist eine **Web-Applikation für Trainer, Vereinsadmins und Inhaltsverantwortliche** in der Kampfsport- und Trainingsplanung: zentrale Übungs- und Methodenverwaltung, strukturierte **Trainingsplanung für Gruppen**, wiederverwendbare **Rahmenprogramme**, sowie **Governance** von Inhalten (Sichtbarkeit, Vereinszuordnung, Plattform-Inhalte).
**Explizit keine persönliche Sportler-App:** Es geht nicht um individuelles Leistungstracking von Endnutzern oder um ein Athleten-Tagebuch; der Fokus liegt auf **vereinlicher/trainersicher Organisation von Wissen und Ablaufplänen**.
---
## 2. Rollen (vereinfachte Nutzerbilder)
Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter Nutzer, aktiver Verein, Plattform- vs. Vereins-Admin).
| Rollenprofil (fachlich) | Typische Aufgaben in der App |
|-------------------------|------------------------------|
| **Trainer / Redakteur** | Übungen anlegen und pflegen, medienreich beschreiben, filtern/suchen; Trainingseinheiten für Gruppen planen; Rahmenprogramme nutzen oder mitgestalten (je nach Berechtigung); Medienbibliothek nutzen. |
| **Vereinsadmin** | Vereinsdaten, Mitgliedschaften, ggf. vereinsgebundene Inhalte und Medien; kann je nach Implementierung **Inhaltsmeldungen zu Vereinsmedien** bearbeiten und **Legal Hold** für Vereinsmedien auslösen. |
| **Plattform-Admin** | Globale Kataloge, Hierarchien, Importe, Nutzerverwaltung (soweit freigeschaltet); **Posteingang** inkl. organisationsbezogener Meldungen; Reifegradmodelle / Matrix-Stack. |
| **Superadmin** | Stärkste technische Rolle: u. a. **offizielle Plattform-Inhalte** (`official`), tiefe Medien-Lifecycle-Operationen, ausgewählte Hochrisiko-Aktionen (z. B. bestimmte Legal-Hold-Fälle). |
**Aktiver Verein:** Nutzer mit Vereinsbezug arbeiten oft im Kontext eines **gewählten aktiven Vereins** (Profil, API-Header); das beeinflusst Sichtbarkeit von Inhalten und Mandantenlogik.
---
## 3. Hauptnavigation (Nutzerpfade)
Über die **Hauptnavigation** (mobil und Desktop) sind u. a. erreichbar:
- **Übersicht** – Einstieg / Dashboard.
- **Posteingang** – für berechtigte Nutzer: **Änderungs- und Organisationsanfragen** sowie **Inhaltsmeldungen** (Workflow, Status, Archiv).
- **Übungen** – Katalogarbeit, Suche, Filter, Detail, Bearbeitung; **Progressionsgraphen** zwischen Übungen; **Fähigkeiten** (Skills) als verknüpfte Dimension.
- **Planung** – Kalender-/Listenlogik für **Trainingseinheiten** (Sektionen, Übungen, optional **Übungsvarianten**); **Trainingsrahmen (Bibliothek)** mit Zielen und Slots; **Durchführungsansicht** und **Coaching-Modus** pro Einheit (je Route).
- **Medien** – zentrale **Medienbibliothek** (Filter, Suche, Tags, Lifecycle, Copyright-Hinweise; rollenabhängige Bearbeitung).
- **Vereine** – Organisation: Vereine, Struktur, Gruppen (soweit für den Nutzer freigeschaltet).
- **Einstellungen** – Profil, Systeminfos, ggf. Rechtstexte; **Trainer-Kontexte** separat (Route `trainer-contexts`).
- **Admin** (nur Admin-Rolle) – Plattformbereich: Nutzer, Hierarchie/Kataloge, Reifegradmodelle, MediaWiki-Import, **Rechtstexte/P-01** u. a.
Öffentlich bzw. ohne volle App: **Impressum, Datenschutz, Nutzungsbedingungen, Medienrichtlinie**; Login/Registrierung/Verifizierung.
---
## 4. Funktionsblöcke im Detail (fachlich)
### 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**.
- **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).
- **Exercise Blocks** („Bausteine“) und gespeicherte Suchpräferenzen, wo implementiert.
- **Kombinationsübungen** („combination“, Migration 056): Sonderform im Übungskatalog mit **Stationen/Slots**, **Trainingsmethode-/Archetyp** (`method_archetype`), optionalem strukturierten **Ablaufprofil** (`method_profile`). In der Planung wie eine Übung ohne Variante einsetzbar; im **Coach** werden Stations-Kandidaten und Archetyp-Hilfstexte angezeigt (Ausbauschritte B/C nach Fachspez § 10.4 dokumentiert unter `.claude/docs/functional/… Kombinationsübungen Spezifikation V2.md` Anhang A).
### 4.2 Fähigkeiten, Methoden, Kataloge
- **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)
- **Matrixbasierte Modelle** mit Stufen und Zelltexten; **kontextsensitive Auflösung** (Fokus, optional Stilrichtung, Trainingsart) über Bindings.
- **Export/Import** einzelner Modelle und **Komplett-Stack** (Admin-Werkzeuge) für Übertrag zwischen Umgebungen oder Backup.
### 4.4 Trainingsplanung
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
- **Phasen & parallele Streams (Breakout):** Eine Einheit kann aus abwechselnden **Ganzgruppenphasen** und **Parallelphasen** bestehen; in einer Parallelphase führen **mehrere Streams** (Teilstrecken) je eigene Abschnitte/Übungen. Planung über Breakout-UI; API liefert **`phases`** und flache **`sections`** (Migration **063**, siehe **`docs/HANDOVER.md`**). Technische Details: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden (Phasen in Vorlagen: Ausbau siehe Handover „offen“).
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
- **Trainingsmodule (Bibliothek):** wiederverwendbare Übungsfolgen; Übernahme in geplante Einheiten; **Fähigkeiten-Profil** und **Filter** in der Modul-Liste (Peer-Vergleich nur unter Modulen).
- **Rahmenprogramm-Liste:** Suche und Filter (Katalog, Dauer, Fähigkeiten) — Peer-Vergleich nur unter Rahmenprogrammen.
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
- **Durchführung („Plan & Ablauf“):** Ablauf anhand Phasen/Streams darstellen und abarbeiten (inkl. Split-Logik in der Anzeige).
- **Coaching-Modus:** eigener Ablauf mit Schritt-für-Schritt-Timeline, Stream-Wahl pro Parallelphase, Hinweis **„Parallelphase · Abschluss“** (Gruppen zusammenführen) vor der nächsten Ganzgruppenphase oder vor dem nächsten Split; **Nachbereitung** mit Ist-Minuten und Speichern wie in der Planung (inkl. **`phases`**). Nach erfolgreichem Speichern Wechsel zur **Plan- und Ablaufsicht** derselben Einheit. Bei **Kombinationsübungen** zusätzlich **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** (Fachspez **Anhang A**; Ausbauschritte B/C).
### 4.5 Medienbibliothek und Archiv
- **Zentrale Medienverwaltung:** Suche, Filter (u. a. Lifecycle, Medientyp, Verein für Admins), Tags, Copyright-Felder.
- **Lifecycle:** aktive Nutzung, Papierkorb-Stufen, Wiederherstellung; endgültiges Entfernen stark eingeschränkt (Superadmin-Kontext).
- **Governance:** Sichtbarkeit (z. B. privat, vereinsbezogen, **official**); **official** ist fachlich „Plattform offiziell“ und an **Superadmin** gebunden.
- **Rechtliche Sofortmaßnahme:** **Legal Hold** kann Medien vor automatisiertem Lifecycle schützen (Fälle aus Meldungen oder Admin-Prozessen).
### 4.6 Organisation und Mitgliedschaft
- **Vereine (Clubs)** mit Struktur (Sparten/Divisions, Trainingsgruppen) je nach Ausprägung.
- **Beitritts- und Mitgliedschaftslogik** (Requests, Rollen) für mandantenfähige Zusammenarbeit.
### 4.7 Governance von Übungsinhalten
- **Ä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)
- **Melden** von problematischen Inhalten (auch aus Medien- und Übungskontexten; **official**-Medien teils ohne Login meldbar).
- **Posteingang für Admins:** Eingang neuer Meldungen, **Statusworkflow** (z. B. eingereicht, in Prüfung, erledigt/abgelehnt), Notizen, **Wiedereröffnen**; getrennte Darstellung abgeschlossener Fälle (Archiv).
- **Priorisierung** bei sensiblen Kategorien (Minderjährige, illegaler Inhalt, Jugendschutz – fachlich automatisch höher gewichtet).
- Anbindung an **Legal Hold** und Audit-Spuren im Medien-Journal wo vorgesehen.
### 4.9 Import und Plattform-Werkzeuge
- **MediaWiki-basierter Import** von Übungsinhalten mit Tracking und Duplikat-Referenzen (Admin).
- **Plattformnutzerverwaltung** und **Rechtstexte** mit editorseitiger und listenbasierter Vorschau (Markdown, strukturierte Ausgabe inkl. PDF-Darstellung – siehe technische Versionsnotizen).
---
## 5. Bekannte Lücken und Planungshinweise (kurz)
Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen** für Product/Design:
- 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:** 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“).
---
## 6. Änderungshistorie dieser Zusammenfassung
| 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`. |
+105 -20
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-05-07
**App-Version / DB-Schema:** App **0.8.59**, DB-Schema siehe `backend/version.py` (`DB_SCHEMA_VERSION`)
**Stand:** 2026-05-20
**App-Version / DB-Schema:** App **`0.8.149`** (Einheiten-Editor Vollseite), DB-Schema **`20260515063`** — maßgeblich **`backend/version.py`**: `APP_VERSION`, `DB_SCHEMA_VERSION`
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
@@ -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` |
@@ -29,9 +31,13 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.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` |
| **Gewichtetes Fähigkeiten-Scoring (Phase 3)** | `.claude/docs/technical/SKILL_SCORING_SPEC.md` |
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
| **Fachlicher Nutzerüberblick (Design/Product)** | **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** |
---
@@ -64,6 +70,15 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
### 2.6 Gewichtetes Fähigkeiten-Scoring (Phase 3, Stand 2026-05-20)
- **Spec:** `.claude/docs/technical/SKILL_SCORING_SPEC.md`
- **Backend:** `skill_scoring.py`, `routers/skill_profiles.py` — Profile on-the-fly aus Übungsvorkommen + `exercise_skills`; **Peer-Kontext getrennt** (`framework_program` | `training_module` | `progression_graph`) über `library_content_visibility_sql`
- **Metriken:** Trainingsgewicht (`weight`); **Peer-%** (`universal_percent`, max. 100 %) nur unter sichtbaren Bausteinen **desselben Typs**; ★ = stärkster Peer je Fähigkeit
- **API:** Skill-Profile pro Artefakt; `POST /api/skill-profiles/batch-summaries` für Listen; `GET /api/skill-discovery/suggestions`
- **Frontend:** KPI-Kacheln + Filter-Modal (UX wie Übungsliste) auf **`/planning/framework-programs`** und **`/planning/training-modules`**; Panels in Editoren; Discovery auf Fähigkeiten-Seite; `SkillTreeMultiSelect` mit Portal-Dropdown in Modals
- **Offen (Backlog):** Corpus-Caching bei großen Bibliotheken; Tests für Typ-Trennung; Filter-Persistenz; Skill-Filter im Dialog „Rahmen übernehmen“; API-Umbenennung `club_*` → Peer-Namen
---
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
@@ -71,6 +86,44 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
### Trainingsplanung: Einheiten-Editor als Vollseite (Stand **0.8.149**)
- **Routen:** `/planning` (Hub), `/planning/units/new`, `/planning/units/:id/edit`; Legacy `/planning?unit={id}` → Redirect auf Edit-Route.
- **Code:** `TrainingUnitEditPage.jsx`, `TrainingUnitFormShell.jsx`, `planningUnitRoutes.js`, `trainingUnitEditorCore.js` (Payload-Drift-Schutz + Vitest).
- **Hub:** `TrainingPlanningPageRoot.jsx` ohne Einheiten-Modal; Modals nur noch Import, Trainer zuweisen, Rahmen-Session/Modul aus Liste.
- **Spec / DoD:** `docs/architecture/TRAINING_UNIT_EDIT_PAGE_MIGRATION.md`; Playwright **14–15** (Edit-Route, Legacy-Redirect).
### Trainingsplan: Phasen, parallele Streams und Coaching (Stand **0.8.137–0.8.140**)
- **Schema / API:** Migration **063** — `training_unit_phases`, `training_unit_parallel_streams`; Sektionen mit `phase_id` bzw. `parallel_stream_id`. **`GET /api/training-units/:id`** liefert **`phases`** (verschachtelt) und weiterhin flache **`sections`**. **`PUT/POST`** mit **`phases`** für Breakout-Einheiten (vgl. `CHANGELOG` **0.8.138**); Legacy: flache `sections` → implizite Ganzgruppen-Phase.
- **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).
- **Ist kurz:** Trainingsmodule-Bibliothek (Phase **1**) umgesetzt; Kombi-Katalog (**056**), Planungs-Snapshot **`planning_method_profile` (057)** mit **Client-Merge** Katalog+Planung (`comboPlanningMethodProfile.js`); Planung: Modal **„Ablauf bearbeiten…“**, Klammer `CombinationPlanBracket`; Coach **Stufe A** mit lesenden Profil-Labels und konsistenter Slot-Darstellung (`CombinationCoachSlots`, `ExerciseFullContent`). **Offen:** Coach **Stufe B/C** (individuelle Archetyp-Steuerung), **Administrierbarkeit der Archetypen** (derzeit nur Konstanten), **einfache Vorbelegung aller** Zeit-/Anzahlfelder, **serverseitige** Profil↔Archetyp-Restriktionen — siehe Fachspez **§ 10.6**.
---
## 4. Stand: Medien-Management (Ist, 2026-05-07)
@@ -105,35 +158,67 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
---
## 5. Geplant: Inline-Medienverlinkung (nicht umgesetzt)
## 5. Inline-Medien im Fließtext (Spec Abschnitt 11 — umgesetzt)
**Ziel:** Mediendarstellung **innerhalb** von Fließtext-Feldern (Ablauf, Ziele, Trainerhinweise), konsistent mit derselben **`exercise_media`‑** bzw. Asset-Governance wie die Medienliste.
**Ist:** Platzhalter-Syntax, zentraler Render-Pfad, Modal-Picker, Größenwahl, Drag-and-Drop in den Übungstextfeldern — siehe **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (Abschnitt 11), **`FEATURES_DELIVERED_2026-Q2.md`** Abschnitt 12.3 und **`PROJECT_STATUS.md`**.
**Norm:** **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — u. a.:
- Verweis auf **`exercise_media.id`** (oder kanonisch übersetzte Markup-Syntax), **keine** zweite Sichtbarkeitslogik.
- **Ein** zentraler Render-/Sanitize-Pfad für Übungstexte; keine verstreuten „roh `dangerouslySetInnerHTML`“-Pfade.
- XSS/CSP: nur Allowlist-HTML und kontrollierte Player-Komponenten.
**Reihenfolge:** Archiv & aktuelle Governance gelten als Basis; Inline ist die **nächste** inhaltliche Ausbaustufe für Medien (siehe **`PROJECT_STATUS.md`** Nächste Schritte).
**Weiteres:** UX-Politik, ggf. strategische Vereinheitlichung der Referenzmodellierung (reine Asset-Referenz vs. `exercise_media`) — siehe Nächste Schritte in **`PROJECT_STATUS.md`**.
---
## 6. Nächste Session — sinnvolle Arbeitspakete
## 6. P-13: Content-Meldeverfahren (vollständig implementiert, 2026-05-11)
1. **Inline §11:** Syntax festlegen (z. B. `{{exerciseMedia:id}}` → kanonisches HTML), Server normalisieren bei Speichern, einen **`renderExerciseRichText()`**-Pfad im Frontend.
2. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
3. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
4. **S3/Adapter:** Speicher-Abstraktion §7 — wenn Produkt es verlangt.
5. **Rahmen/UI:** Kalender „aus Rahmen übernehmen“ weiter anbinden (parallel, unabhängig von Medien).
**DSA-konformes Meldeverfahren (KRIT-03) — App 0.8.87–0.8.94.**
**Backend (`backend/routers/content_reports.py`, Migrationen 052–053):**
- `POST /api/content-reports` — optionale Auth; `official`-Medien ohne Login meldbar; E-Mail-Bestätigung an Melder + Benachrichtigung aller Plattform-Admins (best-effort).
- `GET /api/me/inbox/content-reports` — Plattform-Admin: alle Meldungen; Club-Admin: nur Meldungen zu Medien eigener Vereine.
- `GET /api/content-reports/{id}` — Plattform-Admin + zuständiger Club-Admin.
- `PATCH /api/content-reports/{id}` — Status-Übergang (submitted → under_review → resolved/rejected); Wiedereröffnen (→ submitted) setzt Prüferfelder zurück; Audit-Log-Einträge bei Status- und Notizänderungen.
- `POST /api/content-reports/{id}/legal-hold` — Superadmin (immer) oder Club-Admin (Vereinsmedien, nicht `official`); integriert P-11 `set_legal_hold()`; plain Admin erhält früh 403.
- Automatische Priorisierung `high` für `minors`/`illegal_content`/`youth_protection`.
- Migration 053: `content_report_filed` Event-Typ in `media_asset_audit_log` CHECK-Constraint.
- `open_report_count` in `list_media_assets`-Response für Admin-Nutzer.
- 15 Backend-Tests in `backend/tests/test_p13_content_reports.py` (alle grün nach CI-Fix 0.8.94).
**Frontend:**
- `ReportContentModal.jsx` — Melde-Formular; `onSuccess`-Callback; readOnly-Felder für eingeloggte Nutzer.
- `MediaPreviewModal.jsx` — geteilter Vorschau-Dialog; optionale Melden- und Bearbeiten-Buttons.
- `InboxPage.jsx` — zweiter Abschnitt „Inhaltsmeldungen”; `WorkflowBar` (3-Schritte-Fortschrittsbalken); `ReportDetailModal` mit Workflow, Prüferinfo, Notiz, Wiedereröffnen-Button; Archiv-Trennung (offen vs. abgeschlossen, kollabierbar); Legal-Hold-Button für Superadmin + Club-Admin.
- `OrgInboxContext.jsx` — liefert `contentReports`, `contentReportCount`, `canAccessContentReports`, `isClubAdmin`, `isPlatformAdmin`, `isSuperadmin`, `contentReportsError`; Club-Admins haben Zugriff auf Berichte.
- `MediaLibraryPage.jsx` — rotes Badge mit `open_report_count` auf Medienkarten; Journal-Eintrag für `content_report_filed`; Badge-Aktualisierung via `onSuccess`.
- Melde-Button in **MediaLibraryPage** (Grid + Liste + Viewer), **ExerciseFormPage** (Viewer), **ExerciseAttachmentMediaStrip** (Viewer).
**Offen (explizit zurückgestellt):**
- P-14 Moderations-UI (eigene Seite), P-15 Uploader-Benachrichtigung bei Sperrung, P-16 Beschwerdeverfahren.
- Melde-Einstieg im Coaching-Modus (Feedback-Schritt, nicht kritisch).
---
## 7. Technische Referenz (kurz)
## 7. Nächste Session — sinnvolle Arbeitspakete
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
---
## 8. Technische Referenz (kurz)
| Bereich | Einstieg |
|---------|----------|
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Coach, 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` |
@@ -141,7 +226,7 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
---
## 8. Veraltete Hinweise
## 9. Veraltete Hinweise
`.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
+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) |
| [VERBINDLICHE_REGELN_SHINKAN.md](./VERBINDLICHE_REGELN_SHINKAN.md) | **Verbindliche** Shinkan-spezifische Regeln (Ergänzung zu den globalen Rules) |
## 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).
+992
View File
@@ -0,0 +1,992 @@
# Compliance-Audit – Shinkan Jinkendo
> **Status:** Entwurf — technischer Audit, kein Rechtsanwalt
> **Datum:** 2026-05-09
> **Auditor:** Claude Code
> **App-Version:** 0.8.65
> **Rechtlicher Hinweis:** Dieses Dokument ist eine technische Analyse. Es ersetzt keine Rechtsberatung. Alle als „juristisch zu prüfen" markierten Punkte müssen durch einen Rechtsanwalt oder Datenschutzbeauftragten bewertet werden. Kein Code wurde verändert.
---
## 1. Executive Summary
Die Shinkan Jinkendo App ist technisch solide aufgebaut: robuste Mandantentrennung (TenantContext), mehrstufiges Löschkonzept für Medien, serverseitig erzwungene Zugriffskontrolle. Die Kernarchitektur der Datenschicht ist gut.
**Kritische Compliance-Lücken:**
- Keine Rechtstexte (Impressum, Datenschutzerklärung, Nutzungsbedingungen, Medienrichtlinie)
- Kein DSA-konformes Meldeverfahren für rechtswidrige Inhalte (UGC-Plattform)
- Kein Recht-am-eigenen-Bild/Minderjährigen-Check beim Medienupload
- Kein Self-Service-Löschrecht für Nutzer (nur Admin kann Konten löschen)
- Auth-Token im localStorage (XSS-Risiko, TDDDG-Dokumentationspflicht)
- HSTS-Header fehlt in der Nginx-Konfiguration
- Papierkorb-Retention-Job nicht automatisch geplant
- Passwort-Mindestlänge inkonsistent (Register: 8, PIN-Änderung: 4 Zeichen)
Vor öffentlichem Betrieb sind die kritischen Findings (KRIT-01 bis KRIT-07) zu adressieren.
---
## 2. Scope
| Bereich | Geprüft |
|---------|---------|
| Backend-Router (alle .py) | ✓ |
| Datenbankmigrationen (001–046) | ✓ |
| Frontend App.jsx, Routing, Auth | ✓ |
| API-Authentifizierung und Autorisierung | ✓ |
| Mandanten-/Zugriffschicht (TenantContext, club_tenancy) | ✓ |
| Medien-Archiv (media_assets, lifecycle) | ✓ |
| PWA-Konfiguration (manifest.webmanifest) | ✓ |
| Nginx-Konfiguration (nginx.conf) | ✓ |
| Docker-Compose (docker-compose.yml) | ✓ |
| Vorhandene Tests (backend/tests/*.py) | ✓ |
| LocalStorage / SessionStorage Nutzung | ✓ |
| Rechtstexte (Impressum, DSGVO, AGB) | ✓ |
| CSP / Security-Header | ✓ |
| Passwort-Handling, Session-Management | ✓ |
---
## 3. Annahmen
- App ist öffentlich im Internet erreichbar unter `shinkan.jinkendo.de` (HTTPS)
- SSL/TLS-Terminierung erfolgt am externen Reverse-Proxy vor dem Nginx-Container
- Betreiber ist im EU-Raum ansässig (DSGVO anwendbar)
- Minderjährige können sich registrieren (keine Altersverifikation vorhanden)
- Die Plattform erlaubt Upload und Anzeige von Bildern und Videos mit Personenabbildungen
---
## 4. Nicht geprüfte Bereiche
- Produktions-Infrastruktur (Synology NAS, Raspberry Pi 5) – nur Konfigurationsdateien
- Netzwerkinfrastruktur (Fritz!Box) – außerhalb des Repos
- SMTP-Anbieter im Detail (Anbieter unbekannt aus Umgebungsvariablen)
- Aktive Penetrationstests
- Backup-Prozess und Restore-Test (kein Skript im Repository)
---
## 5. Technische Bestandsaufnahme
### 5.1 Architektur
| Komponente | Technologie | Sicherheitsrelevanz |
|-----------|-------------|---------------------|
| Frontend | React 18 + Vite, SPA | Routing, Token-Speicherung |
| Backend | FastAPI Python 3.12 | Zugriffskontrolle, Validierung |
| Datenbank | PostgreSQL 16 Alpine | Datenhaltung, Mandantentrennung |
| Proxy | Nginx (Docker) | CSP, Security-Header, Upload-Limit |
| Storage | Lokaler Bind-Mount via Docker | Medienspeicherung |
| Auth | Token-basiert (Sessions-Tabelle) | Session-Management |
| PWA | Web App Manifest + Icons | Offline-Caching (kein Service Worker!) |
| E-Mail | SMTP (konfigurierbar) | Registrierung, Passwort-Reset |
| KI | OpenRouter (optional, nicht MVP) | KI-Features |
### 5.2 Authentifizierung
- Token: `secrets.token_urlsafe(32)` (kryptografisch sicher)
- Hashing: bcrypt mit auto-Upgrade von Legacy SHA256
- Session-Ablauf: 30 Tage (konfigurierbar per `session_days`)
- Rate-Limiting: Login 30/min, Forgot-Password 3/min, Register 3/hour (slowapi)
- No-Enumeration: `/forgot-password` gibt keine Info über E-Mail-Existenz preis
### 5.3 Rollen (global)
| Rolle | Rechte |
|-------|--------|
| `trainer` | Standard-Nutzer; Upload, private Übungen, Planung |
| `admin` | Plattform-Admin; alle Vereine, alle Profile einsehbar |
| `superadmin` | Vollzugriff; Official-Promotion, physische Löschung, Admin-Konfiguration |
### 5.4 Vereinsrollen (pro Verein)
| Rolle | Rechte |
|-------|--------|
| `club_admin` | Vereinsstruktur, Mitglieder, Vereins-Medien/Übungen |
| `trainer` | Training planen, Übungen verwalten |
| `content_editor` | Inhalte bearbeiten |
| `division_lead` | Spartenleitung |
### 5.5 PWA / Service Worker
- **Kein Service Worker** im Repository vorhanden
- Keine Workbox- oder sw.js-Datei gefunden
- **Bedeutung:** Das Hauptrisiko (private Medien im PWA-Cache) entfällt mangels Service Worker
### 5.6 Browser-Storage-Nutzung
| Speicherart | Inhalt | TDDDG-Klassifikation |
|-------------|--------|----------------------|
| `localStorage['authToken']` | Auth-Session-Token | Technisch notwendig |
| `localStorage['shinkan_active_club']` | Aktiver Verein (ID) | Technisch notwendig |
| `localStorage['shinkan_active_profile']` | Profil-ID | Technisch notwendig |
| `sessionStorage[storageStepKey]` | Trainingsschritt (Coach-Page) | Session-temporär, nicht personenbezogen |
| `sessionStorage[storageDeltasKey]` | Trainingsdeltas JSON | Session-temporär |
| `sessionStorage[storageDebriefKey]` | Debrief-Status | Session-temporär |
| Cookies | **keine** | – |
| IndexedDB | **keine** | – |
---
## 6. Datenflussanalyse
### 6.1 Registrierung / Login
```
Nutzer → POST /api/auth/register → Profil (inaktiv) + Verifikations-E-Mail
Nutzer → E-Mail-Link → GET /api/auth/verify/{token}
→ Profil aktiv, Session-Token in Response
→ Frontend: localStorage.setItem('authToken', token)
Nutzer → POST /api/auth/login → Token in Response
→ Frontend: localStorage.setItem('authToken', token)
```
Gespeicherte Daten: Name, E-Mail, bcrypt-Hash, Rolle, Tier, trial_ends_at, email_verified, verification_token (temporär, wird nach Verifikation gelöscht)
### 6.2 Medienupload
```
Nutzer → POST /api/exercises/{id}/media (multipart) [50 MB Limit]
→ MIME-Type-Prüfung (magic bytes)
→ SHA256-Hash (Deduplizierung)
→ Dateispeicherung: library/{scope}/{kind}/{sha256}{ext}
→ DB-Eintrag: media_assets + exercise_media
Admin → POST /api/media-assets/bulk-upload [1 GB Limit]
→ gleicher Pfad; Sichtbarkeit + Verein als Formular-Parameter
```
### 6.3 Medienpromotion
```
Vereins-Admin → PATCH /api/media-assets/{id}
→ assert_valid_governance_visibility() → Mitgliedschaftsprüfung
→ Bei visibility=club: club_id Pflicht + Mitgliedschaft
→ Bei visibility=official: NUR Superadmin
→ copyright_notice: KEIN Pflichtfeld (nur im exercises-Router für official)
PROBLEM: Copyright-Pflicht ist NICHT im media_assets-Router für alle Promotions implementiert
```
### 6.4 Medienlöschung
```
Stufe 1 (Soft-Trash, lifecycle_state='trash_soft'):
→ Manuell durch Eigentümer / Vereins-Admin / Superadmin
→ Datei bleibt auf Disk; weiterhin sichtbar (je nach Exercise-Implementierung)
Stufe 2 (Hidden, lifecycle_state='trash_hidden'):
→ Nach 30 Tagen (Job) oder manuell
→ Nicht mehr in normalen Abfragen sichtbar
Stufe 3 (Purge):
→ Nach weiteren 30 Tagen (Job) oder Superadmin manuell
→ Datei physisch gelöscht
PROBLEM: media_retention_job.py ist NICHT automatisch geplant
```
### 6.5 Rechteprüfung
```
Jeder Request → require_auth() → Token aus X-Auth-Token-Header → Session aus DB
Vereinsdaten → get_tenant_context() → TenantContext (profile_id, role, effective_club_id)
Listenabfragen → library_content_visibility_sql() → SQL WHERE-Baustein
Schreibzugriffe → assert_valid_governance_visibility() → 403 bei Verstoß
```
---
## 7. Rollen- und Rechteanalyse
### 7.1 Mandantentrennung – Stärken
- `TenantContext` konsequent in allen vereinsrelevanten Routern via `Depends(get_tenant_context)`
- `library_content_visibility_sql()` als zentraler Sichtbarkeits-Filter (SQL-Ebene)
- `effective_club_id` aus Header nur für Mitglieder, beliebig nur für Plattform-Admins
- Integrationstests vorhanden: `test_access_layer_integration.py`
### 7.2 Klarstellung: Wer kann Vereinsmedien bearbeiten?
Die Audit-Anforderung „alle Vereinsnutzer können bearbeiten" trifft auf die tatsächliche Implementierung **nicht** zu. In `_item_permissions()` (media_assets.py) ist `edit_metadata` nur für `club_admin`-Rolle oder Plattform-Admin True – normale Mitglieder können Vereinsmedien nicht bearbeiten. **Dies ist ein positiver Befund.**
### 7.3 Profil-Löschung (DSGVO-Lücke)
`DELETE /api/profiles/{pid}` – nur Plattform-Admin. Nutzer können ihr eigenes Konto **nicht** selbst löschen. Potenzielle DSGVO-Verletzung (Art. 17).
---
## 8. Medienrechteanalyse
### 8.1 Copyright-Feld
- Vorhanden: `copyright_notice` (max. 8000 Zeichen) in `media_assets`
- Pflichtfeld bei `exercise_media` mit `visibility='official'` (exercises-Router)
- **NICHT** Pflichtfeld beim direkten Upload in das Medienarchiv
- **NICHT** Pflichtfeld bei Promotion von `private` zu `club`
- **NICHT** dokumentiert: Wer hat erklärt? Wann? Welche Lizenzversion?
### 8.2 Rechteerklärung beim Upload
- Keine Einwilligungserklärung beim Upload: „Ich bestätige, alle Rechte an dieser Datei zu besitzen"
- Kein Upload-Dialog mit Pflicht-Checkbox
- Kein Hinweis auf verbotene Inhalte (Rechte Dritter, Persönlichkeitsrechte)
### 8.3 Recht am eigenen Bild
- Keine Abfrage, ob erkennbare Personen abgebildet sind
- Keine Abfrage, ob Minderjährige enthalten sind
- Keine Abfrage nach Einwilligung der abgebildeten Personen
- Juristisch zu prüfen: Anforderungen nach §22 KUG
---
## 9. Löschkonzeptanalyse
### 9.1 Stärken
- Klares 3-Stufen-Lifecycle-Modell (active → trash_soft → trash_hidden → purged)
- Superadmin-Direktlöschung als Sofortmaßnahme
- SHA256-Deduplizierung verhindert doppelte physische Dateien
- Datei-Relokation bei Sichtbarkeitsänderung implementiert
### 9.2 Lücken
| Problem | Risiko |
|---------|--------|
| Papierkorb-Job nicht automatisch geplant | Dateien bleiben physisch nach Ablauf der Fristen |
| Keine Löschung aus Backups dokumentiert | DSGVO Art. 17: Backup-Retention oder Löschprozess nötig |
| Kein Legal-Hold-Status | Bei Rechtsverletzung dauert es 30 Tage bis zur vollständigen Unsichtbarkeit |
| Kein Audit-Log für Löschgründe | Keine Nachvollziehbarkeit für DSA/DSGVO |
| Kein Uploader-Benachrichtigungssystem | Bei Sperrung / Löschung kein Feedback an Uploader |
---
## 10. PWA- / Storage-Analyse
### 10.1 Positiv
- Kein Service Worker → kein PWA-Cache-Risiko für Medien
- Keine Cookies → kein Cookie-Banner nötig (für Cookies)
- CSP-Header gesetzt: `script-src 'self'` (XSS-Mitigation)
### 10.2 LocalStorage-Bewertung
Die localStorage-Nutzung ist technisch notwendig (Auth, Mandantenkontext). Nach TDDDG §25 ist technisch notwendige Speicherung ohne Einwilligung zulässig. Dokumentation in der Datenschutzerklärung ist Pflicht.
### 10.3 Token-Sicherheit
- Auth-Token in `localStorage`: vulnerabel bei XSS
- CSP `script-src 'self'` reduziert XSS-Risiko erheblich
- Kein CSRF-Problem (Token im Header, nicht in Cookie)
- `HttpOnly`-Cookie wäre sicherer, erfordert Architekturanpassung
---
## 11. Datenschutzanalyse (DSGVO)
### 11.1 Identifizierte Verarbeitungsvorgänge
| Vorgang | Rechtsgrundlage (technisch) | VVT-Status |
|---------|----------------------------|-----------|
| Registrierung (Name, E-Mail, Passwort-Hash) | Vertrag (Art. 6 Abs. 1 lit. b) | ❌ Kein VVT |
| Login / Session-Management | Berechtigtes Interesse | ❌ Kein VVT |
| E-Mail-Versand | Vertragserfüllung | ❌ Kein VVT, SMTP-Anbieter unbekannt |
| Medienupload (Bilder/Videos) | Einwilligung oder Vertragserfüllung | ❌ Keine Einwilligung abgeholt |
| Vereinszugehörigkeit | Vertragserfüllung | ❌ Kein VVT |
| Training-Logging | Berechtigtes Interesse | ❌ Kein VVT |
| Backup (implizit) | Berechtigtes Interesse | ❌ Keine Retention dokumentiert |
### 11.2 Betroffenenrechte
| Recht | Status |
|-------|--------|
| Auskunft (Art. 15) | ❌ Kein Self-Service-Export |
| Berichtigung (Art. 16) | ⚠ Nur eigener Name/E-Mail über Einstellungen |
| Löschung (Art. 17) | ❌ Kein Self-Service-Löschung |
| Einschränkung (Art. 18) | ❌ Nicht implementiert |
| Datenübertragbarkeit (Art. 20) | ❌ Kein Export-Endpoint |
| Widerspruch (Art. 21) | ❌ Kein Mechanismus |
### 11.3 Auftragsverarbeiter (identifiziert)
| Dienst | Anbieter | AV-Vertrag |
|--------|----------|-----------|
| Hosting | Selbstbetrieb (Raspberry Pi) | Entfällt |
| SMTP / E-Mail | Unbekannt (Env-Variable) | ❌ Nicht dokumentiert |
| MediaWiki-Import | karatetrainer.net | ❌ Nicht dokumentiert |
| OpenRouter (KI) | OpenRouter.ai | ❌ Nicht dokumentiert |
### 11.4 Minderjährige
- Keine Altersverifikation bei Registrierung
- Keine besondere Schutzmaßnahme
- Juristisch zu prüfen: §8 DSGVO
---
## 12. DSA-/UGC-Analyse
### 12.1 Einordnung
Die App erlaubt Upload von User Generated Content (Bilder, Videos). Inhalte können öffentlich sichtbar sein (`official`-Stufe: plattformweit). Dies ist UGC im Sinne des DSA.
**Juristisch zu prüfen:** Ab welcher Nutzerzahl und unter welchen Voraussetzungen der DSA für diese Plattform gilt.
### 12.2 Fehlende Mechanismen
| DSA-Anforderung | Status |
|-----------------|--------|
| Meldeverfahren für rechtswidrige Inhalte | ❌ |
| „Inhalt melden"-Funktion | ❌ |
| Moderations-Backend mit Statuswerten | ❌ |
| Benachrichtigung des Uploaders bei Sperrung | ❌ |
| Begründung für Moderationsentscheidungen | ❌ |
| Beschwerdemechanismus | ❌ |
| Eskalation für schwere Inhalte (CSAM, Straftaten) | ❌ |
| Audit-Log für Meldungen und Entscheidungen | ❌ |
### 12.3 Was vorhanden ist (Notfall-Maßnahmen)
- Superadmin kann Inhalte sofort physisch löschen (`superadmin_hard_delete`)
- Lifecycle-System ermöglicht schrittweise Deaktivierung
- `official`-Promotion nur durch Superadmin (redaktioneller Prozess)
---
## 13. Sicherheitsanalyse
### 13.1 Positiv bewertete Maßnahmen
| Maßnahme | Status |
|----------|--------|
| HTTPS (Produktion via Reverse-Proxy) | ✓ |
| bcrypt Passwort-Hashing mit Legacy-SHA256-Upgrade | ✓ |
| Rate-Limiting (slowapi) | ✓ |
| CSRF-Schutz (Token im Header, nicht Cookie) | ✓ |
| SQL-Injection-Schutz (parameterisierte Queries) | ✓ |
| CSP-Header (nginx) | ✓ |
| X-Content-Type-Options: nosniff (nginx + FastAPI-Middleware) | ✓ |
| X-Frame-Options: SAMEORIGIN | ✓ |
| Referrer-Policy: strict-origin-when-cross-origin | ✓ |
| Permissions-Policy (camera/mic/geo) | ✓ |
| OpenAPI in Produktion deaktiviert | ✓ |
| DB-Port nur localhost exponiert | ✓ |
| MIME-Type-Validierung beim Upload | ✓ |
| SHA256-Integritätsprüfung + Deduplizierung | ✓ |
| Secrets in .env (nicht im Code) | ✓ |
| User-Enumeration verhindert (forgot-password, resend-verification) | ✓ |
| Path-Traversal-Schutz in media_storage.py (`path_under_media_root` + `.relative_to()`) | ✓ |
| Club-Name-Slugify: nur `[a-z0-9-]` im Dateipfad | ✓ |
| CORS: Origins eingeschränkt (ALLOWED_ORIGINS aus Env) | ✓ |
### 13.2 Sicherheitslücken
| ID | Titel | Schwere | Datei/Nachweis |
|----|-------|---------|----------------|
| SEC-01 | Kein HSTS-Header | Hoch | `frontend/nginx.conf` – kein `Strict-Transport-Security` |
| SEC-02 | Auth-Token in localStorage | Mittel | `frontend/src/context/AuthContext.jsx:47` |
| SEC-03 | `style-src 'unsafe-inline'` in CSP | Niedrig | `frontend/nginx.conf:23` |
| SEC-04 | Passwort-Mindestlänge inkonsistent: Backend 3 Stellen, Frontend-Feld minLength=6, Backend-Register-Minimum=8 | Mittel | `backend/routers/auth.py:104` (`< 4`), `frontend/src/pages/LoginPage.jsx:175` (`minLength="6"`) |
| SEC-05 | ALLOW_PUBLIC_MEDIA_STATIC umgeht Auth für alle Medien | Hoch | `backend/main.py:222-223` |
| SEC-06 | Kein MFA für Superadmins | Mittel | Kein TOTP/OTP implementiert |
| SEC-07 | Kein Audit-Log für Admin-Aktionen | Mittel | Keine `admin_audit_log`-Tabelle |
| SEC-08 | Password-Reset-Token in sessions-Tabelle (Präfix `reset_`) | Niedrig | `backend/routers/auth.py:143` |
| SEC-09 | Kein Backup-Konzept dokumentiert | Mittel | Kein Backup-Skript im Repo |
| SEC-10 | Kein Anti-Virus-Scan für Uploads | Niedrig | Kein ClamAV o.ä. |
| SEC-11 | Kein genereller HTML-Sanitizer für Rich-Text-Felder | Mittel | `backend/exercise_rich_text.py` – nur Inline-Media-Normalisierung, kein bleach/nh3 |
| SEC-12 | `minLength="6"` im Login-Formular, Backend fordert 8 Zeichen | Niedrig | `frontend/src/pages/LoginPage.jsx:175` |
| SEC-13 | Hartcodierte Versionsangabe `v0.1.0 • Development` auf Login-Seite (falsch + Info-Leak) | Niedrig | `frontend/src/pages/LoginPage.jsx:242` |
| SEC-14 | CORS: `allow_methods=["*"]` und `allow_headers=["*"]` breiter als nötig | Niedrig | `backend/main.py:84-87` |
### 13.3 Ergänzende Befunde aus Restprüfung
#### main.py — CORS-Konfiguration
```python
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS, # ✓ aus Env, keine Wildcard-Origins
allow_credentials=True, # ✓ korrekt (kein * + credentials)
allow_methods=["*"], # ⚠ breiter als nötig
allow_headers=["*"], # ⚠ breiter als nötig
)
```
`allow_credentials=True` in Kombination mit `allow_origins=["*"]` wäre ein kritischer Fehler (FastAPI würde ihn aber abweisen). Durch die explizite Origin-Liste ist das Risiko gering. `allow_methods=["*"]` und `allow_headers=["*"]` könnten auf die tatsächlich benötigten Methoden (GET, POST, PUT, PATCH, DELETE) und Header (X-Auth-Token, X-Active-Club-Id, Content-Type) eingeschränkt werden.
#### media_storage.py — Path-Traversal-Schutz (positiv)
`path_under_media_root()` kombiniert zwei unabhängige Prüfungen:
1. String-Prüfung: `".." in key.split("/")`
2. Filesystem-Prüfung: `p.relative_to(media_root.resolve())`
Die Dateiendung wird auf 16 Zeichen begrenzt. Club-Namen werden auf `[a-z0-9-]` normalisiert. SHA256 als Dateiname ist manipulationssicher. **Bewertung: Gut implementiert, kein Path-Traversal-Risiko erkennbar.**
#### exercise_rich_text.py — Fehlender genereller HTML-Sanitizer
Das Modul normalisiert ausschließlich das Inline-Media-Markup (`{{exerciseMedia:id}}` → `<span>`). Es enthält **keinen** generellen HTML-Sanitizer (kein bleach, lxml-cleaner, nh3 o.ä.).
Felder in `RICH_HTML_EXERCISE_FIELDS` (`summary`, `goal`, `execution`, `preparation`, `trainer_notes`) können beliebiges HTML enthalten. Risikominderung:
- CSP `script-src 'self'` verhindert `<script>`-Ausführung
- React's `dangerouslySetInnerHTML` muss im Frontend für XSS genutzt werden — zu prüfen
- Betroffene Felder sind nur für eingeloggte Nutzer sichtbar (kein öffentlicher Angriffspfad)
**Empfehlung:** bleach oder nh3 für Allowlist-basierte HTML-Sanitierung einsetzen.
#### LoginPage.jsx — Weitere Befunde
1. **Keine Rechtstexte-Links:** Kein Link auf Impressum oder Datenschutzerklärung (bestätigt KRIT-01)
2. **`minLength="6"`:** Browser-seitig 6 Zeichen, Backend erzwingt 8 → UX-Bruch, Nutzer sieht kein Frontend-Feedback
3. **Hartcodierter Versionsstring:** `v0.1.0 • Development` ist öffentlich sichtbar, falsch (App ist 0.8.65) und leakt Umgebungsinfo
### 13.5 Warnung: ALLOW_PUBLIC_MEDIA_STATIC (SEC-05)
Das Flag `ALLOW_PUBLIC_MEDIA_STATIC=1` würde bei Aktivierung alle Mediendateien ohne Auth unter `/media/` ausliefern und das gesamte Sichtbarkeitskonzept (privat, Verein, offiziell) für alle gespeicherten Mediendateien unterlaufen. Bestätigt in `backend/main.py:222-223`:
```python
if os.getenv("ALLOW_PUBLIC_MEDIA_STATIC", "").strip().lower() in ("1", "true", "yes"):
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
```
**Dieses Flag darf in Produktionsumgebungen niemals gesetzt sein.** Muss in der Betriebsdokumentation explizit verboten und per Release-Checkliste überprüft werden.
---
## 14. Dokumentationsanalyse
### 14.1 Vorhandene technische Dokumentation
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` ✓
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` ✓
- `backend/version.py` mit CHANGELOG ✓
- `backend/scripts/check_access_layer_hints.py` ✓
### 14.2 Fehlende rechtliche Dokumentation
| Dokument | Status (Audit 2026-05-09) | Stand 2026-05-10 |
|----------|--------------------------|------------------|
| Impressum | ❌ Keine Seite, kein Inhalt, keine Route | ⚠️ Route + Platzhalter vorhanden; Inhalt durch Betreiber/Rechtsanwalt ausstehend |
| Datenschutzerklärung | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
| Nutzungsbedingungen / AGB | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
| Medienrichtlinie / Community-Regeln | ❌ | ⚠️ Route + Platzhalter vorhanden; Inhalt ausstehend |
| Verzeichnis der Verarbeitungstätigkeiten (VVT) | ❌ | ❌ offen (Betreiber-Aufgabe) |
| AV-Verträge mit Auftragsverarbeitern | ❌ | ❌ offen (Betreiber-Aufgabe) |
| Backup-Konzept schriftlich | ❌ | ❌ offen (Betreiber-Aufgabe) |
> **Amendment 2026-05-10:** Routen und Platzhalterseiten implementiert (P-01, 0.8.69); Mobile/PWA via `/settings/legal` (P-01b, 0.8.70); Admin-konfigurierbare Rechtstexte mit DB-Versionierung, Superadmin-UI, PDF-Download, Abschnitts-Editor (P-01c, 0.8.71–0.8.74). KRIT-01 bleibt offen bis zur Veröffentlichung juristisch geprüfter Inhalte.
### 14.3 Fehlende Frontend-Routen
In `frontend/src/App.jsx` fehlen (Stand Audit 2026-05-09):
- `/impressum`
- `/datenschutz`
- `/nutzungsbedingungen`
- `/medienrichtlinie`
Alle müssen **vor der Authentifizierung** erreichbar und in der PWA verfügbar sein.
> **Amendment 2026-05-10 (P-01, Version 0.8.69):** Alle vier Routen sind implementiert und ohne Auth erreichbar. Links in LoginPage-Footer, DesktopSidebar-Footer und `/settings/legal` (P-01b). Migrationsnummer der Datenbank: bis 046 geprüft (Audit-Scope). Migration 047 (legal_documents) wurde außerhalb des Audit-Zeitfensters angelegt — siehe `docs/compliance-implementation.md` §P-01c.
---
## 15. Testanalyse
### 15.1 Vorhandene Tests
| Test-Datei | Inhalt |
|-----------|--------|
| `test_access_layer.py` | Sichtbarkeits-SQL-Logik |
| `test_access_layer_integration.py` | Cross-Tenant-Isolation mit echter DB |
| `test_exercises_delete_policy.py` | DELETE-Logik |
| `test_exercise_media_download.py` | Download-Zugriffsschutz |
| `test_official_exercise_media_rules.py` | Official-Promotion + Copyright |
| `test_media_assets_archive.py` | Deduplizierung, Lifecycle |
| `test_club_exercise_media_copyright.py` | Copyright bei Vereinsübungen |
| `test_exercise_inline_post.py` | Inline-Medien-Validierung |
| `test_exercise_rich_text.py` | HTML-Sanitizer |
| `test_security_release.py` | OpenAPI/Health in Produktion |
| `test_profiles_read_access.py` | Profil-Zugriffsrechte |
### 15.2 Testlücken
| Bereich | Status |
|---------|--------|
| DSA-Meldeverfahren | ❌ Funktion fehlt |
| DSGVO-Betroffenenrechte (Löschung, Export) | ❌ Funktion fehlt |
| Minderjährigen-Check beim Upload | ❌ Funktion fehlt |
| Einwilligungs-Check beim Upload | ❌ Funktion fehlt |
| ALLOW_PUBLIC_MEDIA_STATIC=1 aktiviert | ❌ Nicht getestet |
| Admin-Audit-Log | ❌ Funktion fehlt |
| Passwort-Mindestlänge bei PIN-Änderung | ❌ Nicht getestet |
| Copyright-Pflicht bei Archiv-Promotion | ❌ Nicht getestet |
---
## 16. Risiko-Matrix
### KRITISCH
| ID | Titel | Beschreibung | Betroffene Dateien | Juristisch prüfen | Aufwand |
|----|-------|-------------|-------------------|-------------------|---------|
| KRIT-01 | Keine Rechtstexte | Keine Impressum-, Datenschutz-, AGB- oder Medienrichtlinien-Seite. Öffentlich erreichbare App ohne Impressum ist Ordnungswidrigkeit (TMG §5, TDDDG). | `frontend/src/App.jsx` – keine Routen | Ja | 2–5 Tage (Technik) + Rechtsanwalt |
| KRIT-02 | Kein Self-Service-Löschrecht | Nutzer können ihr Konto nicht selbst löschen (DSGVO Art. 17). Nur Plattform-Admin kann Konten löschen. | `backend/routers/profiles.py:414` | Ja | 5–8 Tage |
| KRIT-03 | Kein DSA-Meldeverfahren | Keine Möglichkeit, rechtswidrige Inhalte zu melden. Kein Moderationssystem für UGC-Plattform. | Kein Router vorhanden | Ja | 10–20 Tage |
| KRIT-04 | Kein Recht-am-eigenen-Bild-Check | Keine Abfrage bei Medienupload, ob Personen oder Minderjährige abgebildet sind. | `backend/routers/exercises.py`, `backend/routers/media_assets.py` | Ja | 3–7 Tage |
| KRIT-05 | Kein DSGVO-Self-Service (Auskunft, Export) | Keine Datenauskunft, kein Datenexport, keine Berichtigungsmöglichkeit (DSGVO Art. 15, 16, 20). | Kein Endpoint | Ja | 5–10 Tage |
| KRIT-06 | Copyright-Pflicht inkonsistent | Copyright ist Pflichtfeld nur im exercises-Router für `official`. Im media_assets-Router (Archiv) kann ohne Copyright zu `club`/`official` promoted werden. | `backend/routers/media_assets.py:766–784` | Ja | 1–2 Tage |
| KRIT-07 | Papierkorb-Job nicht geplant | `media_retention_job.py` existiert, aber kein Cron-Job konfiguriert. Medien bleiben physisch nach Ablauf der DSGVO-Fristen auf dem Server. | `backend/media_retention_job.py` | Nein | 1 Tag |
### HOCH
| ID | Titel | Beschreibung | Aufwand |
|----|-------|-------------|---------|
| HOCH-01 | ALLOW_PUBLIC_MEDIA_STATIC | Wenn gesetzt, sind alle Mediendateien ohne Auth abrufbar – untergräbt gesamtes Sichtbarkeitskonzept | Dokumentation + Test |
| HOCH-02 | Kein HSTS | Kein `Strict-Transport-Security`-Header in nginx.conf | Dokumentation (Reverse-Proxy) |
| HOCH-03 | Auth-Token in localStorage | XSS könnte Token extrahieren; CSP reduziert, eliminiert nicht | Dokumentation (HttpOnly als Langfrist-Plan) |
| HOCH-04 | Kein MFA für Superadmins | Superadmin hat unbegrenzten Systemzugriff ohne zweiten Faktor | 5–8 Tage |
| HOCH-05 | Kein Admin-Audit-Log | Profil-Löschungen, Lifecycle-Aktionen nicht geloggt | 3–5 Tage |
| HOCH-06 | Keine Mindestalter-Abfrage | Keine Schranke gegen Registrierung Minderjähriger | 1–2 Tage |
### MITTEL
| ID | Titel | Beschreibung | Aufwand |
|----|-------|-------------|---------|
| MITT-01 | Passwort-Mindestlänge inkonsistent | Register: 8 Zeichen, `PUT /api/auth/pin`: 4 Zeichen | 30 Min |
| MITT-02 | Keine Sofortsperrung bei Rechtsverletzung | Stufe-1-Papierkorb dauert 30 Tage bis zur vollständigen Unsichtbarkeit | 2–3 Tage |
| MITT-03 | Kein VVT | Kein Verzeichnis der Verarbeitungstätigkeiten (DSGVO Art. 30) | Betreiber |
| MITT-04 | SMTP-Anbieter unbekannt | Kein AV-Vertrag; E-Mail-Dienstleister nicht dokumentiert | Betreiber |
| MITT-05 | sessionStorage nicht bei Logout bereinigt | TrainingCoachPage-Fortschritt bleibt nach Logout im sessionStorage | 0,5 Tage |
| MITT-06 | Keine Löschung aus Backups | DSGVO-Löschungsanfragen greifen nicht auf Backups | Betreiber (Policy) |
| MITT-07 | MediaWiki-Integration ohne AV-Vertrag | Datentransfer zu karatetrainer.net nicht dokumentiert | Betreiber |
| MITT-08 | OpenRouter ohne AV-Vertrag | Erst aktivieren wenn AV-Vertrag vorhanden | Betreiber |
### NIEDRIG
| ID | Titel | Beschreibung | Aufwand |
|----|-------|-------------|---------|
| NIED-01 | `style-src 'unsafe-inline'` | Inline-Styles in CSP erlaubt | Nonce/Hash |
| NIED-02 | Kein Anti-Virus-Scan | Malware-Dateien hochladbar | ClamAV-Integration |
| NIED-03 | Reset-Token in sessions-Tabelle | Token mit `reset_`-Präfix in Auth-Tabelle | Separate Tabelle |
| NIED-04 | SHA256-Hash in API-Response | Datei-Fingerprinting möglich | Response-Filterung |
| NIED-05 | Kein Passwort-Complexity-Check | Nur Mindestlänge geprüft | zxcvbn o.ä. |
| NIED-06 | `minLength="6"` im Login-Formular | Inkonsistent mit Backend (8 Zeichen); Browser lässt 6-7-char-Passwörter zu, Backend lehnt sie dann ab | `frontend/src/pages/LoginPage.jsx:175` |
| NIED-07 | Hartcodierter Versionsstring auf Login-Seite | `v0.1.0 • Development` sichtbar ohne Auth; falsche Version (0.8.65) + Umgebungsinfo | `frontend/src/pages/LoginPage.jsx:242` |
| NIED-08 | CORS allow_methods/headers=`["*"]` | Breiter als nötig; Origins sind korrekt eingeschränkt, aber Methoden/Header nicht | `backend/main.py:84-87` |
| NIED-09 | Kein genereller HTML-Sanitizer für Rich-Text | `exercise_rich_text.py` bereinigt nur Inline-Media-Markup; beliebiges HTML in `summary`, `goal`, `execution` etc. möglich (CSP schützt gegen Script-Execution) | `backend/exercise_rich_text.py` |
---
## 17. Umsetzungsplan
### Empfohlene Reihenfolge
**Etappe 1 – Pflicht vor öffentlichem Betrieb (Kritische Blocker)**
| Paket-ID | Titel | Findings | Aufwand |
|----------|-------|---------|---------|
| P-01 | Rechtstexte (Seiten + Routen, Inhalte durch Rechtsanwalt) | KRIT-01 | 2–5 Tage Technik |
| P-02 | Self-Service-Kontolöschung + Datenexport | KRIT-02, KRIT-05 | 5–8 Tage |
| P-03 | Papierkorb-Retention-Job aktivieren | KRIT-07 | 1 Tag |
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | KRIT-06 | 1 Tag |
| P-05 | Passwort-Mindestlänge angleichen | MITT-01 | 30 Min |
| P-06 | Upload-Einwilligungsdialog (Personen, Minderjährige, Rechte) | KRIT-04 | 2–4 Tage |
**Etappe 2 – Sicherheit und Datenschutz (dringend empfohlen)**
| Paket-ID | Titel | Findings | Aufwand |
|----------|-------|---------|---------|
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test | HOCH-01, SEC-05 | 0,5 Tage |
| P-08 | HSTS und externe Proxy-Sicherheit dokumentieren | HOCH-02, SEC-01 | 0,5 Tage |
| P-09 | Admin-Audit-Log | HOCH-05, SEC-07 | 3–5 Tage |
| P-10 | Mindestalter-Abfrage | HOCH-06 | 1–2 Tage |
| P-11 | Legal-Hold Lifecycle-Status | MITT-02 | 2–3 Tage |
| P-12 | sessionStorage bei Logout bereinigen | MITT-05 | 0,5 Tage |
| P-22 | HTML-Sanitizer für Rich-Text-Felder (bleach/nh3) | NIED-09, SEC-11 | 1–2 Tage |
| P-23 | LoginPage: minLength angleichen + Version entfernen | NIED-06, NIED-07, SEC-12, SEC-13 | 1 Stunde |
| P-24 | CORS einschränken (Methoden + Header) | NIED-08, SEC-14 | 1 Stunde |
**Etappe 3 – DSA-Meldeverfahren (mittelfristig, nach juristischer Klärung)**
| Paket-ID | Titel | Findings | Aufwand |
|----------|-------|---------|---------|
| P-13 | Content-Melde-Backend (content_reports-Tabelle + Endpoints) | KRIT-03 | 5–8 Tage |
| P-14 | Moderations-UI (Frontend) | KRIT-03 | 3–5 Tage |
| P-15 | Uploader-Benachrichtigung bei Sperrung | KRIT-03 | 1–2 Tage |
| P-16 | Beschwerdeverfahren | KRIT-03 | 2–4 Tage |
**Etappe 4 – Langfristige Optimierungen**
| Paket-ID | Titel | Aufwand |
|----------|-------|---------|
| P-17 | MFA für Superadmins (TOTP) | 5–8 Tage |
| P-18 | HttpOnly-Cookie als Auth-Alternative | 3–5 Tage |
| P-19 | Anti-Virus-Scan (ClamAV) | 3–5 Tage |
| P-20 | VVT erstellen | Betreiber |
| P-21 | AV-Verträge abschließen | Betreiber |
---
### P-04 im Detail: Copyright-Pflicht vereinheitlichen
**Technische Änderung Backend:**
In `backend/routers/media_assets.py`, Funktionen `patch_media_asset()` und `bulk_media_patch()`:
- Bei Visibility-Wechsel zu `club` oder `official`: `copyright_notice` muss vorhanden und min. 3 Zeichen lang sein
- Fehler: HTTP 422 mit klarer Fehlermeldung
**Test:** Promotion ohne copyright_notice → HTTP 422; mit copyright_notice → OK
---
### P-05 im Detail: Passwort-Mindestlänge angleichen
**Technische Änderung:**
- `backend/routers/auth.py:104`: `if len(new_pin) < 8:` statt `< 4`
- Fehlermeldung: „Passwort muss mindestens 8 Zeichen lang haben"
---
### P-13 im Detail: Content-Melde-Backend
**Neue DB-Migration (`backend/migrations/047_content_reports.sql`):**
```sql
CREATE TABLE content_reports (
id SERIAL PRIMARY KEY,
reporter_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
target_type VARCHAR(20) NOT NULL CHECK (target_type IN ('exercise', 'media_asset')),
target_id INTEGER NOT NULL,
reason VARCHAR(50) NOT NULL
CHECK (reason IN ('illegal_content', 'copyright', 'personal_rights',
'minor_protection', 'hate_speech', 'spam', 'other')),
description TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'under_review', 'resolved_removed',
'resolved_kept', 'rejected')),
moderator_profile_id INTEGER REFERENCES profiles(id) ON DELETE SET NULL,
moderator_note TEXT,
resolved_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
**Neue Endpoints:**
- `POST /api/reports` – Meldung einreichen (require_auth)
- `GET /api/admin/reports` – Moderations-Queue (Admin/Superadmin)
- `PATCH /api/admin/reports/{id}` – Status setzen + Notiz
---
## 18. Dauerhafter Auditplan
### 18.1 Audit-Frequenzen
| Typ | Frequenz |
|-----|----------|
| Mini-Audit | Bei jedem PR mit Compliance-Relevanz |
| Release-Audit | Vor jedem Produktions-Deployment |
| Quartalsaudit | Alle 3 Monate |
| Jahresaudit | Einmal jährlich (mit Rechtsanwalt/Datenschutzbeauftragtem) |
### 18.2 Sonderaudit-Auslöser
- Neue öffentlich sichtbare Features
- Neue Upload-Funktionen (Medientypen, Quellen)
- Neue Rollen oder Rechteänderungen
- Neue externe Dienstleister
- Einführung von Analytics oder Tracking
- Änderungen am Minderjährigenschutz
- Sicherheitsvorfall oder Datenpanne
- Datenschutzanfrage eines Nutzers
- Meldung rechtswidriger Inhalte
- Größere Architekturänderungen
- Gesetzesänderungen (DSGVO, DSA, TDDDG)
### 18.3 Checkliste: Mini-Audit bei Feature-PR
```
[ ] Betrifft der PR personenbezogene Daten? → DSGVO-Check
[ ] Betrifft der PR Medienupload oder -anzeige? → Rechte-Check + DSA-Check
[ ] Betrifft der PR Rollen oder Sichtbarkeit? → Access-Layer-Check
[ ] Betrifft der PR Storage oder Caching? → TDDDG-Check
[ ] Betrifft der PR externe Dienste? → AV-Vertrag prüfen
[ ] Betrifft der PR Auth oder Session? → Sicherheits-Check
[ ] Neuer Endpoint → require_auth / get_tenant_context vorhanden?
[ ] Neue Datenspalte → Migration + Lösch-Cascade korrekt?
[ ] Neue Frontend-Speicherung → TDDDG-Klassifikation dokumentiert?
[ ] ACCESS_LAYER: python backend/scripts/check_access_layer_hints.py
```
### 18.4 Checkliste: Release-Audit
```
[ ] Versions-Bump (backend/version.py + frontend/src/version.js)
[ ] ALLOW_PUBLIC_MEDIA_STATIC nicht in Prod-Env gesetzt
[ ] OpenAPI/Swagger nicht öffentlich (ENVIRONMENT=production)
[ ] HSTS am externen Reverse-Proxy konfiguriert (manuell prüfen)
[ ] Papierkorb-Retention-Job läuft (Logs prüfen)
[ ] SSL-Zertifikat gültig
[ ] DB-Backup der letzten 24h vorhanden
[ ] Rechtstexte aktuell (kein Placeholder, kein veraltetes Datum)
[ ] pytest -m "not slow" grün
[ ] ACCESS_LAYER_INTEGRATION=1 pytest tests/test_access_layer_integration.py grün
[ ] test_security_release.py grün
[ ] pip-audit (keine kritischen CVEs)
[ ] npm audit --audit-level=high (keine kritischen CVEs)
```
### 18.5 Checkliste: Neues Feature
```
[ ] Verarbeitet das Feature personenbezogene Daten? → VVT aktualisieren
[ ] Neue DB-Tabellen → Lösch-Cascade und Retention definiert?
[ ] Neue API-Endpoints → Access Layer korrekt?
[ ] Feature mit UGC? → DSA-Meldeverfahren abgedeckt?
[ ] Feature mit Medien? → Lifecycle, Sichtbarkeit, Copyright?
[ ] Feature für Minderjährige relevant? → Schutzmaßnahmen?
[ ] Neue localStorage/sessionStorage-Nutzung → TDDDG + Datenschutzerklärung?
[ ] Neue externe Abhängigkeit → AV-Vertrag?
[ ] Keine sensitiven Daten in Fehlerausgaben?
[ ] api.js für alle Frontend API-Calls?
[ ] Tests geschrieben und grün?
```
### 18.6 Checkliste: Änderung am Medienmodell
```
[ ] Neue Medientypen → MIME-Type-Validierung aktualisiert?
[ ] Neue Sichtbarkeitsstufen → library_content_visibility_sql() aktualisiert?
[ ] Lifecycle-Änderungen → Papierkorb-Job angepasst?
[ ] Copyright-Anforderungen konsistent für alle Promotions-Wege?
[ ] ALLOW_PUBLIC_MEDIA_STATIC explizit: In Prod verboten (dokumentiert)?
[ ] Neue Download-Endpoints → require_auth_flexible implementiert?
[ ] Recht-am-eigenen-Bild-Abfragen aktualisiert?
```
### 18.7 Checkliste: Änderung am Rollenmodell
```
[ ] Neue Rollen → assert_valid_governance_visibility() berücksichtigt?
[ ] EXEMPT-Liste in check_access_layer_hints.py aktualisiert?
[ ] test_access_layer*.py angepasst?
[ ] MFA-Anforderung für neue Admin-Rollen geprüft?
[ ] Audit-Log für neue Aktionen?
```
### 18.8 Pflichttests vor Release
```bash
# Zugriffskontrolle
pytest backend/tests/test_access_layer.py -v
# Cross-Tenant-Integration (mit PostgreSQL)
ACCESS_LAYER_INTEGRATION=1 pytest backend/tests/test_access_layer_integration.py -v
# Mediensicherheit
pytest backend/tests/test_exercise_media_download.py -v
pytest backend/tests/test_official_exercise_media_rules.py -v
pytest backend/tests/test_media_assets_archive.py -v
pytest backend/tests/test_club_exercise_media_copyright.py -v
# Sicherheits-Release-Checks
pytest backend/tests/test_security_release.py -v
# Access Layer Script (Strict Mode)
ACCESS_LAYER_STRICT=1 python backend/scripts/check_access_layer_hints.py
# Abhängigkeits-Scan
cd backend && pip-audit
cd frontend && npm audit --audit-level=high
```
### 18.9 Vorlage: Quartalsaudit-Bericht
```markdown
# Compliance-Quartalsaudit Q[X]/[Jahr]
Datum: [DATUM] | Auditor: [NAME]
## 1. Status offener Findings
[Tabelle: ID – Titel – Status]
## 2. Neue Findings dieser Periode
[Tabelle: ID – Titel – Schwere – Aufwand]
## 3. Rechtstexte
[ ] Impressum geprüft: [DATUM]
[ ] Datenschutzerklärung geprüft: [DATUM]
[ ] AGB/Nutzungsbedingungen geprüft: [DATUM]
[ ] Medienrichtlinie geprüft: [DATUM]
## 4. DSGVO-Status
[ ] VVT aktuell
[ ] AV-Verträge vollständig
[ ] Backup-Retention-Policy dokumentiert
[ ] Betroffenenrechte-Mechanismen getestet
## 5. DSA-Status
[ ] Meldeverfahren Test-Meldung durchgeführt: [DATUM]
[ ] Offene Meldungen: [X] (alle bearbeitet: Ja/Nein)
[ ] Eskalationspfad dokumentiert: Ja/Nein
## 6. Technische Sicherheit
[ ] Abhängigkeits-Scan: [DATUM] – Kritische CVEs: [X]
[ ] SSL gültig bis: [DATUM]
[ ] HSTS konfiguriert: Ja/Nein
[ ] Alle Pflichttests grün: Ja/Nein
## 7. Empfehlungen
[Liste]
```
---
## 19. Entscheidungsvorlage
### 19.1 Was ist aktuell kritisch?
1. Keine Rechtstexte – App ist öffentlich ohne Impressum (Ordnungswidrigkeit)
2. Kein Löschrecht für Nutzer – DSGVO Art. 17 verletzt
3. Kein DSA-Meldeverfahren – bei UGC-Plattform möglicherweise Pflicht
4. Copyright-Lücke – Archiv-Upload ohne Copyright-Pflicht bei Promotion
5. Kein Recht-am-eigenen-Bild-Check bei Upload
### 19.2 Was blockiert sicheren öffentlichen Betrieb (technisch)?
1. KRIT-01: Rechtstexte fehlen vollständig
2. KRIT-02: Kein Self-Service-Löschrecht
3. KRIT-07: Papierkorb-Job läuft nicht automatisch
4. HOCH-01: ALLOW_PUBLIC_MEDIA_STATIC muss in Prod-Doku explizit verboten sein
5. HOCH-02: HSTS am externen Reverse-Proxy überprüfen
### 19.3 Mindest-Paket vor erstem öffentlichem Betrieb
- P-05 (30 Min): Passwort-Mindestlänge angleichen
- P-04 (1 Tag): Copyright-Pflicht vereinheitlichen
- P-03 (1 Tag): Papierkorb-Job aktivieren
- P-06 (2 Tage): Upload-Einwilligungsdialog
- P-01 (2 Tage Technik + Rechtsanwalt): Rechtstexte-Seiten
- P-02 (5 Tage): Self-Service-Kontolöschung
### 19.4 Was kann zurückgestellt werden?
- P-17 (HttpOnly-Cookie): Größere Architekturänderung, kein unmittelbarer Compliance-Bedarf
- P-19 (Anti-Virus-Scan): Hoher Aufwand, Risiko bei lokalem Storage gering
- P-13 bis P-16 (DSA-Meldeverfahren): Erst juristisch klären ob und in welchem Umfang erforderlich
### 19.5 Juristisch zu prüfende Fragen
| Thema | Frage |
|-------|-------|
| DSGVO Art. 17 | Wie muss Löschung aus Backups gehandhabt werden? |
| DSA | Ab welcher Nutzerzahl gilt der DSA? Welche Pflichten für Kleinplattformen? |
| §22 KUG | Welche Einwilligungen für Personenbilder im Vereinskontext? |
| §8 DSGVO | Mindestalter für die Registrierung? |
| TDDDG §25 | Muss für localStorage eine Einwilligung eingeholt werden? |
| Impressum-Pflicht | Vollständige Angaben des Verantwortlichen? |
| AV-Verträge | Welche Dienstleister benötigen einen AVV? |
| MediaWiki | Lizenzanforderungen für Übungsinhalte aus karatetrainer.net? |
### 19.6 Organisatorische Aufgaben für den Betreiber
1. Rechtsanwalt beauftragen (Rechtstexte)
2. VVT erstellen (DSGVO Art. 30)
3. AV-Verträge abschließen (SMTP-Anbieter, ggf. MediaWiki)
4. Backup-Prozess dokumentieren und Restore-Tests durchführen
5. Moderationsprozess definieren
6. Notfallkontakt für Datenpannen benennen
7. HSTS am externen Reverse-Proxy sicherstellen
8. Papierkorb-Job-Monitoring einrichten
### 19.7 Verbleibende Risiken nach technischer Umsetzung
- HSTS liegt außerhalb des Repos (Betreiber-Verantwortung)
- Backup-Löschung bei DSGVO-Anfragen erfordert manuelle Prozesse
- Minderjährige können Altersangabe fälschen (kein verlässlicher Online-Altersnachweis)
- Rechtswidrige Inhalte können zwischen Upload und Moderationsentscheidung sichtbar sein
- SMTP-Anbieter kann E-Mail-Inhalte verarbeiten
### 19.8 Freigabe-Formulierungen
Verwende diese exakten Formulierungen zur Freigabe einzelner Pakete:
| Paket | Freigabe-Formulierung |
|-------|----------------------|
| P-05 | „Freigabe zur Umsetzung P-05: Passwort-Mindestlänge angleichen" |
| P-04 | „Freigabe zur Umsetzung P-04: Copyright-Pflicht vereinheitlichen" |
| P-03 | „Freigabe zur Umsetzung P-03: Papierkorb-Retention-Job aktivieren" |
| P-06 | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
| P-01 | „Freigabe zur Umsetzung P-01: Rechtstexte-Seiten technisch anlegen" |
| P-02 | „Freigabe zur Umsetzung P-02: Self-Service-Kontolöschung und Datenexport" |
| P-09 | „Freigabe zur Umsetzung P-09: Admin-Audit-Log" |
| P-13 | „Freigabe zur Umsetzung P-13: Content-Melde-Backend" |
| Etappe 1 komplett | „Freigabe zur Umsetzung Etappe 1" |
| Etappe 1+2 | „Freigabe zur Umsetzung Etappen 1 und 2" |
---
**Audit abgeschlossen. Keine Codeänderungen vorgenommen. Umsetzung erst nach ausdrücklicher Freigabe.**
---
## 20. Regel zur Paket-ID-Stabilität
> Ergänzt: 2026-05-10 — Kanonisches Referenzdokument: `docs/compliance-package-register.md`
### 20.1 Grundsatz
Paket-IDs (P-01 bis P-24 und alle künftigen) werden nach ihrer ersten Vergabe in diesem Dokument **nie wieder umnummeriert, gelöscht oder wiederverwendet.** Die in §17 (Umsetzungsplan) vergebenen IDs sind dauerhaft stabil.
### 20.2 Regeln im Einzelnen
| Regel | Beschreibung |
|-------|-------------|
| **ID-Stabilität** | Eine einmal vergebene Paket-ID bleibt für immer mit dem ursprünglichen fachlichen Inhalt verknüpft. |
| **Titel-Präzisierung erlaubt** | Der Titel eines Pakets darf präzisiert werden, wenn die fachliche Substanz unverändert bleibt. Die ID ändert sich dabei nicht. |
| **Neue Pakete** | Künftige Arbeitspakete erhalten aufsteigende neue IDs (P-25, P-26 …). Keine Wiedervergabe von IDs abgeschlossener oder gelöschter Pakete. |
| **Nacharbeiten mit Suffix** | Nacharbeiten, Korrekturen oder Teilprobleme eines bestehenden Pakets werden mit alphabetischen Suffixen dokumentiert (P-03b, P-05b, …), nicht als eigenständige Hauptpakete. |
| **Freigabe-Formulierung** | Freigaben müssen immer die Paket-ID **und** den kanonischen Titel aus diesem Dokument oder aus `docs/compliance-package-register.md` nennen, um Verwechslungen auszuschließen. |
| **Kanonisches Register** | `docs/compliance-package-register.md` ist die verbindliche Quelle für alle Umsetzungsberichte, Re-Audit-Dokumente und Freigaben. Bei Widerspruch zwischen Dokumenten gilt dieses Audit als ursprüngliche Quelle; das Register als aktuell gepflegte Wahrheit. |
### 20.3 Umgang mit Drift in nachgelagerten Dokumenten
Falls ein nachgelagertes Dokument (Umsetzungsbericht, Re-Audit, Mini-Fix) eine abweichende Beschreibung für eine bekannte ID verwendet, gilt:
1. Die abweichende Beschreibung ist ein **Dokumentationsfehler**, kein neues Paket.
2. Das betroffene Dokument ist auf die kanonische ID und den kanonischen Titel zu korrigieren.
3. Der Drift und die Korrektur sind im Konsistenzbericht des Paketregisters zu vermerken.
4. Kein fachlicher Inhalt darf bei der Korrektur verloren gehen — er wird ggf. dem richtigen Paket-Eintrag zugeordnet.
### 20.4 Freigabe-Vorlagen (aktualisiert)
Verwende diese exakten Formulierungen zur Freigabe einzelner Pakete:
| Paket | Freigabe-Formulierung |
|-------|----------------------|
| P-01 | „Freigabe zur Umsetzung P-01: Rechtstexte" |
| P-02 | „Freigabe zur Umsetzung P-02: Self-Service-Kontolöschung und Datenexport" |
| P-03 | „Freigabe zur Umsetzung P-03: Papierkorb-Retention-Job aktivieren" |
| P-04 | „Freigabe zur Umsetzung P-04: Copyright-Pflicht für Archiv-Promotion vereinheitlichen" |
| P-05 | „Freigabe zur Umsetzung P-05: Passwort-Mindestlänge angleichen" |
| P-06 | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
| P-07 | „Freigabe zur Umsetzung P-07: ALLOW_PUBLIC_MEDIA_STATIC dokumentieren und testen" |
| P-08 | „Freigabe zur Umsetzung P-08: HSTS und externe Proxy-Sicherheit dokumentieren" |
| P-09 | „Freigabe zur Umsetzung P-09: Admin-Audit-Log" |
| P-10 | „Freigabe zur Umsetzung P-10: Mindestalter-Abfrage" |
| P-11 | „Freigabe zur Umsetzung P-11: Legal-Hold Lifecycle-Status" |
| P-12 | „Freigabe zur Umsetzung P-12: sessionStorage bei Logout bereinigen" |
| P-13 | „Freigabe zur Umsetzung P-13: Content-Melde-Backend" |
| P-17 | „Freigabe zur Umsetzung P-17: MFA für Superadmins" |
| P-18 | „Freigabe zur Umsetzung P-18: HttpOnly-Cookie als Auth-Alternative" |
| P-22 | „Freigabe zur Umsetzung P-22: HTML-Sanitizer für Rich-Text-Felder" |
| Etappe 1 komplett | „Freigabe zur Umsetzung Etappe 1" |
| Etappe 1+2 | „Freigabe zur Umsetzung Etappen 1 und 2" |
> Die ursprüngliche Freigabe-Tabelle in §19.8 bleibt erhalten und zeigt den Stand des Initial-Audits. §20.4 ist die aktuellere, vollständigere Version.
---
*Dokument erstellt: 2026-05-09 | Auditor: Claude Code | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
+662
View File
@@ -0,0 +1,662 @@
# Compliance-Implementierung – Umsetzungsbericht
**Erstellt:** 2026-05-09
**Zuletzt aktualisiert:** 2026-05-11
**Audit-Basis:** `docs/compliance-audit.md`
**App-Version nach Umsetzung:** 0.8.94
---
## Freigegebene Pakete und Umsetzungsstatus
### P-01 – Rechtstexte ⚠️ (technischer Teil umgesetzt; juristische Inhalte offen)
**Status:** Technisch teilweise umgesetzt (2026-05-10, Version 0.8.69)
**Betroffene Dateien:**
- `frontend/src/pages/LegalPage.jsx` (neu) — Platzhalter-Komponente für alle vier Seiten
- `frontend/src/App.jsx` — 4 neue öffentliche Routen
- `frontend/src/pages/LoginPage.jsx` — Rechtstext-Links im Card-Footer
- `frontend/src/components/DesktopSidebar.jsx` — Rechtstext-Links im Sidebar-Footer
**Technische Änderung:**
Vier öffentliche Routen angelegt, kein Auth erforderlich, kein Redirect für nicht eingeloggte Nutzer:
- `/impressum` → `<LegalPage type="impressum" />`
- `/datenschutz` → `<LegalPage type="datenschutz" />`
- `/nutzungsbedingungen` → `<LegalPage type="nutzungsbedingungen" />`
- `/medienrichtlinie` → `<LegalPage type="medienrichtlinie" />`
Jede Seite enthält:
- Deutlich sichtbaren Platzhalterhinweis: „MUSTER / PLATZHALTER – Inhalt wird vor Produktivbetrieb juristisch geprüft und durch den Betreiber ergänzt."
- Strukturierte Pflichtfelder je Rechtstext (Betreiber, Rechtsgrundlagen, Betroffenenrechte etc.)
- Querlinks zu den anderen drei Rechtstextseiten
Links zu allen vier Seiten sind in der Login-/Registrierungsseite (Card-Footer) und im Desktop-Sidebar-Footer sichtbar ohne Anmeldung erreichbar.
**Nicht umgesetzt (außerhalb Freigabe):**
Juristische Texte, inhaltliche Überprüfung, Admin-konfigurierbare Inhalte, Einwilligungs-Checkboxen.
**KRIT-01 Blocking-Status:**
Der Blocker KRIT-01 bleibt **offen** bis juristisch geprüfte Texte durch den Betreiber eingepflegt sind. Die technische Voraussetzung (Routen und Seitenstruktur) ist erfüllt.
**Tests:** 5 Playwright-Tests, alle grün:
- Impressum ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
- Datenschutz ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
- Nutzungsbedingungen ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
- Medienrichtlinie ohne Auth erreichbar + Platzhalterhinweis sichtbar + Reload OK
- Login-Seite enthält alle vier Rechtstext-Links
---
### P-01b – Mobile/PWA-Erreichbarkeit der Rechtstexte ✅
**Status:** Umgesetzt (2026-05-10, Version 0.8.70) — Nacharbeit zu P-01
**Betroffene Dateien:**
- `frontend/src/pages/SettingsLegalPage.jsx` (neu) — Hub-Seite `/settings/legal`
- `frontend/src/App.jsx` — Route `/settings/legal` im ProtectedLayout
- `frontend/src/pages/AccountSettingsPage.jsx` — Link zu `/settings/legal`
**Technische Änderung:**
Neue Seite `/settings/legal` im eingeloggten Einstellungsbereich: Hub-Seite mit Links zu allen vier Rechtstextseiten, erreichbar über Einstellungen → Rechtliches. Entspricht dem bestehenden Pattern von `/settings/system`. Auf der AccountSettingsPage ist ein Link „Rechtliches" unterhalb der System-Info-Verlinkung ergänzt.
**Tests:** 3 Playwright-Tests, alle grün (17/17 Gesamt):
- Einstellungen enthält Link zu `/settings/legal`
- `/settings/legal` enthält Überschrift + alle vier Rechtstext-Links
- Jeder Link aus `/settings/legal` führt zur korrekten öffentlichen Route
---
### P-01c – Admin-konfigurierbare Rechtstexte ✅
**Status:** Umgesetzt (2026-05-10, Version 0.8.71) — Nacharbeit zu P-01
**Betroffene Dateien:**
- `backend/migrations/047_legal_documents.sql` (neu) — Tabellen `legal_documents` + `legal_document_audit`
- `backend/routers/legal_documents.py` (neu) — Öffentliche + Superadmin-Endpoints
- `backend/main.py` — Router-Registrierung
- `frontend/src/pages/LegalPage.jsx` — API-Fetch mit Fallback auf statischen Platzhalter
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` (neu) — Superadmin-UI
- `frontend/src/App.jsx` — Route `/admin/legal-documents`
- `frontend/src/components/AdminPageNav.jsx` — Link „Rechtstexte" im Admin-Nav
- `frontend/src/utils/api.js` — 8 neue API-Funktionen
**Technische Änderung:**
**Datenbank (Migration 047):**
Tabelle `legal_documents`: versionierte Rechtstexte mit Workflow `draft → published → archived`. Felder: `document_type` (impressum | privacy_policy | terms_of_use | media_policy), `version` (INT, auto-inkrementiert), `title`, `content_sections` (JSONB: `[{heading, content}]`), `status`, `change_note`, Timestamps, FK auf Ersteller + Publisher. Partial-Unique-Index: nur ein `published`-Datensatz pro `document_type` gleichzeitig. Tabelle `legal_document_audit`: unveränderlicher Änderungslog je Dokument.
**Backend-Endpoints:**
| Endpoint | Auth | Beschreibung |
|----------|------|--------------|
| `GET /api/legal-documents/{type}/published` | Kein | Liefert veröffentlichtes Dokument oder `null` |
| `GET /api/admin/legal-documents` | Superadmin | Alle Versionen aller Typen |
| `POST /api/admin/legal-documents` | Superadmin | Neuen Entwurf anlegen |
| `GET /api/admin/legal-documents/{id}` | Superadmin | Einzeldokument mit `content_sections` |
| `PUT /api/admin/legal-documents/{id}` | Superadmin | Entwurf bearbeiten (nur `status=draft`) |
| `POST /api/admin/legal-documents/{id}/publish` | Superadmin | Veröffentlichen; bisherige Version → `archived` |
| `POST /api/admin/legal-documents/{id}/archive` | Superadmin | Archivieren |
| `GET /api/admin/legal-documents/{id}/audit` | Superadmin | Änderungslog |
**Frontend:**
`LegalPage.jsx` ruft beim Laden `GET /api/legal-documents/{type}/published` ab. Gibt die API `null` zurück (kein veröffentlichtes Dokument vorhanden), zeigt die Seite weiterhin den bisherigen Platzhalter mit MUSTER-Banner. Ist ein Dokument veröffentlicht, wird dessen Inhalt ohne Platzhalter-Banner angezeigt. `AdminLegalDocumentsPage.jsx` unter `/admin/legal-documents` (nur Superadmin) ermöglicht Erstellen, Bearbeiten, Veröffentlichen und Archivieren von Entwürfen mit Tabs pro Dokumententyp und Änderungslog.
**Kein neues npm-Paket notwendig** — JSONB-Struktur mit `{heading, content}` statt Markdown; keine XSS-Gefahr.
**Tests:** 3 Playwright-Tests:
- Rechtstextseiten laden ohne Fehler (API-fetch mit Fallback)
- `/admin/legal-documents` erreichbar für Superadmin mit korrekter Überschrift
- Admin-Nav enthält Link zu Rechtstexten
---
### P-01c Erweiterung — Als-Entwurf-kopieren ✅
**Status:** Umgesetzt (2026-05-10, Version 0.8.72) — Ergänzung zu P-01c
**Betroffene Dateien:**
- `backend/routers/legal_documents.py` — Neuer Endpoint `POST /api/admin/legal-documents/{id}/copy-as-draft`
- `frontend/src/utils/api.js` — `copyLegalDocumentAsDraft(id)`
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` — „Als Entwurf kopieren"-Button in der Dokumentliste
**Technische Änderung:**
Neuer Superadmin-Endpoint kopiert `title` und `content_sections` eines bestehenden Dokuments in einen neuen Entwurf. Die Versionsnummer wird dabei automatisch inkrementiert (letztes Dokument dieses Typs + 1). Status ist immer `draft`. Ermöglicht inkrementelle Überarbeitung ohne vollständige Neueingabe.
**Motivation:** Bei jeder fälligen Textanpassung mussten alle Abschnitte neu erfasst werden. Die Kopierfunktion ermöglicht, den letzten Stand zu übernehmen und nur die geänderten Abschnitte zu bearbeiten.
---
### P-01c Erweiterung — Echter PDF-Download + Abschnitts-Sortierung ✅
**Status:** Umgesetzt (2026-05-10, Version 0.8.74) — Ergänzung zu P-01c
**Betroffene Dateien:**
- `frontend/src/pages/AdminLegalDocumentsPage.jsx` — `generateLegalPdf()` via jsPDF, `SectionEditor` mit Sortierung
- `frontend/src/pages/LegalPage.jsx` — `generateLegalPdf()` via jsPDF, Button „PDF herunterladen"
- `frontend/package.json` — neues npm-Paket `jspdf`
**Technische Änderung — PDF:**
Ersetzt die bisherige `window.open()` + `window.print()`-Lösung (Browser-Druckdialog) durch `jsPDF`. Die Funktion `generateLegalPdf(doc)` erzeugt ein A4-PDF client-seitig mit:
- Titel (bold, 20 pt), Metazeile (Version + Gültigkeitsdatum), Trennlinie
- Abschnitte mit Heading (bold, 11 pt) und Fließtext (10 pt, `splitTextToSize` für automatischen Zeilenumbruch)
- Automatischer Seitenumbruch bei `y > 277 mm`
- Footer auf jeder Seite: „Shinkan Jinkendo | Exportiert am DD.MM.YYYY Seite X von Y"
- Direkter Dateidownload via `pdf.save('{document_type}_v{version}.pdf')`
Gilt sowohl für die Admin-Seite (Download aus der Dokumentliste, ruft `getLegalDocument(id)` für Volldokument ab) als auch für `LegalPage.jsx` (öffentlich, nur bei veröffentlichten Dokumenten).
**Technische Änderung — Abschnitts-Sortierung und Einfügen:**
`SectionEditor` in `AdminLegalDocumentsPage.jsx` erhält:
- ▲/▼-Buttons pro Abschnitt (deaktiviert an den Rändern) — Reihenfolge per Array-Swap
- `InsertButton` zwischen jedem Abschnitt (inkl. vor dem ersten) — fügt leeren Abschnitt an beliebiger Stelle per `splice` ein
- Kein Drag-and-Drop-Framework — reine React-State-Manipulation
---
### P-03 – Papierkorb-Retention-Job aktivieren ✅
**Status:** Umgesetzt
**Betroffene Dateien:**
- `docker-compose.yml` – neuer Service `retention-cron`
**Technische Änderung:**
Neuer Docker-Service `retention-cron` nutzt dasselbe Backend-Image und führt `scripts/media_retention_job.py` täglich um 03:00 Uhr aus. Der Service startet beim ersten Hochfahren sofort und schläft bis zum nächsten 3 AM (Python-basierter Loop ohne externe Cron-Abhängigkeit). Zugriff auf DB und Media-Volume identisch zur Backend-Konfiguration.
**Tests:** Keine automatisierten Tests möglich (Runtime-Verhalten); operativ über Container-Logs (`docker logs shinkan-retention-cron`) überprüfbar.
---
### P-03b – Retention-Zeiten mit Löschkonzept abgleichen ✅
**Status:** Umgesetzt (2026-05-10)
**Betroffene Dateien:**
- `backend/media_lifecycle.py:24` – Default `HIDDEN_TO_PURGE_DAYS`
- `docker-compose.yml` – explizite Env-Variable im `retention-cron`-Service
**Befund des Re-Audits:**
Das fachliche Löschkonzept (Audit §6.4) sieht 30 + 30 Tage vor:
- Stufe 1 → Stufe 2 (Soft → Hidden): 30 Tage ✓ (war bereits korrekt)
- Stufe 2 → Purge (Hidden → gelöscht): **weitere 30 Tage** → Code-Default war 90 Tage ❌
**Technische Änderung:**
```python
# media_lifecycle.py Zeile 24 (vorher "90", jetzt "30"):
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "30")))
```
`docker-compose.yml` enthält jetzt explizit `MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS: "${...:-30}"` mit Kommentar, der das 30+30-Konzept dokumentiert. Der Wert kann per Env-Variable in einzelnen Deployments überschrieben werden.
---
### P-04 – Copyright-Pflicht bei Archiv-Promotion vereinheitlichen ✅
**Status:** Umgesetzt; Tests nachgehärtet (2026-05-10)
**Betroffene Dateien:**
- `backend/routers/media_assets.py` – `patch_media_asset()` und `bulk_media_patch()`
- `backend/tests/test_media_assets_copyright_promotion.py`
**Technische Änderung:**
Beide Endpoints prüfen, ob `copyright_notice` vorhanden ist, wenn `visibility` auf `club` oder `official` gewechselt wird. Priorität: Wert aus dem Request-Body > bestehender Wert in der DB. Ist beides leer, wird HTTP 400 zurückgegeben.
Fehlermeldung: `"Für Vereins- oder offizielle Medien ist eine Urheberrechtsangabe (copyright_notice) Pflicht."` (Umlaut korrekt, 2026-05-10 korrigiert)
**Tests:** 7 Tests, alle grün:
- Promotion zu `club` ohne Copyright → **400** (exakt)
- Promotion zu `official` ohne Copyright → **400** (exakt)
- Promotion zu `club` mit Copyright im Body → **200** + Payload-Prüfung (gehärtet)
- Promotion zu `club`, Copyright bereits auf Asset → **200** + Payload-Prüfung (gehärtet)
- Kein Visibility-Wechsel → keine Copyright-Prüfung → **200** (exakt)
- Bulk: ohne Copyright → in `failed`, `updated_count == 0` (exakt)
- Bulk: mit Copyright → in `updated`, `updated_count == 1` (exakt)
---
### P-05 – Passwort-Mindestlänge angleichen ⚠️ (Teil 1 von 2 – Re-Audit-Auflage offen)
**Status:** Teilweise umgesetzt
**Betroffene Dateien (initialer Fix 2026-05-09):**
- `backend/routers/auth.py:101` – `PUT /api/auth/pin`: `< 4` → `< 8`
- `frontend/src/pages/LoginPage.jsx:175` – `minLength="6"` → `minLength="8"`
- `frontend/src/pages/AccountSettingsPage.jsx:403` – `minLength={4}` → `minLength={8}`
**Verbleibende Lücke identifiziert im Re-Audit 2026-05-09:** `POST /api/auth/reset-password` hatte kein Mindestlängen-Limit → siehe P-05b.
---
### P-05b – reset-password Mindestlänge 8 Zeichen ✅
**Status:** Umgesetzt (2026-05-10)
**Betroffene Dateien:**
- `backend/models.py:29` – `PasswordResetConfirm.new_password`
- `backend/tests/test_auth_password_reset_minlength.py` – 7 neue Tests
**Technische Änderung:**
```python
# models.py (vorher):
class PasswordResetConfirm(BaseModel):
token: str
new_password: str
# models.py (nachher):
class PasswordResetConfirm(BaseModel):
token: str
new_password: str = Field(min_length=8, max_length=128)
```
FastAPI lehnt Requests mit `new_password < 8 Zeichen` nun mit HTTP **422** (Pydantic Validation Error) ab, bevor der Endpoint-Handler ausgeführt wird. Kein DB-Zugriff erfolgt für unvalide Requests.
**Tests:** 7 Tests, alle grün:
- Leer-String → 422
- 1-Zeichen-Passwort → 422
- 7-Zeichen-Passwort (`"1234567"`) → 422
- Exakt 8 Zeichen (`"12345678"`) → **200** ✓
- Langes Passwort → **200** ✓
- Fehlendes `new_password`-Feld → 422
- Gültiges Passwort, ungültiger Token → 400
**P-05 vollständig geschlossen?** Ja — alle passwortverarbeitenden Backend-Endpoints erzwingen jetzt Mindestlänge 8:
| Endpoint | Mindestlänge | Mechanismus |
|---|---|---|
| `POST /api/auth/register` | 8 | `if len(password) < 8` im Handler |
| `PUT /api/auth/pin` | 8 | `if len(new_pin) < 8` im Handler |
| `POST /api/auth/reset-password` | 8 | Pydantic `Field(min_length=8)` |
| Management-Reset (profiles.py) | 8 | Pydantic `Field(min_length=8)` |
| Frontend LoginPage | 8 | `minLength="8"` |
| Frontend AccountSettingsPage | 8 | `minLength={8}` |
---
### P-07 – ALLOW_PUBLIC_MEDIA_STATIC Release-Test ✅
**Status:** Umgesetzt
**Betroffene Dateien:**
- `backend/tests/test_security_release.py` – 2 neue Tests
**Tests:** Beide grün.
---
### P-11 – Legal-Hold Lifecycle-Status ✅
**Status:** Vollständig umgesetzt (2026-05-11, Version 0.8.84 + Nachfixe 0.8.85–0.8.86)
#### P-11 Kernum­setzung (Version 0.8.84)
**Betroffene Dateien:**
- `backend/migrations/051_legal_hold.sql` – neue Spalten `legal_hold_active`, `legal_hold_reason_code`, `legal_hold_reason_note`, `legal_hold_set_by_profile_id`, `legal_hold_set_at`, `legal_hold_released_by_profile_id`, `legal_hold_released_at`, `legal_hold_release_note` in `media_assets`; Audit-Log-CHECK um `legal_hold_set`/`legal_hold_released` erweitert
- `backend/media_legal_hold.py` – Neu: zentrale Services `set_legal_hold`, `release_legal_hold`, `assert_not_under_legal_hold`, `is_media_available_for_normal_use`, `assert_superadmin_for_legal_hold`
- `backend/media_lifecycle.py` – `run_retention_pass()` filtert `AND (legal_hold_active = FALSE OR legal_hold_active IS NULL)` in beiden Retention-Queries
- `backend/routers/media_assets.py` – `admin_legal_hold_router` mit drei Endpoints; `_list_active_visibility_clause()` berücksichtigt `include_legal_hold`-Parameter; `download_media_asset_file()` prüft Legal-Hold für Nicht-Superadmins
- `backend/routers/exercises.py` – `attach_exercise_media_from_asset()` ruft `assert_not_under_legal_hold()` vor Verknüpfung auf
- `backend/main.py` – `app.include_router(media_assets.admin_legal_hold_router)`
- `frontend/src/utils/api.js` – `setMediaAssetLegalHold`, `releaseMediaAssetLegalHold`, `listMediaAssetsWithLegalHold`
- `frontend/src/pages/MediaLibraryPage.jsx` – Legal-Hold-Badge auf Kacheln; Superadmin-Aktionen „Sofort sperren"/„Sperre aufheben" im Edit-Modal; Bestätigungs-Dialog mit Pflichtfeldern; Journal-Renderpfad für `legal_hold_set`/`legal_hold_released`
- `frontend/src/app.css` – CSS-Klassen für Legal-Hold-Badge, -Dialog, -Button
**Neue API-Endpoints (Superadmin):**
- `POST /api/admin/media-assets/{asset_id}/legal-hold` — Sofortsperre setzen (reason_code + reason_note Pflicht)
- `POST /api/admin/media-assets/{asset_id}/legal-hold/release` — Sofortsperre aufheben (release_note Pflicht)
- `GET /api/admin/media-assets/legal-hold` — Liste aller aktuell gesperrten Assets
**Tests:** 15 Backend-Unit-Tests in `backend/tests/test_p11_legal_hold.py` — alle grün.
#### P-11 Nachfixe – UI-Bugs und Sichtbarkeitskorrektur (Version 0.8.85–0.8.86)
Nach Erstimplementierung wurden beim Testen weitere Mängel festgestellt und behoben:
**Version 0.8.85 – UI-Bugfixes:**
- Fix: `submitLegalHold` rief `loadMedia()` statt `loadItems()` auf → "loadMedia is not a function" beim Sperren
- Fix: Listabfrage in `list_media_assets` enthielt `legal_hold_active`, `reason_code`, `reason_note`, `set_at` nicht → Badge und „Sperre aufheben"-Button im Modal waren nie sichtbar
- Fix: Journal-Renderpfad verwendete Keys `nw.legal_hold_reason_code/note` statt `nw.reason_code/note` (Audit-Log-Format) → Begründung und Kommentar nicht angezeigt
- Fix: Archiv-Picker (ExerciseFormPage, ExerciseInlineFileMediaModal) filterte Legal-Hold-Assets bereits client-seitig heraus
**Version 0.8.86 – Vollständige Absicherung der Auslieferung:**
Betroffene Dateien:
- `backend/routers/exercises.py` – `download_exercise_media_file()` gibt HTTP 451 zurück wenn `asset_legal_hold_active=TRUE` (Datei wird nicht ausgeliefert); `enrich_exercise_detail()` SELECT erweitert um `ma.legal_hold_active AS asset_legal_hold_active`
- `backend/routers/media_assets.py` – `list_media_assets` übergibt `include_legal_hold=is_sup` statt `include_legal_hold=(is_plat or is_sup)` — Legal-Hold-Assets nur noch für Superadmin sichtbar, nicht für alle Plattform-Admins
- `frontend/src/components/ExerciseMediaEmbed.jsx` – Zeigt „Medium nicht verfügbar (gesperrt)" statt Datei wenn `asset_legal_hold_active`
- `frontend/src/components/ExerciseMediaThumbTile.jsx` – Zeigt rot-markierte „Gesperrt"-Kachel statt Dateivorschau; kein Preview-Trigger
- `frontend/src/pages/ExerciseFormPage.jsx` – Vorschau-Modal zeigt Hinweis statt Datei wenn `asset_legal_hold_active`
#### Sicherheitsarchitektur (vollständig)
- Legal-Hold ist orthogonal zum normalen Papierkorb-Lifecycle (P-03) — kein 30-Tage-Warten
- `rights_status='blocked'` wird als Schnell-Spiegel gesetzt und bei Aufhebung basierend auf vorhandenen Deklarationen wiederhergestellt (`declared` wenn Deklaration vorhanden, sonst `legacy_unreviewed`)
- Nur Superadmin darf setzen/aufheben; nur Superadmin sieht Legal-Hold-Assets in der Medienliste; normale Nutzer sehen gesperrte Assets nicht
- Retention-Job überspringt Legal-Hold-Assets (verhindert versehentliche Löschung unter laufender Sperrmaßnahme)
- `assert_not_under_legal_hold()` blockiert das Verknüpfen von Legal-Hold-Assets mit Übungen
- Dateiauslieferung (`download_exercise_media_file`) gibt HTTP 451 zurück — keine Umgehung via direkten File-Endpoint
- Frontend-Komponenten zeigen Placeholder statt Datei, auch wenn das Asset bereits in einer Übung verknüpft ist
---
### P-12 – sessionStorage bei Logout bereinigen ✅
**Status:** Umgesetzt (2026-05-10, Version 0.8.68)
**Betroffene Dateien:**
- `frontend/src/context/AuthContext.jsx` – `logout()`
- `tests/dev-smoke-test.spec.js` – neuer Playwright-Test
**Befund (war offen):**
`logout()` löschte nur `localStorage`-Einträge. `TrainingCoachPage` schrieb sessionStorage-Schlüssel mit Präfix `sj_coach_` (`sj_coach_step_{unitId}`, `sj_coach_deltas_{unitId}`, `sj_coach_debrief_{unitId}`), die nach Logout im Tab erhalten blieben. Bei Nutzerwechsel im selben Tab (geteilter Rechner) konnte der neue Nutzer Trainingsfortschritt des Vorgängers sehen.
**Technische Änderung:**
Gezielte Präfix-Löschung aller `sj_coach_*`-Schlüssel beim Logout (kein `sessionStorage.clear()`). Fremde sessionStorage-Schlüssel (Browser-Extensions o. ä.) bleiben erhalten.
```javascript
// AuthContext.jsx logout() — Ergänzung:
for (const key of Object.keys(sessionStorage)) {
if (key.startsWith('sj_coach_')) {
sessionStorage.removeItem(key)
}
}
```
**Begründung gezielte statt vollständiger Löschung:**
Alle Shinkan-spezifischen sessionStorage-Schlüssel sind eindeutig über den Präfix `sj_coach_` identifizierbar (definiert in `TrainingCoachPage.jsx` Zeilen 15–25). Ein `sessionStorage.clear()` würde auch Schlüssel fremder Quellen im selben Tab löschen; die Präfix-Löschung ist spezifischer und sicherer.
**Tests:** Playwright E2E-Test `tests/dev-smoke-test.spec.js` (Test „P-12: sessionStorage wird bei Logout bereinigt"):
- Setzt drei `sj_coach_*`-Schlüssel und einen fremden Schlüssel
- Klickt „Abmelden"
- Prüft: `sj_coach_*` → null (entfernt), fremder Schlüssel → erhalten, `authToken` → null (localStorage weiterhin korrekt bereinigt)
**Hinweis Tests:** Das Projekt verfügt über kein Frontend-Unit-Test-Framework (kein Vitest/Jest in package.json). Der Test ist als Playwright E2E-Test implementiert, der einen laufenden Dev-Server voraussetzt. Automatisierte Ausführung der Playwright-Tests erfordert `npx playwright test` mit gesetzter `PLAYWRIGHT_BASE_URL`.
---
### P-23 – LoginPage: minLength + Versionsstring ✅
**Status:** Umgesetzt
**Betroffene Dateien:**
- `frontend/src/pages/LoginPage.jsx`
**Technische Änderung:**
- `minLength="6"` → `minLength="8"`
- Hardcodierter Versionsstring `v0.1.0 • Development` entfernt
---
### P-24 – CORS allow_methods und allow_headers einschränken ✅
**Status:** Umgesetzt
**Betroffene Dateien:**
- `backend/main.py:85-86`
**Technische Änderung:**
```python
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "X-Auth-Token", "X-Active-Club-Id"],
```
---
## Test-Zusammenfassung (Stand 0.8.94)
```
tests/test_auth_password_reset_minlength.py 7 passed (neu, P-05b)
tests/test_media_assets_copyright_promotion.py 7 passed (gehärtet, P-04)
tests/test_media_rights_declaration.py 25 passed (neu, P-06a–P-06d)
tests/test_security_release.py 9 passed (inkl. 2 P-07-Tests)
tests/test_p11_legal_hold.py 15 passed (neu, P-11)
tests/test_p13_content_reports.py 15 passed (neu, P-13; CI-Fix 0.8.94)
Weitere bestehende Tests: 81 passed, 6 skipped
Gesamt (Backend): 159 passed, 6 skipped, 1 failed
Fehlgeschlagener Test: test_list_media_assets_invalid_lifecycle_400
→ Pre-existing: benötigt laufenden PostgreSQL-Container (Hostname "postgres")
→ Bestand bereits vor allen Compliance-Änderungen (verifiziert per git stash)
Playwright E2E (dev-smoke-test.spec.js): 22+ passed (inkl. P-06-Tests)
→ P-01: 4× Route ohne Auth + Platzhalterhinweis + Reload, 1× Login-Links
→ P-01b: 3× /settings/legal (Link in Einstellungen, Überschrift, Rechtstext-Links)
→ P-01c: 3× Admin-Rechtstexte (Seitenladung, Route /admin/legal-documents, Admin-Nav)
→ P-12: sessionStorage-Bereinigung (grün)
→ P-06: 5× RightsDeclarationDialog (Anzeige, Pflichtfeld-Validierung, Upload-Flow,
Promotions-Dialog, Legacy-Altbestand-Indikator)
Anmerkung jsPDF (0.8.74):
→ PDF-Download via pdf.save() ist ein Browser-Download, kein Server-Request.
→ Kein Backend-Test möglich; funktional im Browser verifizierbar.
→ Playwright-E2E-Test erfordert laufenden Dev-Server (npx playwright test).
Anmerkung P-06+ Journal/Korrektur (0.8.82–0.8.83):
→ Journal-Endpoint und Korrektur-Endpoint durch manuellen API-Test (curl) auf Dev-System verifiziert.
→ Bugfix club_admin-Prüfung (has_club_role) verifiziert: 500 → 200 nach Fix.
→ Keine dedizierte Playwright-Testsuite für Journal-Modal und Korrektur-Formular (UI-Verifikation ausstehend).
Anmerkung P-11 Frontend-Absicherung (0.8.85–0.8.86):
→ UI-Fixes (loadItems, Badge-Sichtbarkeit, Journal-Keys) manuell auf Dev-System verifiziert.
→ 15 Backend-Unit-Tests decken Services und Retention-Schutz ab.
→ Keine Playwright-Tests für Legal-Hold-Aktionen im Modal — manuelle UI-Verifikation.
Anmerkung P-13 Erweiterungen (0.8.88–0.8.94):
→ E-Mail-Benachrichtigungen, Audit-Log, Club-Admin-Rechte, Workflow manuell auf Dev-System verifiziert.
→ CI-Fix (0.8.94): 3 pytest-Tests angepasst (frühzeitige 403, vollständige Mock-Zeile, DB-Mock für COUNT).
→ Alle 15 pytest-Tests grün nach CI-Fix.
→ Keine Playwright-Tests für InboxPage Meldungs-Workflow — manuelle UI-Verifikation.
```
---
### P-06 – Upload-Einwilligungsdialog ⚠️ (technisch vollständig umgesetzt inkl. P-06+; juristische Validierung offen)
**Status:** Technisch vollständig umgesetzt (inkl. P-06+ Volljournal + Korrektur, Version 0.8.83) — KRIT-04 bleibt offen.
**Deklarationsversion:** `p06-v1-conservative`
---
#### P-06a–P-06d — Kernum­setzung (Version 0.8.75)
**Betroffene Dateien:**
- `backend/migrations/048_media_rights_declarations.sql` (neu) — Append-only Deklarations-Log + 3 Schnellfelder in `media_assets` (`rights_status`, `rights_declared_for_visibility`, `rights_declared_at`)
- `backend/migrations/049_media_rights_consent_context.sql` (neu) — Kontext-Freitextfelder in `media_asset_rights_declarations` (`person_consent_context`, `parental_consent_context`, `music_rights_context`, `third_party_rights_context`)
- `backend/media_rights.py` (neu) — Zentrales Policy-Modul: `validate_rights_declaration`, `check_rights_coverage`, `assert_rights_for_promotion`, `assert_rights_for_exercise_link`, `write_rights_declaration`, `update_rights_quick_fields`
- `backend/routers/media_assets.py` — P-06-Enforcement in Bulk-Upload, PATCH, Bulk-PATCH; 3 neue Endpoints
- `backend/routers/exercises.py` — P-06 bei `upload_exercise_media` (neue Assets) und `attach_exercise_media_from_asset`
- `frontend/src/components/RightsDeclarationDialog.jsx` (neu) — Einwilligungsdialog (9 Pflichtfelder + Kontext-Freitexte)
- `frontend/src/pages/MediaLibraryPage.jsx` — Dialog-Integration vor Bulk-Upload; Altbestand-Indikator
- `frontend/src/pages/ExerciseInlineFileMediaModal.jsx` + `ExerciseInlineEmbedModal.jsx` — RightsDeclarationDialog vor Upload
- `frontend/src/utils/api.js` — `bulkUploadMediaAssets` erweitert um P-06-Felder
- `backend/tests/test_media_rights_declaration.py` (neu) — 25 Unit/HTTP-Tests
**Neue Endpoints (P-06b):**
| Endpoint | Beschreibung |
|----------|-------------|
| `POST /api/media-assets/{id}/rights-declarations` | Explizite Re-/Nachdeklaration |
| `GET /api/admin/media-rights/legacy-summary` | Zusammenfassung Altbestand nach Sichtbarkeit (Plattform-Admin) |
| `GET /api/admin/media-rights/legacy-assets` | Paginierte Liste Altbestand club/official (Plattform-Admin) |
**Abweichung von Spec §3 (konservative Erstannahme):**
Person-Fragen sind auch bei Sichtbarkeit `private` Pflicht (§10.1 in `docs/p06-upload-rights-spec.md`).
**Altbestand (Legacy):**
Alle vor Migration 048 hochgeladenen Medien erhalten `rights_status = 'legacy_unreviewed'`.
Promotion blockiert bis Nachdeklaration. In Bibliotheks-UI als „Altbestand ⚠" markiert.
---
#### P-06+ — Volljournal + Korrektur (Version 0.8.82–0.8.83)
**Motivation:** Vollständige Nachvollziehbarkeit aller Medien-Ereignisse, nicht nur der Deklarationen. Plus: Möglichkeit, fehlerhafte Deklarationen mit Begründung nachträglich zu korrigieren (append-only — neueste gilt).
**Betroffene Dateien:**
- `backend/migrations/050_media_audit_log.sql` (neu) — Neue Tabelle `media_asset_audit_log` + `correction_note TEXT` in Deklarations-Tabelle + erweiterter CHECK (action_type += 'correction')
- `backend/media_rights.py` — Neue Funktionen: `write_audit_log_entry()`, `write_rights_correction_declaration()`
- `backend/routers/media_assets.py` — Neues Pydantic-Model `RightsCorrectionBody`; PATCH-Endpoint schreibt Audit-Log-Einträge; Lifecycle-Aktionen schreiben `lifecycle_change`-Einträge; 2 neue Endpoints; Import `has_club_role` ergänzt
- `frontend/src/pages/MediaLibraryPage.jsx` — Journal-Modal komplett überarbeitet: unified `events[]`-Ansicht; Korrektur-Formular inline; Helper-Funktionen `actionTypeLabel`, `eventTypeLabel`, `visLabel`
- `frontend/src/utils/api.js` — Neue Funktion `addMediaAssetDeclarationCorrection(assetId, body)`
- `frontend/src/app.css` — CSS für Audit-Einträge (`--audit`), Korrektur-Einträge (`--correction`), Korrektur-Formular
**Neue Endpoints (P-06+):**
| Endpoint | Auth | Beschreibung |
|----------|------|-------------|
| `GET /api/admin/media-rights/assets/{id}/journal` | Superadmin / Uploader / Vereins-Admin | Volljournal: `events[]` aus Deklarationen + Audit chronologisch gemischt. Gibt `can_correct` zurück. |
| `POST /api/admin/media-rights/assets/{id}/correction` | Superadmin / Uploader / Vereins-Admin | Korrektur-Deklaration (append-only, neueste gilt). Felder = P-06-Dialog + `correction_note`. |
**Automatische Audit-Log-Einträge:**
| event_type | Auslöser |
|-----------|----------|
| `visibility_change` | PATCH wenn `visibility` oder `club_id` sich ändert |
| `copyright_change` | PATCH wenn `copyright_notice` sich ändert |
| `metadata_change` | PATCH wenn `original_filename` etc. sich ändert |
| `lifecycle_change` | Lifecycle-Aktionen: trash_soft, trash_hidden, recover, reactivate (nicht bei Hard-Delete/Purge) |
**Bugfixes in P-06+:**
| Bug | Fix |
|-----|-----|
| Journal + Korrektur gaben 500 (falsches Schema club_admin) | `has_club_role(cur, profile_id, club_id, "club_admin")` statt `AND role = 'admin'` in `club_members` |
| Frontend-Build-Fehler: doppelte `lcLabel`-Deklaration | Duplikat in Zeile 264 von `MediaLibraryPage.jsx` entfernt |
**KRIT-04 Status:**
Offen. Juristische Validierung der Feldtexte (§10.3 p06-v1-conservative, T1–T10), KUG/DSGVO-Anforderungen (§7.1–§7.12 der Spec) und Korrekturfähigkeit (Spec §11.9) steht aus.
Referenz: `docs/p06-upload-rights-spec.md` §10.5, §11.9.
---
### P-13 – Content-Melde-Backend ✅
**Status:** Vollständig umgesetzt (2026-05-11, Version 0.8.87–0.8.94)
**Finding:** KRIT-03
**Architekturentscheidung:** Anstelle einer separaten Moderations-Queue wurde die bestehende Admin-Inbox (`InboxPage.jsx`) um einen zweiten Abschnitt erweitert. Keine generische `inbox_items`-Tabelle, keine separate `/api/admin/reports`-Queue.
#### P-13 Kernum­setzung (Version 0.8.87)
**Betroffene Dateien:**
- `backend/migrations/052_content_reports.sql` (neu) — Tabelle `content_reports` mit Status-Workflow, Priorisierung, 3 Indizes
- `backend/routers/content_reports.py` (neu) — alle Endpoints, Reason-Code-Mapping, Priorisierung
- `backend/tests/test_p13_content_reports.py` (neu) — 15 Unit-Tests
- `backend/main.py` — Router-Registrierung
- `frontend/src/utils/api.js` — 5 neue API-Funktionen (submitContentReport, getInboxContentReports, getContentReport, patchContentReport, setLegalHoldFromReport)
- `frontend/src/context/OrgInboxContext.jsx` — contentReports-State, contentReportCount, canAccessContentReports, isSuperadmin
- `frontend/src/pages/InboxPage.jsx` — zweiter Abschnitt „Inhaltsmeldungen", ReportDetailModal
- `frontend/src/components/ReportContentModal.jsx` (neu) — Meldungsformular
- `frontend/src/components/MediaPreviewModal.jsx` (neu) — geteilter Vorschau-Dialog
**API-Endpoints (Kernum­setzung):**
| Endpoint | Auth | Beschreibung |
|----------|------|--------------|
| `POST /api/content-reports` | Optional | Meldung einreichen (official-Medien ohne Login; eingeloggt: alle sichtbaren Medien) |
| `GET /api/me/inbox/content-reports` | Plattform-Admin | Liste aller Meldungen, JOIN auf Zieltabellen |
| `GET /api/content-reports/{id}` | Plattform-Admin | Einzel-Detail |
| `PATCH /api/content-reports/{id}` | Plattform-Admin | Status/Notiz/Zuweisung; resolution_note Pflicht für Abschluss-Status |
| `POST /api/content-reports/{id}/legal-hold` | Superadmin | Legal Hold via P-11 `set_legal_hold()`; setzt Status auf `resolved_legal_hold` |
**Reason-Code-Mapping (P-13 → P-11):**
| Meldegrund | Legal-Hold reason_code |
|------------|------------------------|
| copyright | copyright_complaint |
| image_rights | rights_dispute |
| privacy | privacy_complaint |
| minors | youth_protection |
| illegal_content | illegal_content |
| youth_protection | youth_protection |
| offensive_content | illegal_content |
| other | other |
---
#### P-13 Erweiterungen — Audit-Log, E-Mail, Workflow, Club-Admin (Version 0.8.88–0.8.94)
**Betroffene Dateien:**
- `backend/migrations/053_content_report_audit_event.sql` (neu) — `content_report_filed` Event-Typ dem `media_asset_audit_log` CHECK-Constraint hinzugefügt (alle 7 gültigen Event-Typen)
- `backend/routers/content_reports.py` — stark erweitert: E-Mail-Benachrichtigungen, Audit-Log, deutsche Labels, Club-Admin-Berechtigungen, Workflow-Verbesserungen, frühzeitige 403-Prüfung
- `backend/routers/media_assets.py` — `open_report_count` Batch-Query für Admin-Nutzer in `list_media_assets`
- `frontend/src/pages/InboxPage.jsx` — vollständig überarbeitetes `ReportDetailModal` mit Workflow-Bar, Archiv-Trennung
- `frontend/src/pages/MediaLibraryPage.jsx` — Badge auf Medienkarten, Journal-Eintrag für `content_report_filed`
- `frontend/src/components/ReportContentModal.jsx` — `onSuccess` Callback, readOnly-Felder für eingeloggte Nutzer
- `frontend/src/context/OrgInboxContext.jsx` — `contentReportsError`, `isClubAdmin`, `isPlatformAdmin` exponiert
**Backend-Erweiterungen:**
- **E-Mail-Benachrichtigungen** (best-effort, nach Commit): Bestätigung an Melder + Benachrichtigung aller Plattform-Admins nach Eingang einer Meldung; `original_filename` oder `exercises.title` als Medienbezeichnung im E-Mail-Betreff
- **Audit-Log-Integration**: Bei `target_type='media_asset'` Eintrag `content_report_filed` in `media_asset_audit_log`; bei Statuswechseln und reinen Notizänderungen via PATCH ebenfalls; deutsche Labels via `REASON_LABELS_DE` / `STATUS_LABELS_DE`
- **Club-Admin-Berechtigungen**: `GET /me/inbox/content-reports` liefert Club-Admins nur Meldungen zu Medien ihrer Vereine (COUNT-Check, 403 wenn keine Club-Admin-Rolle); `GET /content-reports/{id}` und `PATCH` via `_assert_can_manage_report()` auch für Club-Admins (nur eigene Vereinsmedien); `POST /content-reports/{id}/legal-hold` für Club-Admins auf nicht-offizielle Vereinsmedien via `_assert_can_set_legal_hold_from_report()`; Superadmin-Prüfung frühzeitig vor DB-Zugriff (plain Admin → sofort 403)
- **Workflow-Verbesserungen in PATCH**: Wiedereröffnen einer Meldung (`status='submitted'`) setzt `reviewed_by_profile_id` und `reviewed_at` auf NULL zurück
- **`open_report_count`** in `list_media_assets`: Für Admin-Nutzer wird je Medium die Anzahl offener Meldungen (`submitted`/`under_review`) als Batch-Query zurückgegeben
**Frontend-Erweiterungen:**
- **`WorkflowBar`** in InboxPage: 3-Schritte-Fortschrittsbalken (Eingegangen → In Bearbeitung → Abgeschlossen) mit visueller Hervorhebung des aktuellen Schritts
- **`ReportDetailModal`** überarbeitet: zeigt WorkflowBar, Prüferinformationen (`reviewed_by_name`, `reviewed_at`), `resolution_note` (readOnly bei abgeschlossenen Meldungen), eigener „Kommentar speichern"-Button, „Meldung wieder öffnen"-Button für abgeschlossene Meldungen
- **Archiv-Trennung**: Offene Meldungen (`submitted`/`under_review`) im Hauptbereich; abgeschlossene/abgewiesene Meldungen in einer kollabierbaren Archiv-Sektion (Standard: zugeklappt)
- **Legal-Hold-Button** in ReportDetailModal: sichtbar für Superadmin sowie Club-Admins (bei nicht-offiziellen Medien)
- **Badge auf Medienkarten** in MediaLibraryPage: rotes Badge mit `open_report_count` (nur sichtbar wenn > 0); wird nach erfolgreicher Meldung via `onSuccess`-Callback sofort aktualisiert
- **Journal-Eintrag** in MediaLibraryPage: `content_report_filed`-Ereignisse mit Meldungs-ID, Grund, Priorität, Status, Begründung
- **`OrgInboxContext`**: `contentReportsError` (Fehlerstring oder null), `isClubAdmin` und `isPlatformAdmin` exponiert; `contentReportCount` zählt nur offene Meldungen (submitted/under_review)
- **`ReportContentModal`**: `onSuccess`-Callback nach erfolgreichem Submit; Name und E-Mail readOnly für eingeloggte Nutzer (grauer Hintergrund)
- **Melde-Einstieg**: `MediaPreviewModal` (geteilt) + Melden-Button in MediaLibraryPage, ExerciseFormPage und ExerciseAttachmentMediaStrip
**CI-Fix (Version 0.8.94):**
3 pytest-Tests in `test_p13_content_reports.py` repariert: frühzeitige 403-Prüfung in `set_legal_hold_from_report` für plain Admin (vor DB-Zugriff); Test 10 mit korrektem DB-Mock für COUNT-Query; Test 12 mit vollständiger Mock-Zeile (`target_type`, `target_id`, `resolution_note`). Alle 15 Tests grün.
**Nicht in P-13-Scope:** P-14 (Moderations-UI als eigene Seite), P-15 (Uploader-Benachrichtigung per E-Mail bei Sperrung), P-16 (Beschwerdeverfahren).
---
## Nicht umgesetzte Pakete
> Paket-IDs und -Titel gemäß kanonischem Register `docs/compliance-package-register.md`.
> Abweichende Beschreibungen in der Ursprungsversion dieses Abschnitts wurden am 2026-05-10 korrigiert (P-06, P-08, P-09, P-10, P-11, P-18 — Details im Konsistenzbericht des Registers).
| Paket | Kanonischer Titel | Status | Begründung |
|-------|------------------|--------|------------|
| P-01 | Rechtstexte | offen | Scope ausgeschlossen (juristischer Inhalt) |
| P-02 | Self-Service-Kontolöschung + Datenexport | offen | Scope ausgeschlossen |
| P-06 | Upload-Einwilligungsdialog (Recht am eigenen Bild) | **teilweise umgesetzt** | Technisch umgesetzt (2026-05-11, v0.8.75) unter vorläufigen Erstannahmen `p06-v1-conservative` — siehe §P-06 unten. KRIT-04 bleibt offen bis juristische Validierung. |
| P-08 | HSTS / externe Proxy-Sicherheit dokumentieren | offen | Scope ausgeschlossen (außerhalb Repo — Reverse-Proxy) |
| P-09 | Admin-Audit-Log | offen | Scope ausgeschlossen |
| P-10 | Mindestalter-Abfrage | offen | Scope ausgeschlossen |
| P-11 | Legal-Hold Lifecycle-Status | ✅ umgesetzt | Version 0.8.84–0.8.86 — siehe §P-11 oben |
| P-12 | sessionStorage bei Logout bereinigen | ✅ umgesetzt | Version 0.8.68 — siehe §P-12 oben |
| P-13 | Content-Melde-Backend | ✅ umgesetzt | Version 0.8.87 — siehe §P-13 unten |
| P-14 | Moderations-UI | offen | Scope ausgeschlossen |
| P-15 | Uploader-Benachrichtigung bei Sperrung | offen | Scope ausgeschlossen |
| P-16 | Beschwerdeverfahren | offen | Scope ausgeschlossen |
| P-17 | MFA für Superadmins (TOTP) | offen | Scope ausgeschlossen |
| P-18 | HttpOnly-Cookie als Auth-Alternative | offen | Scope ausgeschlossen |
| P-19 | Anti-Virus-Scan (ClamAV) | offen | Scope ausgeschlossen |
| P-20 | VVT erstellen | offen | Scope ausgeschlossen (Betreiber-Aufgabe) |
| P-21 | AV-Verträge abschließen | offen | Scope ausgeschlossen (Betreiber-Aufgabe) |
| P-22 | HTML-Sanitizer für Rich-Text-Felder | offen | Scope ausgeschlossen |
---
## Re-Audit-Empfehlung
Operativ prüfen (Stand 0.8.94):
1. **P-03/P-03b**: `docker logs shinkan-retention-cron` — Job läuft täglich 03:00 Uhr; Retention-Zeiten: 30 → 30 Tage
2. **P-04**: Manuell: PATCH privates Medium auf `official` ohne `copyright_notice` → muss 400 liefern
3. **P-05b**: Manuell: Reset-Link mit 7-Zeichen-Passwort → muss mit Fehler abgewiesen werden
4. **P-24**: Browser DevTools Preflight → `Access-Control-Allow-Headers: content-type, x-auth-token, x-active-club-id`
5. **P-06**: Manuell: Upload ohne `rights_holder_confirmed` → muss 400 liefern; Journal-Endpoint für vorhandene Assets → muss 200 + `events[]` liefern; Korrektur-Endpoint → muss neue Deklaration mit `action_type='correction'` schreiben
6. **P-06 Audit-Log**: PATCH Sichtbarkeit eines Assets → `media_asset_audit_log` muss Eintrag `visibility_change` enthalten
7. **P-11**: Superadmin → Medium sperren → in Übung öffnen → Kachel zeigt „Gesperrt"; direkter Dateiaufruf `/exercises/{id}/media/{mid}/file` → muss HTTP 451 liefern; Plattform-Admin (kein Superadmin) → gesperrtes Medium darf in Medienliste nicht erscheinen
8. **P-13 Grundfunktion**: Anonym → `POST /api/content-reports` für official-Medium ohne Auth → muss 200 liefern; `good_faith_confirmed=false` → muss 400 liefern; Plattform-Admin → `GET /api/me/inbox/content-reports` → Liste; Superadmin → `POST /api/content-reports/{id}/legal-hold` → setzt Legal Hold + Report-Status `resolved_legal_hold`
9. **P-13 E-Mail**: Meldung einreichen → Melder erhält Bestätigungs-E-Mail; Plattform-Admins erhalten Benachrichtigungs-E-Mail (sofern SMTP konfiguriert)
10. **P-13 Club-Admin**: Club-Admin → `GET /api/me/inbox/content-reports` → liefert nur Meldungen zu Medien des eigenen Vereins; Club-Admin → `PATCH /api/content-reports/{id}` für Meldung zu eigenem Vereinsmedium → muss 200 liefern
11. **P-13 Audit-Log**: Meldung einreichen für media_asset → `media_asset_audit_log` muss Eintrag `content_report_filed` enthalten; Statuswechsel via PATCH → muss weiteren Audit-Eintrag enthalten
12. **P-13 Badge**: Medium mit offener Meldung in Medienbibliothek → rotes Badge mit Zähler sichtbar
13. **P-13 Workflow**: Abgeschlossene Meldungen in InboxPage im Archiv (kollabierbar); Wiedereröffnen einer Meldung → `reviewed_by_profile_id` und `reviewed_at` werden zurückgesetzt
Nächster vollständiger Re-Audit empfohlen nach juristischer Klärung P-06/KRIT-04 (Textfreigabe T1–T10) und nach Einpflegen der Rechtstexte P-01 durch Betreiber.
+435
View File
@@ -0,0 +1,435 @@
# Compliance-Paketregister – Shinkan Jinkendo
**Typ:** Kanonisches Referenzdokument
**Erstellt:** 2026-05-10
**Basisdokument:** `docs/compliance-audit.md` (Initial-Audit 2026-05-09, App-Version 0.8.65)
**Letzte Aktualisierung:** 2026-05-11 (App-Version 0.8.94)
---
> **Verbindliche Regel:** Paket-IDs werden nach ihrer ersten Vergabe in `docs/compliance-audit.md` nie wieder umnummeriert oder wiederverwendet. Dieses Dokument ist der kanonische Verweis für alle Freigaben, Umsetzungsberichte und Audits. Abweichende Nummerierungen in nachgelagerten Dokumenten sind Fehler und müssen auf die kanonische ID korrigiert werden. Nacharbeiten zu einem Paket erhalten Suffixe (z. B. P-03b, P-05b), keine neue Hauptnummer.
---
## Status-Legende
| Symbol | Bedeutung |
|--------|-----------|
| ✅ implemented | Vollständig umgesetzt und getestet |
| ⚠️ partially implemented | Teilweise umgesetzt; Nacharbeit dokumentiert |
| ❌ open | Nicht umgesetzt, offen |
| 🔒 scope excluded | Bewusst außerhalb des technischen Umsetzungsscopes |
---
## Etappe 1 – Pflicht vor öffentlichem Betrieb
### P-01 – Rechtstexte
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Rechtstexte (Impressum, Datenschutzerklärung, AGB, Medienrichtlinie) |
| **Findings** | KRIT-01 |
| **Etappe** | 1 |
| **Status** | ⚠️ partially implemented |
| **Letzter Stand** | Technischer Teil vollständig umgesetzt (2026-05-10, Version 0.8.74, inkl. P-01b + P-01c + Erweiterungen): Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`, `/medienrichtlinie` öffentlich erreichbar ohne Auth. Platzhalterseiten mit strukturierten Pflichtfeldern und sichtbarem Muster-Hinweis. Links in LoginPage, DesktopSidebar und `/settings/legal` (Mobile/PWA, P-01b, 0.8.70). Admin-konfigurierbare Rechtstexte mit Versionierung + Publish/Archive-Workflow (DB 047, Superadmin-UI `/admin/legal-documents`, P-01c, 0.8.71). Als-Entwurf-kopieren: `POST /api/admin/legal-documents/{id}/copy-as-draft` (0.8.72). Echter PDF-Download via jsPDF (direkter Dateidownload, A4, Seitenumbruch, Footer), Abschnitte sortieren (▲/▼) und an beliebiger Stelle einfügen (0.8.74). **Juristisch geprüfte Inhalte fehlen noch — Betreiber + Rechtsanwalt erforderlich. KRIT-01 bleibt offen bis zur Veröffentlichung echter Texte.** |
| **Verweise** | `docs/compliance-audit.md` §14.2, §17, §19.1; `docs/compliance-implementation.md` §P-01, §P-01b, §P-01c; `frontend/src/pages/LegalPage.jsx`; `frontend/src/pages/SettingsLegalPage.jsx`; `frontend/src/pages/AdminLegalDocumentsPage.jsx`; `backend/routers/legal_documents.py`; `backend/migrations/047_legal_documents.sql` |
| **Hinweise** | P-01b (Mobile-Erreichbarkeit, 0.8.70) und P-01c (Admin-konfigurierbar, 0.8.71) als Suffix-Pakete ergänzt und vollständig umgesetzt. Erweiterungen: copy-as-draft (0.8.72), jsPDF + Abschnitts-Sortierung/-Einfügen (0.8.74). Keine Nummerierungsabweichung. |
---
### P-02 – Self-Service-Kontolöschung + Datenexport
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Self-Service-Kontolöschung und Datenexport (DSGVO Art. 17, 15, 20) |
| **Findings** | KRIT-02, KRIT-05 |
| **Etappe** | 1 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. `DELETE /api/profiles/{pid}` nur für Plattform-Admin. |
| **Verweise** | `docs/compliance-audit.md` §7.3, §11.2, §17 |
| **Hinweise** | In `docs/compliance-implementation.md` als „Self-Service-Löschworkflow" bezeichnet — inhaltlich korrekt, Titel leicht abgekürzt. |
---
### P-03 – Papierkorb-Retention-Job aktivieren
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Papierkorb-Retention-Job aktivieren (automatische tägliche Ausführung) |
| **Findings** | KRIT-07 |
| **Etappe** | 1 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt in Version 0.8.66. Neuer Docker-Service `retention-cron` in `docker-compose.yml`. Python-basierter Loop, täglich 03:00 Uhr. |
| **Nacharbeit** | P-03b (Retention-Zeiten mit Löschkonzept abgleichen) — siehe unten |
| **Verweise** | `docs/compliance-audit.md` §9.2, §17; `docs/compliance-implementation.md` §P-03 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
#### P-03b – Nacharbeit: Retention-Zeiten mit Löschkonzept abgleichen
| Feld | Inhalt |
|------|--------|
| **Typ** | Nacharbeit zu P-03 (kein eigenes Hauptpaket) |
| **Status** | ✅ implemented (2026-05-10, Version 0.8.67) |
| **Befund** | Default `HIDDEN_TO_PURGE_DAYS` war 90 Tage; fachliches Löschkonzept sieht 30+30 vor. |
| **Änderung** | `backend/media_lifecycle.py`: Default `"90"` → `"30"`; `docker-compose.yml`: Env-Variable dokumentiert. |
| **Verweise** | `docs/compliance-implementation.md` §P-03b |
---
### P-04 – Copyright-Pflicht für Archiv-Promotion vereinheitlichen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Copyright-Pflicht bei Archiv-Promotion vereinheitlichen |
| **Findings** | KRIT-06 |
| **Etappe** | 1 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `patch_media_asset()` und `bulk_media_patch()` erzwingen `copyright_notice` bei Promotion auf `club`/`official`. 7 Tests, alle grün. |
| **Verweise** | `docs/compliance-audit.md` §6.3, §8.1, §17; `docs/compliance-implementation.md` §P-04; `backend/tests/test_media_assets_copyright_promotion.py` |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-05 – Passwort-Mindestlänge angleichen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Passwort-Mindestlänge angleichen (alle Endpoints: mindestens 8 Zeichen) |
| **Findings** | MITT-01, SEC-04, SEC-12, NIED-06 |
| **Etappe** | 1 |
| **Status** | ✅ implemented (vollständig, inkl. P-05b) |
| **Letzter Stand** | Version 0.8.66: `PUT /api/auth/pin`, `LoginPage.jsx`, `AccountSettingsPage.jsx`. Version 0.8.67: `POST /api/auth/reset-password` via P-05b. Alle 6 Punkte geschlossen. |
| **Nacharbeit** | P-05b (`reset-password` Mindestlänge) — siehe unten |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-04, SEC-12), §16 (MITT-01); `docs/compliance-implementation.md` §P-05, §P-05b |
| **Hinweise** | P-05 gilt als vollständig geschlossen nach Abschluss von P-05b (2026-05-10). |
#### P-05b – Nacharbeit: reset-password Mindestlänge
| Feld | Inhalt |
|------|--------|
| **Typ** | Nacharbeit zu P-05 (kein eigenes Hauptpaket) |
| **Status** | ✅ implemented (2026-05-10, Version 0.8.67) |
| **Befund** | `POST /api/auth/reset-password` hatte kein Mindestlängen-Limit im Backend. |
| **Änderung** | `backend/models.py`: `PasswordResetConfirm.new_password = Field(min_length=8, max_length=128)`. 7 neue Tests. |
| **Verweise** | `docs/compliance-implementation.md` §P-05b; `backend/tests/test_auth_password_reset_minlength.py` |
---
### P-06 – Upload-Einwilligungsdialog
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Upload-Einwilligungsdialog (Recht am eigenen Bild, Personen, Minderjährige) |
| **Findings** | KRIT-04 |
| **Etappe** | 1 |
| **Status** | ⚠️ teilweise umgesetzt (KRIT-04 offen) |
| **Letzter Stand** | **Vollständig technisch umgesetzt inkl. P-06+ (2026-05-11, v0.8.83)** unter vorläufigen Erstannahmen `p06-v1-conservative`. **Kernum­setzung (v0.8.75):** Migration 048 (`media_asset_rights_declarations` + 3 Schnellfelder in `media_assets`); Migration 049 (Kontext-Felder); `backend/media_rights.py`; Enforcement in Bulk-Upload, PATCH, Bulk-PATCH, exercises.py; `RightsDeclarationDialog.jsx`; Altbestand-Indikator; 3 neue Admin-Endpoints. **P-06+ Volljournal + Korrektur (v0.8.82–0.8.83):** Migration 050 (`media_asset_audit_log` + `correction_note` in Deklarations-Tabelle); automatische Audit-Log-Einträge bei Sichtbarkeits-, Copyright-, Metadaten- und Lifecycle-Änderungen; neuer Journal-Endpoint `GET /api/admin/media-rights/assets/{id}/journal` (chronologisch gemischte events[] aus Deklarationen + Audit); neuer Korrektur-Endpoint `POST /api/admin/media-rights/assets/{id}/correction`; Zugriff für Superadmin + Uploader + Vereins-Admin; Korrektur-Formular im Journal-Modal. Juristische Klärungspunkte (§22 KUG, §8 DSGVO, Widerrufsrecht etc.) offen — KRIT-04 bleibt. Details: `docs/p06-upload-rights-spec.md` §10, §11; `docs/compliance-implementation.md` §P-06. |
| **Verweise** | `docs/compliance-audit.md` §8.2, §8.3, §11.4, §17; `docs/p06-upload-rights-spec.md`; `docs/compliance-implementation.md` §P-06; `backend/media_rights.py`; `backend/migrations/048_media_rights_declarations.sql`; `backend/migrations/050_media_audit_log.sql` |
| **Hinweise** | **Drift-Hinweis (2026-05-10):** In `docs/compliance-implementation.md` (vor Korrektur) wurde P-06 fälschlich als „HSTS-Header" beschrieben. Korrigiert. **P-06+ (2026-05-11, v0.8.82–0.8.83):** Volljournal + Korrektur als notwendige Erweiterung nach Ersterstellung implementiert. Bugfix: Club-Admin-Prüfung im Journal/Korrektur-Endpoint nutzte falsches Schema (`role`-Spalte auf `club_members` existiert nicht) — korrigiert auf `has_club_role()`. |
---
## Etappe 2 – Sicherheit und Datenschutz
### P-07 – ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren und Release-Test einrichten |
| **Findings** | HOCH-01, SEC-05 |
| **Etappe** | 2 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt in Version 0.8.66. 2 Tests in `test_security_release.py`: Flag deaktiviert per Default; Flag aktiviert mounted `/media`. |
| **Verweise** | `docs/compliance-audit.md` §13.5, §17; `docs/compliance-implementation.md` §P-07; `backend/tests/test_security_release.py` |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-08 – HSTS / externe Proxy-Sicherheit dokumentieren
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | HSTS und externe Proxy-Sicherheit dokumentieren |
| **Findings** | HOCH-02, SEC-01 |
| **Etappe** | 2 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. HSTS liegt außerhalb des Repo-Scopes (Reverse-Proxy/Fritz!Box). Betreiber-Verantwortung. |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-01), §19.7 |
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) fehlte P-08 vollständig in der „Nicht umgesetzte Pakete"-Tabelle. Der Inhalt „HSTS-Header" war fälschlich P-06 zugeordnet. Korrigiert in `docs/compliance-implementation.md`. |
---
### P-09 – Admin-Audit-Log
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Admin-Audit-Log (Protokollierung von Admin-Aktionen) |
| **Findings** | HOCH-05, SEC-07 |
| **Etappe** | 2 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Keine `admin_audit_log`-Tabelle vorhanden. Profil-Löschungen und Lifecycle-Aktionen nicht protokolliert. |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-07), §16 (HOCH-05), §17 |
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde P-09 fälschlich als „Kein Einwilligungsdialog Recht am eigenes Bild" beschrieben. Der korrekte Titel ist „Admin-Audit-Log". Der Einwilligungsdialog gehört zu P-06. Korrigiert in `docs/compliance-implementation.md`. |
---
### P-10 – Mindestalter-Abfrage
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Mindestalter-Abfrage bei Registrierung |
| **Findings** | HOCH-06 |
| **Etappe** | 2 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Keine Altersverifikation bei Registrierung. Juristisch zu prüfen (§8 DSGVO). |
| **Verweise** | `docs/compliance-audit.md` §11.4, §16 (HOCH-06), §17 |
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde P-10 fälschlich als „DSA-Meldeverfahren" beschrieben. Der korrekte Titel ist „Mindestalter-Abfrage". Das DSA-Meldeverfahren gehört zu P-13–P-16. Korrigiert in `docs/compliance-implementation.md`. |
---
### P-11 – Legal-Hold Lifecycle-Status
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Legal-Hold Lifecycle-Status (Sofortsperrung bei Rechtsverletzung) |
| **Findings** | MITT-02 |
| **Etappe** | 2 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Vollständig umgesetzt in Version 0.8.84 (2026-05-11), mit Nachfixen in 0.8.85–0.8.86. **Kernum­setzung (0.8.84):** Migration 051 (`legal_hold_active` + Metadatenfelder in `media_assets`; Audit-Log-Ereignistypen `legal_hold_set`/`legal_hold_released`); zentrales Service-Modul `media_legal_hold.py`; Retention-Job überspringt Legal-Hold-Assets; 3 Superadmin-API-Endpoints; Frontend-Badge + Bestätigungs-Dialog + Journal-Renderpfad; 15 Backend-Unit-Tests. **Nachfixe (0.8.85):** UI-Bugs behoben (loadItems, Badge-Sichtbarkeit, Journal-Keys). **Nachfixe (0.8.86):** `download_exercise_media_file` gibt HTTP 451 für Legal-Hold-Assets zurück; `enrich_exercise_detail` liefert `asset_legal_hold_active` mit; `ExerciseMediaEmbed` + `ExerciseMediaThumbTile` + `ExerciseFormPage` zeigen Placeholder statt Datei; Medienliste (`list_media_assets`) nur noch für Superadmin mit Legal-Hold-Einträgen (nicht mehr alle Plattform-Admins). |
| **Verweise** | `docs/compliance-audit.md` §9.2, §16 (MITT-02), §17; `docs/compliance-implementation.md` §P-11; `backend/media_legal_hold.py`; `backend/routers/media_assets.py` (admin_legal_hold_router); `backend/routers/exercises.py` (download_exercise_media_file, enrich_exercise_detail); `backend/migrations/051_legal_hold.sql`; `backend/tests/test_p11_legal_hold.py`; `frontend/src/components/ExerciseMediaEmbed.jsx`; `frontend/src/components/ExerciseMediaThumbTile.jsx` |
| **Hinweise** | Orthogonal zum normalen Papierkorb-Lifecycle (P-03). `rights_status='blocked'` wird als Schnell-Spiegel gesetzt und bei Aufhebung basierend auf vorhandenen Deklarationen wiederhergestellt. Dateiauslieferung über den exercise-Media-Endpoint gibt HTTP 451 zurück — keine Umgehung über direkten Download. Scope abgegrenzt: P-13 (Meldeverfahren), P-14 (DSA-Transparenz), P-15 (DSA-Moderationslog), P-16 (DSA-Beschwerdeweg) bleiben eigene Pakete. |
---
### P-12 – sessionStorage bei Logout bereinigen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | sessionStorage bei Logout bereinigen |
| **Findings** | MITT-05 |
| **Etappe** | 2 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt 2026-05-10, Version 0.8.68. `logout()` in `AuthContext.jsx` löscht jetzt alle `sj_coach_*`-Schlüssel via Präfix-Iteration. Gezielte Löschung (kein `sessionStorage.clear()`), fremde Schlüssel bleiben erhalten. Playwright-Test ergänzt in `tests/dev-smoke-test.spec.js`. |
| **Verweise** | `docs/compliance-audit.md` §5.6, §16 (MITT-05), §17; `docs/compliance-implementation.md` §P-12; `frontend/src/context/AuthContext.jsx`; `tests/dev-smoke-test.spec.js` |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-22 – HTML-Sanitizer für Rich-Text-Felder
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | HTML-Sanitizer für Rich-Text-Felder (bleach/nh3 Allowlist) |
| **Findings** | NIED-09, SEC-11 |
| **Etappe** | 2 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. `exercise_rich_text.py` normalisiert nur Inline-Media-Markup. Beliebiges HTML in `summary`, `goal`, `execution`, `preparation`, `trainer_notes` möglich. CSP schützt gegen Script-Execution. |
| **Verweise** | `docs/compliance-audit.md` §13.3 (SEC-11), §13.2 (NIED-09), §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-23 – LoginPage: minLength angleichen + Versionsstring entfernen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | LoginPage: minLength angleichen und hartcodierten Versionsstring entfernen |
| **Findings** | NIED-06, NIED-07, SEC-12, SEC-13 |
| **Etappe** | 2 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `minLength="6"` → `"8"`; Versionsstring `v0.1.0 • Development` entfernt. |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-12, SEC-13, NIED-06, NIED-07), §17; `docs/compliance-implementation.md` §P-23 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-24 – CORS einschränken
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | CORS allow_methods und allow_headers auf tatsächlich benötigte Werte einschränken |
| **Findings** | NIED-08, SEC-14 |
| **Etappe** | 2 |
| **Status** | ✅ implemented |
| **Letzter Stand** | Umgesetzt in Version 0.8.66. `allow_methods=["GET","POST","PUT","PATCH","DELETE","OPTIONS"]`; `allow_headers=["Content-Type","X-Auth-Token","X-Active-Club-Id"]`. |
| **Verweise** | `docs/compliance-audit.md` §13.3, §17; `docs/compliance-implementation.md` §P-24 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
## Etappe 3 – DSA-Meldeverfahren
### P-13 – Content-Melde-Backend
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Content-Melde-Backend (content_reports-Tabelle + Endpoints) |
| **Findings** | KRIT-03 |
| **Etappe** | 3 → B (vorgezogen; → `docs/compliance-roadmap.md` §4) |
| **Status** | ✅ implemented |
| **Letzter Stand** | Vollständig umgesetzt in Version 0.8.87 (Kernum­setzung) + 0.8.88–0.8.94 (Erweiterungen + CI-Fix). **Kernum­setzung (0.8.87):** Migration 052 (`content_reports`-Tabelle, Indizes); `POST /api/content-reports` (optionale Auth, official-Medien ohne Login, good_faith_confirmed-Pflicht, auto-Priorisierung); `GET /api/me/inbox/content-reports` (Plattform-Admin, JOIN auf Zieltabellen); `GET /api/content-reports/{id}`; `PATCH /api/content-reports/{id}` (Status/Notiz/Zuweisung, resolution_note Pflicht für Abschluss-Status); `POST /api/content-reports/{id}/legal-hold` (Superadmin, P-11 set_legal_hold(), reason_code-Mapping, setzt Status auf resolved_legal_hold). Inbox-Integration in `InboxPage.jsx`; `ReportContentModal.jsx` + `MediaPreviewModal.jsx` (geteilt). 15 Backend-Unit-Tests. **Erweiterungen (0.8.88–0.8.94):** Migration 053 (content_report_filed Event-Typ im Audit-Log CHECK-Constraint); E-Mail-Benachrichtigungen nach Meldungseingang (Bestätigung an Melder + alle Plattform-Admins, best-effort); Audit-Log-Einträge bei Meldungseingang, Statuswechsel, reinen Notizänderungen; deutsche Labels (REASON_LABELS_DE, STATUS_LABELS_DE); Club-Admin-Berechtigung (sieht und bearbeitet Meldungen zu Medien eigener Vereine; Legal Hold auf nicht-offizielle Vereinsmedien); frühzeitige 403 für plain Admin in set_legal_hold_from_report (vor DB-Zugriff); Wiedereröffnen einer Meldung (status=submitted setzt reviewed_by/at zurück); WorkflowBar (3-Schritte-Fortschrittsbalken) in InboxPage; Archiv-Trennung (offene vs. abgeschlossene Meldungen, kollabierbar); open_report_count-Badge auf Medienkarten (MediaLibraryPage); Journal-Eintrag content_report_filed in MediaLibraryPage; isClubAdmin/isPlatformAdmin/contentReportsError in OrgInboxContext; onSuccess-Callback in ReportContentModal. **CI-Fix (0.8.94):** 3 pytest-Tests repariert; alle 15 Tests grün. |
| **Verweise** | `docs/compliance-audit.md` §12, §17; `backend/migrations/052_content_reports.sql`; `backend/migrations/053_content_report_audit_event.sql`; `backend/routers/content_reports.py`; `backend/routers/media_assets.py`; `backend/tests/test_p13_content_reports.py`; `frontend/src/pages/InboxPage.jsx`; `frontend/src/context/OrgInboxContext.jsx`; `frontend/src/pages/MediaLibraryPage.jsx`; `frontend/src/components/ReportContentModal.jsx`; `frontend/src/components/MediaPreviewModal.jsx`; `frontend/src/utils/api.js` |
| **Hinweise** | Architekturentscheidung: Die bestehende Admin-Inbox (`InboxPage.jsx`) wurde um einen zweiten Abschnitt erweitert statt einer separaten Moderations-Queue. Club-Admin-Rechte sind bewusst auf Vereinsmedien (nicht official) beschränkt. P-14 (Moderations-UI), P-15 (Uploader-Benachrichtigung bei Sperrung — SMTP vorhanden), P-16 (Beschwerdeverfahren) folgen in Etappe D. |
---
### P-14 – Moderations-UI
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Moderations-UI (Frontend für Moderation-Queue) |
| **Findings** | KRIT-03 |
| **Etappe** | 3 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Abhängig von P-13. |
| **Verweise** | `docs/compliance-audit.md` §12, §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-15 – Uploader-Benachrichtigung bei Sperrung
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Uploader-Benachrichtigung bei Sperrung oder Löschung |
| **Findings** | KRIT-03 |
| **Etappe** | 3 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Kein Benachrichtigungssystem vorhanden. |
| **Verweise** | `docs/compliance-audit.md` §9.2, §12, §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-16 – Beschwerdeverfahren
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Beschwerdeverfahren (Nutzer-Rechtsbehelfsweg gegen Moderationsentscheidungen) |
| **Findings** | KRIT-03 |
| **Etappe** | 3 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Abhängig von P-13–P-15. |
| **Verweise** | `docs/compliance-audit.md` §12, §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
## Etappe 4 – Langfristige Optimierungen
### P-17 – MFA für Superadmins (TOTP)
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | MFA für Superadmins (TOTP-Zweifaktorauthentifizierung) |
| **Findings** | HOCH-04, SEC-06 |
| **Etappe** | 4 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Kein TOTP/OTP implementiert. |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-06), §16 (HOCH-04), §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-18 – HttpOnly-Cookie als Auth-Alternative
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | HttpOnly-Cookie als Auth-Alternative (XSS-Schutz für Auth-Token) |
| **Findings** | HOCH-03, SEC-02 |
| **Etappe** | 4 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Auth-Token liegt weiterhin in `localStorage`. Größere Architekturänderung erforderlich. |
| **Verweise** | `docs/compliance-audit.md` §10.3, §13.2 (SEC-02), §17 |
| **Hinweise** | **Drift-Hinweis:** In `docs/compliance-implementation.md` (vor Korrektur 2026-05-10) wurde der Inhalt „HttpOnly-Cookie-Migration" fälschlich P-11 zugeordnet. Der korrekte Titel gehört zu P-18. Korrigiert in `docs/compliance-implementation.md`. |
---
### P-19 – Anti-Virus-Scan (ClamAV)
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Anti-Virus-Scan für Uploads (ClamAV oder vergleichbar) |
| **Findings** | NIED-02, SEC-10 |
| **Etappe** | 4 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Hoher Aufwand, Risiko bei lokalem Storage gering. |
| **Verweise** | `docs/compliance-audit.md` §13.2 (SEC-10), §16 (NIED-02), §17 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-20 – VVT erstellen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | Verzeichnis der Verarbeitungstätigkeiten (VVT) erstellen (DSGVO Art. 30) |
| **Findings** | MITT-03 |
| **Etappe** | 4 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Betreiber-Aufgabe. Identifizierte Verarbeitungsvorgänge in `docs/compliance-audit.md` §11.1. |
| **Verweise** | `docs/compliance-audit.md` §11.1, §17, §19.6 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
### P-21 – AV-Verträge abschließen
| Feld | Inhalt |
|------|--------|
| **Kanonischer Titel** | AV-Verträge mit Auftragsverarbeitern abschließen (SMTP, MediaWiki, OpenRouter) |
| **Findings** | MITT-04, MITT-07, MITT-08 |
| **Etappe** | 4 |
| **Status** | ❌ open |
| **Letzter Stand** | Nicht umgesetzt. Betreiber-Aufgabe. Drei identifizierte Auftragsverarbeiter ohne Vertrag. |
| **Verweise** | `docs/compliance-audit.md` §11.3, §17, §19.6 |
| **Hinweise** | Keine Nummerierungsabweichung festgestellt. |
---
## Übersichtstabelle aller Pakete
| ID | Kanonischer Titel | Etappe | Findings | Status |
|----|------------------|--------|----------|--------|
| P-01 | Rechtstexte | 1 | KRIT-01 | ⚠️ partially implemented |
| P-02 | Self-Service-Kontolöschung + Datenexport | 1 | KRIT-02, KRIT-05 | ❌ open |
| P-03 | Papierkorb-Retention-Job aktivieren | 1 | KRIT-07 | ✅ implemented |
| P-03b | _Nacharbeit:_ Retention-Zeiten mit Löschkonzept abgleichen | — | — | ✅ implemented |
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | 1 | KRIT-06 | ✅ implemented |
| P-05 | Passwort-Mindestlänge angleichen | 1 | MITT-01, SEC-04, SEC-12, NIED-06 | ✅ implemented |
| P-05b | _Nacharbeit:_ reset-password Mindestlänge | — | — | ✅ implemented |
| P-06 | Upload-Einwilligungsdialog | 1 | KRIT-04 | ⚠️ teilweise (KRIT-04 offen) |
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Test | 2 | HOCH-01, SEC-05 | ✅ implemented |
| P-08 | HSTS / externe Proxy-Sicherheit dokumentieren | 2 | HOCH-02, SEC-01 | ❌ open |
| P-09 | Admin-Audit-Log | 2 | HOCH-05, SEC-07 | ❌ open |
| P-10 | Mindestalter-Abfrage | 2 | HOCH-06 | ❌ open |
| P-11 | Legal-Hold Lifecycle-Status | 2 | MITT-02 | ✅ implemented |
| P-12 | sessionStorage bei Logout bereinigen | 2 | MITT-05 | ✅ implemented |
| P-13 | Content-Melde-Backend | 3→B | KRIT-03 | ✅ implemented |
| P-14 | Moderations-UI | 3 | KRIT-03 | ❌ open |
| P-15 | Uploader-Benachrichtigung bei Sperrung | 3 | KRIT-03 | ❌ open |
| P-16 | Beschwerdeverfahren | 3 | KRIT-03 | ❌ open |
| P-17 | MFA für Superadmins (TOTP) | 4 | HOCH-04, SEC-06 | ❌ open |
| P-18 | HttpOnly-Cookie als Auth-Alternative | 4 | HOCH-03, SEC-02 | ❌ open |
| P-19 | Anti-Virus-Scan (ClamAV) | 4 | NIED-02, SEC-10 | ❌ open |
| P-20 | VVT erstellen | 4 | MITT-03 | ❌ open |
| P-21 | AV-Verträge abschließen | 4 | MITT-04, MITT-07, MITT-08 | ❌ open |
| P-22 | HTML-Sanitizer für Rich-Text-Felder | 2 | NIED-09, SEC-11 | ❌ open |
| P-23 | LoginPage: minLength angleichen + Versionsstring entfernen | 2 | NIED-06, NIED-07, SEC-12, SEC-13 | ✅ implemented |
| P-24 | CORS einschränken (Methoden + Header) | 2 | NIED-08, SEC-14 | ✅ implemented |
---
## Fortschritt
**Implementiert (vollständig):** P-03, P-03b, P-04, P-05, P-05b, P-07, P-11, P-12, P-13, P-23, P-24 — 11 Pakete (inkl. 2 Nacharbeiten)
**Teilweise implementiert:** P-01 (technischer Teil vollständig inkl. P-01b, P-01c, copy-as-draft, jsPDF; juristische Inhalte offen) — 1 Paket
**Teilweise umgesetzt (KRIT offen):** P-06 (Upload-Einwilligungsdialog inkl. P-06+ Volljournal + Korrektur — KRIT-04 bis juristische Validierung ausstehend)
**Offen:** P-02, P-08, P-09, P-10, P-14, P-15, P-16, P-17, P-18, P-19, P-20, P-21, P-22 — 13 Pakete
**App-Version bei letzter Aktualisierung:** 0.8.94
**Letztes Umsetzungsdatum:** 2026-05-11
---
*Erstellt: 2026-05-10 | Quelle: `docs/compliance-audit.md` (Initial-Audit 2026-05-09) | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
+364
View File
@@ -0,0 +1,364 @@
# Compliance-Roadmap – Shinkan Jinkendo
**Typ:** Lebendes Steuerungsdokument
**Erstellt:** 2026-05-10
**App-Version:** 0.8.94
**Zuletzt aktualisiert:** 2026-05-11
---
## 1. Zweck und Geltung
Dieses Dokument steuert die aktuelle Priorisierung, Release-Readiness und nächste Freigabeschritte für das Compliance-Programm. Es ersetzt **keines** der folgenden Dokumente, sondern ergänzt sie:
| Dokument | Rolle |
|----------|-------|
| `docs/compliance-audit.md` | Historischer Initialbefund (unveränderlich als Quelle) |
| `docs/compliance-package-register.md` | Kanonische Quelle für Paket-IDs und aktuellen Paketstatus |
| `docs/compliance-implementation.md` | Chronologischer Umsetzungsnachweis |
| **`docs/compliance-roadmap.md`** | **Aktuelle Prioritäten, Release-Gates, nächste Freigaben** |
**Bindungsregeln:**
- Paket-IDs → immer aus dem Paketregister
- Historische Findings und Severity-Einstufungen → immer aus dem Initial-Audit
- Aktuelle Reihenfolge und Freigabeempfehlungen → **dieses Dokument**
Diese Roadmap ist nach jedem Re-Audit zu aktualisieren. Abweichungen von der bisherigen Priorität werden mit Datum und Begründung dokumentiert (→ §4, §10).
---
## 2. Aktueller Stand (2026-05-11)
### App-Version: 0.8.94
### Teilweise umgesetzte Pakete
| ID | Titel | Version | Offen |
|----|-------|---------|-------|
| P-01 | Rechtstexte | 0.8.74 | Juristische Inhalte — Betreiber + Rechtsanwalt |
| P-06 | Upload-Einwilligungsdialog + P-06+ Volljournal + Korrektur | 0.8.83 | KRIT-04: Juristische Validierung (§22 KUG, §8 DSGVO, Widerrufsrecht, Texte p06-v1-conservative) |
### Vollständig geschlossene Pakete
| ID | Titel | Version |
|----|-------|---------|
| P-03 | Papierkorb-Retention-Job aktivieren | 0.8.66 |
| P-03b | _Nacharbeit:_ Retention-Zeiten 30+30 Tage | 0.8.67 |
| P-04 | Copyright-Pflicht für Archiv-Promotion vereinheitlichen | 0.8.66 |
| P-05 | Passwort-Mindestlänge angleichen (alle Endpoints) | 0.8.66–0.8.67 |
| P-05b | _Nacharbeit:_ reset-password Mindestlänge | 0.8.67 |
| P-07 | ALLOW_PUBLIC_MEDIA_STATIC dokumentieren + Release-Test | 0.8.66 |
| P-12 | sessionStorage bei Logout bereinigen | 0.8.68 |
| P-23 | LoginPage: minLength angleichen + Versionsstring entfernen | 0.8.66 |
| P-24 | CORS einschränken (Methoden + Header) | 0.8.66 |
| P-01b | _Nacharbeit:_ Mobile/PWA-Erreichbarkeit Rechtstexte via `/settings/legal` | 0.8.70 |
| P-01c | _Nacharbeit:_ Admin-konfigurierbare Rechtstexte (DB 047, Superadmin-UI, API) | 0.8.71 |
| P-01c+ | _Erweiterung:_ Als-Entwurf-kopieren (`copy-as-draft`) | 0.8.72 |
| P-01c++ | _Erweiterung:_ Echter PDF-Download (jsPDF) + Abschnitts-Sortierung/-Einfügen | 0.8.74 |
| P-13 | Content-Melde-Backend + Erweiterungen (Audit-Log, E-Mail, Club-Admin, Workflow) | 0.8.87–0.8.94 |
**Vollständig abgeschlossen:** 10 Hauptpakete + 4 Nacharbeiten + 2 Erweiterungen = 16 Umsetzungseinheiten (P-13 inkl. umfangreicher Nachfixe 0.8.88–0.8.94)
**Teilweise umgesetzt (technisch):** P-01, P-06
### Offene Pakete (13)
P-02, P-08, P-09, P-10, P-14, P-15, P-16, P-17, P-18, P-19, P-20, P-21, P-22
### Gesamtstatus
> **⛔ Nicht öffentlich freigabefähig**
**Begründung:** Die App kann im aktuellen Zustand nicht für allgemeine öffentliche Registrierung beworben oder aktiv vermarktet werden. Folgende zwingende Voraussetzungen fehlen noch:
1. **P-01:** Kein Impressum, keine Datenschutzerklärung, keine AGB. Eine öffentlich erreichbare App ohne Impressum ist eine Ordnungswidrigkeit nach § 5 DDG.
2. **P-06:** Keine Einwilligungserklärung beim Medienupload. Personenbilder können ohne jede Rechteabklärung hochgeladen werden.
3. **P-02:** Nutzer können ihr Konto nicht selbst löschen (DSGVO Art. 17). Der Prozess ist noch nicht einmal fachlich spezifiziert.
4. ~~**P-13:** Keine Möglichkeit, rechtswidrige Inhalte zu melden.~~ ✅ **Implementiert (v0.8.87).** Content-Melde-Backend umgesetzt: POST `/api/content-reports`, Admin-Inbox-Integration, P-11 Legal-Hold-Anbindung.
5. ~~**P-11:** Kein Legal-Hold-Status.~~ ✅ **Implementiert (v0.8.84).**
**Was geöffnet bleiben kann (mit Dokumentation):** Vereinsinterne Nutzung durch bekannte Trainer-Gruppen ist mit dem aktuellen Stand vertretbar, solange keine öffentliche Vermarktung stattfindet und kein `official`-Content aktiviert wird.
---
## 3. Aktuelle Blocker vor öffentlichem Betrieb
Die folgenden Pakete sind vor der Freigabe für allgemeine öffentliche Registrierung zwingend zu adressieren. Die Reihenfolge entspricht der in §5 definierten Umsetzungsreihenfolge.
### Blocker 1 — P-01: Rechtstexte
**Finding:** KRIT-01 (Ordnungswidrigkeit, § 5 DDG)
**Technischer Stand:** ⚠️ Vollständige technische Infrastruktur vorhanden (Version 0.8.74):
- Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`, `/medienrichtlinie` öffentlich ohne Auth erreichbar (P-01, 0.8.69)
- Mobile/PWA-Erreichbarkeit via `/settings/legal` (P-01b, 0.8.70)
- Admin-konfigurierbare Rechtstexte: DB-Versionierung, Publish/Archive-Workflow, Superadmin-UI `/admin/legal-documents` (P-01c, 0.8.71)
- Als-Entwurf-kopieren: Bestehendes Dokument als Basis für neue Version übernehmen (0.8.72)
- Echter PDF-Download via jsPDF (direkter Dateidownload, kein Druckdialog), Abschnitte sortieren (▲/▼) und an beliebiger Stelle einfügen (0.8.74)
**Warum noch offen:** Impressum, Datenschutzerklärung und AGB ohne juristisch geprüfte Inhalte genügen der gesetzlichen Pflicht nicht. Die Superadmin-UI bietet alle Werkzeuge zum Einpflegen, Versionieren und Veröffentlichen von Texten — sobald Inhalte vorliegen, verschwindet der Platzhalter-Banner automatisch.
**Nächster Schritt:** Rechtsanwalt beauftragen → Inhalte über `/admin/legal-documents` einpflegen → Veröffentlichen → Platzhaltermarkierung verschwindet automatisch.
### Blocker 2 — P-06: Upload-Einwilligungsdialog
**Finding:** KRIT-04 (§22 KUG, §8 DSGVO)
**Warum zwingend:** Jeder hochgeladene Bildinhalt mit erkennbaren Personen ist ohne dokumentierte Einwilligung rechtlich problematisch. Das Risiko besteht nicht erst bei öffentlichen Inhalten — es beginnt beim Upload.
**Technischer Stand:** ⚠️ Vollständig technisch umgesetzt (v0.8.83):
- **P-06a–P-06d (v0.8.75):** Deklarations-Log, Backend-Enforcement, `RightsDeclarationDialog.jsx`, 3 neue Admin-Endpoints, Altbestand-Indikator, 25 Backend-Tests
- **P-06+ Volljournal + Korrektur (v0.8.83):** Vollständiger Audit-Log (`media_asset_audit_log`) für alle Asset-Änderungen; Journal-Endpoint (`events[]` chronologisch); Korrektur-Endpoint für nachträgliche Deklarations-Korrekturen; Zugriff Superadmin + Uploader + Vereins-Admin
**Warum noch KRIT-04 offen:** Juristische Validierung der Einwilligungsformulierungen (§7.7), KUG-Anforderungen im Vereinskontext (§7.2), Minderjährigenschutz (§7.4) und Altbestand-Behandlung (§7.8) steht aus. Texte sind Arbeitsfassungen (`p06-v1-conservative`) ohne anwaltliche Freigabe.
**Nächster Schritt:** Rechtsanwalt für juristische Prüfung der Feldtexte (T1–T10 in `docs/p06-upload-rights-spec.md` §10.3) und der offenen KUG/DSGVO-Fragen beauftragen. Nach Klärung: Textfreigabe eintragen → KRIT-04 kann geschlossen werden.
### ~~Blocker 3 — P-11: Legal-Hold Lifecycle-Status~~ ✅ Implementiert (v0.8.84–0.8.86)
**Finding:** MITT-02
**Abgeschlossen:** 2026-05-11. Migration 051, `media_legal_hold.py`, Retention-Schutz, Superadmin-API + Frontend (0.8.84); UI-Bugfixes (0.8.85); vollständige Auslieferungssperre (`download_exercise_media_file` HTTP 451), Frontend-Placeholder in allen Übungskomponenten, Medienliste nur noch für Superadmin mit Legal-Hold-Einträgen (0.8.86). Details: `docs/compliance-package-register.md` §P-11.
### ~~Blocker 3 (neu) — P-13: Content-Melde-Backend (Minimalversion)~~ ✅ Implementiert (v0.8.87)
**Finding:** KRIT-03
**Abgeschlossen:** 2026-05-11. Migration 052 (`content_reports`); `POST /api/content-reports` (optionale Auth, official-Medien ohne Login meldbar); `GET /api/me/inbox/content-reports` (Plattform-Admin); `PATCH /api/content-reports/{id}`; `POST /api/content-reports/{id}/legal-hold` (Superadmin, P-11-Integration, reason_code-Mapping). Inbox-Erweiterung `InboxPage.jsx` mit zweitem Abschnitt „Inhaltsmeldungen". Keine separate Moderations-Queue — bestehende Admin-Inbox erweitert. 15 Backend-Unit-Tests. Details: `docs/compliance-package-register.md` §P-13.
### Blocker 5 — P-02: DSGVO-Self-Service (fachliche Spezifikation zuerst)
**Finding:** KRIT-02, KRIT-05
**Warum zuerst spezifizieren, dann umsetzen:** P-02 berührt Kontolöschung, Medienarchiv, Vereinsinhalte, Backups und Fristen. Eine voreilige Implementierung riskiert unvollständige oder juristisch falsche Umsetzung. → Erst spezifizieren (→ §5 Etappe C), dann freigeben.
**Juristisch zu klären:** Anonymisierung vs. Löschung bei Vereinsinhalten; Backup-Retention-Policy.
### Blocker 6 — P-08: HSTS-Betriebsnachweis (Betreiber-Aufgabe)
**Finding:** HOCH-02, SEC-01
**Status:** Außerhalb des Repo-Scopes. HSTS muss am externen Reverse-Proxy (Fritz!Box → Synology → Nginx) konfiguriert sein.
**Anforderung:** Vor öffentlichem Betrieb: manueller Nachweis (z. B. `curl -I https://shinkan.jinkendo.de` zeigt `Strict-Transport-Security`-Header).
**Nicht im Code zu lösen** — aber als Release-Gate dokumentiert (→ §7).
---
## 4. Abweichungen gegenüber der ursprünglichen Audit-Reihenfolge
### P-13 wird vorgezogen (Etappe 3 → Etappe B)
Das Initial-Audit (`docs/compliance-audit.md` §17) ordnete P-13–P-16 (DSA-Meldeverfahren) in Etappe 3 ein, nach den Sicherheits- und Datenschutzpaketen von Etappe 2. Die Begründung war: juristische Klärung des DSA-Anwendungsbereichs zuerst.
**Aktuelle Einschätzung (2026-05-10):** Diese Reihenfolge bleibt für den vollen DSA-Stack (P-14–P-16) richtig. Für den Kern von P-13 — die technische Möglichkeit, eine Inhaltsmeldung abzugeben und zu bearbeiten — ist eine Vorziehung geboten, weil:
- Die App erlaubt bereits jetzt Upload und Anzeige von Nutzerinhalten mit `official`-Sichtbarkeit
- Das Risiko ungemeldeter Rechtsverletzungen ist kein langfristiges, sondern ein unmittelbares
- Die juristische DSA-Bewertung (ab welcher Nutzerzahl, welche Pflichten) bleibt offen — sie entscheidet über den Umfang, nicht über das Ob einer Grundfähigkeit
- Eine minimale Melde-Queue kostet weniger als P-14–P-16 zusammen und schafft handlungsfähige Grundstruktur
**Keine ID-Änderung:** P-13 bleibt P-13. Die Neuprioritisierung ist eine Planungsentscheidung, keine inhaltliche Änderung des Pakets.
### P-22 (HTML-Sanitizer) bleibt in Etappe D
Das Initial-Audit platzierte P-22 in Etappe 2. Die aktuelle Einschätzung: CSP `script-src 'self'` reduziert das XSS-Risiko für eingeloggte Nutzer erheblich. Das Risiko ist real, aber kein harter Blocker vor öffentlichem Betrieb im Vergleich zu P-01, P-06, P-11, P-13. P-22 bleibt auf der Roadmap, wird aber nicht als Release-Gate behandelt.
---
## 5. Aktuell empfohlene Umsetzungsreihenfolge
### ✅ Etappe A – Abgeschlossen (2026-05-10, Version 0.8.68)
| Paket | Titel | Aufwand | Status |
|-------|-------|---------|--------|
| P-12 | sessionStorage bei Logout bereinigen | ~15 min | ✅ umgesetzt |
**Abschluss:** P-12 wurde am 2026-05-10 in Version 0.8.68 umgesetzt. `logout()` in `AuthContext.jsx` löscht alle `sj_coach_*`-Schlüssel via Präfix-Iteration. Playwright-Test verifiziert. MITT-05 geschlossen.
---
### Etappe B – Technische Grundlagen für öffentlichen Betrieb
Reihenfolge innerhalb der Etappe ist flexibel; P-01 und P-06 haben keine gegenseitige Abhängigkeit.
| Paket | Titel | Aufwand | Abhängigkeit | Freigabe-Formulierung |
|-------|-------|---------|-------------|----------------------|
| P-01 | Rechtstexte technisch anlegen (Platzhalter-Seiten, Routen) | 2–4 h Technik | Inhalt durch Rechtsanwalt separat | „Freigabe zur Umsetzung P-01: Rechtstexte" |
| P-06 | Upload-Einwilligungsdialog | 2–4 Tage | — | „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog" |
| ~~P-11~~ | ~~Legal-Hold Lifecycle-Status~~ | — | ✅ implementiert (v0.8.84) | — |
| ~~P-13~~ | ~~Content-Melde-Backend (Minimalversion)~~ | — | ✅ implementiert (v0.8.87) | — |
**Hinweis P-01:** Die technische Anlage (leere Seiten, Routen `/impressum`, `/datenschutz`, `/nutzungsbedingungen`) ist von der juristischen Ausarbeitung des Inhalts zu trennen. Beide Teilschritte können unabhängig voneinander freigegeben und durchgeführt werden.
**Hinweis P-13:** ✅ Vollständig implementiert (v0.8.87–0.8.94). Kernum­setzung: `POST /api/content-reports`, `GET /api/me/inbox/content-reports`, `PATCH /api/content-reports/{id}`, `POST /api/content-reports/{id}/legal-hold`. Erweiterungen: Audit-Log (Migration 053), E-Mail-Benachrichtigungen, Club-Admin-Rechte (Vereinsmedien), Workflow-Bar + Archiv-Trennung, Badge auf Medienkarten, CI-Fix (15 Tests grün). Keine separate Moderations-Queue — bestehende Admin-Inbox erweitert. P-14 (Moderations-UI), P-15 (Uploader-Benachrichtigung), P-16 (Beschwerdeverfahren) folgen in Etappe D.
---
### Etappe C – DSGVO-Self-Service sauber spezifizieren (vor Umsetzungsfreigabe)
P-02 erhält eine eigene Spezifikationsphase, bevor eine Umsetzungsfreigabe erteilt wird. Zu klärende Punkte:
| Frage | Entscheidungsträger |
|-------|---------------------|
| Löschung vs. Anonymisierung bei Vereinsinhalten | Betreiber + Rechtsanwalt |
| Verhalten bei Medien, die anderen Vereinen zugeordnet sind | Betreiber + Technik |
| Umgang mit Backups (Retention vs. Löschung auf Antrag) | Betreiber + Rechtsanwalt |
| Fristen: Bearbeitungszeit für Löschanträge | Rechtsanwalt |
| Audit-Log für Löschanträge (wer, wann, was) | Technik |
| Datenexport-Format und Umfang | Technik + Betreiber |
Erst wenn diese Fragen beantwortet und als Spec dokumentiert sind, wird P-02 in Etappe C freigegeben.
---
### Etappe D – Ausbau und langfristige Optimierungen
| Paket | Titel | Aufwand | Priorität |
|-------|-------|---------|-----------|
| P-09 | Admin-Audit-Log | 3–5 Tage | Hoch |
| P-10 | Mindestalter-Abfrage | 1–2 Tage | Mittel |
| P-14 | Moderations-UI (Frontend) | 3–5 Tage | Mittel (nach P-13) |
| P-15 | Uploader-Benachrichtigung bei Sperrung | 1–2 Tage | Mittel (nach P-13) |
| P-16 | Beschwerdeverfahren | 2–4 Tage | Niedrig (nach P-15) |
| P-08 | HSTS-Dokumentation / Betriebsnachweis | Betreiber | Hoch (Release-Gate) |
| P-22 | HTML-Sanitizer für Rich-Text-Felder | 1–2 Tage | Mittel |
| P-20 | VVT erstellen | Betreiber | Hoch |
| P-21 | AV-Verträge abschließen | Betreiber | Hoch |
| P-02 | Self-Service-Kontolöschung + Datenexport | 5–8 Tage | Hoch (nach Spezifikation Etappe C) |
| P-17 | MFA für Superadmins (TOTP) | 5–8 Tage | Mittel |
| P-18 | HttpOnly-Cookie als Auth-Alternative | 3–5 Tage | Niedrig |
| P-19 | Anti-Virus-Scan (ClamAV) | 3–5 Tage | Niedrig |
---
## 6. Nächste empfohlene Freigabe
**P-01 + P-01b + P-01c technisch vollständig umgesetzt (Version 0.8.74).** Rechtstexte über Login, Desktop-Sidebar und Einstellungen → Rechtliches (Mobile/PWA) erreichbar. Superadmin kann über `/admin/legal-documents` versionierte Rechtstexte anlegen, bearbeiten (inkl. Abschnitts-Sortierung und Einfügen an beliebiger Stelle), als Entwurf kopieren, veröffentlichen und als PDF herunterladen — sobald Inhalte eingepflegt sind, verschwindet der Platzhalter-Banner automatisch. Juristische Inhalte bleiben offen (Betreiber + Rechtsanwalt).
Die nächste technische Freigabe sollte **Etappe B** umfassen — beginnend mit P-06:
**P-06 Spezifikation vorhanden** (`docs/p06-upload-rights-spec.md`, 2026-05-10). Die Umsetzung setzt die Entscheidung über 12 juristische Klärungspunkte voraus (§22 KUG im Vereinskontext, §8 DSGVO Minderjährigenschutz, Widerrufsrecht, Speicherfristen für Einwilligungen). Erst nach dieser Klärung:
> „Freigabe zur Umsetzung P-06: Upload-Einwilligungsdialog"
oder als Paket (nach Klärung P-06):
> „Freigabe zur Umsetzung Etappe B: P-06, P-11, P-13"
**Parallel dazu Betreiber-Aufgabe:**
Rechtsanwalt für die Ausarbeitung der Inhalte von P-01 beauftragen — Inhalte über `/admin/legal-documents` einpflegen und veröffentlichen. Dies ist eine Betreiber-Aufgabe, keine weitere technische Freigabe.
**Nach P-01 vollständig (Inhalte eingepflegt):** Gate 1 rückt näher — verbleibende Blocker: P-06, P-02 (Spez.), P-11, P-13, P-08 (Betreiber).
---
## 7. Release-Gates
### Gate 1 — Öffentliche allgemeine Registrierung freischalten
Folgende Bedingungen müssen **alle** erfüllt sein:
| Bedingung | Paket | Typ |
|-----------|-------|-----|
| Impressum und Datenschutzerklärung mit juristisch geprüftem Inhalt | P-01 | ⚠️ Routen vorhanden — Inhalte durch Rechtsanwalt erforderlich |
| Upload-Einwilligungsdialog aktiv | P-06 | Code |
| DSGVO-Löschprozess spezifiziert (Spec akzeptiert, auch wenn nicht vollständig implementiert) | P-02 | Spezifikation |
| Legal-Hold-Status vorhanden | P-11 | ✅ Bereits erfüllt (Version 0.8.84–0.8.86) |
| Content-Melde-Backend (Minimalversion) aktiv | P-13 | Code |
| HSTS am externen Reverse-Proxy nachgewiesen | P-08 | Betreiber |
| Papierkorb-Retention-Job läuft (Monitoring aktiv) | P-03 | Bereits erfüllt |
| `ALLOW_PUBLIC_MEDIA_STATIC` nicht in Prod-Env gesetzt | P-07 | Bereits erfüllt |
| sessionStorage bei Logout bereinigt | P-12 | ✅ Bereits erfüllt (Version 0.8.68) |
**Darf bei Gate 1 offen bleiben (mit Dokumentation):**
- P-02 vollständige Implementierung (Spezifikation genügt als Zwischenstand, wenn aktiver Prozess für Löschanfragen per E-Mail dokumentiert ist)
- P-09 Admin-Audit-Log
- P-10 Mindestalter-Abfrage
- P-14–P-16 Moderationsausbau
- P-17 MFA, P-18 HttpOnly-Cookie, P-19 Anti-Virus-Scan
- P-20 VVT (in Erstellung), P-21 AV-Verträge (in Klärung)
---
### Gate 2 — Aktivierung öffentlicher Official-Medien (`visibility = official`)
Bevor Inhalte mit `official`-Sichtbarkeit (plattformweit sichtbar, ohne Login) aktiv eingesetzt werden:
| Bedingung | Paket | Typ |
|-----------|-------|-----|
| Gate 1 vollständig erfüllt | — | Voraussetzung |
| Upload-Einwilligungsdialog für Personenbilder aktiv | P-06 | Code |
| Legal-Hold-Status aktiv (Sofortsperrung möglich) | P-11 | ✅ Bereits erfüllt (Version 0.8.84–0.8.86) |
| Content-Melde-Backend aktiv | P-13 | Code |
| Copyright-Pflicht bei Promotion aktiv und getestet | P-04 | Bereits erfüllt |
| Moderationsprozess organisatorisch dokumentiert (wer, wie schnell, Eskalationspfad) | — | Betreiber |
---
### Gate 3 — Aktivierung öffentlicher Inhalte im Vereinsbereich (`visibility = club`)
Bedingungen für Vereinsinhalte sind weniger streng als für `official`, da der Personenkreis begrenzt ist:
| Bedingung | Status |
|-----------|--------|
| Copyright-Pflicht bei Promotion aktiv | ✅ bereits erfüllt (P-04) |
| Papierkorb-Retention-Job aktiv | ✅ bereits erfüllt (P-03) |
| Upload-Einwilligungsdialog vorhanden | muss mit P-06 kommen |
| Mitgliedschaftsbasierte Zugriffskontrolle funktioniert | ✅ (TenantContext, library_content_visibility_sql) |
---
## 8. Juristisch zu prüfende Punkte
Alle folgenden Punkte erfordern Einschätzung durch einen Rechtsanwalt oder Datenschutzbeauftragten. Keine der nachfolgenden Einschätzungen ist rechtlich verbindlich.
| Thema | Frage | Priorität |
|-------|-------|-----------|
| **Rechtstexte** | Vollständige Angaben Impressum, Datenschutzerklärung, AGB, Medienrichtlinie. Inhalte können nicht technisch generiert werden. | Sofort |
| **DSA-Anwendungsbereich** | Ab welcher Nutzerzahl und unter welchen Voraussetzungen gilt der DSA für diese Plattform? Welche Pflichten für sehr kleine Plattformen? | Vor öffentlichem Betrieb |
| **Einwilligungsmodell Personenbilder** | §22 KUG: Welche Einwilligungen sind für Bilder erkennbarer Personen im Vereinskontext erforderlich? Reicht eine pauschale Upload-Erklärung? | Vor öffentlichem Betrieb |
| **Minderjährigenschutz** | §8 DSGVO: Ab welchem Alter ist keine elterliche Einwilligung nötig? Wie ist mit Bildern Minderjähriger umzugehen? | Vor öffentlichem Betrieb |
| **DSGVO-Löschprozess** | Anonymisierung vs. Löschung bei Vereinsinhalten; Umgang mit Backups; Fristen für Löschanträge (Art. 17) | Vor Implementierung P-02 |
| **Datenübertragbarkeit** | Welcher Exportumfang ist für Art. 20 DSGVO ausreichend? Welches Format? | Vor Implementierung P-02 |
| **AV-Verträge** | Welche Dienstleister benötigen einen AVV (SMTP-Anbieter, MediaWiki, OpenRouter)? | Vor öffentlichem Betrieb |
| **Backup-Retention** | Wie muss die Backup-Retention-Policy aussehen, damit DSGVO-Löschanfragen auch Backups erfassen? | Vor öffentlichem Betrieb |
| **MediaWiki-Lizenz** | Welche Lizenzanforderungen gelten für Übungsinhalte von karatetrainer.net? | Klärenswert |
---
## 9. Betreiber-Aufgaben
Diese Punkte liegen außerhalb des Code-Scopes und erfordern organisatorische Maßnahmen durch den Betreiber:
| Aufgabe | Bezug | Dringlichkeit |
|---------|-------|--------------|
| Rechtsanwalt beauftragen (Rechtstexte, DSA, KUG) | P-01, P-06 | Sofort |
| VVT erstellen (DSGVO Art. 30) | P-20 | Vor öffentlichem Betrieb |
| AV-Verträge klären (SMTP, MediaWiki, OpenRouter) | P-21 | Vor öffentlichem Betrieb |
| HSTS am Reverse-Proxy (Fritz!Box/Synology) konfigurieren und nachweisen | P-08 | Vor öffentlichem Betrieb |
| Backup-Konzept dokumentieren und Restore-Test durchführen | — | Dringend empfohlen |
| Moderationsprozess organisatorisch festlegen: Wer moderiert? Wie schnell? Eskalationspfad? | P-13–P-16 | Vor Aktivierung öffentlicher Inhalte |
| Notfallkontakt für Datenpannen benennen (DSGVO Art. 33) | — | Vor öffentlichem Betrieb |
| Papierkorb-Retention-Job überwachen (`docker logs shinkan-retention-cron`) | P-03 | Laufend |
---
## 10. Aktualisierungsregel
| Anlass | Maßnahme |
|--------|----------|
| Nach jedem Re-Audit | §2 (Aktueller Stand) und §5 (Reihenfolge) aktualisieren |
| Nach jeder Freigabe | Paketregister (`docs/compliance-package-register.md`) aktualisieren; §2 dieser Roadmap anpassen |
| Prioritätsänderung gegenüber bisheriger Roadmap | Datum und Begründung in §4 dokumentieren |
| Neue Paket-IDs | Immer im Initial-Audit + Paketregister vergeben; nie nur in dieser Roadmap |
| Paketstatus | Nie direkt in dieser Roadmap pflegen — immer aus Paketregister übernehmen |
**Diese Roadmap enthält keine eigenständigen Statusangaben.** §2 wird durch Abfrage des Paketregisters befüllt und bei Aktualisierungen synchronisiert.
---
## Anhang: Schnellreferenz Freigabe-Formulierungen
| Freigabe | Formulierung | Status |
|----------|-------------|--------|
| ~~P-12 allein~~ | ~~„Freigabe zur Umsetzung P-12: sessionStorage bei Logout bereinigen"~~ | ✅ historisch abgeschlossen (Version 0.8.68) |
| ~~P-01 technisch~~ | ~~„Freigabe zur Umsetzung P-01: Rechtstexte technisch anlegen"~~ | ✅ historisch abgeschlossen (Version 0.8.69) |
| ~~P-01b~~ | ~~„Freigabe zur Umsetzung P-01b: Mobile/PWA-Zugriff auf Rechtliches"~~ | ✅ historisch abgeschlossen (Version 0.8.70) |
| ~~P-01c~~ | ~~„Freigabe zur Umsetzung P-01c: Admin-konfigurierbare Rechtstexte"~~ | ✅ historisch abgeschlossen (Version 0.8.71); Erweiterungen copy-as-draft (0.8.72) + jsPDF/Sortierung (0.8.74) |
| **P-06** | **„Freigabe zur Umsetzung P-06 auf Basis konservativer Erstannahmen"** | ✅ erteilt + vollständig umgesetzt (2026-05-11, v0.8.75–0.8.83) — technisch umgesetzt unter `p06-v1-conservative` inkl. P-06+ Volljournal + Korrektur; KRIT-04 bleibt bis juristische Validierung |
| **P-11** | **„Freigabe zur Umsetzung P-11: Legal-Hold Lifecycle-Status"** | ✅ vollständig umgesetzt (2026-05-11, v0.8.84–0.8.86) — Migration 051, Retention-Schutz, Superadmin-API + Frontend (0.8.84); UI-Bugfixes (0.8.85); Auslieferungssperre + Frontend-Placeholder + Superadmin-only Medienliste (0.8.86); 15 Backend-Tests |
| ~~P-13~~ | ~~„Freigabe zur Umsetzung P-13: Content-Melde-Backend"~~ | ✅ vollständig umgesetzt (2026-05-11, v0.8.87–0.8.94) — Kernum­setzung + Audit-Log, E-Mail-Benachrichtigungen, Club-Admin-Rechte, Workflow-Management, Badge, CI-Fix; 15 Backend-Tests |
| P-02 Spezifikation | „Freigabe zur Spezifikation P-02: DSGVO-Self-Service-Prozess" | offen |
---
*Erstellt: 2026-05-10 | Quellen: `docs/compliance-audit.md`, `docs/compliance-package-register.md`, `docs/compliance-implementation.md` | Kein Rechtsanwalt; alle rechtlichen Einschätzungen sind juristisch zu prüfen.*
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more