Author SHA1 Message Date
Lars b35a5ae216 Merge pull request 'SplitSession auch für Rahmenprogramme' (#36) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m8s
Reviewed-on: #36
2026-05-16 09:02:51 +02:00
Lars 8c07cf36ee Enhance section movement functionality in TrainingUnitSectionsEditor
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
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
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / k6 /health Baseline (pull_request) Successful in 33s
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
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m14s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Added a new check to prevent section movement across slots that crosses the boundary between 'parallel' and 'whole_group' phases, improving the logic for section management and ensuring valid operations during edits.
2026-05-16 08:09:24 +02:00
Lars f1c470a8a3 Improve section movement validation in TrainingUnitSectionsEditor
Deploy Development / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m12s
- 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
Deploy Development / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m22s
2026-05-16 07:45:53 +02:00
Lars c3eb5a62c4 Update version to 0.8.141 and enhance training plan template handling
Deploy Development / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m13s
- 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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
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
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 20s
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
- Updated CLAUDE.md and PROJECT_STATUS.md to reflect the latest app version (0.8.140) and database schema (20260515063) as of 2026-05-14.
- Enhanced DOMAIN_MODEL.md and PARALLEL_TRAINING_STREAMS_CONCEPT.md to clarify the implementation of phases and parallel streams in training units.
- Improved HANDOVER.md with detailed descriptions of the coaching and breakout functionalities, including rejoin logic and session management.
- Updated FACHLICHE_NUTZERFUNKTIONEN.md to include new features related to training planning and execution, emphasizing the integration of phases and parallel streams.
- Revised FEATURES_DELIVERED_2026-Q2.md to document the latest changes and improvements in the training framework and media management.
2026-05-15 22:11:05 +02:00
Lars bd9cfaa6e4 Merge pull request 'Parlellsession- Plan' (#35) from develop into main
Deploy Production / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m14s
Reviewed-on: #35
2026-05-15 22:04:52 +02:00
Lars a4f11a8225 Enhance TrainingCoachPage and trainingPlanUtils with split rejoin transition logic
Deploy Development / deploy (push) Successful in 39s
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
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m11s
Test Suite / k6 /health Baseline (pull_request) Successful in 34s
Test Suite / playwright-tests (pull_request) Successful in 1m20s
- Introduced a new utility function to determine when to prompt for a split rejoin transition between phases, improving user guidance during training sessions.
- Updated TrainingCoachPage to incorporate this logic, enhancing the flow of navigation through training timelines.
- Refactored button actions to provide clearer options for users when managing group transitions, optimizing the user experience during training.
2026-05-15 18:52:27 +02:00
Lars 5e5350d5ac Enhance TrainingCoachPage and trainingPlanUtils with session storage management and phase handling improvements
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- 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
Deploy Development / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m26s
- 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
Deploy Development / deploy (push) Successful in 44s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m8s
Test Suite / pytest-backend (push) Successful in 41s
Test Suite / lint-backend (push) Successful in 0s
- 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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 11s
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 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
Deploy Development / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / playwright-tests (push) Successful in 1m8s
- 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
Deploy Development / deploy (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m13s
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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 11s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m7s
Test Suite / pytest-backend (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
- Introduced functions to add and manage parallel phases and sections, allowing for more flexible training unit configurations.
- Implemented logic to handle the addition of whole group sections and parallel streams, improving the user experience in the editor.
- Added utility functions for reordering sections and checking for content within parallel stream buckets.
- Updated state management to ensure proper handling of section titles and removal of streams, enhancing overall functionality.
2026-05-15 07:50:16 +02:00
Lars 0a203aaf75 Enhance TrainingUnitSectionsEditor with parallel phase management features
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m10s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
- Introduced logic to limit the number of streams per parallel phase, ensuring compliance with the defined maximum.
- Added utility functions for managing stream indices and visual representation of streams.
- Implemented section movement within parallel streams, allowing for reordering while maintaining stream integrity.
- Updated UI components to reflect changes in stream handling, including disabling buttons when limits are reached.
- Enhanced state management for parallel stream tabs, improving user experience in navigating between streams.
2026-05-15 07:37:51 +02:00
Lars f50e9db523 chore(version): update version and changelog for release 0.8.140
Deploy Development / deploy (push) Successful in 42s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / pytest-backend (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 1m8s
- 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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
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
Deploy Development / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m9s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
- Bumped APP_VERSION to 0.8.138 and updated the changelog to reflect recent changes.
- Enhanced training unit planning with support for POST/PUT requests including phases and parallel streams.
- Fixed role assignment validation for stream co-trainers and added integration tests for phase handling.
- Updated the training planning API to improve data structure and retrieval for nested phases and sections.
2026-05-15 07:04:24 +02:00
Lars 639392e133 Merge pull request 'Bug Fix Dashboard + Performance Phase 3a' (#34) from develop into main
Deploy Production / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m1s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #34
2026-05-14 11:51:53 +02:00
Lars d153a22545 Merge pull request 'Bug Fixing Kombi-Übungen - Performance Update 1 (Phase 0-2)' (#33) from develop into main
Deploy Production / deploy (push) Successful in 43s
Test Suite / build-frontend (push) Successful in 12s
Test Suite / k6 /health Baseline (push) Successful in 32s
Test Suite / pytest-backend (push) Successful in 36s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 58s
Reviewed-on: #33
2026-05-14 09:09:55 +02:00
Lars 81d1e9bdfd Merge pull request 'minor improvements. Darstellung, Handlung, Popups' (#32) from develop into main
Deploy Production / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 12s
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
Lars 3214055531 Merge pull request 'Module und Kombinationsübnungen in Version 0.8' (#31) from develop into main
Deploy Production / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 13s
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
Lars 4c974620d8 Merge pull request 'DGSVO Compliance update 1' (#30) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 12s
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
Lars 3134160003 Merge pull request 'feat(admin): restrict admin access and enhance navigation for superadmins' (#29) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #29
2026-05-09 13:30:32 +02:00
Lars b19940c997 Merge pull request 'Administration für Vereinsadmin, Sperren von Usern, Inbox, Medienmanger für alle, etc.' (#28) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 26s
Reviewed-on: #28
2026-05-09 11:01:02 +02:00
Lars dbc9057601 Merge pull request 'feat(exercises): bump version to 0.8.65 and enhance club media copyright handling' (#27) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #27
2026-05-09 09:05:28 +02:00
Lars 6136813f60 Merge pull request 'feat(clubs): enhance co-trainer ID handling for training groups' (#26) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #26
2026-05-08 13:39:58 +02:00
Lars d82b805ffa Merge pull request 'feat(exercises): update to version 0.8.64 and enhance inline media functionality' (#25) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 31s
Reviewed-on: #25
2026-05-08 13:28:30 +02:00
Lars c8c40474d1 Merge pull request 'Inline Medien' (#24) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #24
2026-05-08 12:39:27 +02:00
Lars f035b5bb0b Merge pull request 'MediaPfad extern, Upload Manager Bug Fixes' (#23) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 35s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Reviewed-on: #23
2026-05-08 11:17:12 +02:00
Lars 696cb09bf4 Merge pull request 'Medienmanager update 1' (#22) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #22
2026-05-07 16:30:20 +02:00
Lars 33fedd5ec6 Merge pull request 'Medienmanager und Sicherheitsupdate' (#21) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #21
2026-05-07 16:00:18 +02:00
Lars c8a08f8a94 Merge pull request 'pre-Prod Alpha' (#18) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Successful in 23s
Reviewed-on: #18
2026-05-07 10:37:21 +02:00
Lars d04ebee1f6 Merge pull request 'UX - Filter' (#12) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Failing after 28s
Reviewed-on: #12
2026-05-06 21:25:56 +02:00
Lars 0c1fbab0ef Merge pull request 'Mandantenfähigkeit V1.1' (#11) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 22s
Test Suite / pytest-backend (push) Successful in 11s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #11
2026-05-05 23:11:49 +02:00
Lars a7d68c0646 Merge pull request 'Mandantenfähigkeit V1' (#10) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Failing after 46s
Reviewed-on: #10
2026-05-05 22:34:25 +02:00
Lars a34dc19f5d Merge pull request 'Trainingsplanung und Rahmenplanung' (#9) from develop into main
Deploy Production / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Failing after 58s
Reviewed-on: #9
2026-05-05 16:05:01 +02:00
Lars 9227b98431 Merge pull request 'feat: enhance MediaWiki integration and error handling in SMW client' (#8) from develop into main
Deploy Production / deploy (push) Successful in 39s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 52s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #8
2026-04-29 13:56:58 +02:00
Lars 390b0ecb73 Merge pull request 'chore: clean up docker-compose files and enhance SQL migration for skills' (#7) from develop into main
Deploy Production / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #7
2026-04-29 13:43:57 +02:00
Lars 7e7adfab54 Merge pull request 'bug fixes' (#6) from develop into main
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 1m29s
Test Suite / lint-backend (push) Successful in 1s
Reviewed-on: #6
2026-04-29 13:37:21 +02:00
Lars bce235b9f6 Merge pull request 'feat: enhance Playwright configuration and CI workflow for E2E testing' (#5) from develop into main
Deploy Production / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Failing after 4s
Reviewed-on: #5
2026-04-29 12:37:28 +02:00
Lars 5334836207 Merge pull request 'feat: enhance database migration handling and health check endpoint' (#4) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #4
2026-04-29 12:31:03 +02:00
Lars 38d78abc3b Merge pull request 'bug fix' (#3) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m59s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #3
2026-04-29 11:54:17 +02:00
Lars a143532486 Merge pull request 'Version 0.1' (#2) from develop into main
Deploy Production / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (push) Failing after 1m53s
Reviewed-on: #2
2026-04-29 11:20:41 +02:00
Lars 2f54fef88e Merge pull request 'feat: update docker-compose and Nginx configuration for improved service dependencies and API routing' (#1) from develop into main
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 1m56s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #1
2026-04-29 08:52:11 +02:00
25 changed files with 5227 additions and 539 deletions

No files matched your search

+14 -10
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-12
**Version (Code):** 0.8.110 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260512057` (`backend/version.py`, DB_SCHEMA_VERSION)
**Stand:** 2026-05-14
**Version (Code):** 0.8.140 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260515063` (`backend/version.py`, DB_SCHEMA_VERSION)
**Branch:** develop
---
@@ -15,7 +15,7 @@
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
@@ -36,7 +36,8 @@
1. Kalender‑UI: „Aus Rahmen übernehmen“ an **`from-framework-slot`** anbinden; ggf. Bulk.
2. Governance: Sichtbarkeit **club/official** für Rahmen so ausprägen, dass andere Trainer kopieren dürfen (Policy + API).
3. Optional Backlog Graph: Alternativgruppen / bessere Visualisierung (**§4**).
4. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
4. **Breakout / Coaching (Arbeitspaket):** Backend-Konsistenz `phases`↔`sections`, Run-UI vs. Spec (Stream-Tabs), Vorlagen phasenfähig, E2E-Smoke — siehe **`docs/HANDOVER.md`** (Tabelle „Coaching & Breakout“).
5. **Kombinationsübungen / Coach (Fachspez § 10.6):** Coach **Stufe B/C** (archetypgesteuerte Durchführung); **Archetyp-Verwaltung** jenseits Code-Konstanten; **Massen-Vorbelegung** aller Slot-Zeit/Anzahl-Felder; **serverseitige** Validierung Profil ↔ Archetyp — siehe `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` (Pakete **4e–4g**) und `COMBINATION_TIMING_PROFILE_PLAN.md`.
---
@@ -92,6 +93,8 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
- [x] **Optionale Zuordnung einer Übungsvariante** pro Eintrag (`exercise_variant_id`)
- [x] **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:**
@@ -155,18 +158,19 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
| Dokument | Pfad | Stand | Status |
|----------|------|-------|--------|
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-12 | neu, Ist-Überblick |
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-12 | Verweis Version siehe `version.py` |
| Fachliche Nutzerfunktionen (Design/Product) | `docs/FACHLICHE_NUTZERFUNKTIONEN.md` | 2026-05-14 | Phasen/Coach/Rejoin |
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-14 | §11a Breakout |
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-05-12 | Verweis Nutzerüberblick |
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-12 | Version 0.4.5, Verweis Nutzerüberblick |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-14 | Parallele Streams Ist 063 |
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-12 | auf 0.8.96 + P-13/P-01 + Nutzerüberblick |
| Parallele Streams (Fach/Technik) | `functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`, `technical/PARALLEL_TRAINING_STREAMS_SPEC.md` | 2026-05-14 | Ist-Stand P1 teils |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-14 | Keyset, KPIs, Breakout/Coach Kurzverweis |
---
@@ -177,4 +181,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
---
**Letzte Aktualisierung:** 2026-05-12 (Version 0.8.96, Executive Summary P-13/P-01, `docs/FACHLICHE_NUTZERFUNKTIONEN.md`)
**Letzte Aktualisierung:** 2026-05-14 (Version 0.8.140, DB 063, Handover Coaching/Breakout)
+4 -6
View File
@@ -474,25 +474,23 @@ skill_level_definitions (
**Konkretisierung (037/API):** `POST /api/training-units/from-framework-slot` legt eine geplante Einheit aus dem Slot‑Blueprint an; **`origin_framework_slot_id`** dient als Herkunftsreferenz (**Lineage light**; weiteres Feedback/Lineage‑Konzept: Konzeptpapier Schritt **E**).
### Parallele Trainingsstreams (Breakout, Entwurf)
### Parallele Trainingsstreams (Breakout)
**Fachlich:** Eine Kalender‑**Einheit** kann aus **Phasen** bestehen — z. B. gemeinsamer Block, dann **beliebig viele parallele** „Teilstrecken“ (**Streams**) mit je eigenem Miniplan (Abschnitte/Übungen), erneut gemeinsamer Block. Das ist **nicht** dasselbe wie ein **Rahmenprogramm‑Slot** (Serien‑Session über Wochen): Slots strukturieren **mehrere Einheiten** in einem Programm; **Streams** strukturieren **gleichzeitige** Abläufe **innerhalb einer** Einheit.
**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`.
**Schema-Hinweis (2026-05):** Tabelle `training_unit_sections` hat **`UNIQUE (training_unit_id, order_index)`** (Migration 031). Damit sind **zwei gleichzeitige „Spuren“ mit jeweils eigener Sektion auf derselben `order_index`** nicht abbildbar — Voraussetzung für Parallele Streams ist eine **geplante Migrations-/Constraint-Anpassung** (partielle Uniques pro Phase/Stream); siehe Arbeitsdokument `.claude/docs/working/PARALLEL_TRAINING_STREAMS_ANALYSIS_AND_IMPLEMENTATION_PLAN.md`. **Keine invasive Migration ohne explizite Freigabe.**
---
## Medien-Archiv & Übungs-Anhänge (Stand 2026-05-07)
- **`media_assets`:** Zentrale Datei-/Asset-Zeile (technisch u. a. SHA‑Dedupe, Sichtbarkeit, `club_id`, Lifecycle, Copyright, Speicherreferenz unter `library/…`). Siehe **`DATABASE_SCHEMA.md`**, **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
- **`exercise_media`:** Verknüpfung **Übung ↔ Asset** (`media_asset_id`) oder **Embed** ohne Asset; Felder wie `context` (`ablauf` \| `detail` \| `trainer_hint`), Sortierung, Primär-Medium.
- **`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.
---
@@ -1,6 +1,6 @@
# Parallele Trainingsstreams (Breakout) — Fachkonzept
**Status:** Entwurf zur Abstimmung · **Stand:** 2026-05-14
**Status:** MVP-Umsetzung **teilweise** (Code) · **Stand:** 2026-05-14
**Ziel:** Planung und Durchführung von Training mit **phasenweise gemeinsamem** Ablauf und **beliebig vielen parallelen Teilstrecken** (Breakout-Sessions), inkl. Sonderfall **rotierende Stationen**.
**Technische Ausarbeitung:** `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`
@@ -95,7 +95,14 @@ Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächste
---
## 8. Verwandte Dokumente
## 9. Umsetzungsstand (kurz, 2026-05-14)
- **Erreicht:** Datenmodell Phasen/Streams (**063**), API **GET/PUT** mit **`phases`**, Planungs-Breakout-UI, Durchführung und Coach nutzen dieselbe Phasen-/Stream-Logik im Frontend (`trainingPlanUtils.js`). **Synchronisationspunkt** fachlich umgesetzt: vor nächster Ganzgruppenphase oder nächstem Split erscheint im Coach die **Rejoin-Karte** (mehrere Streams), sofern nicht am absoluten Planende.
- **Noch offen:** vollständige **Persistenz-Konsistenz** bei nachträglich geänderten Sektionen, **Vorlagen** mit Phasen, **Trainer pro Stream** in der UI, ggf. **Stream-Tabs** in der Durchführungsansicht wie in §5.2 skizziert — siehe **`docs/HANDOVER.md`** (Arbeitspaket-Tabelle).
---
## 10. Verwandte Dokumente
| Dokument | Bezug |
|----------|--------|
@@ -103,4 +110,5 @@ Alle Streams (oder alle Kinder insgesamt) **wechseln gleichzeitig** zur nächste
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombinationsübungen, Archetypen, Stationslogik **im Item** |
| `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 |
@@ -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,7 +169,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
---
## 14. Verweise
## 15. Verweise
| Thema | Dokument |
|--------|----------|
@@ -170,5 +179,7 @@ Einzelnorm: **`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Kurzüberblick gel
| 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` |
@@ -1,23 +1,26 @@
# Parallele Trainingsstreams — Technische Spezifikation (Umsetzung)
**Status:** Entwurf · **Stand:** 2026-05-14
**Status:** Umsetzung **Phase 1 (teils)** · **Stand:** 2026-05-14
**Fachgrundlage:** `.claude/docs/functional/PARALLEL_TRAINING_STREAMS_CONCEPT.md`
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand Analyse 2026-05-14): eine `training_unit` mit **`training_unit_sections`** und **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung **`TrainingUnitRunPage`** (sequentiell über Sektionen).
Dieses Dokument beschreibt die **Umsetzung** auf Basis der **aktuellen Codebasis** (Stand 2026-05-14): **`training_unit_phases` / `training_unit_parallel_streams`** (Migration **063**) und **`training_unit_sections`** mit Phasen-/Stream-Bezug; **`training_unit_section_items`** (Übung/Notiz, optional `planning_method_profile` für Kombinationsübungen, Migration **057**); Rahmen-**Blueprint**-Einheiten mit `framework_slot_id` (**037**); Leitung **`lead_trainer_profile_id`** (**038**); Co-Trainer **`assistant_trainer_profile_ids`** JSONB (**042**); Durchführung und Coaching über **`TrainingUnitRunPage`**, **`TrainingCoachPage`** und **`trainingPlanUtils.js`**.
---
## 1. Ist-Stand (relevant)
## 1. Ist-Stand (Code, 2026-05-14)
| Bereich | Aktuell |
|---------|---------|
| Planstruktur | **Eine** lineare Liste `training_unit_sections` je `training_unit_id`; Items in `training_unit_section_items`. |
| Rahmenprogramm | `training_framework_slots` verweisen auf **Blueprint**-`training_units` — Slots = **Serien-Spalten**, nicht simultane Breakouts in **einer** Halle. |
| Kombinationsübung | Ein **Item** kann Kombi sein; `planning_method_profile` = Snapshot; Coaching-UI teilweise (`CombinationPlanBracket` in Run/Peek). |
| Trainer-Zuweisung | `lead_trainer_profile_id`, `assistant_trainer_profile_ids` am **`training_units`**-Kopf; **keine** Zuordnung zu „welcher parallelen Spur“. |
| Run-Modus | `TrainingUnitRunPage`: sortierte Sektionen/Items, Checkliste, Fortschritt in `sessionStorage` pro Einheit. |
| **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**). |
**Konsequenz:** Parallele Streams erfordern ein **erweitertes konzeptionelles „Gefäß“** unterhalb der Einheit (Phasen und/oder Streams) und eine **Verknüpfung** bestehender Sektionen mit diesem Gefäß — oder eine **Migration** zu einem neuen Pflicht-Container (siehe §3).
**Hinweis:** Die frühere Planungsvariante „nur lineare `training_unit_sections` ohne Phasen“ gilt weiter für Alt-Daten; Migration **063** ordnet Bestand einer Default-Ganzgruppenphase zu.
---
@@ -37,9 +40,11 @@ training_unit (Kalender-Einheit)
## 3. Datenmodell — Optionen
**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)
Neue Tabellen (Namen bei Implementierung final festlegen):
Die Tabellen sind **umgesetzt** (Namen final):
| Tabelle | Zweck |
|---------|--------|
@@ -109,15 +114,15 @@ Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; P
---
## 8. Implementierungsphasen (Vorschlag)
## 8. Implementierungsphasen (Abgleich)
| Phase | Inhalt |
|-------|--------|
| **P1** | Schema Phasen + Streams; Migration; GET/PATCH Einheit verschachtelt; Planungs-UI; Run-UI mit Stream-Tabs |
| **P2** | Trainer-Zuordnung pro Stream + effektive Anzeige; Vorlagen erweitert |
| **P3** | Synchroner Hallen-Takt / Rotationsmatrix (falls fachlich freigegeben) |
| 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
@@ -127,4 +132,5 @@ Nur **`training_unit_parallel_streams`** + `parallel_stream_id` auf Sektionen; P
| `technical/TRAINING_FRAMEWORK_SPEC.md` | Rahmen-Slot vs. Parallelität |
| `technical/TRAINING_MODULES_AND_COMBINATION_EXERCISES_SPEC.md` | Kombi, `planning_method_profile` |
| `technical/DATABASE_SCHEMA.md`, `backend/migrations/` | DDL-Historie |
| `frontend/src/pages/TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Ist-UI |
| `TrainingPlanningPage.jsx`, `TrainingUnitRunPage.jsx`, `TrainingFrameworkProgramEditPage.jsx` | Planung, Durchführung, Rahmen |
| `frontend/src/utils/trainingPlanUtils.js`, `TrainingCoachPage.jsx` | Phasen-Timeline, Rejoin, Coach-Speichern |
+1 -1
View File
@@ -86,7 +86,7 @@ frontend/src/
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
Kurz (Stand 2026-05-12): App **0.8.96**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
Kurz (Stand 2026-05-14): App- und DB-Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text**, **Inhaltsmeldungen (P-13)** im Posteingang, Mandanten-Sync aktiver Verein, Planung mit **Phasen & parallelen Streams (Breakout, 063)**, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, Nutzerüberblick **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`**, `PARALLEL_TRAINING_STREAMS_SPEC.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Abschnitt 11 umgesetzt).
### Log (Auszug)
@@ -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';
+12 -3
View File
@@ -21,6 +21,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,
)
@@ -132,6 +133,7 @@ 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
@@ -139,6 +141,7 @@ def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
s["blueprint_training_unit_id"] = uid
unit_min: Dict[str, Any] = {"id": uid}
_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
@@ -250,6 +253,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
@@ -296,10 +300,13 @@ def _insert_slots_and_blueprints(
)
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:
@@ -432,7 +439,7 @@ def create_training_framework_program(
)
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)
conn.commit()
@@ -543,7 +550,9 @@ 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:
cur.execute(
+615 -92
View File
@@ -484,6 +484,94 @@ def _normalize_assistant_trainer_profile_ids(
)
return uniq
def _normalize_stream_assigned_trainer_profile_ids(
cur,
raw_val: Any,
*,
group_id: Optional[int],
profile_id: int,
role: str,
unit_created_by: Optional[int],
eff_lead_nid: Optional[int],
) -> Any:
"""
JSONB-Liste für training_unit_parallel_streams.assigned_trainer_profile_ids.
Ohne group_id (Rahmen-Blueprint): nur Profil-Existenz + keine Überschneidung mit Leitung.
Mit group_id: gleiche Vereins-/Zuweisungsregeln wie assistant_trainer_profile_ids.
"""
if raw_val is None:
return None
if not isinstance(raw_val, list):
raise HTTPException(
status_code=400,
detail="assigned_trainer_profile_ids (Stream) muss Liste oder null sein",
)
ids_in: List[int] = []
for x in raw_val:
try:
i = int(x)
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="assigned_trainer_profile_ids (Stream) ungültig",
)
if i < 1:
raise HTTPException(
status_code=400,
detail="assigned_trainer_profile_ids (Stream) ungültig",
)
ids_in.append(i)
uniq = sorted(set(ids_in))
for nid in uniq:
cur.execute("SELECT 1 FROM profiles WHERE id = %s", (nid,))
if not cur.fetchone():
raise HTTPException(
status_code=400,
detail="Profil für Stream-Co-Trainer nicht gefunden",
)
if eff_lead_nid is not None and nid == eff_lead_nid:
raise HTTPException(
status_code=400,
detail="Leitung und Stream-Co-Trainer dürfen sich nicht überschneiden",
)
if group_id is None:
return uniq
cur.execute(
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
(group_id,),
)
gr = cur.fetchone()
if not gr:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
grd = dict(gr)
cid = grd.get("club_id")
if cid is None:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
club_i = int(cid)
if not is_platform_admin(role) and not _caller_may_assign_session_trainers(
cur, grd, profile_id, role, unit_created_by
):
raise HTTPException(status_code=403, detail="Keine Berechtigung, Co-Trainer (Stream) zuzuweisen")
eligible = {grd["trainer_id"]} if grd.get("trainer_id") else set()
for x in grd.get("co_trainer_ids") or []:
try:
eligible.add(int(x))
except (TypeError, ValueError):
continue
for nid in uniq:
if is_platform_admin(role):
continue
if nid in eligible:
continue
if not _profile_active_in_club(cur, club_i, nid):
raise HTTPException(
status_code=400,
detail="Stream-Co-Trainer nur mit aktiver Mitgliedschaft im Verein dieser Gruppe",
)
return uniq
def _normalize_planning_method_profile_payload(raw) -> Optional[Dict[str, Any]]:
"""None = Katalog wirksam; Dict = Snapshot fuer diese Platzierung."""
if raw is None:
@@ -702,51 +790,88 @@ def _fetch_phases_nested(cur, unit_id: int) -> List[Dict[str, Any]]:
return out
def _sections_clone_payload(cur, unit_id: int) -> List[Dict[str, Any]]:
"""Sektionen/Items für eine tiefe Kopie (ohne DB-IDs / Join-Felder)."""
secs = _fetch_sections(cur, unit_id)
out: List[Dict[str, Any]] = []
for sec in secs:
items_clean: List[Dict[str, Any]] = []
for it in sorted(sec.get("items", []), key=lambda x: x.get("order_index", 0)):
itype = it.get("item_type") or ("exercise" if it.get("exercise_id") else "note")
oix = it.get("order_index")
if itype == "note":
note_item = {
"item_type": "note",
"order_index": oix,
"note_body": it.get("note_body") or "",
}
sm = _optional_source_training_module_id_payload(it.get("source_training_module_id"))
if sm is not None:
note_item["source_training_module_id"] = sm
items_clean.append(note_item)
continue
if itype != "exercise" or not it.get("exercise_id"):
continue
ex_item = {
"item_type": "exercise",
def _clone_section_payload_dict(sec: Dict[str, Any]) -> Dict[str, Any]:
"""Sektion inkl. Items ohne DB-IDs (für phases-Payload / Kopie)."""
items_clean: List[Dict[str, Any]] = []
for it in sorted(sec.get("items", []), key=lambda x: x.get("order_index", 0)):
itype = it.get("item_type") or ("exercise" if it.get("exercise_id") else "note")
oix = it.get("order_index")
if itype == "note":
note_item = {
"item_type": "note",
"order_index": oix,
"exercise_id": it["exercise_id"],
"exercise_variant_id": it.get("exercise_variant_id"),
"planned_duration_min": it.get("planned_duration_min"),
"actual_duration_min": it.get("actual_duration_min"),
"notes": it.get("notes"),
"modifications": it.get("modifications"),
"planning_method_profile": it.get("planning_method_profile"),
"note_body": it.get("note_body") or "",
}
sm = _optional_source_training_module_id_payload(it.get("source_training_module_id"))
if sm is not None:
ex_item["source_training_module_id"] = sm
items_clean.append(ex_item)
out.append(
{
"title": sec.get("title"),
"order_index": sec.get("order_index"),
"guidance_notes": sec.get("guidance_notes"),
"items": items_clean,
}
)
note_item["source_training_module_id"] = sm
items_clean.append(note_item)
continue
if itype != "exercise" or not it.get("exercise_id"):
continue
ex_item = {
"item_type": "exercise",
"order_index": oix,
"exercise_id": it["exercise_id"],
"exercise_variant_id": it.get("exercise_variant_id"),
"planned_duration_min": it.get("planned_duration_min"),
"actual_duration_min": it.get("actual_duration_min"),
"notes": it.get("notes"),
"modifications": it.get("modifications"),
"planning_method_profile": it.get("planning_method_profile"),
}
sm = _optional_source_training_module_id_payload(it.get("source_training_module_id"))
if sm is not None:
ex_item["source_training_module_id"] = sm
items_clean.append(ex_item)
row: Dict[str, Any] = {
"title": sec.get("title"),
"order_index": sec.get("order_index"),
"guidance_notes": sec.get("guidance_notes"),
"items": items_clean,
}
stid = sec.get("source_template_section_id")
if stid is not None and stid != "":
try:
stid_i = int(stid)
if stid_i >= 1:
row["source_template_section_id"] = stid_i
except (TypeError, ValueError):
pass
return row
def _phases_clone_payload(cur, unit_id: int) -> List[Dict[str, Any]]:
"""Vollständige Phasen/Streams/Sektionen für tiefe Kopie (ohne DB-IDs)."""
nested = _fetch_phases_nested(cur, unit_id)
out: List[Dict[str, Any]] = []
for ph in nested:
kind = str(ph.get("phase_kind") or "").strip().lower()
if kind not in ("whole_group", "parallel"):
kind = "whole_group"
pd: Dict[str, Any] = {
"order_index": ph.get("order_index"),
"phase_kind": kind,
"title": ph.get("title"),
"guidance_notes": ph.get("guidance_notes"),
}
if kind == "whole_group":
pd["sections"] = [_clone_section_payload_dict(s) for s in ph.get("sections") or []]
pd["streams"] = []
else:
pd["sections"] = []
streams_clean: List[Dict[str, Any]] = []
for st in ph.get("streams") or []:
sd: Dict[str, Any] = {
"order_index": st.get("order_index"),
"title": st.get("title"),
"notes": st.get("notes"),
"assigned_trainer_profile_ids": st.get("assigned_trainer_profile_ids"),
"sections": [_clone_section_payload_dict(s) for s in st.get("sections") or []],
}
streams_clean.append(sd)
pd["streams"] = streams_clean
out.append(pd)
return out
@@ -757,6 +882,7 @@ def _copy_blueprint_into_scheduled_unit(
planned_date: str,
profile_id: int,
origin_framework_slot_id: Optional[int],
role: str,
) -> int:
cur.execute(
"""
@@ -812,8 +938,8 @@ def _copy_blueprint_into_scheduled_unit(
if not row:
raise HTTPException(status_code=404, detail="Blueprint-Einheit nicht gefunden")
nu = row["id"]
cloned = _sections_clone_payload(cur, blueprint_unit_id)
_replace_unit_sections(cur, nu, cloned)
cloned = _phases_clone_payload(cur, blueprint_unit_id)
_replace_unit_phases(cur, nu, cloned, profile_id, role, profile_id)
return nu
@@ -859,6 +985,52 @@ def _resolve_training_unit_section_id(cur, unit_id: int, section_order_index: in
return int(r["id"])
def _resolve_training_unit_section_id_for_apply(
cur,
unit_id: int,
section_order_index: int,
*,
phase_order_index: Optional[int],
parallel_stream_order_index: Optional[int],
) -> int:
"""Ziel-Abschnitt: ganzes Gruppen physisch (nur section_order_index) oder innerhalb eines Parallelstreams."""
if parallel_stream_order_index is None:
return _resolve_training_unit_section_id(cur, unit_id, section_order_index)
if phase_order_index is None:
raise HTTPException(
status_code=400,
detail="phase_order_index ist bei parallel_stream_order_index Pflicht",
)
cur.execute(
"""
SELECT tus.id
FROM training_unit_sections tus
INNER JOIN training_unit_parallel_streams st ON st.id = tus.parallel_stream_id
INNER JOIN training_unit_phases p ON p.id = st.phase_id
WHERE tus.training_unit_id = %s
AND tus.order_index = %s
AND st.order_index = %s
AND p.order_index = %s
AND LOWER(TRIM(p.phase_kind)) = 'parallel'
ORDER BY tus.id ASC
LIMIT 1
""",
(
unit_id,
section_order_index,
parallel_stream_order_index,
phase_order_index,
),
)
r = cur.fetchone()
if not r:
raise HTTPException(
status_code=400,
detail="Abschnitt im Parallelstream für diese Indizes nicht gefunden",
)
return int(r["id"])
def _append_copied_module_items_to_section(
cur,
section_id: int,
@@ -1054,6 +1226,140 @@ def _replace_unit_sections(cur, unit_id: int, sections_in: List[Any]):
)
def _replace_unit_phases(
cur,
unit_id: int,
phases_in: List[Any],
profile_id: int,
role: str,
unit_created_by: Optional[int],
) -> None:
"""Ersetzt Phasen inkl. paralleler Streams und Sektionen (voller Plan)."""
if not isinstance(phases_in, list):
raise HTTPException(status_code=400, detail="phases muss eine Liste sein")
cur.execute(
"""
SELECT tu.group_id,
COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) AS eff_lead
FROM training_units tu
LEFT JOIN training_groups tg ON tg.id = tu.group_id
WHERE tu.id = %s
""",
(unit_id,),
)
ur = cur.fetchone()
group_id_opt = int(ur["group_id"]) if ur and ur.get("group_id") is not None else None
eff_lead_raw = ur.get("eff_lead") if ur else None
eff_lead_nid = int(eff_lead_raw) if eff_lead_raw is not None else None
_clear_unit_plan_content(cur, unit_id)
for pi, ph in enumerate(phases_in):
kind = str(ph.get("phase_kind") or "").strip().lower()
if kind not in ("whole_group", "parallel"):
raise HTTPException(
status_code=400,
detail="phase_kind muss whole_group oder parallel sein",
)
# Reihenfolge strikt aus der Liste (pi): vermeidet UNIQUE(tu, order_index)-Kollisionen,
# wenn der Client dieselbe phase_order_index mehrfach trägt (z. B. nach Zuordnungswechseln).
p_oix = int(pi)
cur.execute(
"""
INSERT INTO training_unit_phases (training_unit_id, order_index, phase_kind, title, guidance_notes)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(
unit_id,
p_oix,
kind,
ph.get("title"),
ph.get("guidance_notes"),
),
)
phase_id = int(cur.fetchone()["id"])
if kind == "whole_group":
secs = ph.get("sections")
if secs is None:
secs = []
if not isinstance(secs, list):
raise HTTPException(status_code=400, detail="sections muss Liste sein")
for si, sec in enumerate(secs):
_insert_one_replacement_section(
cur, unit_id, sec, si, phase_id=phase_id, parallel_stream_id=None
)
else:
streams = ph.get("streams")
if streams is None:
streams = []
if not isinstance(streams, list):
raise HTTPException(status_code=400, detail="streams muss Liste sein")
for si, st in enumerate(streams):
raw_asst = st.get("assigned_trainer_profile_ids")
asst_norm = _normalize_stream_assigned_trainer_profile_ids(
cur,
raw_asst,
group_id=group_id_opt,
profile_id=profile_id,
role=role,
unit_created_by=unit_created_by,
eff_lead_nid=eff_lead_nid,
)
asst_db = None if asst_norm is None else PsycopgJson(asst_norm)
st_oix = st.get("order_index")
if st_oix is None:
st_oix = si
cur.execute(
"""
INSERT INTO training_unit_parallel_streams (
phase_id, order_index, title, notes, assigned_trainer_profile_ids
) VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(
phase_id,
int(st_oix),
st.get("title"),
st.get("notes"),
asst_db,
),
)
sid = int(cur.fetchone()["id"])
secs = st.get("sections")
if secs is None:
secs = []
if not isinstance(secs, list):
raise HTTPException(
status_code=400,
detail="sections (Stream) muss Liste sein",
)
for ti, sec in enumerate(secs):
_insert_one_replacement_section(
cur, unit_id, sec, ti, phase_id=None, parallel_stream_id=sid
)
def _assert_single_plan_content_key_create(data: dict) -> None:
"""Höchstens ein Plan-Inhalt: phases | sections | exercises (Non-None)."""
n = sum(1 for k in ("phases", "sections", "exercises") if data.get(k) is not None)
if n > 1:
raise HTTPException(
status_code=400,
detail="Nur eines von phases, sections oder exercises angeben",
)
def _assert_single_plan_content_key_update(data: dict) -> None:
"""PUT: höchstens einer der Keys phases | sections | exercises."""
keys = [k for k in ("phases", "sections", "exercises") if k in data]
if len(keys) > 1:
raise HTTPException(
status_code=400,
detail="Nur eines von phases, sections oder exercises im Body gleichzeitig",
)
def _distinct_exercise_ids_in_unit(cur, unit_id: int) -> List[int]:
cur.execute(
"""
@@ -1217,32 +1523,187 @@ def _insert_sections_from_legacy_exercises(cur, unit_id: int, exercises_in: List
_insert_section_items(cur, sid, filtered, start_order=0)
def _instantiate_from_template(cur, unit_id: int, template_id: int):
_clear_unit_plan_content(cur, unit_id)
pid = _ensure_default_whole_group_phase(cur, unit_id, order_index=0)
def _normalize_training_plan_template_section_payload(sec: Any, si: int) -> Dict[str, Any]:
title = (sec.get("title") or "").strip() or f"Abschnitt {si + 1}"
order_ix = sec.get("order_index")
if order_ix is None:
order_ix = si
try:
order_ix = int(order_ix)
except (TypeError, ValueError):
order_ix = si
pk = str(sec.get("phase_kind") or "whole_group").strip().lower()
if pk not in ("whole_group", "parallel"):
pk = "whole_group"
try:
p_oi = int(sec.get("phase_order_index") if sec.get("phase_order_index") is not None else 0)
except (TypeError, ValueError):
p_oi = 0
p_so: Optional[int] = None
if pk == "parallel":
raw_so = sec.get("parallel_stream_order_index")
try:
p_so = int(raw_so) if raw_so is not None and raw_so != "" else 0
except (TypeError, ValueError):
p_so = 0
return {
"title": title,
"order_index": order_ix,
"guidance_text": sec.get("guidance_text"),
"phase_kind": pk,
"phase_order_index": p_oi,
"parallel_stream_order_index": p_so,
}
def _insert_training_plan_template_sections(cur, template_id: int, sections_in: List[Any]) -> None:
for si, sec in enumerate(sections_in):
row = _normalize_training_plan_template_section_payload(sec, si)
cur.execute(
"""
INSERT INTO training_plan_template_sections (
template_id, order_index, title, guidance_text,
phase_kind, phase_order_index, parallel_stream_order_index
) VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
(
template_id,
row["order_index"],
row["title"],
row["guidance_text"],
row["phase_kind"],
row["phase_order_index"],
row["parallel_stream_order_index"],
),
)
def _template_rows_to_phases_payload(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Flache Vorlagen-Sektionen → `phases`-Liste wie beim Training-Unit PUT (nur Gliederung, leere items)."""
if not rows:
return []
phases_out: List[Dict[str, Any]] = []
i = 0
n = len(rows)
while i < n:
r0 = rows[i]
pk0 = str(r0.get("phase_kind") or "whole_group").strip().lower()
if pk0 not in ("whole_group", "parallel"):
pk0 = "whole_group"
try:
p_oix0 = int(r0.get("phase_order_index") if r0.get("phase_order_index") is not None else 0)
except (TypeError, ValueError):
p_oix0 = 0
run: List[Dict[str, Any]] = []
while i < n:
r = rows[i]
pk = str(r.get("phase_kind") or "whole_group").strip().lower()
if pk not in ("whole_group", "parallel"):
pk = "whole_group"
try:
p_oix = int(r.get("phase_order_index") if r.get("phase_order_index") is not None else 0)
except (TypeError, ValueError):
p_oix = 0
if pk != pk0 or p_oix != p_oix0:
break
run.append(r)
i += 1
if pk0 == "whole_group":
secs = []
for j, rr in enumerate(run):
tid = rr.get("id")
secs.append(
{
"title": rr.get("title"),
"order_index": j,
"guidance_notes": rr.get("guidance_text"),
"items": [],
**(
{"source_template_section_id": int(tid)}
if tid is not None
else {}
),
}
)
phases_out.append(
{
"phase_kind": "whole_group",
"order_index": p_oix0,
"title": None,
"guidance_notes": None,
"sections": secs,
}
)
else:
by_stream: Dict[int, List[Dict[str, Any]]] = {}
for rr in run:
raw_so = rr.get("parallel_stream_order_index")
try:
so = int(raw_so) if raw_so is not None and raw_so != "" else 0
except (TypeError, ValueError):
so = 0
by_stream.setdefault(so, []).append(rr)
stream_order = sorted(by_stream.keys())
streams = []
for so in stream_order:
bucket = by_stream[so]
st: Dict[str, Any] = {
"order_index": so,
"title": None,
"notes": None,
"sections": [],
}
for j, rr in enumerate(bucket):
tid = rr.get("id")
st["sections"].append(
{
"title": rr.get("title"),
"order_index": j,
"guidance_notes": rr.get("guidance_text"),
"items": [],
**(
{"source_template_section_id": int(tid)}
if tid is not None
else {}
),
}
)
streams.append(st)
phases_out.append(
{
"phase_kind": "parallel",
"order_index": p_oix0,
"title": None,
"guidance_notes": None,
"streams": streams,
}
)
return phases_out
def _instantiate_from_template(
cur,
unit_id: int,
template_id: int,
*,
profile_id: int,
role: str,
unit_created_by: int,
) -> None:
cur.execute(
"""
SELECT id, title, guidance_text
SELECT id, title, guidance_text, order_index, phase_kind, phase_order_index, parallel_stream_order_index
FROM training_plan_template_sections
WHERE template_id = %s
ORDER BY order_index
""",
(template_id,),
)
rows = cur.fetchall()
for gi, row in enumerate(rows):
r = r2d(row)
cur.execute(
"""
INSERT INTO training_unit_sections (
training_unit_id, phase_id, parallel_stream_id, order_index, title, guidance_notes, source_template_section_id
) VALUES (%s, %s, NULL, %s, %s, %s, %s)
""",
(unit_id, pid, gi, r["title"], r["guidance_text"], r["id"]),
)
# Fallback: keine Sektionen in Vorlage → ein leerer Block
rows_raw = cur.fetchall()
rows = [r2d(r) for r in rows_raw]
if not rows:
_clear_unit_plan_content(cur, unit_id)
pid = _ensure_default_whole_group_phase(cur, unit_id, order_index=0)
cur.execute(
"""
INSERT INTO training_unit_sections (
@@ -1251,6 +1712,18 @@ def _instantiate_from_template(cur, unit_id: int, template_id: int):
""",
(unit_id, pid),
)
return
phases_payload = _template_rows_to_phases_payload(rows)
_clear_unit_plan_content(cur, unit_id)
_replace_unit_phases(
cur,
unit_id,
phases_payload,
profile_id,
role,
unit_created_by,
)
def _fetch_training_plan_template_row(cur, tid: int) -> Dict[str, Any]:
@@ -1368,18 +1841,7 @@ def create_training_plan_template(data: dict, tenant: TenantContext = Depends(ge
(club_id, profile_id, name, data.get("description"), visibility),
)
tid = cur.fetchone()["id"]
for si, sec in enumerate(sections_in):
title = (sec.get("title") or "").strip() or f"Abschnitt {si + 1}"
order_ix = sec.get("order_index")
if order_ix is None:
order_ix = si
cur.execute(
"""
INSERT INTO training_plan_template_sections (template_id, order_index, title, guidance_text)
VALUES (%s, %s, %s, %s)
""",
(tid, order_ix, title, sec.get("guidance_text")),
)
_insert_training_plan_template_sections(cur, tid, sections_in)
conn.commit()
return get_training_plan_template(tid, tenant)
@@ -1437,18 +1899,7 @@ def update_training_plan_template(template_id: int, data: dict, tenant: TenantCo
"DELETE FROM training_plan_template_sections WHERE template_id = %s", (template_id,)
)
sections_in = data["sections"] or []
for si, sec in enumerate(sections_in):
title = (sec.get("title") or "").strip() or f"Abschnitt {si + 1}"
order_ix = sec.get("order_index")
if order_ix is None:
order_ix = si
cur.execute(
"""
INSERT INTO training_plan_template_sections (template_id, order_index, title, guidance_text)
VALUES (%s, %s, %s, %s)
""",
(template_id, order_ix, title, sec.get("guidance_text")),
)
_insert_training_plan_template_sections(cur, template_id, sections_in)
conn.commit()
return get_training_plan_template(template_id, tenant)
@@ -1913,7 +2364,11 @@ def get_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenant_c
def apply_training_module_to_training_unit(
unit_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
):
"""Kopiert die Positionen eines Trainingsmoduls ans Ende eines Abschnitts (lokal bearbeitbar)."""
"""Kopiert Modul-Positionen ans Ende eines Abschnitts.
Ziel: `section_order_index` in einer whole_group-Phase (Standard) oder
zusätzlich `phase_order_index` + `parallel_stream_order_index` für einen Stream.
"""
profile_id = tenant.profile_id
role = tenant.global_role
if not _has_planning_role(role):
@@ -1935,12 +2390,44 @@ def apply_training_module_to_training_unit(
if section_order_index < 0:
raise HTTPException(status_code=400, detail="section_order_index ungültig")
ps_raw = data.get("parallel_stream_order_index")
parallel_stream_oi: Optional[int] = None
if ps_raw is not None and ps_raw != "":
try:
parallel_stream_oi = int(ps_raw)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="parallel_stream_order_index ungültig")
if parallel_stream_oi < 0:
raise HTTPException(status_code=400, detail="parallel_stream_order_index ungültig")
phase_oi: Optional[int] = None
ph_raw = data.get("phase_order_index")
if ph_raw is not None and ph_raw != "":
try:
phase_oi = int(ph_raw)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="phase_order_index ungültig")
if phase_oi < 0:
raise HTTPException(status_code=400, detail="phase_order_index ungültig")
if phase_oi is not None and parallel_stream_oi is None:
raise HTTPException(
status_code=400,
detail="phase_order_index nur zusammen mit parallel_stream_order_index",
)
with get_db() as conn:
cur = get_cursor(conn)
unit_row = _training_unit_guard_row(cur, unit_id)
_assert_training_unit_permission(cur, unit_row, profile_id, role)
section_id = _resolve_training_unit_section_id(cur, unit_id, section_order_index)
section_id = _resolve_training_unit_section_id_for_apply(
cur,
unit_id,
section_order_index,
phase_order_index=phase_oi,
parallel_stream_order_index=parallel_stream_oi,
)
mod_items, src_mid = load_training_module_for_apply(cur, module_id, profile_id, role)
_append_copied_module_items_to_section(cur, section_id, mod_items, src_mid)
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
@@ -2048,13 +2535,24 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
unit_id = cur.fetchone()["id"]
_assert_single_plan_content_key_create(data)
phases_in = data.get("phases")
sections_in = data.get("sections")
exercises_in = data.get("exercises")
if sections_in is not None:
if phases_in is not None:
_replace_unit_phases(cur, unit_id, phases_in, profile_id, role, profile_id)
elif sections_in is not None:
_replace_unit_sections(cur, unit_id, sections_in)
elif tpl_id_safe:
_instantiate_from_template(cur, unit_id, tpl_id_safe)
_instantiate_from_template(
cur,
unit_id,
tpl_id_safe,
profile_id=profile_id,
role=role,
unit_created_by=profile_id,
)
elif exercises_in is not None:
_insert_sections_from_legacy_exercises(cur, unit_id, exercises_in)
@@ -2230,16 +2728,33 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
cur.execute(
"UPDATE training_units SET plan_template_id = %s WHERE id = %s", (tid, unit_id)
)
_instantiate_from_template(cur, unit_id, tid)
_instantiate_from_template(
cur,
unit_id,
tid,
profile_id=profile_id,
role=role,
unit_created_by=int(unit_row.get("created_by") or profile_id),
)
content_handled = True
if not content_handled and "sections" in data:
_assert_single_plan_content_key_update(data)
if not content_handled and "phases" in data:
_replace_unit_phases(
cur,
unit_id,
data.get("phases") or [],
profile_id,
role,
unit_row.get("created_by"),
)
elif not content_handled and "sections" in data:
_replace_unit_sections(cur, unit_id, data["sections"] or [])
elif not content_handled and "exercises" in data:
_clear_unit_plan_content(cur, unit_id)
_insert_sections_from_legacy_exercises(cur, unit_id, data["exercises"] or [])
if content_handled or "sections" in data or "exercises" in data:
if content_handled or any(k in data for k in ("phases", "sections", "exercises")):
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
conn.commit()
@@ -2351,6 +2866,7 @@ def create_training_unit_from_framework_slot(data: dict, tenant: TenantContext =
str(planned_date),
profile_id,
slot_id,
role,
)
_promote_private_exercises_used_in_unit(cur, new_id, profile_id, role)
@@ -2426,7 +2942,14 @@ def quick_create_training_unit(data: dict, tenant: TenantContext = Depends(get_t
unit_id = cur.fetchone()["id"]
if tpl_id_safe:
_instantiate_from_template(cur, unit_id, tpl_id_safe)
_instantiate_from_template(
cur,
unit_id,
tpl_id_safe,
profile_id=profile_id,
role=role,
unit_created_by=profile_id,
)
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
conn.commit()
@@ -0,0 +1,206 @@
"""
PostgreSQL-Integration: Rahmenprogramm-Slot mit verschachtelten `phases` (Blueprint-Unit).
Aktivierung:
- Lokal: TRAINING_PLANNING_INTEGRATION=1
- CI: .gitea/workflows/test.yml setzt die Variable beim pytest-Lauf.
Prüft `_insert_slots_and_blueprints` → `_replace_unit_phases` wie beim API-PUT mit Slot-Payload.
"""
from __future__ import annotations
import os
import uuid
import pytest
from db import get_db, get_cursor
from routers.training_framework_programs import _insert_slots_and_blueprints
from routers.training_planning import _fetch_phases_nested
def _integration_enabled() -> bool:
return os.getenv("TRAINING_PLANNING_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
not _integration_enabled(),
reason="TRAINING_PLANNING_INTEGRATION=1 und PostgreSQL (DB_*) erforderlich",
),
]
def _db_ping() -> bool:
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT 1 AS ok")
row = cur.fetchone()
return row is not None and row.get("ok") == 1
except Exception:
return False
@pytest.fixture(scope="module")
def db_ready():
if not _db_ping():
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/…)")
def test_framework_blueprint_slot_phases_roundtrip(db_ready):
"""Ein Slot mit `phases` erzeugt eine Blueprint-Unit mit identischer Phasenstruktur."""
suffix = uuid.uuid4().hex[:12]
club_name = f"fw_ph_club_{suffix}"
email = f"fw_ph_{suffix}@test.local"
from auth import hash_pin
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_name, "F", "active"),
)
club_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email, hash_pin("x"), f"FWPH {suffix}", "trainer", club_id),
)
profile_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO exercises (title, goal, execution, visibility, status, created_by)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(f"Übung FWPH {suffix}", "Ziel", "Ablauf", "private", "draft", profile_id),
)
ex_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO training_framework_programs (
title, description,
planned_period_start, planned_period_end,
visibility, club_id, created_by,
focus_area_id, style_direction_id
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
f"Rahmen FWPH {suffix}",
None,
None,
None,
"private",
club_id,
profile_id,
None,
None,
),
)
fw_id = int(cur.fetchone()["id"])
phases_in = [
{
"phase_kind": "whole_group",
"order_index": 0,
"title": "Aufwärmen",
"sections": [
{
"title": "Gemeinsam",
"order_index": 0,
"items": [
{"item_type": "note", "order_index": 0, "note_body": "Los"},
],
},
],
},
{
"phase_kind": "parallel",
"order_index": 1,
"title": "Breakout",
"streams": [
{
"order_index": 0,
"title": "Matte A",
"sections": [
{
"title": "Technik A",
"order_index": 0,
"items": [
{
"item_type": "exercise",
"order_index": 0,
"exercise_id": ex_id,
"planned_duration_min": 10,
},
],
},
],
},
],
},
]
slots_in = [
{
"sort_order": 0,
"title": "Session 1",
"notes": None,
"phases": phases_in,
},
]
_insert_slots_and_blueprints(cur, fw_id, slots_in, profile_id, "trainer")
cur.execute(
"""
SELECT id FROM training_framework_slots
WHERE framework_program_id = %s
ORDER BY sort_order
LIMIT 1
""",
(fw_id,),
)
slot_row = cur.fetchone()
assert slot_row is not None
slot_id = int(slot_row["id"])
cur.execute(
"SELECT id FROM training_units WHERE framework_slot_id = %s",
(slot_id,),
)
bu_row = cur.fetchone()
assert bu_row is not None
blueprint_unit_id = int(bu_row["id"])
nested = _fetch_phases_nested(cur, blueprint_unit_id)
conn.commit()
try:
assert len(nested) == 2
assert nested[0]["phase_kind"] == "whole_group"
assert len(nested[0].get("sections") or []) == 1
assert nested[1]["phase_kind"] == "parallel"
streams = nested[1].get("streams") or []
assert len(streams) == 1
assert len(streams[0].get("sections") or []) == 1
assert streams[0]["sections"][0]["title"] == "Technik A"
assert int(streams[0]["sections"][0]["items"][0]["exercise_id"]) == ex_id
finally:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM training_framework_programs WHERE id = %s", (fw_id,))
cur.execute("DELETE FROM exercises WHERE id = %s", (ex_id,))
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
cur.execute("DELETE FROM clubs WHERE id = %s", (club_id,))
conn.commit()
@@ -1,5 +1,5 @@
"""
PostgreSQL-Integration: Roundtrip _replace_unit_sections ↔ _fetch_sections.
PostgreSQL-Integration: Roundtrip _replace_unit_sections / _replace_unit_phases ↔ Fetch-Helfer.
Aktivierung:
- Lokal: TRAINING_PLANNING_INTEGRATION=1
@@ -15,7 +15,12 @@ import uuid
import pytest
from db import get_db, get_cursor
from routers.training_planning import _fetch_sections, _replace_unit_sections
from routers.training_planning import (
_fetch_phases_nested,
_fetch_sections,
_replace_unit_phases,
_replace_unit_sections,
)
def _integration_enabled() -> bool:
@@ -157,3 +162,129 @@ def test_replace_sections_roundtrip(db_ready):
cur.execute("DELETE FROM profiles WHERE id = %s", (profile_id,))
cur.execute("DELETE FROM 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()
+34 -4
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.137"
BUILD_DATE = "2026-05-12"
DB_SCHEMA_VERSION = "20260515063"
APP_VERSION = "0.8.141"
BUILD_DATE = "2026-05-14"
DB_SCHEMA_VERSION = "20260515064"
MODULE_VERSIONS = {
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
@@ -24,7 +24,7 @@ MODULE_VERSIONS = {
"exercises": "2.28.0", # GET /api/exercises Keyset cursor_updated_at + cursor_id; Sortierung id als Tie-break
"training_units": "0.3.0", # GET /api/training-units Keyset cursor_planned_date + cursor_id (+ optional cursor_planned_time); Sort mit id-Tiebreak
"training_programs": "0.1.0",
"planning": "0.10.0", # Migration 063: training_unit_phases + parallel_streams; Sektionen phase_id|parallel_stream_id; GET phases + sections
"planning": "0.12.0", # Trainingsvorlagen: Phasen/Streams in template_sections (064); Instantiate über _replace_unit_phases
"dashboard": "1.1.0", # GET /api/dashboard/kpis inkl. training_home (ein Client-Roundtrip für KPIs + nächste Termine)
"training_modules": "1.0.0",
"import_wiki": "1.0.0",
@@ -36,6 +36,36 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
{
"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",
+7 -3
View File
@@ -75,10 +75,12 @@ Die sichtbaren Funktionen hängen von **Rolle** und **Kontext** ab (eingeloggter
### 4.4 Trainingsplanung
- **Trainingseinheiten** als planbare Objekte mit **Sektionen** und **Einträgen** (Übungen, ggf. mit **Variante** und Metadaten wie Dauer).
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden.
- **Phasen & parallele Streams (Breakout):** Eine Einheit kann aus abwechselnden **Ganzgruppenphasen** und **Parallelphasen** bestehen; in einer Parallelphase führen **mehrere Streams** (Teilstrecken) je eigene Abschnitte/Übungen. Planung über Breakout-UI; API liefert **`phases`** und flache **`sections`** (Migration **063**, siehe **`docs/HANDOVER.md`**). Technische Details: `.claude/docs/technical/PARALLEL_TRAINING_STREAMS_SPEC.md`.
- **Trainingsvorlagen / Mikrovorlagen** (wo eingerichtet): Struktur wiederverwenden (Phasen in Vorlagen: Ausbau siehe Handover „offen“).
- **Trainingsrahmenprogramm (Bibliothek):** übergeordnete Programme mit **Zielen** und **Slots**; Slot-Inhalt technisch als **Blueprint-Trainingsunit** abgebildet.
- **Materialisierung:** aus einem Rahmen-Slot kann eine **konkrete Kalender-Einheit** für eine Gruppe erzeugt werden (API vorhanden; UI-Anbindung kann erweitert werden).
- **Durchführung:** Ansicht zum Abarbeiten einer Einheit; **Coaching-Modus** als separater Erlebnispfad (generischer Zeit-Block pro Platzierung); bei **Kombinationsübungen** zusätzliche **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** siehe Kombination-Fachspez **Anhang A** (implementierter Umfang vs. nächste Stufen).
- **Durchführung („Plan & Ablauf“):** Ablauf anhand Phasen/Streams darstellen und abarbeiten (inkl. Split-Logik in der Anzeige).
- **Coaching-Modus:** eigener Ablauf mit Schritt-für-Schritt-Timeline, Stream-Wahl pro Parallelphase, Hinweis **„Parallelphase · Abschluss“** (Gruppen zusammenführen) vor der nächsten Ganzgruppenphase oder vor dem nächsten Split; **Nachbereitung** mit Ist-Minuten und Speichern wie in der Planung (inkl. **`phases`**). Nach erfolgreichem Speichern Wechsel zur **Plan- und Ablaufsicht** derselben Einheit. Bei **Kombinationsübungen** zusätzlich **Stations-/Kandidaten-Schicht und Archetyp-Hinweise** (Fachspez **Anhang A**; Ausbauschritte B/C).
### 4.5 Medienbibliothek und Archiv
@@ -118,7 +120,8 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
- Kalender-UX: **„Aus Rahmen übernehmen“** flächendeckend und ggf. bulkfähig anbinden.
- **Policies** für geteilte Rahmen (Wer darf Bibliotheks-Rahmen sehen/kopieren?).
- **Skill-Kategorie-Admin-UI**, **Dark Mode/Responsive/PWA-Ausbau**, **KI-Suche** über Volltext hinaus – je nach Backlog.
- **Coach / Kombination:** nächste Stufen **Zeitleisten-Splitting** und **Archetyp-Timer** (Fachspez § 10.4 Stufe B/C; Umsetzungsplan Phase 4b–d); **geführtes Erfassen** von `method_profile` im Übungseditor.
- **Coach / Kombination:** Kombi-spezifische **Archetyp-Stufen B/C** (Zeitleisten-Splitting, archetypnahe Timer — Fachspez § 10.4); **geführtes Erfassen** von `method_profile` im Übungseditor.
- **Breakout:** vollständige **Server-Spiegelung** neuer Abschnitte in **`phases`**; **Vorlagen** phasengleich mit Kalendereinheit; optional **Stream-Tabs** in der Durchführungsansicht laut technischer Spec — siehe **`docs/HANDOVER.md`** (Arbeitspaket „Coaching & Breakout“).
---
@@ -126,5 +129,6 @@ Nicht als „broken“ gemeint, sondern als **typische nächste Ausbaustellen**
| Datum | Änderung |
|-------|----------|
| 2026-05-14 | Trainingsplanung: Phasen/parallele Streams, Coaching (Rejoin, Nachbereitung → Planansicht); Lücken §5 ergänzt. Verweis `HANDOVER.md`. |
| 2026-05-12 | Erstfassung für Übergabe an fachliches Design; Abgleich mit Code-Navigation, `version.py`, `HANDOVER.md`, `FEATURES_DELIVERED`, `DOMAIN_MODEL`. |
| 2026-05-12 | Kombinationsübungen + Coaching Stufe A; Verweise auf Fachspezifikation (`…Kombinationsuebungen…` V3 Anhang A) und `TRAINING_MODULES_IMPLEMENTATION_PLAN.md`. |
+42 -15
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-05-13
**App-Version / DB-Schema:** App **0.8.120**, DB-Schema **`20260514062`** (`backend/version.py`: `APP_VERSION`, `DB_SCHEMA_VERSION`)
**Stand:** 2026-05-14
**App-Version / DB-Schema:** App **`0.8.140`** (u. a. Planungs-Breakout-UI), 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**.
@@ -76,7 +76,32 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
### Trainingsmodule, Kombinationsübungen und Coach (Stand **0.8.120**)
### 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).
@@ -155,17 +180,18 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
## 7. Nächste Session — sinnvolle Arbeitspakete
1. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
2. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
3. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
4. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
5. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
6. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
7. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
8. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
9. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
10. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
11. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
1. **Coaching & Breakout (Regression):** Mehrphasen-Einheit mit zwei Splits und Ganzgruppen dazwischen — Rejoin-Karten, Nachbereitung speichern, Anzeige in Plan & Ablauf (`docs/HANDOVER.md` Arbeitspaket-Tabelle).
2. **P-13 Frontend-Verifikation:** Melde-Flow in Medienbibliothek, Inbox-Workflow (Status, Archiv, Wiedereröffnen), Club-Admin-Ansicht manuell auf Dev-System durchspielen. E-Mail-Benachrichtigungen verifizieren (SMTP-Log).
3. **Inline (Spec Abschnitt 11):** Basis umgesetzt — verbleibend: gezielte UX-Politik; optional Server-Normalisierung/Absicherung prüfen, falls Produkt es verlangt.
4. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
5. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
6. **S3/Adapter:** Speicher-Abstraktion (Spec Abschnitt 7) — wenn Produkt es verlangt.
7. **Rahmen/UI:** Kalender „aus Rahmen übernehmen” weiter anbinden (parallel, unabhängig von Medien).
8. **Fachlicher Nutzerüberblick:** bei größeren UX-Änderungen **`docs/FACHLICHE_NUTZERFUNKTIONEN.md`** mitpflegen.
9. **Kombinations-Coach (Archetyp B/C):** Fachspez § 10.4 / **§ 10.6**; nach Implementierung **Anhang A** + `TRAINING_MODULES_IMPLEMENTATION_PLAN.md` aktualisieren (kein Doc-Drift).
10. **Archetyp-Administration:** Konfiguration oder DB statt nur `COMBINATION_ARCHETYPE_IDS` / `combinationArchetypes.js` (Paket **4e**).
11. **Kombi-Zeitfelder:** Massen-Vorbelegung aller Slots aus Archetyp/Global + optionales Modal beim Archetypwechsel (Paket **4f**, `COMBINATION_TIMING_PROFILE_PLAN.md`).
12. **Backend-Validierung** `method_profile` / `planning_method_profile` je Archetyp (Paket **4g**).
---
@@ -174,7 +200,8 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Bereich | Einstieg |
|---------|----------|
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`** (`COMBINATION_ARCHETYPE_IDS`, `enrich_exercise_detail`), **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Coach-Kombination / Merge-Profil (Frontend) | `TrainingCoachPage.jsx`, `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
| Coach, Plan-Timeline, PUT-Payload phasiert | `TrainingCoachPage.jsx`, **`frontend/src/utils/trainingPlanUtils.js`** (`flattenPlanTimeline`, `buildCoachSavePlanPayload`, `sectionsWithPlanLocForDisplay`, Split-Rejoin-Helfer), `TrainingUnitRunPage.jsx` |
| Coach-Kombination / Merge-Profil (Frontend) | `ExerciseFullContent.jsx`, `CombinationCoachSlots.jsx`, `CombinationPlanBracket.jsx`, `utils/comboPlanningMethodProfile.js`, `utils/combinationMethodProfileUi.js`, `constants/combinationArchetypes.js` |
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
| Frontend API | `frontend/src/utils/api.js` |
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
@@ -9,6 +9,7 @@
- **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).
+87
View File
@@ -5935,6 +5935,78 @@ a.analysis-split__nav-item {
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 42%, transparent);
}
/* Planungseditor: Einfügebänder — Split vs. Ganzgruppe (inaktiv sichtbar, aktiv weiterhin Akzent-Ring) */
.tu-section-dropband--region-split {
height: 12px;
background: hsl(200 38% 92%);
border: 1px dashed hsl(200 42% 58%);
}
.tu-section-dropband--region-whole {
height: 12px;
background: color-mix(in srgb, var(--accent) 10%, var(--surface2));
border: 1px dashed color-mix(in srgb, var(--accent) 32%, transparent);
}
.tu-section-dropband--region-split-to-whole {
height: 12px;
background: linear-gradient(
90deg,
hsl(200 38% 92%) 0%,
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 100%
);
border: 1px dashed hsl(200 36% 50%);
}
.tu-section-dropband--region-whole-to-split {
height: 12px;
background: linear-gradient(
90deg,
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 0%,
hsl(200 38% 92%) 100%
);
border: 1px dashed hsl(200 36% 50%);
}
.tu-section-dropband--region-neutral {
height: 11px;
border: 1px dashed color-mix(in srgb, var(--border) 70%, transparent);
background: color-mix(in srgb, var(--surface2) 55%, transparent);
}
/* Stream-Tag / Planende: klar getrennte Drop-Ziele bei parallelen Phasen */
.tu-stream-chip-pill--drop-active {
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent);
}
.tu-section-dropband--whole-plan-end {
background: color-mix(in srgb, var(--accent) 14%, var(--surface2));
border: 1px dashed color-mix(in srgb, var(--accent) 35%, transparent);
height: 14px;
}
.tu-section-stream-append__drop {
margin: 0;
width: 100%;
}
/* Parallele Phase: feste Einfügebänder oberhalb/unterhalb des Split-Headers */
.tu-phase-drop--above-split,
.tu-phase-drop--below-split {
margin: 6px 2px 8px;
min-height: 14px;
}
.tu-section-dropband--phase-parallel-slot {
height: 14px;
background: linear-gradient(
180deg,
color-mix(in srgb, var(--accent) 12%, var(--surface2)) 0%,
hsl(200 30% 94%) 100%
);
border: 1px dashed color-mix(in srgb, var(--accent) 38%, transparent);
}
.tu-sec-drag-grip {
flex-shrink: 0;
display: inline-flex;
@@ -6586,6 +6658,21 @@ button.combo-coach-cand-link:hover {
max-width: none !important;
padding: 0 !important;
}
/* Split: jede weitere Breakout-Spalte auf neuer Seite (Gesamtplan-Druck) */
.training-run-breakout-stream--page-break {
break-before: page;
page-break-before: always;
}
.training-run-parallel-columns {
display: block !important;
}
.training-run-breakout-stream {
margin-bottom: 14px;
}
.training-run-phase-schedule {
break-inside: avoid;
page-break-inside: avoid;
}
.training-run-section,
.training-run-header {
break-inside: avoid;
File diff suppressed because it is too large. Load diff
@@ -5,6 +5,18 @@ import { trainingVisibilityShortDE } from '../../utils/trainingPlanningPageHelpe
/**
* Dialog: Trainingsmodul in die Abschnitte einer Einheit einfügen (Bibliothekskopie).
*/
function formatModuleApplySectionOptionLabel(section, flatIndex) {
const title = (section?.title || '').trim() || `Abschnitt ${flatIndex + 1}`
const pl = section?.planLoc
if (pl?.phaseKind === 'parallel') {
const st = (pl.streamTitle || '').trim()
const streamHint = st ? ` — ${st}` : ''
return `${title}${streamHint} (Phase ${pl.phaseOrderIndex ?? 0}, Stream ${pl.parallelStreamOrderIndex ?? 0})`
}
return title
}
export default function TrainingPlanningModuleApplyModal({
open,
busy,
@@ -101,7 +113,7 @@ export default function TrainingPlanningModuleApplyModal({
>
{(sections || []).map((s, i) => (
<option key={`sec-opt-u-${i}`} value={String(i)}>
{(s.title || `Abschnitt ${i + 1}`).trim()}
{formatModuleApplySectionOptionLabel(s, i)}
</option>
))}
</select>
@@ -148,7 +160,7 @@ export default function TrainingPlanningModuleApplyModal({
>
{(sections || []).map((s, i) => (
<option key={`sec-opt-${i}`} value={String(i)}>
{(s.title || `Abschnitt ${i + 1}`).trim()}
{formatModuleApplySectionOptionLabel(s, i)}
</option>
))}
</select>
@@ -11,15 +11,16 @@ import TrainingPlanningFrameworkImportModal from './TrainingPlanningFrameworkImp
import TrainingPlanningModuleApplyModal from './TrainingPlanningModuleApplyModal'
import TrainingPlanningTrainerAssignModal from './TrainingPlanningTrainerAssignModal'
import TrainingPlanningUnitFormModal from './TrainingPlanningUnitFormModal'
/* Parallele Trainingsstreams (Breakout): Planungs-API bleibt flache sections/items bis Schema-Paket 1–2;
Payload-Aufbau → buildSectionsPayload (trainingUnitSectionsForm); Backend _replace_unit_sections. */
/* Parallele Streams: Editor bleibt flache Abschnittsliste; `planLoc` pro Abschnitt steuert PUT `phases` vs. Legacy `sections`. */
import {
defaultSection,
normalizeUnitToForm,
enrichSectionsWithVariants,
buildSectionsPayload,
buildPlanPayloadForSave,
hydrateExercisePlanningRow,
insertTrainingModuleIntoPlanningSections,
templateSectionsPayloadFromFormSections,
formSectionsFromPlanTemplateRows,
} from '../../utils/trainingUnitSectionsForm'
import {
addDaysIsoDate,
@@ -550,12 +551,8 @@ function TrainingPlanningPageRoot() {
setFormData((fd) => ({
...fd,
sections: (tpl.sections || []).length
? tpl.sections.map((s) => ({
title: s.title,
guidance_notes: s.guidance_text || '',
items: []
}))
: [defaultSection()]
? formSectionsFromPlanTemplateRows(tpl.sections)
: [defaultSection()],
}))
} catch (err) {
toast.error('Vorlage laden: ' + err.message)
@@ -652,10 +649,7 @@ function TrainingPlanningPageRoot() {
try {
await api.createTrainingPlanTemplate({
name: name.trim(),
sections: formData.sections.map((s) => ({
title: s.title || 'Abschnitt',
guidance_text: s.guidance_notes?.trim() ? s.guidance_notes.trim() : null
}))
sections: templateSectionsPayloadFromFormSections(formData.sections),
})
await loadPlanTemplates()
toast.success('Vorlage gespeichert.')
@@ -664,6 +658,29 @@ function TrainingPlanningPageRoot() {
}
}
const handleDeletePlanTemplate = useCallback(
async (tpl) => {
if (!tpl?.id) return
const label = (tpl.name || '').trim() || `Vorlage #${tpl.id}`
if (
!window.confirm(
`Trainingsvorlage „${label}“ wirklich löschen? Die Aktion kann nicht rückgängig gemacht werden.`
)
) {
return
}
try {
await api.deleteTrainingPlanTemplate(tpl.id)
setDraftPlanTemplateId((prev) => (String(prev) === String(tpl.id) ? '' : prev))
await loadPlanTemplates()
toast.success('Vorlage gelöscht.')
} catch (err) {
toast.error(err.message || 'Löschen fehlgeschlagen')
}
},
[loadPlanTemplates, toast]
)
const openModuleApplyModal = useCallback(async (placement) => {
setModuleApplyErr('')
setModuleApplySearchQuery('')
@@ -959,7 +976,7 @@ function TrainingPlanningPageRoot() {
return
}
try {
const sectionsPayload = buildSectionsPayload(formData.sections)
const planPart = buildPlanPayloadForSave(formData.sections)
const payload = {
planned_date: formData.planned_date,
planned_time_start: formData.planned_time_start || null,
@@ -972,7 +989,7 @@ function TrainingPlanningPageRoot() {
status: formData.status || 'planned',
notes: formData.notes || null,
trainer_notes: formData.trainer_notes || null,
sections: sectionsPayload
...planPart,
}
if (editingUnit) {
payload.debrief_completed =
@@ -1930,6 +1947,7 @@ function TrainingPlanningPageRoot() {
draftPlanTemplateId={draftPlanTemplateId}
onDraftTemplateSelect={applyTemplateFromSelect}
planTemplates={planTemplates}
onDeletePlanTemplate={handleDeletePlanTemplate}
clubDirectory={clubDirectory}
clubDirectoryForCo={clubDirectoryForCo}
planningModalClubId={planningModalClubId}
@@ -18,6 +18,7 @@ export default function TrainingPlanningUnitFormModal({
draftPlanTemplateId,
onDraftTemplateSelect,
planTemplates,
onDeletePlanTemplate,
clubDirectory,
clubDirectoryForCo,
planningModalClubId,
@@ -129,6 +130,70 @@ export default function TrainingPlanningUnitFormModal({
</div>
)}
{planTemplates.length > 0 && typeof onDeletePlanTemplate === 'function' ? (
<details
className="card"
style={{
marginBottom: '1.35rem',
padding: '12px 14px',
background: 'var(--surface2)',
border: '1px solid var(--border)',
}}
>
<summary style={{ cursor: 'pointer', fontWeight: 600, color: 'var(--text1)' }}>
Gespeicherte Vorlagen löschen
</summary>
<p style={{ margin: '0.65rem 0 0.75rem', fontSize: '0.82rem', color: 'var(--text2)', lineHeight: 1.45 }}>
Du kannst eigene Vorlagen entfernen. Plattform-Admins dürfen auch fremde Vorlagen löschen. Einheiten, die
noch auf eine Vorlage verweisen, behalten ihren Ablauf; die Verknüpfung zur Vorlage wird vom Server
entfernt.
</p>
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{planTemplates.map((t, ti) => {
const roleLc = String(user?.role || '').toLowerCase()
const isPlatformAdmin = roleLc === 'admin' || roleLc === 'superadmin'
const canDel =
user &&
(isPlatformAdmin || Number(t.created_by) === Number(user.id))
return (
<li
key={t.id}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '10px',
padding: '8px 0',
borderTop: ti === 0 ? 'none' : '1px solid var(--border)',
}}
>
<span style={{ minWidth: 0, flex: 1, fontSize: '0.9rem' }}>
<strong style={{ color: 'var(--text1)' }}>{t.name}</strong>
{typeof t.sections_count === 'number' ? (
<span style={{ fontSize: '0.82rem', color: 'var(--text2)', marginLeft: '6px' }}>
· {t.sections_count} Abschn.
</span>
) : null}
</span>
{canDel ? (
<button
type="button"
className="btn btn-danger"
style={{ flexShrink: 0, padding: '6px 12px', fontSize: '0.82rem' }}
onClick={() => onDeletePlanTemplate(t)}
>
Löschen
</button>
) : (
<span style={{ fontSize: '0.78rem', color: 'var(--text3)', flexShrink: 0 }}>nur Lesen</span>
)}
</li>
)
})}
</ul>
</details>
) : null}
<form onSubmit={onSubmit}>
<h3 style={{ marginBottom: '1rem' }}>Planung</h3>
@@ -353,6 +418,7 @@ export default function TrainingPlanningUnitFormModal({
onRequestExercisePick={onRequestExercisePick}
onPeekExercise={onPeekExercise}
showExecutionExtras={Boolean(editingUnit) && sectionsEditMode === 'debrief'}
enableParallelPhaseControls
/>
</div>
+597 -94
View File
@@ -1,21 +1,43 @@
/**
* Coach-Modus: eine Position nach der anderen mit Assistentenhinweisen, Zeitnahme und optionaler Nachbereitung.
* Parallele Streams: Schritte aus flattenPlanTimeline (linear); Stream-/Phasenwahl später einzubinden.
* Coach-Modus: Schrittfolge mit Split-Punkten (branch_gate), Stream-Wahl pro paralleler Phase, Assistenz und Zeitnahme.
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
import api from '../utils/api'
import ExerciseFullContent from '../components/ExerciseFullContent'
import ExercisePeekModal from '../components/ExercisePeekModal'
import {
COACH_ENTRY_BRANCH_GATE,
buildCoachSavePlanPayload,
coachBranchPicksStepStorageSuffix,
coachBranchPicksStorageKey,
coachOutlineGroupsFromTimeline,
coachShouldPromptSplitRejoin,
coachShouldPromptSplitRejoinTransition,
durationOverridesMapFromDeltas,
findCoachTimelineJumpIndexForPhase,
flattenPlanTimeline,
itemStableKey,
sectionsToPutPayload,
listCoachStreamFocusOptions,
mergeCoachBranchPicksWithUrlFocus,
normalizeCoachBranchPicks,
summarizeTimelineEntry,
} from '../utils/trainingPlanUtils'
function storageStepKey(unitId) {
return `sj_coach_step_${unitId}`
function storageStepKey(unitId, mergedPicks) {
return `sj_coach_step_${unitId}_${coachBranchPicksStepStorageSuffix(mergedPicks)}`
}
function clearCoachStepStorageForUnit(unitId) {
const pref = `sj_coach_step_${unitId}_`
try {
for (let i = sessionStorage.length - 1; i >= 0; i -= 1) {
const k = sessionStorage.key(i)
if (k && k.startsWith(pref)) sessionStorage.removeItem(k)
}
} catch {
/* ignore */
}
}
function storageDeltasKey(unitId) {
@@ -55,14 +77,16 @@ function CoachControlsBand({
showJumpToTimerOwnerRow = true,
onJumpToTimerOwner,
timerOwnerLabelIndex,
branchGateMode = false,
}) {
const disPrev = step <= 0
const disNext = step >= timelineLength - 1
const disNext = branchGateMode || step >= timelineLength - 1
const alive = runStartAt != null || pausedAccumMs > 0
const canApplyForOwner = roundedMinForApply != null && roundedMinForApply >= 1
const canApplyForOwner = !branchGateMode && roundedMinForApply != null && roundedMinForApply >= 1
const istLabelMin = roundedMinForApply == null ? '—' : String(roundedMinForApply)
const doneLabel =
timelineLength <= 1
const doneLabel = branchGateMode
? 'Zuerst Gruppe wählen'
: timelineLength <= 1
? 'Nachbereitung öffnen'
: isLastCoachStep
? 'Nachbereitung & Ist-Zeit'
@@ -106,6 +130,7 @@ function CoachControlsBand({
type="button"
className="btn btn-primary"
style={{ minHeight: '44px', flex: '1 1 auto', fontWeight: 700 }}
disabled={branchGateMode}
onClick={onTimerStart}
>
▶ Start{alive ? ` · ${clockStr}` : ''}
@@ -118,7 +143,7 @@ function CoachControlsBand({
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px', flex: '0 1 auto', fontWeight: 600 }} disabled={!canApplyForOwner} onClick={onApplyActual}>
Ist ({istLabelMin}&nbsp;Min)
</button>
{alive && (
{alive && !branchGateMode && (
<button
type="button"
className="btn btn-secondary"
@@ -134,6 +159,7 @@ function CoachControlsBand({
type="button"
className="btn btn-primary"
style={{ width: '100%', minHeight: '44px', fontWeight: 700, lineHeight: 1.2, padding: '6px 10px', whiteSpace: 'normal', textAlign: 'center' }}
disabled={branchGateMode}
onClick={onDone}
>
{doneLabel}
@@ -156,8 +182,11 @@ function CoachControlsBand({
export default function TrainingCoachPage() {
const { unitId } = useParams()
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
const idNum = unitId ? parseInt(unitId, 10) : NaN
const coachFocusResetRef = useRef(null)
const [unit, setUnit] = useState(null)
const [loadError, setLoadError] = useState(null)
const [loading, setLoading] = useState(true)
@@ -170,6 +199,8 @@ export default function TrainingCoachPage() {
const [coachDebriefPhase, setCoachDebriefPhase] = useState(false)
const [step, setStep] = useState(0)
const [branchPicks, setBranchPicks] = useState({})
const [streamChoiceHint, setStreamChoiceHint] = useState(null)
const [deltas, setDeltas] = useState({})
const [runStartAt, setRunStartAt] = useState(null)
@@ -177,6 +208,8 @@ export default function TrainingCoachPage() {
const [timerOwningStep, setTimerOwningStep] = useState(null)
const [, setPulse] = useState(0)
const [splitRejoinPrompt, setSplitRejoinPrompt] = useState(null)
const [trainerAppend, setTrainerAppend] = useState('')
const [saveMarkDone, setSaveMarkDone] = useState(true)
const [saving, setSaving] = useState(false)
@@ -188,12 +221,52 @@ export default function TrainingCoachPage() {
setUnit(u)
}, [idNum])
const coachFocus = useMemo(() => {
const poRaw = searchParams.get('po')
const soRaw = searchParams.get('so')
if (poRaw == null || poRaw === '' || soRaw == null || soRaw === '') return null
const po = parseInt(poRaw, 10)
const so = parseInt(soRaw, 10)
if (!Number.isFinite(po) || !Number.isFinite(so)) return null
if (!unit) return null
const opts = listCoachStreamFocusOptions(unit)
if (!opts.some((o) => o.phaseOrder === po && o.streamOrder === so)) return null
return { phaseOrder: po, streamOrder: so }
}, [searchParams, unit])
const mergedPicks = useMemo(
() => mergeCoachBranchPicksWithUrlFocus(branchPicks, coachFocus),
[branchPicks, coachFocus]
)
const streamFocusOptions = useMemo(() => (unit ? listCoachStreamFocusOptions(unit) : []), [unit])
const navigationKey = coachBranchPicksStepStorageSuffix(mergedPicks)
const streamQuickSelectValue = useMemo(() => {
for (let i = 0; i < streamFocusOptions.length; i++) {
const o = streamFocusOptions[i]
if (mergedPicks[o.phaseOrder] === o.streamOrder) return o.valueKey
}
return ''
}, [streamFocusOptions, mergedPicks])
const hasStreamSelectParams =
(searchParams.get('po') != null && searchParams.get('po') !== '') ||
(searchParams.get('so') != null && searchParams.get('so') !== '')
const streamParamsInvalid = Boolean(unit && hasStreamSelectParams && !coachFocus)
const timeline = useMemo(() => flattenPlanTimeline(unit, mergedPicks), [unit, mergedPicks])
const outlineGroups = useMemo(() => coachOutlineGroupsFromTimeline(timeline), [timeline])
useEffect(() => {
if (!unitId || Number.isNaN(idNum)) {
setLoadError('Ungültige Trainingseinheit')
setLoading(false)
return
}
coachFocusResetRef.current = null
let cancelled = false
;(async () => {
setLoading(true)
@@ -201,9 +274,13 @@ export default function TrainingCoachPage() {
try {
await reloadUnit()
if (cancelled) return
let nextBranchPicks = {}
try {
const s = parseInt(sessionStorage.getItem(storageStepKey(idNum)), 10)
if (!Number.isNaN(s) && s >= 0) setStep(s)
const br = sessionStorage.getItem(coachBranchPicksStorageKey(idNum))
if (br) {
const o = JSON.parse(br)
if (o && typeof o === 'object') nextBranchPicks = normalizeCoachBranchPicks(o)
}
} catch {
/* ignore */
}
@@ -221,6 +298,10 @@ export default function TrainingCoachPage() {
} catch {
/* ignore */
}
if (!cancelled) {
setBranchPicks(nextBranchPicks)
setStreamChoiceHint(null)
}
} catch (e) {
if (!cancelled) setLoadError(e.message || 'Laden fehlgeschlagen')
} finally {
@@ -233,8 +314,68 @@ export default function TrainingCoachPage() {
}, [unitId, idNum, reloadUnit])
useEffect(() => {
sessionStorage.setItem(storageStepKey(idNum), String(step))
}, [idNum, step])
if (!unit) return
const po = searchParams.get('po')
const so = searchParams.get('so')
if ((po == null || po === '') && (so == null || so === '')) return
const p = parseInt(po, 10)
const s = parseInt(so, 10)
if (!Number.isFinite(p) || !Number.isFinite(s)) {
setSearchParams({}, { replace: true })
return
}
const opts = listCoachStreamFocusOptions(unit)
if (opts.length === 0 || !opts.some((o) => o.phaseOrder === p && o.streamOrder === s)) {
setSearchParams({}, { replace: true })
}
}, [unit, searchParams, setSearchParams])
useEffect(() => {
if (!unit) return
const ab = searchParams.get('atBranch')
if (ab == null || ab === '') return
const po = parseInt(ab, 10)
const phaseOrders = [...new Set(streamFocusOptions.map((o) => o.phaseOrder))]
if (!Number.isFinite(po) || !phaseOrders.includes(po)) {
const next = new URLSearchParams(searchParams)
next.delete('atBranch')
next.delete('preferSo')
setSearchParams(next, { replace: true })
}
}, [unit, searchParams, setSearchParams, streamFocusOptions])
useEffect(() => {
if (!unit || timeline.length === 0) return
const ab = searchParams.get('atBranch')
if (ab == null || ab === '') return
const po = parseInt(ab, 10)
if (!Number.isFinite(po)) return
const prefRaw = searchParams.get('preferSo')
const pref = prefRaw != null && prefRaw !== '' ? parseInt(prefRaw, 10) : NaN
const ix = findCoachTimelineJumpIndexForPhase(timeline, po, Number.isFinite(pref) ? pref : null)
if (ix >= 0) {
setStep(ix)
if (Number.isFinite(pref)) setStreamChoiceHint({ phaseOrder: po, streamOrder: pref })
}
const next = new URLSearchParams(searchParams)
next.delete('atBranch')
next.delete('preferSo')
setSearchParams(next, { replace: true })
}, [unit, timeline, searchParams, setSearchParams])
useEffect(() => {
if (Number.isNaN(idNum)) return
try {
sessionStorage.setItem(coachBranchPicksStorageKey(idNum), JSON.stringify(branchPicks))
} catch {
/* quota */
}
}, [idNum, branchPicks])
useEffect(() => {
if (Number.isNaN(idNum)) return
sessionStorage.setItem(storageStepKey(idNum, mergedPicks), String(step))
}, [idNum, mergedPicks, step])
useEffect(() => {
try {
@@ -258,46 +399,91 @@ export default function TrainingCoachPage() {
return () => clearInterval(iv)
}, [runStartAt])
const timeline = useMemo(() => flattenPlanTimeline(unit), [unit])
const clampStep = (s, len = timeline.length) =>
Math.max(0, Math.min(s, Math.max(len - 1, 0)))
const timerReset = useCallback(() => {
setRunStartAt(null)
setPausedAccumMs(0)
setTimerOwningStep(null)
}, [])
useEffect(() => {
if (!unit) return
if (timeline.length === 0) {
setStep(0)
return
}
if (coachDebriefPhase) return
setStep((prev) => clampStep(prev, timeline.length))
if (coachDebriefPhase) {
setStep(timeline.length - 1)
} else {
setStep((prev) => clampStep(prev, timeline.length))
}
}, [unit, timeline.length, coachDebriefPhase])
useEffect(() => {
if (!coachDebriefPhase || !unit || timeline.length === 0) return
setStep(timeline.length - 1)
}, [coachDebriefPhase, unit, timeline.length])
if (!unit || Number.isNaN(idNum)) return
if (timeline.length === 0) {
setStep(0)
return
}
const prev = coachFocusResetRef.current
if (prev === null) {
coachFocusResetRef.current = navigationKey
} else if (prev !== navigationKey) {
coachFocusResetRef.current = navigationKey
setCoachDebriefPhase(false)
setSplitRejoinPrompt(null)
timerReset()
} else {
return
}
try {
const raw = sessionStorage.getItem(storageStepKey(idNum, mergedPicks))
const s = parseInt(raw, 10)
const maxIdx = Math.max(0, timeline.length - 1)
if (!Number.isNaN(s) && s >= 0) setStep(Math.min(s, maxIdx))
else setStep(0)
} catch {
setStep(0)
}
}, [unit, idNum, navigationKey, mergedPicks, timeline.length, timerReset])
const elapsedMs =
pausedAccumMs + (runStartAt != null ? Date.now() - runStartAt : 0)
const tickDisplaySec = Math.max(0, Math.floor(elapsedMs / 1000))
const currentEntry = timeline[step]
const nextEntry = timeline[step + 1] || null
const next2Entry = timeline[step + 2] || null
const safeStep = useMemo(() => {
if (!timeline.length) return 0
return Math.min(Math.max(0, step), timeline.length - 1)
}, [step, timeline.length])
useLayoutEffect(() => {
if (!timeline.length) return
const max = timeline.length - 1
const s = Math.min(Math.max(0, step), max)
if (s !== step) setStep(s)
}, [step, timeline.length])
const currentEntry = timeline[safeStep] ?? null
const nextEntry = timeline[safeStep + 1] || null
const next2Entry = timeline[safeStep + 2] || null
const clockStr = formatClock(tickDisplaySec)
const roundedMinApply = elapsedMs <= 650 ? null : Math.max(1, Math.round(elapsedMs / 60000))
const showJumpToTimerOwner =
timerOwningStep != null &&
step !== timerOwningStep &&
safeStep !== timerOwningStep &&
(runStartAt != null || pausedAccumMs > 0)
const isLastCoachStep = timeline.length > 0 && step >= timeline.length - 1
const isLastCoachStep =
timeline.length > 0 &&
safeStep >= timeline.length - 1 &&
currentEntry?.entryKind !== COACH_ENTRY_BRANCH_GATE
const timerStart = () => {
setRunStartAt(Date.now())
setTimerOwningStep(step)
setTimerOwningStep(safeStep)
}
const timerPause = () => {
@@ -307,14 +493,8 @@ export default function TrainingCoachPage() {
}
}
const timerReset = () => {
setRunStartAt(null)
setPausedAccumMs(0)
setTimerOwningStep(null)
}
const applySuggestedDuration = () => {
const idx = timerOwningStep != null ? timerOwningStep : step
const idx = timerOwningStep != null ? timerOwningStep : safeStep
const ent = timeline[idx]
const item = ent?.item
if (!item || item.item_type !== 'exercise') return
@@ -325,12 +505,28 @@ export default function TrainingCoachPage() {
timerPause()
}
const pickStreamForPhase = useCallback(
(phaseOrder, streamOrder) => {
if (!Number.isFinite(phaseOrder) || !Number.isFinite(streamOrder)) return
setStreamChoiceHint(null)
setSplitRejoinPrompt(null)
setBranchPicks((prev) => ({ ...normalizeCoachBranchPicks(prev), [phaseOrder]: streamOrder }))
timerReset()
setCoachDebriefPhase(false)
setSearchParams({ po: String(phaseOrder), so: String(streamOrder) }, { replace: true })
},
[timerReset, setSearchParams]
)
const atBranchGate = currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE
const goPrev = () => setStep((s) => clampStep(s - 1))
const goNext = () => setStep((s) => clampStep(s + 1))
const markCurrentDoneAdvance = () => {
const ownerIdx = timerOwningStep != null ? timerOwningStep : step
const ownerIdx = timerOwningStep != null ? timerOwningStep : safeStep
const ent = timeline[ownerIdx]
if (ent?.entryKind === COACH_ENTRY_BRANCH_GATE) return
const item = ent?.item
if (item?.item_type === 'exercise' && elapsedMs > 650) {
const key = itemStableKey(item, ent.secOrder, ent.ii)
@@ -340,7 +536,12 @@ export default function TrainingCoachPage() {
timerReset()
const lastIdx = timeline.length - 1
if (step >= lastIdx && lastIdx >= 0) {
if (safeStep >= lastIdx && lastIdx >= 0) {
const rejoin = coachShouldPromptSplitRejoin(unit, timeline[safeStep])
if (rejoin) {
setSplitRejoinPrompt(rejoin)
return
}
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
@@ -349,25 +550,31 @@ export default function TrainingCoachPage() {
}
return
}
const nextIdx = safeStep + 1
if (nextIdx < timeline.length) {
const rejoinMid = coachShouldPromptSplitRejoinTransition(unit, timeline[safeStep], timeline[nextIdx])
if (rejoinMid) {
setSplitRejoinPrompt(rejoinMid)
return
}
}
setStep((s) => clampStep(s + 1, timeline.length))
}
const durationOverridesForApi = useMemo(() => {
const out = {}
for (let i = 0; i < timeline.length; i++) {
const ent = timeline[i]
const { item } = ent
if (item.item_type !== 'exercise' || item.id == null) continue
const k = itemStableKey(item, ent.secOrder, ent.ii)
const dv = deltas[k]?.actual_duration_min
if (dv !== undefined && dv !== '' && dv !== null && !Number.isNaN(Number(dv))) {
out[String(item.id)] = { actual_duration_min: Number(dv) }
}
}
return out
}, [timeline, deltas])
useEffect(() => {
if (!atBranchGate) return
if (runStartAt != null || pausedAccumMs > 0) timerReset()
}, [step, atBranchGate, runStartAt, pausedAccumMs, timerReset])
const durationOverridesForApi = useMemo(() => durationOverridesMapFromDeltas(unit, deltas), [unit, deltas])
useEffect(() => {
if (currentEntry?.entryKind === COACH_ENTRY_BRANCH_GATE) {
setCatalogExercise(null)
setCatalogError(null)
setCatalogLoading(false)
return
}
const item = currentEntry?.item
if (!item || item.item_type === 'note') {
setCatalogExercise(null)
@@ -403,16 +610,16 @@ export default function TrainingCoachPage() {
return () => {
cancelled = true
}
}, [step, currentEntry?.item?.exercise_id, currentEntry?.item?.exercise_variant_id, currentEntry?.item?.item_type])
}, [step, currentEntry?.entryKind, currentEntry?.item?.exercise_id, currentEntry?.item?.exercise_variant_id, currentEntry?.item?.item_type])
const handleSaveDebrief = async () => {
setSaveOk(null)
setSaving(true)
try {
const sectionsPayload = sectionsToPutPayload(unit, durationOverridesForApi)
const sectionsPayloadPart = buildCoachSavePlanPayload(unit, durationOverridesForApi)
const tn = trainerAppend.trim()
const payload = {
sections: sectionsPayload,
...sectionsPayloadPart,
...(saveMarkDone ? { status: 'completed' } : {}),
}
if (tn) {
@@ -422,18 +629,24 @@ export default function TrainingCoachPage() {
.trim()
}
await api.updateTrainingUnit(idNum, payload)
await reloadUnit()
setTrainerAppend('')
try {
sessionStorage.removeItem(storageDeltasKey(idNum))
sessionStorage.removeItem(storageDebriefKey(idNum))
sessionStorage.removeItem(coachBranchPicksStorageKey(idNum))
clearCoachStepStorageForUnit(idNum)
} catch {
/* ignore */
}
setDeltas({})
setBranchPicks({})
setStreamChoiceHint(null)
setSplitRejoinPrompt(null)
setCoachDebriefPhase(false)
setSaveOk('Gespeichert.')
setDebriefOpen(false)
setSaveOk('Gespeichert.')
setSearchParams({}, { replace: true })
navigate(`/planning/run/${unitId}`, { replace: true })
} catch (e) {
setSaveOk(`Fehler: ${e.message || e}`)
} finally {
@@ -487,6 +700,41 @@ export default function TrainingCoachPage() {
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
Planung
</button>
{streamFocusOptions.length > 0 ? (
<label
className="no-print"
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '0.82rem', color: 'var(--text2)' }}
>
<span style={{ color: 'var(--text3)', whiteSpace: 'nowrap' }}>Ansicht</span>
<select
className="form-input"
style={{ minWidth: 'min(220px, 72vw)', margin: 0, padding: '6px 8px', fontSize: '0.82rem' }}
value={streamQuickSelectValue}
onChange={(e) => {
setSplitRejoinPrompt(null)
setCoachDebriefPhase(false)
timerReset()
const v = e.target.value
if (!v) {
setBranchPicks({})
setStreamChoiceHint(null)
setSplitRejoinPrompt(null)
setSearchParams({}, { replace: true })
} else {
const [ppo, sso] = v.split('-').map((x) => parseInt(x, 10))
pickStreamForPhase(ppo, sso)
}
}}
>
<option value="">Ablauf mit Split-Punkten (Standard)</option>
{streamFocusOptions.map((o) => (
<option key={o.valueKey} value={o.valueKey}>
{o.label}
</option>
))}
</select>
</label>
) : null}
<button
type="button"
className="btn btn-primary"
@@ -497,6 +745,111 @@ export default function TrainingCoachPage() {
</button>
</nav>
{streamParamsInvalid ? (
<p
className="no-print card"
style={{
padding: '10px 12px',
fontSize: '0.82rem',
color: 'var(--danger)',
marginBottom: '8px',
flexShrink: 0,
}}
>
Ungültige Stream-Parameter in der Adresszeile — es wird der Gesamtplan angezeigt.
</p>
) : null}
{splitRejoinPrompt && !coachDebriefPhase ? (
<div
className="card no-print"
style={{
flexShrink: 0,
marginBottom: '10px',
padding: '16px 14px',
borderRadius: '12px',
border: '2px solid var(--accent)',
background: 'linear-gradient(135deg, var(--accent-light), var(--surface))',
}}
>
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
Parallelphase · Abschluss
</div>
<p style={{ fontSize: '0.95rem', fontWeight: 700, margin: '0 0 8px', color: 'var(--text1)' }}>
{splitRejoinPrompt.phaseTitle != null && String(splitRejoinPrompt.phaseTitle).trim()
? String(splitRejoinPrompt.phaseTitle).trim()
: `Phase ${splitRejoinPrompt.phaseOrderIndex}`}
{' — '}
alle Gruppen zusammen?
</p>
<p style={{ fontSize: '0.84rem', color: 'var(--text2)', margin: '0 0 12px', lineHeight: 1.45 }}>
Diese Phase hat mehrere Streams. Kurz mit dem anderen Trainer klären, dann gemeinsam weitermachen. Ist-Zeiten
und Speichern erfolgen in der Nachbereitung am Ende der Einheit.
</p>
<ul style={{ margin: '0 0 14px', paddingLeft: '1.2rem', fontSize: '0.82rem', color: 'var(--text2)' }}>
{splitRejoinPrompt.streams.map((st) => (
<li key={st.printStreamId || `s-${st.streamOrder}`}>
{st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}{' '}
<span style={{ color: 'var(--text3)' }}>(ca. {st.minutes} Min. Üb.)</span>
</li>
))}
</ul>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{safeStep < timeline.length - 1 ? (
<button
type="button"
className="btn btn-primary"
style={{ minHeight: '48px', fontWeight: 700 }}
onClick={() => {
setSplitRejoinPrompt(null)
setStep((s) => clampStep(s + 1, timeline.length))
}}
>
Gruppen zusammengeführt — weiter mit dem Plan
</button>
) : (
<button
type="button"
className="btn btn-primary"
style={{ minHeight: '48px', fontWeight: 700 }}
onClick={() => {
setSplitRejoinPrompt(null)
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
} catch {
/* ignore */
}
}}
>
Alle Gruppen fertig — zur Nachbereitung
</button>
)}
<button type="button" className="btn btn-secondary" style={{ minHeight: '44px' }} onClick={() => setSplitRejoinPrompt(null)}>
Zurück — andere Gruppe läuft noch
</button>
<button
type="button"
className="btn btn-secondary"
style={{ minHeight: '44px', fontSize: '0.82rem' }}
onClick={() => {
setSplitRejoinPrompt(null)
setCoachDebriefPhase(true)
try {
sessionStorage.setItem(storageDebriefKey(idNum), '1')
} catch {
/* ignore */
}
}}
>
{safeStep < timeline.length - 1
? 'Ausnahme: jetzt schon zur Nachbereitung'
: 'Ausnahme: trotzdem zur Nachbereitung'}
</button>
</div>
</div>
) : null}
<header
className="card training-coach-hero training-coach-hero--compact"
style={{
@@ -510,44 +863,93 @@ export default function TrainingCoachPage() {
>
<div style={{ fontSize: '0.7rem', color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
Coach ·{' '}
{coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(step || 0) + 1} / ${Math.max(timeline.length, 1)}`}
{coachDebriefPhase ? 'Nachbereitung · abschließend speichern' : `Schritt ${(safeStep || 0) + 1} / ${Math.max(timeline.length, 1)}`}
</div>
<h1 style={{ fontSize: '1.1rem', margin: '4px 0 0', lineHeight: 1.28 }}>
{unit.planned_date}
{unit.planned_time_start && ` · ${String(unit.planned_time_start).slice(0, 5)}`}
{unit.planned_focus ? ` · ${unit.planned_focus}` : ''}
</h1>
{streamFocusOptions.length > 0 ? (
<p style={{ fontSize: '0.8rem', color: 'var(--text2)', margin: '8px 0 0', lineHeight: 1.4 }}>
Parallele Phasen erscheinen als Schritt <strong>Gruppe wählen</strong> — kein Durcheinander mehr aus
verschränkten Streams. Pro paralleler Phase entscheiden Sie (oder der Co-Trainer auf dem eigenen Gerät), welcher
Stream coacht wird. Kurzwahl oben springt die betreffende Phase sofort auf einen Stream (z. B. zwischen Gruppen
wechseln).
{Object.keys(mergedPicks).length > 0 ? (
<span style={{ display: 'block', marginTop: '6px', color: 'var(--text3)', fontSize: '0.78rem' }}>
Aktuell festgelegt:{' '}
{Object.keys(mergedPicks)
.map((pk) => {
const po = parseInt(pk, 10)
const so = mergedPicks[pk]
const o = streamFocusOptions.find((x) => x.phaseOrder === po && x.streamOrder === so)
return o?.label ?? `Phase ${po} · Stream ${so}`
})
.join(' · ')}
</span>
) : null}
</p>
) : null}
</header>
{outlineOpen && (
<div className="card training-coach-outline" style={{ flexShrink: 0, marginBottom: '8px', padding: '10px 12px', maxHeight: 'min(28vh, 260px)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
<div style={{ fontSize: '0.75rem', color: 'var(--text3)', marginBottom: '6px', flexShrink: 0 }}>Ablauf · Antippen zum Springen</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px', overflowY: 'auto', minHeight: 0 }}>
{timeline.map((ent, ix) => {
const lbl = summarizeTimelineEntry(ent)
const secTitle = ent.sec.title || `Abschnitt ${ent.si + 1}`
const active = coachDebriefPhase ? ix === timeline.length - 1 : ix === step
return (
<button
key={`${itemStableKey(ent.item, ent.secOrder, ent.ii)}-${ix}`}
type="button"
className={`btn ${active ? 'btn-primary' : 'btn-secondary'}`}
<div style={{ fontSize: '0.75rem', color: 'var(--text3)', marginBottom: '6px', flexShrink: 0 }}>
Trainingsrahmen · nach Blöcken und Streams
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', overflowY: 'auto', minHeight: 0 }}>
{outlineGroups.map((grp) => (
<div key={grp.mergeKey} style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
<div
style={{
textAlign: 'left',
justifyContent: 'flex-start',
opacity: active ? 1 : 0.92,
fontWeight: active ? 700 : 500
}}
onClick={() => {
setCoachDebriefPhase(false)
setStep(ix)
fontSize: '0.72rem',
fontWeight: 700,
color: 'var(--accent-dark)',
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
<span style={{ opacity: 0.75 }}>{secTitle.substring(0, 14)} › </span>
<span>{lbl}</span>
</button>
)
})}
{grp.heading}
{grp.sub ? <span style={{ fontWeight: 600, color: 'var(--text3)', textTransform: 'none' }}> · {grp.sub}</span> : null}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
{grp.entries.map(({ ix, ent }) => {
const lbl = summarizeTimelineEntry(ent)
const ctx = ent.coachContext || ''
const active = coachDebriefPhase ? ix === timeline.length - 1 : ix === safeStep
const rowKey =
ent.entryKind === COACH_ENTRY_BRANCH_GATE
? `gate-${ix}`
: `${itemStableKey(ent.item, ent.secOrder, ent.ii)}-${ix}`
return (
<button
key={rowKey}
type="button"
className={`btn ${active ? 'btn-primary' : 'btn-secondary'}`}
style={{
textAlign: 'left',
justifyContent: 'flex-start',
opacity: active ? 1 : 0.92,
fontWeight: active ? 700 : 500,
}}
onClick={() => {
setCoachDebriefPhase(false)
setStep(ix)
}}
>
{ctx ? (
<span style={{ opacity: 0.8, display: 'block', fontSize: '0.72rem', marginBottom: '2px' }}>
{ctx.length > 42 ? `${ctx.slice(0, 40)}…` : ctx}
</span>
) : null}
<span>{lbl}</span>
</button>
)
})}
</div>
</div>
))}
</div>
</div>
)}
@@ -567,13 +969,16 @@ export default function TrainingCoachPage() {
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
{timeline
.filter((e) => e.item.item_type === 'exercise')
.filter((e) => e.item?.item_type === 'exercise')
.map((ent) => {
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
return (
<label key={`db-${k}`} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
<span style={{ wordBreak: 'break-word' }}>{summarizeTimelineEntry(ent)}</span>
<span style={{ wordBreak: 'break-word' }}>
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
{summarizeTimelineEntry(ent)}
</span>
<input
type="number"
min="0"
@@ -636,6 +1041,8 @@ export default function TrainingCoachPage() {
</div>
) : (
<>
{!splitRejoinPrompt ? (
<>
<div
className="training-coach-assist training-coach-assist--compact"
style={{
@@ -649,7 +1056,12 @@ export default function TrainingCoachPage() {
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--accent-dark)', marginBottom: '6px' }}>
Als Nächstes
</div>
{nextEntry ? (
{atBranchGate ? (
<p style={{ margin: 0, fontSize: '0.88rem', color: 'var(--text2)', lineHeight: 1.45 }}>
Wählen Sie unten eine Gruppe. Danach zeigt der Coach fortlaufend nur die Übungen dieses Streams in dieser
parallelen Phase.
</p>
) : nextEntry ? (
<>
<p style={{ margin: '0', fontSize: '0.9rem', color: 'var(--text1)', lineHeight: 1.4 }}>
<strong>Nächste:</strong> {summarizeTimelineEntry(nextEntry)}
@@ -668,7 +1080,7 @@ export default function TrainingCoachPage() {
</div>
<CoachControlsBand
step={step}
step={safeStep}
timelineLength={timeline.length}
onPrev={goPrev}
onNext={goNext}
@@ -684,15 +1096,99 @@ export default function TrainingCoachPage() {
isLastCoachStep={isLastCoachStep}
showJumpToTimerOwner={showJumpToTimerOwner}
showJumpToTimerOwnerRow
onJumpToTimerOwner={() => setStep(timerOwningStep ?? step)}
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
<div className="training-coach-scroll">
{currentEntry?.item?.item_type === 'note' ? (
{atBranchGate && currentEntry?.branchMeta ? (
<div
className="card"
style={{
padding: '18px 16px',
marginBottom: '12px',
borderRadius: '14px',
border: '2px solid var(--accent)',
background: 'linear-gradient(180deg, var(--accent-light) 0%, var(--surface) 38%)',
boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
}}
>
<div style={{ fontSize: '0.74rem', fontWeight: 800, color: 'var(--accent-dark)', marginBottom: '6px', letterSpacing: '0.04em' }}>
⑂ SPLIT — GRUPPE WÄHLEN
</div>
<p style={{ fontSize: '1.05rem', fontWeight: 800, margin: '0 0 8px', color: 'var(--text1)' }}>
{currentEntry.branchMeta.phaseTitle != null && String(currentEntry.branchMeta.phaseTitle).trim()
? String(currentEntry.branchMeta.phaseTitle).trim()
: `Phase ${currentEntry.branchMeta.phaseOrderIndex}`}
</p>
<p style={{ fontSize: '0.88rem', color: 'var(--text2)', margin: '0 0 16px', lineHeight: 1.45 }}>
Tippen Sie auf eine Kachel, um <strong>diese Gruppe</strong> zu coachen. Andere Trainer:innen wählen auf
ihrem Gerät parallel eine andere Kachel.
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '12px' }}>
{(currentEntry.branchMeta.streams || []).map((st) => {
const hinted =
streamChoiceHint?.phaseOrder === currentEntry.branchMeta.phaseOrderIndex &&
streamChoiceHint?.streamOrder === st.streamOrder
const label = st.streamTitle?.trim() ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`
const baseBg = hinted ? 'var(--accent)' : 'var(--surface2)'
const baseColor = hinted ? '#fff' : 'var(--text1)'
const borderCol = hinted ? 'var(--accent-dark)' : 'var(--border)'
return (
<button
key={st.printStreamId || `s-${st.streamOrder}`}
type="button"
className="btn"
style={{
textAlign: 'left',
justifyContent: 'flex-start',
flexDirection: 'column',
alignItems: 'stretch',
padding: '14px 16px',
minHeight: '96px',
fontWeight: 700,
background: baseBg,
color: baseColor,
border: `2px solid ${borderCol}`,
borderRadius: '12px',
boxShadow: hinted ? '0 4px 0 var(--accent-dark)' : '0 3px 0 hsl(200 20% 78%)',
transition: 'transform 0.08s ease, box-shadow 0.08s ease',
}}
onClick={() => pickStreamForPhase(currentEntry.branchMeta.phaseOrderIndex, st.streamOrder)}
>
<span style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '1rem' }}>
<span style={{ fontSize: '1.35rem', lineHeight: 1 }} aria-hidden="true">
{hinted ? '◉' : '○'}
</span>
<span>{label}</span>
</span>
<span
style={{
display: 'block',
fontSize: '0.82rem',
fontWeight: 600,
opacity: hinted ? 0.95 : 0.88,
marginTop: '8px',
}}
>
≈ {st.minutes} Min. Üb. · Jetzt aktivieren
</span>
{hinted ? (
<span style={{ display: 'block', fontSize: '0.74rem', fontWeight: 600, marginTop: '8px', opacity: 0.92 }}>
Vorschlag aus Planansicht — trotzdem andere Kachel möglich
</span>
) : null}
</button>
)
})}
</div>
</div>
) : currentEntry?.item?.item_type === 'note' ? (
<div className="card" style={{ padding: '16px 14px' }}>
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '8px' }}>
{currentEntry.sec.title || 'Abschnitt'} · Coach-Notiz · Teil {step + 1}
{currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Coach-Notiz · Teil{' '}
{safeStep + 1}
</div>
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginBottom: '6px' }}>Coach-Notiz</div>
<p style={{ fontSize: '1.05rem', lineHeight: 1.52, whiteSpace: 'pre-wrap', margin: 0 }}>{currentEntry.item.note_body || ''}</p>
@@ -701,7 +1197,8 @@ export default function TrainingCoachPage() {
<>
<div className="card training-coach-plan-strip" style={{ padding: '12px 14px', marginBottom: '12px', borderRadius: '12px', borderLeft: `3px solid var(--accent)` }}>
<div style={{ fontSize: '0.74rem', color: 'var(--text3)', marginBottom: '6px' }}>
In diesem Training · {currentEntry?.sec.title || 'Abschnitt'} · Teil {step + 1}
In diesem Training · {currentEntry?.coachContext || currentEntry?.sec?.title || 'Abschnitt'} · Teil{' '}
{safeStep + 1}
</div>
{currentEntry?.item && (
<>
@@ -789,13 +1286,16 @@ export default function TrainingCoachPage() {
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '12px' }}>
{timeline
.filter((e) => e.item.item_type === 'exercise')
.filter((e) => e.item?.item_type === 'exercise')
.map((ent) => {
const k = itemStableKey(ent.item, ent.secOrder, ent.ii)
const val = deltas[k]?.actual_duration_min ?? ent.item.actual_duration_min ?? ''
return (
<label key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 88px', gap: '10px', alignItems: 'center', fontSize: '0.88rem' }}>
<span style={{ wordBreak: 'break-word' }}>{summarizeTimelineEntry(ent)}</span>
<span style={{ wordBreak: 'break-word' }}>
{ent.coachContext ? <span style={{ color: 'var(--text3)' }}>{ent.coachContext} · </span> : null}
{summarizeTimelineEntry(ent)}
</span>
<input
type="number"
min="0"
@@ -841,7 +1341,7 @@ export default function TrainingCoachPage() {
</div>
<CoachControlsBand
step={step}
step={safeStep}
timelineLength={timeline.length}
onPrev={goPrev}
onNext={goNext}
@@ -857,9 +1357,12 @@ export default function TrainingCoachPage() {
isLastCoachStep={isLastCoachStep}
showJumpToTimerOwner={showJumpToTimerOwner}
showJumpToTimerOwnerRow={false}
onJumpToTimerOwner={() => setStep(timerOwningStep ?? step)}
onJumpToTimerOwner={() => setStep(timerOwningStep ?? safeStep)}
timerOwnerLabelIndex={timerOwningStep ?? 0}
branchGateMode={atBranchGate}
/>
</>
) : null}
</>
)}
</div>
@@ -12,8 +12,12 @@ import {
defaultSection,
normalizeUnitToForm,
enrichSectionsWithVariants,
buildSectionsPayload,
buildPlanPayloadForSave,
hydrateExercisePlanningRow,
reorderBlockIntoParallelStreamEnd,
indicesOfParallelPhase,
reorderSectionBeforeParallelRunAsWholeGroup,
reorderSectionAsFirstInParallelStream,
} from '../utils/trainingUnitSectionsForm'
const DND_FW_SLOT = 'application/x-shinkan-framework-slot'
@@ -47,10 +51,10 @@ function emptySlot() {
async function enrichFrameworkSlotSections(slots) {
const out = []
for (const s of slots || []) {
const sec = normalizeUnitToForm({ sections: s.sections, exercises: s.exercises })
const baseSecs = s.sections && s.sections.length ? s.sections : [defaultSection('Ablauf')]
out.push({
...s,
sections: await enrichSectionsWithVariants(sec),
sections: await enrichSectionsWithVariants(baseSecs),
})
}
return out
@@ -131,7 +135,11 @@ function serverFrameworkToForm(fw) {
slots: (fw.slots || []).map((s) => ({
title: s.title || '',
notes: s.notes || '',
sections: normalizeUnitToForm({ sections: s.sections, exercises: s.exercises }),
sections: normalizeUnitToForm({
sections: s.sections,
exercises: s.exercises,
phases: s.phases,
}),
})),
}
}
@@ -150,13 +158,16 @@ function buildApiPayload(form) {
const slots = (form.slots || []).map((s, si) => {
const secList = s.sections && s.sections.length ? s.sections : [defaultSection('Ablauf')]
const sectionsPayload = buildSectionsPayload(secList)
return {
const plan = buildPlanPayloadForSave(secList)
const base = {
sort_order: si,
title: (s.title || '').trim() || null,
notes: (s.notes || '').trim() || null,
sections: sectionsPayload,
}
if (plan.phases) {
return { ...base, phases: plan.phases }
}
return { ...base, sections: plan.sections }
})
const focusAreaId =
@@ -553,7 +564,17 @@ export default function TrainingFrameworkProgramEditPage() {
}
const moveSectionsAcrossFrameworkSlots = useCallback(
({ fromSlot, fromSectionIdx, toSlot, toSectionIdx }) => {
(payload) => {
const {
fromSlot,
fromSectionIdx,
toSlot,
toSectionIdx,
toParallelStream,
parallelPhaseRunOrderIndex,
insertBeforeParallelInTarget,
firstInParallelStreamInTarget,
} = payload
setForm((prev) => {
const slots = prev.slots.map((sl) => ({
...sl,
@@ -571,6 +592,44 @@ export default function TrainingFrameworkProgramEditPage() {
}
const fromSecs = slots[fromSlot].sections
const toSecs = slots[toSlot].sections
const applyParallelStreamEnd =
toParallelStream != null && toParallelStream.po != null && toParallelStream.so != null
? (secs, insertedAt) => {
const po = Number(toParallelStream.po) || 0
const so = Number(toParallelStream.so) || 0
return reorderBlockIntoParallelStreamEnd(secs, insertedAt, po, so)
}
: null
/** Gesamten Parallel-Lauf aus fromSlot an toSectionIdx in toSlot legen */
if (parallelPhaseRunOrderIndex != null && parallelPhaseRunOrderIndex !== '') {
const po = Number(parallelPhaseRunOrderIndex) || 0
const idxs = indicesOfParallelPhase(fromSecs, po)
if (!idxs.length) {
return prev
}
const blocks = idxs.map((i) => fromSecs[i])
for (const i of [...idxs].sort((a, b) => b - a)) {
fromSecs.splice(i, 1)
}
if (fromSlot === toSlot) {
let insertAt = Number(toSectionIdx) || 0
for (const i of idxs) {
if (i < insertAt) insertAt -= 1
}
insertAt = Math.max(0, Math.min(insertAt, fromSecs.length))
fromSecs.splice(insertAt, 0, ...blocks)
slots[fromSlot].sections = fromSecs
return { ...prev, slots }
}
const insertAt = Math.max(0, Math.min(Number(toSectionIdx) || 0, toSecs.length))
toSecs.splice(insertAt, 0, ...blocks)
slots[toSlot].sections = toSecs
return { ...prev, slots }
}
if (
typeof fromSectionIdx !== 'number' ||
fromSectionIdx < 0 ||
@@ -586,12 +645,48 @@ export default function TrainingFrameworkProgramEditPage() {
if (fromSectionIdx < toSectionIdx) insertAt = toSectionIdx - 1
insertAt = Math.max(0, Math.min(insertAt, fromSecs.length))
fromSecs.splice(insertAt, 0, block)
if (applyParallelStreamEnd) {
slots[fromSlot].sections = applyParallelStreamEnd(fromSecs, insertAt)
} else {
slots[fromSlot].sections = fromSecs
}
return { ...prev, slots }
}
if (insertBeforeParallelInTarget != null && insertBeforeParallelInTarget !== '') {
const tpo = Number(insertBeforeParallelInTarget) || 0
const pIdxs = indicesOfParallelPhase(toSecs, tpo)
const ins = pIdxs.length ? pIdxs[0] : toSecs.length
toSecs.splice(ins, 0, block)
slots[toSlot].sections = reorderSectionBeforeParallelRunAsWholeGroup(toSecs, ins, tpo)
return { ...prev, slots }
}
if (
firstInParallelStreamInTarget != null &&
firstInParallelStreamInTarget.po != null &&
firstInParallelStreamInTarget.so != null
) {
const fpo = Number(firstInParallelStreamInTarget.po) || 0
const fso = Number(firstInParallelStreamInTarget.so) || 0
const nextSecs = [...toSecs, block]
const movedFromI = nextSecs.length - 1
slots[toSlot].sections = reorderSectionAsFirstInParallelStream(
nextSecs,
movedFromI,
fpo,
fso
)
return { ...prev, slots }
}
const toSecs = slots[toSlot].sections
const ia = Math.max(0, Math.min(toSectionIdx, toSecs.length))
toSecs.splice(ia, 0, block)
if (applyParallelStreamEnd) {
slots[toSlot].sections = applyParallelStreamEnd(toSecs, ia)
} else {
slots[toSlot].sections = toSecs
}
return { ...prev, slots }
})
},
@@ -694,6 +789,7 @@ export default function TrainingFrameworkProgramEditPage() {
showExecutionExtras={false}
wideExerciseGrid
slotIndex={si}
enableParallelPhaseControls
onMoveSectionsAcrossSlots={moveSectionsAcrossFrameworkSlots}
onSectionsChange={(updater) => {
setForm((prev) => ({
@@ -758,7 +854,7 @@ export default function TrainingFrameworkProgramEditPage() {
<strong style={{ color: 'var(--text1)' }}>Rahmenprogramm (Bibliothek):</strong> Wiederverwendbare Vorlage mit
Zielen und Session‑Slots. Die <strong>Zuordnung zu Gruppe oder Kalendertermin</strong> erfolgt aus der{' '}
<strong>Gruppen‑Planung</strong> („Übernahme“). Pro Slot planst du den Ablauf wie bei einer Trainingsseinheit:{' '}
<strong>Abschnitte</strong>, Übungen mit Varianten und Dauer, <strong>Zwischen‑Anmerkungen</strong>.
<strong>Abschnitte</strong>, optional <strong>Ganzgruppen- und parallele Phasen (Breakout)</strong>, Übungen mit Varianten und Dauer, <strong>Zwischen‑Anmerkungen</strong>. Abschnitte kannst du per Ziehen auch in eine andere Session legen.
</div>
</details>
+514 -162
View File
@@ -1,13 +1,18 @@
/**
* Trainingsablauf anzeigen, drucken und lokal auf der Matte abhaken (Fortschritt im Browser gespeichert).
* Parallele Streams: rendering nutzt sortedSections/sortedItems (trainingPlanUtils); Fortschritt pro unitId — später ggf. pro Stream.
* Phasen: Ganzgruppe vs. Split (planLoc); Druck mit optional getrennten Breakout-Seiten.
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import api from '../utils/api'
import ExercisePeekModal from '../components/ExercisePeekModal'
import CombinationPlanBracket from '../components/CombinationPlanBracket'
import { itemStableKey, sortedSections, sortedItems } from '../utils/trainingPlanUtils'
import {
buildPlanRunViewModelFromSections,
itemStableKey,
sectionsWithPlanLocForDisplay,
sortedItems,
} from '../utils/trainingPlanUtils'
import { effectiveComboMethodProfile } from '../utils/comboPlanningMethodProfile'
function storageKey(unitId) {
@@ -37,6 +42,8 @@ export default function TrainingUnitRunPage() {
const [loading, setLoading] = useState(true)
const [checked, setChecked] = useState(() => new Set())
const [peekCtx, setPeekCtx] = useState(null)
/** null | printStreamId z. B. p0-s1 — nur dieser Split-Stream in @media print */
const [printOnlyStreamId, setPrintOnlyStreamId] = useState(null)
const loadChecked = useCallback((uid) => {
try {
@@ -108,20 +115,245 @@ export default function TrainingUnitRunPage() {
}
}, [idNum, persistChecked])
const sections = useMemo(() => sortedSections(unit), [unit])
const sections = useMemo(() => sectionsWithPlanLocForDisplay(unit), [unit])
const planModel = useMemo(() => buildPlanRunViewModelFromSections(sections), [sections])
const totalPlannedMin = useMemo(() => {
let t = 0
for (const sec of sections) {
for (const it of sortedItems(sec)) {
if (it.item_type === 'exercise' && it.planned_duration_min != null) {
const n = Number(it.planned_duration_min)
if (Number.isFinite(n)) t += n
}
const printStreamOptions = useMemo(() => {
const opts = []
for (const run of planModel.runs) {
if (run.kind !== 'parallel' || !run.streams) continue
for (const st of run.streams) {
opts.push({
id: st.printStreamId,
label: `${run.phaseTitle ? String(run.phaseTitle).trim().slice(0, 28) : `Phase ${run.phaseOrderIndex}`} · ${st.streamTitle ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}`,
})
}
}
return t
}, [sections])
return opts
}, [planModel.runs])
const totalPlannedMin = planModel.totalMin
const showWholeGroupInView = !printOnlyStreamId
const showStreamColumn = (streamPrintId) => !printOnlyStreamId || streamPrintId === printOnlyStreamId
const renderSectionCard = (sec, siInUnit) => {
const secOrder = sec.order_index ?? siInUnit
const items = sortedItems(sec)
return (
<section
key={sec.id ?? `sec-${secOrder}-${siInUnit}`}
className="card training-run-section"
style={{ padding: '1.15rem 1.25rem' }}
>
<h2 style={{ fontSize: '1.05rem', marginBottom: '0.65rem', color: 'var(--accent-dark)' }}>
{sec.title || `Abschnitt ${siInUnit + 1}`}
</h2>
{sec.guidance_notes && (
<p
style={{
fontSize: '0.88rem',
color: 'var(--text2)',
marginBottom: '0.85rem',
whiteSpace: 'pre-wrap',
}}
>
{sec.guidance_notes}
</p>
)}
<ul
style={{
listStyle: 'none',
padding: 0,
margin: 0,
display: 'flex',
flexDirection: 'column',
gap: '0.65rem',
}}
>
{items.map((it, ii) => {
const ck = itemStableKey(it, secOrder, ii)
const done = checked.has(ck)
if (it.item_type === 'note') {
return (
<li
key={ck}
className={`training-run-item training-run-item--note${done ? ' training-run-item--done' : ''}`}
>
<label
style={{
display: 'flex',
gap: '0.75rem',
alignItems: 'flex-start',
cursor: 'pointer',
fontSize: '0.92rem',
}}
>
<input
type="checkbox"
className="training-run-checkbox training-run-checkbox--printable"
checked={done}
onChange={() => toggle(ck)}
style={{ marginTop: '4px', width: '20px', height: '20px' }}
/>
<span style={{ whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>
<em style={{ fontStyle: 'normal', color: 'var(--text3)', fontSize: '0.8rem' }}>
Notiz
</em>
<br />
{it.note_body || ''}
</span>
</label>
</li>
)
}
const title =
it.exercise_title || (it.exercise_id ? `Übung #${it.exercise_id}` : 'Übung')
const variant = it.exercise_variant_name ? ` (${it.exercise_variant_name})` : ''
const plan = formatMin(it.planned_duration_min)
const extras = []
if (it.exercise_focus_area) extras.push(it.exercise_focus_area)
const exKind = String(it.exercise_kind || 'simple').toLowerCase().trim()
const isComboRow = exKind === 'combination'
const metaParts = [...extras, isComboRow ? 'Kombination' : null, plan].filter(Boolean)
const comboEffectiveProfile = isComboRow
? effectiveComboMethodProfile(
it.catalog_method_profile || {},
it.planning_method_profile ?? null
)
: null
return (
<li
key={ck}
className={`training-run-item training-run-item--exercise${done ? ' training-run-item--done' : ''}`}
>
<label
style={{
display: 'flex',
gap: '0.75rem',
alignItems: 'flex-start',
cursor: 'pointer',
}}
>
<input
type="checkbox"
className="training-run-checkbox training-run-checkbox--printable"
checked={done}
onChange={() => toggle(ck)}
style={{
marginTop: '6px',
width: '22px',
height: '22px',
flexShrink: 0,
}}
/>
<span style={{ flex: 1, minWidth: 0 }}>
<span style={{ fontSize: '1.02rem', fontWeight: 600 }}>
{title}
{variant}
</span>
{metaParts.length > 0 && (
<div
style={{
fontSize: '0.85rem',
color: 'var(--text3)',
marginTop: '3px',
lineHeight: 1.35,
}}
>
{metaParts.join(' · ')}
</div>
)}
{(it.notes || it.modifications) && (
<div
style={{
marginTop: '0.35rem',
fontSize: '0.88rem',
color: 'var(--text2)',
whiteSpace: 'pre-wrap',
}}
>
{it.notes && (
<>
<strong style={{ fontWeight: 600 }}>Coach:</strong> {it.notes}
</>
)}
{it.modifications && (
<>
{it.notes ? <br /> : null}
<strong style={{ fontWeight: 600 }}>Anpassung:</strong> {it.modifications}
</>
)}
</div>
)}
{isComboRow && it.exercise_id ? (
<div className="training-run-combo-embed">
<CombinationPlanBracket
methodArchetype={String(it.catalog_method_archetype || '').trim()}
methodProfile={comboEffectiveProfile || {}}
combinationSlots={
Array.isArray(it.combination_slots) ? it.combination_slots : []
}
planningAdjusted={
it.planning_method_profile != null &&
typeof it.planning_method_profile === 'object' &&
!Array.isArray(it.planning_method_profile)
}
/>
</div>
) : null}
{it.exercise_id && (
<div
className="no-print"
style={{
display: 'flex',
flexWrap: 'wrap',
gap: '10px',
marginTop: '0.55rem',
alignItems: 'center',
}}
>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: '0.82rem', margin: 0 }}
onClick={() =>
setPeekCtx({
exerciseId: it.exercise_id,
variantId:
it.exercise_variant_id != null
? Number(it.exercise_variant_id)
: null,
peekExtras: isComboRow
? {
catalog_method_profile: it.catalog_method_profile,
planning_method_profile: it.planning_method_profile,
}
: undefined,
})
}
>
Katalog (Popup)
</button>
<Link
to={`/exercises/${it.exercise_id}`}
style={{ fontSize: '0.82rem', color: 'var(--accent)' }}
>
Vollständige Seite öffnen
</Link>
</div>
)}
</span>
</label>
</li>
)
})}
</ul>
</section>
)
}
if (loading) {
return (
@@ -153,21 +385,66 @@ export default function TrainingUnitRunPage() {
onClose={() => setPeekCtx(null)}
/>
<nav className="training-run-toolbar no-print" style={{ marginBottom: '1rem', display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
<nav
className="training-run-toolbar no-print"
style={{
marginBottom: '1rem',
display: 'flex',
gap: '0.5rem',
flexWrap: 'wrap',
alignItems: 'center',
}}
>
<button type="button" className="btn btn-secondary" onClick={() => navigate('/planning')}>
Zur Planung
</button>
<Link
to={`/planning/run/${unitId}/coach`}
className="btn btn-primary"
style={{ textDecoration: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
style={{
textDecoration: 'none',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
Im Training (Coach)
</Link>
<button type="button" className="btn btn-secondary" onClick={() => window.print()}>
Drucken / PDF
</button>
<button type="button" className="btn btn-secondary" title="Alle Häkchen auf dieser Matte zurücksetzen" onClick={() => confirm('Fortschritt wirklich zurücksetzen?') && clearProgress()}>
{printStreamOptions.length > 0 ? (
<label
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
fontSize: '0.86rem',
color: 'var(--text2)',
}}
>
Druck / Vorschau
<select
className="form-input"
style={{ marginBottom: 0, minWidth: '200px', fontSize: '0.86rem' }}
value={printOnlyStreamId || ''}
onChange={(e) => setPrintOnlyStreamId(e.target.value || null)}
>
<option value="">Gesamter Plan (empfohlen)</option>
{printStreamOptions.map((o) => (
<option key={o.id} value={o.id}>
Nur: {o.label}
</option>
))}
</select>
</label>
) : null}
<button
type="button"
className="btn btn-secondary"
title="Alle Häkchen auf dieser Matte zurücksetzen"
onClick={() => confirm('Fortschritt wirklich zurücksetzen?') && clearProgress()}
>
Fortschritt leeren
</button>
</nav>
@@ -201,10 +478,81 @@ export default function TrainingUnitRunPage() {
</span>
{totalPlannedMin > 0 && (
<span>
<strong>Geplante Zeit (Übungen):</strong> ca. {totalPlannedMin} Min.
<strong>Geplante Zeit (Übungen, gesamt):</strong> ca. {totalPlannedMin} Min.
</span>
)}
</div>
{printOnlyStreamId ? (
<div
className="no-print"
style={{
marginTop: '0.75rem',
padding: '0.5rem 0.75rem',
background: 'hsl(200 40% 94%)',
borderRadius: '8px',
fontSize: '0.82rem',
color: 'hsl(200 25% 28%)',
}}
>
Vorschau wie fürs Drucken: nur die gewählte Split-Gruppe. Ganzgruppen-Blöcke sind ausgeblendet.
</div>
) : null}
{planModel.mode === 'phased' && planModel.runs.length > 0 && showWholeGroupInView && (
<div
className="training-run-phase-schedule training-run-notes-print"
style={{
marginTop: '1rem',
padding: '0.75rem 0.9rem',
background: 'var(--surface2)',
borderRadius: '8px',
fontSize: '0.86rem',
overflowX: 'auto',
}}
>
<strong style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text1)' }}>
Zeitplanung (Summe Übungsminuten)
</strong>
<table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '280px' }}>
<thead>
<tr style={{ textAlign: 'left', color: 'var(--text3)', fontSize: '0.78rem' }}>
<th style={{ padding: '4px 8px 4px 0', fontWeight: 600 }}>Block</th>
<th style={{ padding: '4px 8px', fontWeight: 600 }}>Art</th>
<th style={{ padding: '4px 8px', fontWeight: 600 }}> Min</th>
<th style={{ padding: '4px 0 4px 8px', fontWeight: 600 }}>∑ bis hier</th>
</tr>
</thead>
<tbody>
{planModel.runs.map((run, ri) => {
const cum = planModel.runCumulativeEnds[ri]
const label =
run.phaseTitle != null && String(run.phaseTitle).trim()
? String(run.phaseTitle).trim()
: run.kind === 'legacy'
? 'Ablauf'
: run.kind === 'whole_group'
? `Ganzgruppe (Phase ${run.phaseOrderIndex})`
: `Parallel (Phase ${run.phaseOrderIndex})`
return (
<tr key={`sched-${ri}-${run.kind}`} style={{ borderTop: '1px solid var(--border)' }}>
<td style={{ padding: '6px 8px 6px 0', verticalAlign: 'top' }}>{label}</td>
<td style={{ padding: '6px 8px', color: 'var(--text2)', whiteSpace: 'nowrap' }}>
{run.kind === 'parallel' ? 'Split' : run.kind === 'legacy' ? '—' : 'Ganzgruppe'}
</td>
<td style={{ padding: '6px 8px' }}>{run.minutes || '—'}</td>
<td style={{ padding: '6px 0 6px 8px', fontWeight: 600 }}>{cum}</td>
</tr>
)
})}
</tbody>
</table>
{unit.planned_time_start && (
<p style={{ margin: '0.55rem 0 0', fontSize: '0.78rem', color: 'var(--text3)', lineHeight: 1.4 }}>
Hinweis: Startzeit oben im Kopf; Minuten sind aus den Übungseinplanungen — ohne Pausen und ohne
automatische Uhrzeitliste.
</p>
)}
</div>
)}
{unit.notes && (
<div
className="training-run-notes-print"
@@ -213,7 +561,7 @@ export default function TrainingUnitRunPage() {
padding: '0.65rem 0.85rem',
background: 'var(--accent-light)',
borderRadius: '8px',
fontSize: '0.92rem'
fontSize: '0.92rem',
}}
>
<strong>Hinweis Teilnehmer:</strong> {unit.notes}
@@ -226,171 +574,175 @@ export default function TrainingUnitRunPage() {
Noch keine Abschnitte in diesem Plan. Unter <Link to="/planning">Planung</Link> bearbeiten.
</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
{sections.map((sec, si) => {
const secOrder = sec.order_index ?? si
const items = sortedItems(sec)
return (
<section key={sec.id ?? `sec-${si}`} className="card training-run-section" style={{ padding: '1.15rem 1.25rem' }}>
<h2 style={{ fontSize: '1.05rem', marginBottom: '0.65rem', color: 'var(--accent-dark)' }}>
{sec.title || `Abschnitt ${si + 1}`}
</h2>
{sec.guidance_notes && (
<p style={{ fontSize: '0.88rem', color: 'var(--text2)', marginBottom: '0.85rem', whiteSpace: 'pre-wrap' }}>
{sec.guidance_notes}
</p>
)}
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '0.65rem' }}>
{items.map((it, ii) => {
const ck = itemStableKey(it, secOrder, ii)
const done = checked.has(ck)
if (it.item_type === 'note') {
<div className="training-run-body" style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
{planModel.runs.map((run, runIdx) => {
if (run.kind === 'parallel') {
const visibleStreams = run.streams.filter((st) => showStreamColumn(st.printStreamId))
if (!visibleStreams.length) return null
return (
<div
key={`run-p-${run.phaseOrderIndex}-${runIdx}`}
className="training-run-phase training-run-phase--parallel"
>
<div
className="card training-run-phase-banner"
style={{
padding: '0.85rem 1rem',
background: 'linear-gradient(135deg, hsl(200 35% 94%), var(--surface2))',
border: '1px solid hsl(200 40% 80%)',
borderRadius: '10px',
}}
>
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--text3)', letterSpacing: '0.04em' }}>
PARALLELE PHASE
</div>
<div style={{ fontSize: '1.02rem', fontWeight: 700, color: 'var(--accent-dark)', marginTop: '4px' }}>
{run.phaseTitle ? String(run.phaseTitle).trim() : `Phase ${run.phaseOrderIndex}`}
</div>
<div style={{ fontSize: '0.82rem', color: 'var(--text2)', marginTop: '4px' }}>
{printOnlyStreamId
? `Auszug eine Gruppe · ca. ${visibleStreams[0]?.minutes ?? run.minutes} Min. (Üb.)`
: `Geplante Übungszeit (gesamt): ca. ${run.minutes} Min. · Jede Spalte kann separat gedruckt werden (Dropdown oder Seitenumbruch).`}
</div>
</div>
<div
className="training-run-parallel-columns"
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
gap: '1rem',
alignItems: 'start',
}}
>
{visibleStreams.map((st, streamIdx) => {
const siUnit = (sec) => Math.max(0, sections.indexOf(sec))
return (
<li key={ck} className={`training-run-item training-run-item--note${done ? ' training-run-item--done' : ''}`}>
<label
<div
key={st.printStreamId}
className={
'training-run-breakout-stream' +
(!printOnlyStreamId && streamIdx > 0
? ' training-run-breakout-stream--page-break'
: '')
}
data-print-id={st.printStreamId}
>
<div
className="training-run-stream-ribbon"
style={{
marginBottom: '10px',
padding: '8px 12px',
borderRadius: '8px',
background: 'hsl(200 38% 92%)',
border: '1px dashed hsl(200 42% 58%)',
fontSize: '0.88rem',
fontWeight: 700,
color: 'hsl(200 30% 28%)',
display: 'flex',
gap: '0.75rem',
alignItems: 'flex-start',
cursor: 'pointer',
fontSize: '0.92rem'
flexWrap: 'wrap',
alignItems: 'center',
justifyContent: 'space-between',
gap: '8px',
}}
>
<input type="checkbox" className="training-run-checkbox" checked={done} onChange={() => toggle(ck)} style={{ marginTop: '4px', width: '20px', height: '20px' }} />
<span style={{ whiteSpace: 'pre-wrap', color: 'var(--text2)' }}>
<em style={{ fontStyle: 'normal', color: 'var(--text3)', fontSize: '0.8rem' }}>Notiz</em>
<br />
{it.note_body || ''}
<span>
{st.streamTitle ? String(st.streamTitle).trim() : `Gruppe ${st.streamOrder + 1}`}
<span style={{ fontWeight: 500, marginLeft: '8px', opacity: 0.85 }}>
· ca. {st.minutes} Min. (Üb.)
</span>
</span>
</label>
</li>
<Link
className="no-print"
to={`/planning/run/${unitId}/coach?atBranch=${run.phaseOrderIndex}&preferSo=${st.streamOrder}`}
style={{
fontSize: '0.78rem',
fontWeight: 600,
color: 'var(--accent-dark)',
textDecoration: 'underline',
textUnderlineOffset: '2px',
whiteSpace: 'nowrap',
}}
>
Coach · Split-Punkt (Vorschlag)
</Link>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
{st.sections.map((sec) => renderSectionCard(sec, siUnit(sec)))}
</div>
</div>
)
}
})}
</div>
</div>
)
}
const title =
it.exercise_title ||
(it.exercise_id ? `Übung #${it.exercise_id}` : 'Übung')
const variant = it.exercise_variant_name ? ` (${it.exercise_variant_name})` : ''
const plan = formatMin(it.planned_duration_min)
const extras = []
if (it.exercise_focus_area) extras.push(it.exercise_focus_area)
const exKind = String(it.exercise_kind || 'simple').toLowerCase().trim()
const isComboRow = exKind === 'combination'
const metaParts = [...extras, isComboRow ? 'Kombination' : null, plan].filter(Boolean)
const comboEffectiveProfile = isComboRow
? effectiveComboMethodProfile(
it.catalog_method_profile || {},
it.planning_method_profile ?? null,
)
: null
if (!showWholeGroupInView) return null
return (
<li key={ck} className={`training-run-item training-run-item--exercise${done ? ' training-run-item--done' : ''}`}>
<label
style={{
display: 'flex',
gap: '0.75rem',
alignItems: 'flex-start',
cursor: 'pointer'
}}
>
<input type="checkbox" className="training-run-checkbox" checked={done} onChange={() => toggle(ck)} style={{ marginTop: '6px', width: '22px', height: '22px', flexShrink: 0 }} />
<span style={{ flex: 1, minWidth: 0 }}>
<span style={{ fontSize: '1.02rem', fontWeight: 600 }}>
{title}
{variant}
</span>
{metaParts.length > 0 && (
<div style={{ fontSize: '0.85rem', color: 'var(--text3)', marginTop: '3px', lineHeight: 1.35 }}>
{metaParts.join(' · ')}
</div>
)}
{(it.notes || it.modifications) && (
<div style={{ marginTop: '0.35rem', fontSize: '0.88rem', color: 'var(--text2)', whiteSpace: 'pre-wrap' }}>
{it.notes && (
<>
<strong style={{ fontWeight: 600 }}>Coach:</strong> {it.notes}
</>
)}
{it.modifications && (
<>
{it.notes ? <br /> : null}
<strong style={{ fontWeight: 600 }}>Anpassung:</strong> {it.modifications}
</>
)}
</div>
)}
{isComboRow && it.exercise_id ? (
<div className="training-run-combo-embed">
<CombinationPlanBracket
methodArchetype={String(it.catalog_method_archetype || '').trim()}
methodProfile={comboEffectiveProfile || {}}
combinationSlots={
Array.isArray(it.combination_slots) ? it.combination_slots : []
}
planningAdjusted={
it.planning_method_profile != null &&
typeof it.planning_method_profile === 'object' &&
!Array.isArray(it.planning_method_profile)
}
/>
</div>
) : null}
{it.exercise_id && (
<div className="no-print" style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', marginTop: '0.55rem', alignItems: 'center' }}>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: '0.82rem', margin: 0 }}
onClick={() =>
setPeekCtx({
exerciseId: it.exercise_id,
variantId:
it.exercise_variant_id != null
? Number(it.exercise_variant_id)
: null,
peekExtras: isComboRow
? {
catalog_method_profile: it.catalog_method_profile,
planning_method_profile: it.planning_method_profile,
}
: undefined,
})
}
>
Katalog (Popup)
</button>
<Link
to={`/exercises/${it.exercise_id}`}
style={{ fontSize: '0.82rem', color: 'var(--accent)' }}
>
Vollständige Seite öffnen
</Link>
</div>
)}
</span>
</label>
</li>
)
})}
</ul>
</section>
return (
<div
key={`run-wg-${run.phaseOrderIndex}-${runIdx}`}
className="training-run-phase training-run-phase--whole training-run-wg-block"
>
{run.kind !== 'legacy' ? (
<div
className="card training-run-phase-banner"
style={{
padding: '0.85rem 1rem',
marginBottom: '0.25rem',
background: 'color-mix(in srgb, var(--accent) 12%, var(--surface2))',
border: '1px solid color-mix(in srgb, var(--accent) 28%, var(--border))',
borderRadius: '10px',
}}
>
<div style={{ fontSize: '0.72rem', fontWeight: 700, color: 'var(--text3)', letterSpacing: '0.04em' }}>
GANZGRUPPE
</div>
<div style={{ fontSize: '1.02rem', fontWeight: 700, color: 'var(--accent-dark)', marginTop: '4px' }}>
{run.phaseTitle ? String(run.phaseTitle).trim() : `Phase ${run.phaseOrderIndex}`}
</div>
<div style={{ fontSize: '0.82rem', color: 'var(--text2)', marginTop: '4px' }}>
Geplante Übungszeit: ca. {run.minutes} Min.
</div>
</div>
) : null}
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
{run.sections.map((sec) => renderSectionCard(sec, Math.max(0, sections.indexOf(sec))))}
</div>
</div>
)
})}
</div>
)}
{unit.trainer_notes && (
<div className="card training-run-trainer-note no-print" style={{ marginTop: '1.25rem', padding: '1rem', borderLeft: `4px solid var(--accent)` }}>
<div style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text3)', marginBottom: '0.35rem', textTransform: 'uppercase' }}>
<div
className="card training-run-trainer-note no-print"
style={{
marginTop: '1.25rem',
padding: '1rem',
borderLeft: `4px solid var(--accent)`,
}}
>
<div
style={{
fontSize: '0.75rem',
fontWeight: 700,
color: 'var(--text3)',
marginBottom: '0.35rem',
textTransform: 'uppercase',
}}
>
Nur Trainer
</div>
<p style={{ fontSize: '0.92rem', whiteSpace: 'pre-wrap' }}>{unit.trainer_notes}</p>
</div>
)}
<footer className="no-print training-run-footer" style={{ marginTop: '1.75rem', textAlign: 'center', fontSize: '0.82rem', color: 'var(--text3)' }}>
<footer
className="no-print training-run-footer"
style={{ marginTop: '1.75rem', textAlign: 'center', fontSize: '0.82rem', color: 'var(--text3)' }}
>
Haken werden nur auf diesem Gerät gespeichert (Session — Tab schließen kann sie löschen).
</footer>
</div>
+508 -7
View File
@@ -2,7 +2,15 @@
* Hilfen für Trainingsplan-Ansicht, Coach-Modus und API-Payload für PUT /training-units/:id.
*/
import { cloneJsonSerializablePlanningProfile } from './trainingUnitSectionsForm'
import {
buildPlanPayloadForSave,
cloneJsonSerializablePlanningProfile,
defaultPlanLocWholeGroup,
inheritPlanLocForPhasedSave,
phaseRunsFromSections,
sectionIndicesForParallelStream,
streamsForParallelPhaseOrders,
} from './trainingUnitSectionsForm'
export function sortedSections(unit) {
const raw = unit?.sections
if (!Array.isArray(raw)) return []
@@ -20,11 +28,352 @@ export function itemStableKey(it, secOrder, ix) {
return `${secOrder}-${it?.item_type || 'row'}-${ix}`
}
/** Flache Reihenfolge wie auf der Matte: alle Notizen und Übungen nacheinander.
* Parallele Streams: aktuell strikt linear (sortedSections × sortedItems); für Breakout phase/stream‑aware erweitern. */
export function flattenPlanTimeline(unit) {
export function sumExerciseMinutesInSection(sec) {
let t = 0
for (const it of sortedItems(sec)) {
if (it.item_type === 'exercise' && it.planned_duration_min != null) {
const n = Number(it.planned_duration_min)
if (Number.isFinite(n)) t += n
}
}
return t
}
/**
* GET liefert `planLoc` oft nicht auf flachen `sections`, aber `unit.phases` (verschachtelt).
* Baut pro Abschnitt `planLoc` für phaseRuns / Darstellung (camelCase wie im Editor).
*/
function planLocBySectionIdFromPhases(phases) {
const byId = new Map()
if (!Array.isArray(phases)) return byId
for (const ph of phases) {
const po = Number(ph.order_index ?? ph.orderIndex ?? 0) || 0
const pk = String(ph.phase_kind ?? ph.phaseKind ?? '')
.toLowerCase()
.trim()
const phaseTitle = ph.title ?? ph.phaseTitle ?? null
const phaseGuidanceNotes = ph.guidance_notes ?? ph.guidanceNotes ?? null
if (pk === 'whole_group') {
for (const sec of ph.sections || []) {
const sid = sec.id != null ? Number(sec.id) : NaN
if (!Number.isFinite(sid)) continue
byId.set(sid, {
phaseKind: 'whole_group',
phaseOrderIndex: po,
parallelStreamOrderIndex: null,
phaseTitle,
phaseGuidanceNotes,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
})
}
} else if (pk === 'parallel') {
for (const st of ph.streams || []) {
const so = Number(st.order_index ?? st.orderIndex ?? 0) || 0
const streamTitle = st.title ?? st.streamTitle ?? null
const streamNotes = st.notes ?? st.streamNotes ?? null
const streamAssignedTrainerProfileIds =
st.assigned_trainer_profile_ids ?? st.streamAssignedTrainerProfileIds ?? null
for (const sec of st.sections || []) {
const sid = sec.id != null ? Number(sec.id) : NaN
if (!Number.isFinite(sid)) continue
byId.set(sid, {
phaseKind: 'parallel',
phaseOrderIndex: po,
parallelStreamOrderIndex: so,
phaseTitle,
phaseGuidanceNotes,
streamTitle,
streamNotes,
streamAssignedTrainerProfileIds,
})
}
}
}
}
return byId
}
function maxPhaseOrderIndexFromNestedPhases(phases) {
let m = -1
if (!Array.isArray(phases)) return m
for (const ph of phases) {
const po = Number(ph.order_index ?? ph.orderIndex ?? 0)
if (Number.isFinite(po)) m = Math.max(m, po)
}
return m
}
export function sectionsWithPlanLocForDisplay(unit) {
const sorted = sortedSections(unit)
const byId = planLocBySectionIdFromPhases(unit?.phases)
const merged = sorted.map((s) => {
const sid = s.id != null ? Number(s.id) : NaN
if (Number.isFinite(sid) && byId.has(sid)) {
return { ...s, planLoc: { ...byId.get(sid) } }
}
if (s.planLoc && s.planLoc.phaseKind) return s
return { ...s }
})
const inherited = inheritPlanLocForPhasedSave(merged)
const maxPhPo = maxPhaseOrderIndexFromNestedPhases(unit?.phases)
return inherited.map((s) => {
const sid = s.id != null ? Number(s.id) : NaN
if (!Number.isFinite(sid) || byId.has(sid)) return s
const pl = s.planLoc
if (pl?.phaseKind === 'parallel') {
const po = maxPhPo >= 0 ? maxPhPo + 1 : 0
return {
...s,
planLoc: {
...defaultPlanLocWholeGroup(po),
phaseTitle: pl.phaseTitle ?? null,
phaseGuidanceNotes: pl.phaseGuidanceNotes ?? null,
},
}
}
return s
})
}
/**
* Läuft auf bereits angereichter Abschnittsliste (gleiche Objektreferenzen wie in Slices).
*/
export function buildPlanRunViewModelFromSections(sections) {
if (!sections.length) {
return { mode: 'empty', runs: [], totalMin: 0, runCumulativeEnds: [] }
}
const runsMeta = phaseRunsFromSections(sections)
const runs = []
let cum = 0
const runCumulativeEnds = []
if (runsMeta.length === 0) {
const minutes = sections.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
cum = minutes
runCumulativeEnds.push(cum)
runs.push({
kind: 'legacy',
phaseOrderIndex: 0,
phaseTitle: null,
minutes,
sections,
streams: null,
globalOrderSections: sections,
})
return { mode: 'legacy', runs, totalMin: minutes, runCumulativeEnds }
}
for (const r of runsMeta) {
const slice = sections.slice(r.start, r.end)
if (r.phaseKind === 'whole_group') {
const minutes = slice.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
cum += minutes
runCumulativeEnds.push(cum)
const phaseTitle = slice[0]?.planLoc?.phaseTitle ?? null
runs.push({
kind: 'whole_group',
phaseOrderIndex: r.phaseOrderIndex,
phaseTitle,
minutes,
sections: slice,
streams: null,
globalOrderSections: slice,
})
} else {
const po = r.phaseOrderIndex
const streamOrders = streamsForParallelPhaseOrders(slice, po)
const streams = streamOrders.map((so) => {
const idxs = sectionIndicesForParallelStream(slice, po, so)
const streamSecs = idxs
.map((i) => slice[i])
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
const first = streamSecs[0]
const streamTitle = first?.planLoc?.streamTitle ?? null
const minutes = streamSecs.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
return {
streamOrder: so,
streamTitle,
minutes,
sections: streamSecs,
printStreamId: `p${po}-s${so}`,
}
})
const minutes = slice.reduce((s, sec) => s + sumExerciseMinutesInSection(sec), 0)
cum += minutes
runCumulativeEnds.push(cum)
const phaseTitle = slice[0]?.planLoc?.phaseTitle ?? null
runs.push({
kind: 'parallel',
phaseOrderIndex: po,
phaseTitle,
minutes,
streams,
sections: null,
globalOrderSections: slice,
})
}
}
return { mode: 'phased', runs, totalMin: cum, runCumulativeEnds }
}
/** @param {object} unit Trainingseinheit inkl. `sections`, optional `phases` (GET) */
export function buildPlanRunViewModel(unit) {
return buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
}
function coachContextLabelForSection(sec, sectionsList) {
const pl = sec?.planLoc
if (!pl?.phaseKind) return 'Ablauf'
if (pl.phaseKind === 'whole_group') {
const pt = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : null
return pt ? `Ganzgruppe · ${pt}` : 'Ganzgruppe'
}
const pt = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : `Phase ${pl.phaseOrderIndex ?? 0}`
const so = pl.parallelStreamOrderIndex ?? 0
const st = pl.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : `Gruppe ${so + 1}`
return `Parallel · ${pt} · ${st}`
}
export const COACH_ENTRY_BRANCH_GATE = 'branch_gate'
/** Normalisierte Stream-Wahl pro paralleler Phase (Phase-Index → Stream-Order). */
export function normalizeCoachBranchPicks(raw) {
const out = {}
if (!raw || typeof raw !== 'object') return out
for (const [k, v] of Object.entries(raw)) {
const pk = parseInt(String(k), 10)
const sv = typeof v === 'number' ? v : parseInt(String(v), 10)
if (Number.isFinite(pk) && Number.isFinite(sv)) out[pk] = sv
}
return out
}
/**
* URL-/Dropdown-Fokus `coachFocus` in Pick-Map mergen (fest gewählter Stream für eine Phase).
* @param {object} branchPicks Roh-Picks (z. B. aus Session)
* @param {{ phaseOrder: number, streamOrder: number }|null} coachFocusUrl z. B. ?po=&so=
*/
export function mergeCoachBranchPicksWithUrlFocus(branchPicks, coachFocusUrl) {
const m = normalizeCoachBranchPicks(branchPicks)
if (
coachFocusUrl != null &&
Number.isFinite(coachFocusUrl.phaseOrder) &&
Number.isFinite(coachFocusUrl.streamOrder)
) {
m[coachFocusUrl.phaseOrder] = coachFocusUrl.streamOrder
}
return m
}
/** Kurzstring für SessionStorage-Schlüssel (Sortierung stabil). */
export function coachBranchPicksStepStorageSuffix(mergedPicks) {
const keys = Object.keys(mergedPicks)
.map((k) => parseInt(String(k), 10))
.filter((n) => Number.isFinite(n))
.sort((a, b) => a - b)
if (!keys.length) return 'full'
return keys.map((k) => `p${k}-s${mergedPicks[k]}`).join('_')
}
export function coachBranchPicksStorageKey(unitId) {
return `sj_coach_branches_${unitId}`
}
/**
* Index zum Springen: Co-Trainer-Link atBranch+preferSo — Gate falls noch offen, sonst erste Kachel im Stream.
*/
export function findCoachTimelineJumpIndexForPhase(timeline, phaseOrder, preferStreamOrder = null) {
const po = Number(phaseOrder)
if (!Number.isFinite(po) || !Array.isArray(timeline)) return -1
const hint = preferStreamOrder != null && Number.isFinite(Number(preferStreamOrder)) ? Number(preferStreamOrder) : null
if (hint != null) {
const ixStream = timeline.findIndex(
(e) =>
e.entryKind !== COACH_ENTRY_BRANCH_GATE &&
e.runMeta?.kind === 'parallel' &&
e.runMeta.phaseOrderIndex === po &&
e.runMeta.streamOrder === hint
)
if (ixStream >= 0) return ixStream
}
const ixGate = timeline.findIndex(
(e) => e.entryKind === COACH_ENTRY_BRANCH_GATE && e.branchMeta?.phaseOrderIndex === po
)
return ixGate
}
/** Gruppiert die flache Coach-Timeline für den Trainingsrahmen (Überschriften + Einträge). */
export function coachOutlineGroupsFromTimeline(timeline) {
const groups = []
for (let ix = 0; ix < timeline.length; ix++) {
const ent = timeline[ix]
let mergeKey = `ix-${ix}`
let heading = 'Ablauf'
let sub = ''
if (ent.entryKind === COACH_ENTRY_BRANCH_GATE) {
const po = ent.branchMeta?.phaseOrderIndex ?? 0
mergeKey = `gate-${po}`
heading = 'Split · Gruppe wählen'
const pt = ent.branchMeta?.phaseTitle
sub =
pt != null && String(pt).trim()
? String(pt).trim()
: `Parallele Phase ${po}`
} else {
const rm = ent.runMeta
if (rm?.kind === 'whole_group') {
mergeKey = `wg-${rm.phaseOrderIndex}`
const pl = ent.sec?.planLoc
const ptt = pl?.phaseTitle
heading = 'Ganzgruppe'
sub = ptt != null && String(ptt).trim() ? String(ptt).trim() : ''
} else if (rm?.kind === 'parallel' && rm.streamOrder != null) {
mergeKey = `par-${rm.phaseOrderIndex}-s${rm.streamOrder}`
const pl = ent.sec?.planLoc
const ptt = pl?.phaseTitle
const stt = pl?.streamTitle
const ptl = ptt != null && String(ptt).trim() ? String(ptt).trim() : `Phase ${rm.phaseOrderIndex}`
const stl = stt != null && String(stt).trim() ? String(stt).trim() : `Gruppe ${rm.streamOrder + 1}`
heading = `Parallel · ${ptl}`
sub = stl
} else if (rm?.kind === 'legacy') {
mergeKey = 'legacy'
heading = 'Ablauf'
sub = ''
} else {
mergeKey = `misc-${ix}`
}
}
const prev = groups[groups.length - 1]
if (!prev || prev.mergeKey !== mergeKey) {
groups.push({ mergeKey, heading, sub, entries: [{ ix, ent }] })
} else {
prev.entries.push({ ix, ent })
}
}
return groups
}
/**
* Flache Coach-Reihenfolge. Pro paralleler Phase ohne Eintrag in branchPicks: ein sichtbarer branch_gate,
* damit keine verschränkten Split-Übungen, bis eine Gruppe gewählt wurde.
* @param {object} unit
* @param {object} branchPicks z. B. { 0: 1 } = Phase 0 → Stream 1
*/
export function flattenPlanTimeline(unit, branchPicks = {}) {
const sections = sectionsWithPlanLocForDisplay(unit)
const model = buildPlanRunViewModelFromSections(sections)
if (model.mode === 'empty') return []
const picks = normalizeCoachBranchPicks(branchPicks)
const list = []
sortedSections(unit).forEach((sec, si) => {
const pushSectionItems = (sec, coachCtx, runMeta) => {
const si = Math.max(0, sections.indexOf(sec))
const secOrder = sec.order_index ?? si
sortedItems(sec).forEach((item, ii) => {
list.push({
@@ -34,13 +383,165 @@ export function flattenPlanTimeline(unit) {
flatIndex: list.length,
sec,
item,
coachContext: coachCtx,
runMeta: runMeta || null,
})
})
})
}
for (const run of model.runs) {
if (run.kind === 'legacy') {
const meta = { kind: 'legacy', phaseOrderIndex: 0, streamOrder: null }
for (const sec of run.globalOrderSections) {
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
}
continue
}
if (run.kind === 'whole_group') {
const meta = { kind: 'whole_group', phaseOrderIndex: run.phaseOrderIndex, streamOrder: null }
for (const sec of run.globalOrderSections) {
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
}
continue
}
if (run.kind === 'parallel') {
const po = run.phaseOrderIndex
const chosen = picks[po]
const hasPick = chosen !== undefined && chosen !== null && Number.isFinite(Number(chosen))
if (!hasPick) {
list.push({
entryKind: COACH_ENTRY_BRANCH_GATE,
si: -1,
ii: -1,
secOrder: -1,
flatIndex: list.length,
sec: null,
item: null,
coachContext: '',
branchMeta: {
phaseOrderIndex: po,
phaseTitle: run.phaseTitle,
streams: run.streams || [],
},
runMeta: { kind: 'parallel', phaseOrderIndex: po, streamOrder: null },
})
} else {
const st = run.streams?.find((x) => x.streamOrder === Number(chosen))
const meta = { kind: 'parallel', phaseOrderIndex: po, streamOrder: Number(chosen) }
if (st?.sections?.length) {
for (const sec of st.sections) {
pushSectionItems(sec, coachContextLabelForSection(sec, sections), meta)
}
}
}
}
}
return list
}
export function summarizeTimelineEntry({ item }) {
/** Optionen für Coach-Stream-Auswahl (phases · Gruppe). */
export function listCoachStreamFocusOptions(unit) {
const model = buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
const opts = []
for (const run of model.runs) {
if (run.kind !== 'parallel' || !run.streams?.length) continue
const phaseLabel =
run.phaseTitle != null && String(run.phaseTitle).trim()
? String(run.phaseTitle).trim()
: `Phase ${run.phaseOrderIndex}`
for (const st of run.streams) {
const gl =
st.streamTitle != null && String(st.streamTitle).trim()
? String(st.streamTitle).trim()
: `Gruppe ${st.streamOrder + 1}`
opts.push({
phaseOrder: run.phaseOrderIndex,
streamOrder: st.streamOrder,
label: `${phaseLabel} · ${gl}`,
valueKey: `${run.phaseOrderIndex}-${st.streamOrder}`,
})
}
}
return opts
}
/** Alle Ist-Minuten-Overrides aus lokalem Delta-State für PUT (unabhängig von gefilterter Coach-Timeline). */
export function durationOverridesMapFromDeltas(unit, deltas) {
const out = {}
if (!unit || !deltas || typeof deltas !== 'object') return out
const sections = sortedSections(unit)
sections.forEach((sec, si) => {
const secOrder = sec.order_index ?? si
sortedItems(sec).forEach((it, ii) => {
if (it.item_type !== 'exercise' || it.id == null) return
const k = itemStableKey(it, secOrder, ii)
const dv = deltas[k]?.actual_duration_min
if (dv !== undefined && dv !== '' && dv !== null && !Number.isNaN(Number(dv))) {
out[String(it.id)] = { actual_duration_min: Number(dv) }
}
})
})
return out
}
/** PUT-Body für Coach-Speichern: `phases` wenn Plan Phasen hat, sonst `sections` (wie Planungseditor). */
export function buildCoachSavePlanPayload(unit, durationOverridesByItemId = {}) {
const withLoc = sectionsWithPlanLocForDisplay(unit)
const withDur = withLoc.map((sec) => ({
...sec,
items: sortedItems(sec).map((it) => {
if (it.item_type !== 'exercise' || it.id == null) return it
const o = durationOverridesByItemId[String(it.id)]
const av = o?.actual_duration_min
if (av !== undefined && av !== '' && av !== null && Number.isFinite(Number(av))) {
return { ...it, actual_duration_min: Number(av) }
}
return it
}),
}))
return buildPlanPayloadForSave(withDur)
}
/**
* Nach dem letzten Block eines Streams: Rückfrage, wenn die parallele Phase mehrere Gruppen hat.
*/
export function coachShouldPromptSplitRejoin(unit, lastTimelineEntry) {
const rm = lastTimelineEntry?.runMeta
if (!rm || rm.kind !== 'parallel' || rm.streamOrder == null) return null
const model = buildPlanRunViewModelFromSections(sectionsWithPlanLocForDisplay(unit))
const run = model.runs.find((r) => r.kind === 'parallel' && r.phaseOrderIndex === rm.phaseOrderIndex)
if (!run?.streams || run.streams.length <= 1) return null
return {
phaseOrderIndex: run.phaseOrderIndex,
phaseTitle: run.phaseTitle,
streams: run.streams,
}
}
/**
* Nach dem letzten Block eines gewählten Streams: Rückfrage vor Ganzgruppenphase oder vor dem nächsten Split,
* wenn die aktuelle Parallelphase mehrere Streams hat.
*/
export function coachShouldPromptSplitRejoinTransition(unit, currentEntry, nextEntry) {
if (!currentEntry || !nextEntry) return null
const cRm = currentEntry.runMeta
if (!cRm || cRm.kind !== 'parallel' || cRm.streamOrder == null) return null
const intoWholeGroup = nextEntry.runMeta?.kind === 'whole_group'
const intoNextSplit = nextEntry.entryKind === COACH_ENTRY_BRANCH_GATE
if (!intoWholeGroup && !intoNextSplit) return null
return coachShouldPromptSplitRejoin(unit, currentEntry)
}
export function summarizeTimelineEntry(ent) {
if (!ent) return ''
if (ent.entryKind === COACH_ENTRY_BRANCH_GATE) {
const t = ent.branchMeta?.phaseTitle != null && String(ent.branchMeta.phaseTitle).trim()
? String(ent.branchMeta.phaseTitle).trim()
: ''
return t ? `Split wählen · ${t}` : 'Split · Gruppe wählen'
}
const { item } = ent
if (!item) return ''
if (item.item_type === 'note') {
const t = String(item.note_body || '').trim()
+819 -59
View File
@@ -5,6 +5,201 @@ export function defaultSection(title = 'Hauptteil') {
return { title, guidance_notes: '', items: [] }
}
/** Standard-`planLoc` für eine Ganzgruppen-Phase (Editor-Breakout-UI). */
export function defaultPlanLocWholeGroup(phaseOrderIndex = 0) {
return {
phaseKind: 'whole_group',
phaseOrderIndex,
parallelStreamOrderIndex: null,
phaseTitle: null,
phaseGuidanceNotes: null,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
}
/** Standard-`planLoc` für einen Stream innerhalb einer parallelen Phase. */
export function defaultPlanLocParallel(phaseOrderIndex, streamOrderIndex) {
return {
phaseKind: 'parallel',
phaseOrderIndex,
parallelStreamOrderIndex: streamOrderIndex,
phaseTitle: null,
phaseGuidanceNotes: null,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
}
export function planLocKey(pl) {
if (!pl || !pl.phaseKind) return ''
if (pl.phaseKind === 'whole_group') return `wg:${pl.phaseOrderIndex ?? 0}`
return `par:${pl.phaseOrderIndex ?? 0}:${pl.parallelStreamOrderIndex ?? 0}`
}
export function maxPhaseOrderIndexFromSections(sections) {
let m = -1
for (const s of sections || []) {
const pl = s?.planLoc
if (!pl || typeof pl.phaseOrderIndex !== 'number') continue
if (pl.phaseOrderIndex > m) m = pl.phaseOrderIndex
}
return m
}
/**
* Eindeutige Ziele für die Zuordnung eines Abschnitts (Dropdown).
* `template` ist ein vollständiges planLoc-Objekt zum Kopieren.
*/
export function buildPlanTargetOptions(sections) {
const map = new Map()
for (const s of sections || []) {
const pl = s?.planLoc
if (!pl?.phaseKind) continue
if (pl.phaseKind === 'whole_group') {
const po = pl.phaseOrderIndex ?? 0
const k = `wg:${po}`
if (!map.has(k)) {
const title = pl.phaseTitle != null && String(pl.phaseTitle).trim() ? String(pl.phaseTitle).trim() : ''
map.set(k, {
key: k,
label: title || `Ganzgruppe · Phase ${po}`,
template: { ...pl },
})
}
} else {
const po = pl.phaseOrderIndex ?? 0
const so = pl.parallelStreamOrderIndex ?? 0
const k = `par:${po}:${so}`
if (!map.has(k)) {
const st = pl.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : ''
map.set(k, {
key: k,
label: st || `Parallel · Phase ${po} · Stream ${so}`,
template: { ...pl },
})
}
}
}
return [...map.values()].sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }))
}
/** Max. Streams pro paralleler Phase (UI + API-Schutz). */
export const MAX_PARALLEL_STREAMS_PER_PHASE = 5
/** Farben pro Stream-Index (max. 5 unterschiedliche Farbzyklen). */
export function parallelStreamVisual(streamOrderIndex) {
const n = Math.max(0, Number(streamOrderIndex) || 0)
const hues = [200, 135, 38, 285, 22]
const h = hues[n % hues.length]
return {
border: `hsl(${h} 50% 36%)`,
soft: `hsl(${h} 36% 94%)`,
tabBg: `hsl(${h} 34% 92%)`,
tabBgActive: `hsl(${h} 40% 82%)`,
}
}
export function streamTabLabelFromIndices(sections, globalIndices) {
const first = globalIndices?.[0]
if (first === undefined || !sections?.[first]) return 'Stream'
const pl = sections[first].planLoc
const t = pl?.streamTitle != null && String(pl.streamTitle).trim() ? String(pl.streamTitle).trim() : ''
if (t) return t
const so = pl?.parallelStreamOrderIndex ?? 0
return `Stream ${so + 1}`
}
/** Sortierte Stream-Indizes innerhalb einer parallelen Phase (für Reiter). */
export function streamsForParallelPhaseOrders(sections, phaseOrderIndex) {
const set = new Set()
const po = Number(phaseOrderIndex) || 0
for (const s of sections || []) {
const L = s?.planLoc
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po) {
set.add(L.parallelStreamOrderIndex ?? 0)
}
}
return [...set].sort((a, b) => a - b)
}
/** Globale Abschnitts-Indizes eines Streams. */
export function sectionIndicesForParallelStream(sections, phaseOrderIndex, streamOrderIndex) {
const out = []
const po = Number(phaseOrderIndex) || 0
const so = Number(streamOrderIndex) || 0
;(sections || []).forEach((s, i) => {
const L = s?.planLoc
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po && (L.parallelStreamOrderIndex ?? 0) === so) {
out.push(i)
}
})
return out
}
/** Abschnitte an den angegebenen globalen Indizes entfernen (mindestens ein Abschnitt bleibt). */
export function reorderWithoutIndices(prev, removeGlobalIndices) {
const set = new Set(removeGlobalIndices || [])
const next = (prev || []).filter((_, i) => !set.has(i))
return next.length ? next : [defaultSection()]
}
/**
* Ob in den Abschnitten eines Stream-Buckets planerisch etwas steht (Übungen, Text-Anmerkungen).
* Trennlinien-Marker (---) zählen nicht als Inhalt.
*/
export function parallelStreamBucketHasContent(sections, globalIndices, separatorBody = '---') {
for (const gi of globalIndices || []) {
const sec = (sections || [])[gi]
if (!sec) continue
for (const it of sec.items || []) {
if ((it.item_type || '') === 'note') {
const b = (it.note_body || '').trim()
if (b && b !== separatorBody) return true
} else {
if (it.exercise_id) return true
if ((it.exercise_title || '').trim()) return true
}
}
}
return false
}
/** Parallele Phase auflösen: alle Abschnitte dieser Phase werden Ganzgruppe (gleicher phaseOrderIndex). */
export function dissolveParallelPhaseToWholeGroup(sections, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
return (sections || []).map((s) => {
const L = s?.planLoc
if (L?.phaseKind !== 'parallel' || (L.phaseOrderIndex ?? 0) !== po) return s
return {
...s,
planLoc: {
...defaultPlanLocWholeGroup(po),
phaseTitle: L.phaseTitle ?? null,
phaseGuidanceNotes: L.phaseGuidanceNotes ?? null,
},
}
})
}
export function reorderWithinBucketIndices(prev, bucketGlobalIndicesSorted, oldPos, newPos) {
const sortedIdx = [...bucketGlobalIndicesSorted].sort((a, b) => a - b)
if (oldPos === newPos || oldPos < 0 || newPos < 0 || oldPos >= sortedIdx.length || newPos >= sortedIdx.length) {
return prev
}
const values = sortedIdx.map((gi) => prev[gi])
const arr = [...values]
const [x] = arr.splice(oldPos, 1)
arr.splice(newPos, 0, x)
const next = [...prev]
sortedIdx.forEach((gi, k) => {
next[gi] = arr[k]
})
return next
}
function normalizeCatalogMethodProfile(cp) {
if (cp && typeof cp === 'object' && !Array.isArray(cp)) return { ...cp }
return {}
@@ -156,65 +351,132 @@ function parseOptionalSourceTrainingModuleIdForPayload(v) {
return Number.isFinite(n) && n >= 1 ? n : null
}
function sortByOrderIndex(arr) {
return [...(arr || [])].sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
}
/** Katalog-Abschnitt (GET) → Editor-Zeilen inkl. Kombi/Modul-Meta — wird von Legacy `sections` und von `phases` genutzt. */
function formItemsFromApiItems(items) {
return (items || []).map((it) => {
if (it.item_type === 'note') {
const sm = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
const rowNote = {
item_type: 'note',
note_body: it.note_body || '',
source_training_module_id: '',
source_module_title: '',
}
if (sm != null) {
rowNote.source_training_module_id = sm
rowNote.source_module_title = (
it.source_module_title ||
it.source_training_module_title ||
''
).trim()
}
return rowNote
}
const smEx = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
const ek = String(it.exercise_kind || 'simple').toLowerCase().trim()
const isCombo = ek === 'combination'
return {
item_type: 'exercise',
exercise_id: it.exercise_id,
exercise_kind: isCombo ? 'combination' : 'simple',
exercise_variant_id: isCombo ? '' : it.exercise_variant_id ?? '',
exercise_title: it.exercise_title || '',
variants: [],
planned_duration_min:
it.planned_duration_min !== null && it.planned_duration_min !== undefined
? String(it.planned_duration_min)
: '',
actual_duration_min:
it.actual_duration_min !== null && it.actual_duration_min !== undefined
? String(it.actual_duration_min)
: '',
notes: it.notes ?? '',
modifications: it.modifications ?? '',
catalog_method_archetype: String(it.catalog_method_archetype ?? '').trim(),
catalog_method_profile: normalizeCatalogMethodProfile(it.catalog_method_profile),
planning_method_profile: normalizePlanningMethodProfile(it.planning_method_profile),
...(smEx != null
? {
source_training_module_id: smEx,
source_module_title: (
it.source_module_title ||
it.source_training_module_title ||
''
).trim(),
}
: {}),
}
})
}
/** GET `phases` → flache Editor-Abschnitte mit `planLoc` (für PUT `phases` Roundtrip). */
function normalizePhasesToFormSections(fullUnit) {
const phases = sortByOrderIndex(fullUnit.phases || [])
const out = []
for (const ph of phases) {
const pOi = ph.order_index ?? 0
const pk = String(ph.phase_kind || 'whole_group').toLowerCase().trim()
const basePhaseLoc = {
phaseTitle: ph.title ?? null,
phaseGuidanceNotes: ph.guidance_notes ?? null,
}
if (pk === 'parallel') {
for (const st of sortByOrderIndex(ph.streams || [])) {
const sOi = st.order_index ?? 0
const streamLoc = {
phaseKind: 'parallel',
phaseOrderIndex: pOi,
parallelStreamOrderIndex: sOi,
...basePhaseLoc,
streamTitle: st.title ?? null,
streamNotes: st.notes ?? null,
streamAssignedTrainerProfileIds: st.assigned_trainer_profile_ids ?? null,
}
for (const sec of sortByOrderIndex(st.sections || [])) {
out.push({
title: sec.title,
guidance_notes: sec.guidance_notes || '',
items: formItemsFromApiItems(sec.items),
planLoc: { ...streamLoc },
})
}
}
} else {
const loc = {
phaseKind: 'whole_group',
phaseOrderIndex: pOi,
parallelStreamOrderIndex: null,
...basePhaseLoc,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
for (const sec of sortByOrderIndex(ph.sections || [])) {
out.push({
title: sec.title,
guidance_notes: sec.guidance_notes || '',
items: formItemsFromApiItems(sec.items),
planLoc: { ...loc },
})
}
}
}
return out.length ? out : [defaultSection()]
}
export function normalizeUnitToForm(fullUnit) {
if (Array.isArray(fullUnit?.phases) && fullUnit.phases.length > 0) {
return normalizePhasesToFormSections(fullUnit)
}
if (fullUnit.sections && fullUnit.sections.length) {
return fullUnit.sections.map((sec) => ({
title: sec.title,
guidance_notes: sec.guidance_notes || '',
items: (sec.items || []).map((it) => {
if (it.item_type === 'note') {
const sm = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
const rowNote = {
item_type: 'note',
note_body: it.note_body || '',
source_training_module_id: '',
source_module_title: '',
}
if (sm != null) {
rowNote.source_training_module_id = sm
rowNote.source_module_title = (
it.source_module_title ||
it.source_training_module_title ||
''
).trim()
}
return rowNote
}
const smEx = parseOptionalSourceTrainingModuleIdForPayload(it.source_training_module_id)
const ek = String(it.exercise_kind || 'simple').toLowerCase().trim()
const isCombo = ek === 'combination'
return {
item_type: 'exercise',
exercise_id: it.exercise_id,
exercise_kind: isCombo ? 'combination' : 'simple',
exercise_variant_id: isCombo ? '' : it.exercise_variant_id ?? '',
exercise_title: it.exercise_title || '',
variants: [],
planned_duration_min:
it.planned_duration_min !== null && it.planned_duration_min !== undefined
? String(it.planned_duration_min)
: '',
actual_duration_min:
it.actual_duration_min !== null && it.actual_duration_min !== undefined
? String(it.actual_duration_min)
: '',
notes: it.notes ?? '',
modifications: it.modifications ?? '',
catalog_method_archetype: String(it.catalog_method_archetype ?? '').trim(),
catalog_method_profile: normalizeCatalogMethodProfile(it.catalog_method_profile),
planning_method_profile: normalizePlanningMethodProfile(it.planning_method_profile),
...(smEx != null
? {
source_training_module_id: smEx,
source_module_title: (
it.source_module_title ||
it.source_training_module_title ||
''
).trim(),
}
: {}),
}
}),
items: formItemsFromApiItems(sec.items),
}))
}
if (fullUnit.exercises && fullUnit.exercises.length) {
@@ -398,10 +660,9 @@ export function parseMin(v) {
return Number.isFinite(n) ? n : null
}
/** PUT /api/training-units/:id `sections` — flache order_index pro Einheit; Parallelität bricht am DB-UNIQUE (training_unit_id, order_index) bis Migration. */
export function buildSectionsPayload(sections) {
return sections.map((sec, si) => ({
order_index: si,
export function buildOneSectionPayload(sec, orderIndex) {
return {
order_index: orderIndex,
title: (sec.title || '').trim() || 'Abschnitt',
guidance_notes: sec.guidance_notes?.trim() ? sec.guidance_notes.trim() : null,
items: (sec.items || [])
@@ -446,7 +707,506 @@ export function buildSectionsPayload(sections) {
return rowEx
})
.filter(Boolean),
}))
}
}
/** PUT /api/training-units: Legacy `sections` (eine whole_group-Phase) wenn kein `planLoc` gesetzt ist. */
export function buildSectionsPayload(sections) {
return sections.map((sec, si) => buildOneSectionPayload(sec, si))
}
function stripPlanLoc(sec) {
if (!sec || typeof sec !== 'object') return sec
const { planLoc: _pl, ...rest } = sec
return rest
}
function phaseIndexToInt(v, fallback = 0) {
if (v === null || v === undefined || v === '') return fallback
const n = typeof v === 'number' ? v : Number(v)
return Number.isFinite(n) ? n : fallback
}
/**
* planLoc für Phasen-PUT kanonisieren (Großschreibung, numerische Indizes).
* Verhindert u. a. abgebrochene Phasen-Runs bei "0" !== 0 und falsche whole_group-Zweige.
*/
function canonicalPlanLocForPhasedSave(pl) {
if (!pl || typeof pl !== 'object') return null
const rawKind = String(pl.phaseKind || '').toLowerCase().trim()
let kind = rawKind === 'parallel' || rawKind === 'whole_group' ? rawKind : null
if (
!kind &&
pl.parallelStreamOrderIndex != null &&
pl.parallelStreamOrderIndex !== ''
) {
kind = 'parallel'
}
if (!kind) return null
const phaseOrderIndex = phaseIndexToInt(pl.phaseOrderIndex, 0)
let parallelStreamOrderIndex = null
if (kind === 'parallel') {
parallelStreamOrderIndex = phaseIndexToInt(pl.parallelStreamOrderIndex, 0)
}
return {
...pl,
phaseKind: kind,
phaseOrderIndex,
parallelStreamOrderIndex,
}
}
export function inheritPlanLocForPhasedSave(sections) {
let prev = { ...defaultPlanLocWholeGroup(0) }
return (sections || []).map((s) => {
const canon = canonicalPlanLocForPhasedSave(s?.planLoc)
if (canon) {
prev = { ...canon }
return { ...s, planLoc: prev }
}
return { ...s, planLoc: { ...prev } }
})
}
/** Phasen-„Runs“ in der flachen Abschnittsliste (Reihenfolge wie beim Speichern). */
export function phaseRunsFromSections(sections) {
const norm = inheritPlanLocForPhasedSave(sections)
const runs = []
let i = 0
while (i < norm.length) {
const loc0 = norm[i]?.planLoc
if (!loc0?.phaseKind) {
i += 1
continue
}
const pOi = loc0.phaseOrderIndex ?? 0
const pk = loc0.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
const start = i
while (i < norm.length) {
const L = norm[i]?.planLoc
if (!L?.phaseKind) break
const pk2 = L.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
if ((L.phaseOrderIndex ?? 0) !== pOi || pk2 !== pk) break
i += 1
}
runs.push({ phaseKind: pk, phaseOrderIndex: pOi, start, end: i })
}
return runs
}
/** Vertauscht zwei unmittelbar benachbarte Runs (upperRunIndex = erste der beiden). */
export function swapAdjacentPhaseRuns(prev, upperRunIndex) {
const runs = phaseRunsFromSections(prev)
const a = upperRunIndex
const b = upperRunIndex + 1
if (a < 0 || b >= runs.length) return prev
const rgA = runs[a]
const rgB = runs[b]
const head = prev.slice(0, rgA.start)
const blA = prev.slice(rgA.start, rgA.end)
const blB = prev.slice(rgB.start, rgB.end)
const tail = prev.slice(rgB.end)
return [...head, ...blB, ...blA, ...tail]
}
export function movePhaseRunUpByPhaseOrder(prev, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const runs = phaseRunsFromSections(prev)
const rIdx = runs.findIndex((r) => r.phaseKind === 'parallel' && r.phaseOrderIndex === po)
if (rIdx <= 0) return prev
return swapAdjacentPhaseRuns(prev, rIdx - 1)
}
export function movePhaseRunDownByPhaseOrder(prev, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const runs = phaseRunsFromSections(prev)
const rIdx = runs.findIndex((r) => r.phaseKind === 'parallel' && r.phaseOrderIndex === po)
if (rIdx < 0 || rIdx >= runs.length - 1) return prev
return swapAdjacentPhaseRuns(prev, rIdx)
}
/**
* Abschnitt verschieben und planLoc an der Einfügestelle an Nachbarn anpassen.
* Regel: Einfügen vor Abschnitt X übernimmt X.planLoc; am Listenende nach Parallel → neue Ganzgruppen-Phase.
*/
export function reorderBlocksImmutableWithPlanLoc(prev, fromI, toBeforeIdx) {
const arr = [...prev]
if (fromI < 0 || fromI >= arr.length) return prev
const [moved] = arr.splice(fromI, 1)
let insertAt = toBeforeIdx
if (fromI < toBeforeIdx) insertAt = toBeforeIdx - 1
insertAt = Math.max(0, Math.min(insertAt, arr.length))
const below = insertAt < arr.length ? arr[insertAt] : undefined
const above = insertAt > 0 ? arr[insertAt - 1] : undefined
let planLocNext = null
const belowKind = below?.planLoc?.phaseKind
const aboveKind = above?.planLoc?.phaseKind
const movedKind = moved?.planLoc?.phaseKind
const belowPo = below?.planLoc?.phaseOrderIndex ?? 0
const movedPo = moved?.planLoc?.phaseOrderIndex ?? 0
if (belowKind === 'parallel' && aboveKind === 'whole_group') {
if (movedKind !== 'parallel') {
planLocNext = { ...above.planLoc }
} else if (movedPo !== belowPo) {
planLocNext = { ...below.planLoc }
}
} else if (belowKind === 'parallel' && !above) {
if (movedKind !== 'parallel') {
planLocNext = defaultPlanLocWholeGroup(0)
}
}
if (!planLocNext && belowKind) {
planLocNext = { ...below.planLoc }
}
if (!planLocNext && insertAt === arr.length) {
if (!above) {
planLocNext = defaultPlanLocWholeGroup(0)
} else if (above.planLoc?.phaseKind === 'parallel') {
const mx = maxPhaseOrderIndexFromSections(arr)
planLocNext = defaultPlanLocWholeGroup(mx + 1)
} else if (above.planLoc?.phaseKind === 'whole_group') {
planLocNext = { ...above.planLoc }
}
}
if (!planLocNext && above?.planLoc?.phaseKind === 'whole_group') {
planLocNext = { ...above.planLoc }
}
if (!planLocNext && above?.planLoc?.phaseKind === 'parallel') {
const mx = maxPhaseOrderIndexFromSections(arr)
planLocNext = defaultPlanLocWholeGroup(mx + 1)
}
let nextMoved = { ...moved }
if (planLocNext) {
nextMoved = { ...moved, planLoc: planLocNext }
} else {
nextMoved = stripPlanLoc(moved)
}
arr.splice(insertAt, 0, nextMoved)
return arr
}
/**
* Abschnitt direkt vor den Parallel-Lauf setzen (immer Ganzgruppe oberhalb der Split-Phase).
*/
export function reorderSectionBeforeParallelRunAsWholeGroup(prev, fromI, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const idxs = indicesOfParallelPhase(prev, po)
if (!idxs.length || fromI < 0 || fromI >= (prev?.length ?? 0)) return prev
const fg = idxs[0]
const arr = [...prev]
const [moved] = arr.splice(fromI, 1)
let insertAt = fg
if (fromI < insertAt) insertAt -= 1
insertAt = Math.max(0, Math.min(insertAt, arr.length))
const above = insertAt > 0 ? arr[insertAt - 1] : undefined
let planLocNext
if (above?.planLoc?.phaseKind === 'whole_group') {
planLocNext = { ...above.planLoc }
} else if (!above) {
planLocNext = defaultPlanLocWholeGroup(0)
} else {
const mx = maxPhaseOrderIndexFromSections(arr)
planLocNext = defaultPlanLocWholeGroup(mx + 1)
}
arr.splice(insertAt, 0, { ...moved, planLoc: planLocNext })
return arr
}
/** Abschnitt als neuen ersten Eintrag der Parallel-Phase (gleiche Phasen-/Stream-Metadaten wie bisheriger Kopf). */
export function reorderSectionAsFirstInParallelPhase(prev, fromI, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const idxs = indicesOfParallelPhase(prev, po)
if (!idxs.length || fromI < 0 || fromI >= (prev?.length ?? 0)) return prev
let fg = idxs[0]
const arr = [...prev]
const headTpl = { ...arr[fg].planLoc }
const [moved] = arr.splice(fromI, 1)
if (fromI < fg) fg -= 1
fg = Math.max(0, Math.min(fg, arr.length))
arr.splice(fg, 0, { ...moved, planLoc: { ...headTpl } })
return arr
}
/** Abschnitt als ersten Eintrag eines parallelen Streams setzen (planLoc wie erster Abschnitt dieses Streams, bzw. leerer Stream wie reorderBlockIntoParallelStreamEnd). */
export function reorderSectionAsFirstInParallelStream(prev, fromI, phaseOrderIndex, streamOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const so = Number(streamOrderIndex) || 0
const len = prev?.length ?? 0
if (fromI < 0 || fromI >= len) return prev
const arr = [...prev]
const [moved] = arr.splice(fromI, 1)
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
let insertAt
let headTpl
let skipFromIAdjust = false
if (streamIdx.length) {
const first = Math.min(...streamIdx)
headTpl = { ...arr[first].planLoc }
insertAt = first
} else {
const phaseIdx = indicesOfParallelPhase(arr, po)
if (!phaseIdx.length) {
const ml = moved?.planLoc
if (ml?.phaseKind !== 'parallel' || (ml.phaseOrderIndex ?? 0) !== po) return prev
headTpl = {
...ml,
parallelStreamOrderIndex: so,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
insertAt = Math.min(fromI, arr.length)
skipFromIAdjust = true
} else {
const ref = arr[phaseIdx[phaseIdx.length - 1]]
headTpl = {
...ref.planLoc,
parallelStreamOrderIndex: so,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
insertAt = phaseIdx[phaseIdx.length - 1] + 1
}
}
if (!skipFromIAdjust && fromI < insertAt) insertAt -= 1
insertAt = Math.max(0, Math.min(insertAt, arr.length))
arr.splice(insertAt, 0, { ...moved, planLoc: { ...headTpl } })
return arr
}
/**
* Abschnitt ans Ende eines parallelen Streams setzen (planLoc wie dieser Stream).
* Leerer Stream: Einfügen hinter den letzten Abschnitt der zugehörigen parallelen Phase, planLoc vom Referenz-Abschnitt mit angepasstem streamIndex.
*/
export function reorderBlockIntoParallelStreamEnd(prev, fromI, phaseOrderIndex, streamOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const so = Number(streamOrderIndex) || 0
const len = prev?.length ?? 0
if (fromI < 0 || fromI >= len) return prev
const arr = [...prev]
const [moved] = arr.splice(fromI, 1)
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
let insertAt
let planLocTemplate
if (streamIdx.length) {
const last = Math.max(...streamIdx)
planLocTemplate = { ...arr[last].planLoc }
insertAt = last + 1
} else {
const phaseIdx = indicesOfParallelPhase(arr, po)
if (!phaseIdx.length) return prev
const ref = arr[phaseIdx[phaseIdx.length - 1]]
planLocTemplate = {
...ref.planLoc,
parallelStreamOrderIndex: so,
streamTitle: null,
streamNotes: null,
streamAssignedTrainerProfileIds: null,
}
insertAt = phaseIdx[phaseIdx.length - 1] + 1
}
insertAt = Math.max(0, Math.min(insertAt, arr.length))
arr.splice(insertAt, 0, { ...moved, planLoc: { ...planLocTemplate } })
return arr
}
/** Globales insertBeforeIndex, um einen Abschnitt hinter den letzten des Streams einzufügen (z. B. Rahmen-Slots). */
export function globalInsertBeforeIndexForParallelStreamEnd(sections, phaseOrderIndex, streamOrderIndex) {
const arr = sections || []
const po = Number(phaseOrderIndex) || 0
const so = Number(streamOrderIndex) || 0
const streamIdx = sectionIndicesForParallelStream(arr, po, so)
if (streamIdx.length) return Math.max(...streamIdx) + 1
const phaseIdx = indicesOfParallelPhase(arr, po)
if (!phaseIdx.length) return arr.length
return Math.max(...phaseIdx) + 1
}
/** Alle globalen Indizes einer parallelen Phase (alle Streams), sortiert. */
export function indicesOfParallelPhase(sections, phaseOrderIndex) {
const po = Number(phaseOrderIndex) || 0
const out = []
;(sections || []).forEach((s, i) => {
const L = s?.planLoc
if (L?.phaseKind === 'parallel' && (L.phaseOrderIndex ?? 0) === po) out.push(i)
})
return out.sort((a, b) => a - b)
}
/** Gesamten Parallel-Block an neue Position (insertBefore globale Liste) schieben. */
export function moveParallelPhaseRunToInsertBefore(prev, phaseOrderIndex, toBeforeIdx) {
const po = Number(phaseOrderIndex) || 0
const indices = indicesOfParallelPhase(prev, po)
if (!indices.length) return prev
const indexSet = new Set(indices)
const blocks = indices.map((i) => prev[i])
const without = prev.filter((_, i) => !indexSet.has(i))
let ins = toBeforeIdx
for (const i of indices) {
if (i < toBeforeIdx) ins -= 1
}
ins = Math.max(0, Math.min(ins, without.length))
return [...without.slice(0, ins), ...blocks, ...without.slice(ins)]
}
/**
* Nach Drag&Drop: wenn aus einer Parallelphase noch ≤1 Stream übrig ist (vorher ≥2), Rückfrage wie beim Stream-Löschen.
*/
export function afterSectionReorderParallelGuard(prev, next) {
const seenPo = new Set()
for (const s of prev || []) {
const L = s?.planLoc
if (L?.phaseKind !== 'parallel') continue
seenPo.add(L.phaseOrderIndex ?? 0)
}
let out = next
for (const po of seenPo) {
const prevN = streamsForParallelPhaseOrders(prev, po).length
if (prevN < 2) continue
const nowN = streamsForParallelPhaseOrders(out, po).length
if (nowN <= 1) {
if (
window.confirm(
'In dieser parallelen Phase ist nur noch eine Gruppe übrig. Parallelaufbau auflösen und alle zugehörigen Abschnitte als gemeinsame Ganzgruppen-Phase führen?'
)
) {
out = dissolveParallelPhaseToWholeGroup(out, po)
}
}
}
return out
}
function buildPhasesPayloadFromFlat(sections) {
const norm = inheritPlanLocForPhasedSave(sections)
const phases = []
let i = 0
while (i < norm.length) {
const loc0 = norm[i].planLoc
const pOi = loc0.phaseOrderIndex ?? 0
const pk = loc0.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
const run = []
while (i < norm.length) {
const L = norm[i].planLoc
const pk2 = L.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
if ((L.phaseOrderIndex ?? 0) !== pOi || pk2 !== pk) break
run.push(norm[i])
i += 1
}
const head = run[0].planLoc
if (pk === 'whole_group') {
phases.push({
phase_kind: 'whole_group',
order_index: pOi,
title: head.phaseTitle ?? null,
guidance_notes: head.phaseGuidanceNotes ?? null,
sections: run.map((s, idx) => buildOneSectionPayload(stripPlanLoc(s), idx)),
})
} else {
const byStream = new Map()
for (const s of run) {
const soi = s.planLoc.parallelStreamOrderIndex ?? 0
if (!byStream.has(soi)) byStream.set(soi, [])
byStream.get(soi).push(s)
}
const streamOrder = [...byStream.keys()].sort((a, b) => a - b)
const streams = streamOrder.map((soi) => {
const bucket = byStream.get(soi)
const h = bucket[0].planLoc
const st = {
order_index: soi,
title: h.streamTitle ?? null,
notes: h.streamNotes ?? null,
sections: bucket.map((s, idx) => buildOneSectionPayload(stripPlanLoc(s), idx)),
}
const asst = h.streamAssignedTrainerProfileIds
if (asst !== null && asst !== undefined) st.assigned_trainer_profile_ids = asst
return st
})
phases.push({
phase_kind: 'parallel',
order_index: pOi,
title: head.phaseTitle ?? null,
guidance_notes: head.phaseGuidanceNotes ?? null,
streams,
})
}
}
return { phases }
}
/**
* Speichern einer Einheit: flache `sections` oder verschachtelte `phases`, sobald `planLoc` gesetzt ist.
*/
export function buildPlanPayloadForSave(sections) {
const list = Array.isArray(sections) ? sections : []
const anyPhased = list.some((s) => s && canonicalPlanLocForPhasedSave(s.planLoc) != null)
if (!anyPhased) {
return { sections: buildSectionsPayload(list) }
}
return buildPhasesPayloadFromFlat(list)
}
/** Payload-Zeilen für POST/PUT /api/training-plan-templates (inkl. Split-/Phasen-Metadaten). */
export function templateSectionsPayloadFromFormSections(sections) {
const norm = inheritPlanLocForPhasedSave(Array.isArray(sections) ? sections : [])
return norm.map((s, si) => {
const canon = canonicalPlanLocForPhasedSave(s.planLoc)
const pk = canon?.phaseKind === 'parallel' ? 'parallel' : 'whole_group'
const poi = canon?.phaseOrderIndex ?? 0
const pso = canon?.phaseKind === 'parallel' ? (canon.parallelStreamOrderIndex ?? 0) : null
return {
order_index: si,
title: (s.title || '').trim() || `Abschnitt ${si + 1}`,
guidance_text: s.guidance_notes?.trim() ? s.guidance_notes.trim() : null,
phase_kind: pk,
phase_order_index: poi,
parallel_stream_order_index: pso,
}
})
}
/** GET-Vorlage → Editor-Abschnitte mit planLoc (Split-Sessions). */
export function formSectionsFromPlanTemplateRows(templateSections) {
const rows = Array.isArray(templateSections) ? [...templateSections] : []
rows.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))
if (!rows.length) return [defaultSection()]
return rows.map((s) => {
const pk = String(s.phase_kind || 'whole_group').toLowerCase().trim()
const poiRaw = s.phase_order_index
const poi = poiRaw == null || poiRaw === '' ? 0 : Number(poiRaw)
const phaseOrderIndex = Number.isFinite(poi) ? poi : 0
const soRaw = s.parallel_stream_order_index
let planLoc
if (pk === 'parallel') {
const so = soRaw == null || soRaw === '' ? 0 : Number(soRaw)
planLoc = {
...defaultPlanLocParallel(phaseOrderIndex, Number.isFinite(so) ? so : 0),
}
} else {
planLoc = { ...defaultPlanLocWholeGroup(phaseOrderIndex) }
}
return {
title: s.title || 'Abschnitt',
guidance_notes: s.guidance_text || '',
items: [],
planLoc,
}
})
}
/** Fügt die Positionen eines Moduls in lokale Abschnitte ein (wie eine Übung, ohne Zwischenspeichern der Einheit). */