249 Commits
Author SHA1 Message Date
Lars 3134160003 Merge pull request 'feat(admin): restrict admin access and enhance navigation for superadmins' (#29) from develop into main
Test Suite / build-frontend (push) Successful in 8s
Deploy Production / deploy (push) Successful in 37s
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 01be9ffcd4 feat(admin): restrict admin access and enhance navigation for superadmins
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 37s
Test Suite / pytest-backend (pull_request) Successful in 24s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 24s
- Updated access control to ensure only superadmins can view admin routes and manage users.
- Refactored navigation components to reflect the new role-based access, removing platform admin references.
- Enhanced the admin user management page to streamline functionality for superadmins, including password reset options.
- Improved overall user experience by clarifying navigation paths and access permissions for different user roles.
2026-05-09 13:26:22 +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
Test Suite / build-frontend (push) Successful in 7s
Deploy Production / deploy (push) Successful in 37s
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: #28
2026-05-09 11:01:02 +02:00
Lars 30c1c259d2 feat(access): enhance visibility handling for club-related content
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / playwright-tests (pull_request) Successful in 30s
- Updated visibility logic for exercises, media assets, and training programs to ensure access is correctly managed based on active club memberships.
- Refactored SQL queries to streamline visibility checks for platform admins and club members, ensuring only relevant content is displayed.
- Improved user interface elements to reflect the status of club memberships, including visual indicators for inactive memberships.
- Enhanced test cases to validate the new visibility logic and ensure proper access control across various components.
2026-05-09 10:55:58 +02:00
Lars 24c70c5ea0 feat(memberships, profiles, clubs): enhance active club membership handling
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new utility function to filter and return only active club memberships, improving role management and access control.
- Updated various components and pages to utilize the new active club memberships function, ensuring only relevant memberships are considered.
- Enhanced user interface elements to reflect the status of club memberships, including visual indicators for inactive memberships.
- Improved backend logic for resolving tenant contexts and managing club roles based on active memberships.
2026-05-09 10:42:56 +02:00
Lars 624c19dcba feat(auth, profiles, club_memberships): enhance password reset and club admin management
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Integrated a new password reset mechanism for user accounts, allowing admins to send reset links via email.
- Updated the management password reset functionality to differentiate between direct password setting and email link requests.
- Added validation to ensure at least one active club admin remains when modifying club member roles.
- Improved the user interface for password management in the admin panel, providing clearer feedback and options for password resets.
2026-05-09 10:32:33 +02:00
Lars f54372d7b5 feat(profiles): implement management password reset functionality for admins
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Added a new endpoint for superadmins and platform admins to reset passwords for other profiles.
- Introduced a management password reset feature in the admin user management page, allowing for secure password updates.
- Enhanced user interface to support password reset actions, including validation and feedback for successful updates.
- Updated API utility functions to handle the new password reset request.
2026-05-09 10:15:16 +02:00
Lars c46f5f99be feat(admin): enhance admin navigation and user management features
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 26s
Test Suite / pytest-backend (push) Failing after 27s
Test Suite / lint-backend (push) Successful in 0s
- Updated admin navigation to conditionally display links based on user roles, including new components for platform admin routes.
- Refactored user management page to support club-specific roles and improved access control for platform and club admins.
- Introduced visibility clauses for media assets based on user roles and club memberships.
- Enhanced media library page to reflect user permissions and provide appropriate navigation options.
- Improved overall user experience with better role handling and navigation structure.
2026-05-09 10:02:56 +02:00
Lars 58a38702b9 feat(org-inbox): implement join request inbox for platform and club admins
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 30s
Test Suite / lint-backend (push) Successful in 0s
- Added new API endpoint to retrieve join requests accessible by platform admins and club admins.
- Implemented frontend components to display join requests in the inbox, including navigation updates and badge notifications.
- Enhanced sidebar and navigation to conditionally show inbox based on user permissions.
- Updated styles for inbox components and added responsive design for dashboard integration.
- Introduced context management for inbox state and notifications on join request actions.
2026-05-09 09:13:38 +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 / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #27
2026-05-09 09:05:28 +02:00
Lars 59fb8a5527 feat(exercises): bump version to 0.8.65 and enhance club media copyright handling
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 25s
Test Suite / pytest-backend (push) Successful in 30s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 23s
- Incremented application version to 0.8.65 and updated changelog with new features.
- Added support for setting default copyright notices for club exercises, allowing users to apply a common copyright notice to linked media assets.
- Enhanced error handling to prompt users for copyright information when required.
- Updated tests to verify the new copyright handling functionality.
2026-05-09 09:03:21 +02:00
Lars 6136813f60 Merge pull request 'feat(clubs): enhance co-trainer ID handling for training groups' (#26) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 35s
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 a7cecca36f feat(clubs): enhance co-trainer ID handling for training groups
Test Suite / build-frontend (push) Successful in 8s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (pull_request) Successful in 26s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new functions to normalize and convert co-trainer IDs for JSONB storage.
- Updated `create_training_group` and `update_training_group` methods to utilize the new JSONB handling for co-trainer IDs.
- Ensured invalid entries are discarded and only unique, positive integers are stored.
2026-05-08 13:37:30 +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 / playwright-tests (push) Successful in 31s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #25
2026-05-08 13:28:30 +02:00
Lars bab9b178a4 feat(exercises): update to version 0.8.64 and enhance inline media functionality
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 14s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (pull_request) Successful in 22s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.8.64 and updated changelog with new features.
- Implemented inline media support in Rich Text Editor, allowing for drag-and-drop functionality and auto-scrolling.
- Enhanced media handling with a modal picker for media insertion, size selection, and improved user experience.
- Updated documentation to reflect changes in media handling and inline media specifications.
- Adjusted various API specifications to support new inline media features.
2026-05-08 13:27:15 +02:00
Lars c8c40474d1 Merge pull request 'Inline Medien' (#24) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Reviewed-on: #24
2026-05-08 12:39:27 +02:00
Lars 5cf775c920 feat(exercises): bump version to 0.8.64 and enhance media handling
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 23s
- Incremented application version to 0.8.64 and updated changelog with new features.
- Improved media handling in the Rich Text Editor with auto-scrolling during drag-and-drop.
- Added new CSS styles for video thumbnails and enhanced layout for media items.
- Removed deprecated `ExerciseAttachmentMediaStrip` from the ExerciseFullContent component.
- Updated ExerciseFormPage to manage form dirty state and prevent data loss on navigation.
2026-05-08 12:35:28 +02:00
Lars 337f29401b feat(exercises): update inline media functionality and version bump to 0.8.63
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 30s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.8.63 and updated changelog with new features.
- Enhanced inline media handling in the Rich Text Editor, including support for captions.
- Introduced new CSS styles for improved media display and layout in the editor.
- Replaced `ExerciseMediaEmbed` with `ExerciseAttachmentMediaStrip` for better media management in exercise content.
2026-05-08 12:20:24 +02:00
Lars 311a106d93 feat(exercises): enhance inline media functionality and update styles
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated inline media markup to include a new data attribute for media size.
- Enhanced the Rich Text Editor to support media size selection when inserting inline media.
- Improved CSS styles for inline media display, accommodating different sizes (small, medium, full).
- Bumped version to 0.8.62 and updated changelog to reflect these changes.
2026-05-08 12:00:02 +02:00
Lars 979e328cef chore(release): bump version to 0.8.61 and update changelog
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
- Updated application version to 0.8.61.
- Added changelog entry for version 0.8.61, detailing the new inline help feature for the "Bild/Video im Text" functionality, including a visible 📎-chip in the editor and prompts for failed insertions.
2026-05-08 11:51:28 +02:00
Lars cc51b0f08f feat(exercises): implement inline media support in exercise content
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Added functionality for inline media references in exercise text using `{{exerciseMedia:id}}` syntax, which normalizes to a canonical `<span>` element.
- Updated the frontend to utilize `ExerciseRichTextBlock` for rendering exercise content, allowing for embedded media display.
- Enhanced the Rich Text Editor to support inserting inline media placeholders.
- Version bump to 0.8.60 to reflect these changes in media handling and exercise content management.
2026-05-08 11:44:29 +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 / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #23
2026-05-08 11:17:12 +02:00
Lars f745e5d082 feat(nginx): add media location handling with Content-Security-Policy
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (pull_request) Successful in 24s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (pull_request) Successful in 22s
Test Suite / lint-backend (push) Successful in 0s
- Implemented specific location blocks for `/media` and `/media/` to serve the React media library correctly.
- Added Content-Security-Policy headers to enhance security for media resources.
- Ensured proper handling of requests to prevent 404 errors on media reloads.
2026-05-08 11:15:19 +02:00
LarsandCursor b6de1f15ea feat(media): implement centralized media archive and inline media linking
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a centralized media archive (`/media`) with lifecycle management, including soft delete and recovery options.
- Enhanced media upload functionality to support multiple files and automatic type inference.
- Updated documentation to reflect the new media architecture and inline media linking specifications.
- Version bump to 0.8.59 to accommodate changes in media handling and database schema.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:56:43 +02:00
Lars 3ff47779e0 feat(tenant_context): enhance effective_club_id resolution for platform admins without header
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 31s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated resolve_tenant_context to use stored active_club_id if the club exists when no header is provided.
- Adjusted comments for clarity regarding platform admin behavior.
- Added unit tests to verify new behavior for platform admins in test_access_layer.py.

version bump to 1.0.5 for tenant_context module.
2026-05-08 10:45:58 +02:00
LarsandCursor d3055f6f2f Medien: offizielle Assets nur Superadmin verwaltbar; Lesemodus; Upload-Verein vorausfüllen
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 28s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:35:28 +02:00
LarsandCursor f354bd9f77 Governance: official nur Superadmin; Privat-Archiv Verein wählbar; Club-Übung Copyright; gleiche Medienordner
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 47s
Test Suite / pytest-backend (push) Successful in 33s
Test Suite / lint-backend (push) Successful in 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:20:41 +02:00
LarsandCursor 01636b5baf Medien: Vereinsordner aus Namen statt library/club/c{id}
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:06:05 +02:00
LarsandCursor 3e4fa0dc39 Medien: library-Pfade nach Medientyp (image/video/pdf/other) unterteilen
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:03:00 +02:00
LarsandCursor 8d85649cf8 refactor(media): Vereinsflache Ablage; private als u{profile} unter Verein
- club: library/club/c{id}/{sha} (kein shared/)
- private: library/club/c{id}/u{profile}/{sha} statt …/private/
- Dedupe private: sha + club_id + uploaded_by_profile_id
- version 0.8.54

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:00:37 +02:00
LarsandCursor 3f0d02edab fix(media): Vereinsordner für private/shared; kein library/private mehr
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- library/club/c{id}/private/* und …/shared/* (club visibility)
- Private Archiv-Upload: effective_club_id oder club_id Form; Plattform braucht Header
- media_assets.club_id bei private gesetzt; Dedupe pro Verein
- Übungs-Upload: dedupe_club für private aus exercise.club_id oder Mandant
- PATCH: club_id für private erhalten; Relocate inkl. private
- version 0.8.53

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:58:28 +02:00
LarsandCursor 4fb77d6927 feat(media): library/* Speicherpfade nach Sichtbarkeit und Verein
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- media_storage.library_storage_key + relocate_local_media_file
- Übungs- und Archiv-Upload nutzen library/private|club/c*|official
- PATCH/Bulk-Patch: bei visibility/club_id Datei umziehen, storage_key + exercise_media.file_path
- pytest: test_library_storage_key; Mocks angepasst
- version 0.8.52 / media_assets 1.7.0 / exercises 2.17.0

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:47:16 +02:00
LarsandCursor b8842cf98e feat(docker): Mediumpfade über .env (SHINKAN_MEDIA_HOST, MEDIA_ROOT)
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 22s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Bind-Mount statt Named-Volumes für Backend-/app/media; MEDIA_ROOT wird
an den Container durchgereicht (entspricht FastAPI). .env.example: MEDIA_DIR
durch SHINKAN_MEDIA_HOST/MEDIA_ROOT ersetzt, Kommentare für Prod/Dev.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:22:03 +02:00
LarsandCursor f8a7247ccc revert: Dev/Compose/Frontend auf Stand ceef6f0 (07.05.2026 22:02)
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Alle Änderungen nach dem letzten verifizierten Deploy (ceef6f0) für
docker-compose.dev-env.yml, docker-compose.yml, .env.example sowie
main.jsx, MediaLibraryPage, ExerciseFormPage zurückgesetzt;
ErrorBoundary entfernt. Entspricht dem funktionierenden develop-Stand
von Gitea an diesem Zeitpunkt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:18:07 +02:00
Lars d758de3852 feat: add MEDIAWIKI_CATEGORY_MODELS to docker-compose and refactor MediaLibraryPage
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m43s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Introduced MEDIAWIKI_CATEGORY_MODELS environment variable in docker-compose.yml for better configuration.
- Refactored MediaLibraryPage to simplify video rendering by replacing createElement with JSX syntax, enhancing readability and maintainability.
- Removed lazy loading and Suspense for MediaLibraryPage to streamline component rendering.
2026-05-08 09:07:51 +02:00
Lars c1d1c2d7e0 feat: implement lazy loading for MediaLibraryPage and optimize video rendering
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m43s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Refactored MediaLibraryPage to use React's lazy loading and Suspense for improved performance during page load.
- Updated video rendering logic to utilize createElement for better flexibility and maintainability.
- Enhanced loading state with a spinner to improve user experience while media content is being fetched.
2026-05-08 09:02:19 +02:00
Lars bebcf5af73 refactor: update media icons in MediaLibraryPage for clarity
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m42s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Renamed imported media icons to avoid naming conflicts, using 'LucideImage' and 'LucideVideo' for better clarity.
- Updated the MediaTypeGlyph component to utilize the renamed icons for rendering media types, ensuring consistent icon representation.
2026-05-08 08:59:13 +02:00
Lars 5b13a0a526 chore: refine media path configuration in environment files
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m43s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
- Updated .env.example to clarify SHINKAN_MEDIA_HOST usage for different environments.
- Modified docker-compose files to set default values for SHINKAN_MEDIA_HOST, ensuring consistent media path handling in development and production.
- Enhanced comments for better understanding of media path configurations.
2026-05-08 08:41:27 +02:00
Lars c921f0dd8f refactor: update media handling configuration and improve upload acceptance
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m45s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Modified .env.example to include SHINKAN_MEDIA_HOST and MEDIA_ROOT for better media path management.
- Updated docker-compose files to utilize SHINKAN_MEDIA_HOST for volume mounts, ensuring consistent media directory handling across environments.
- Enhanced ExerciseFormPage and MediaLibraryPage to specify accepted media types explicitly, improving compatibility and user experience during uploads.
2026-05-08 08:35:15 +02:00
Lars ceef6f09e2 feat: improve media library layout and loading behavior
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 28s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Added a hidden anchor element to the media library for smooth scrolling to the top of the grid after uploads.
- Introduced a sequence reference to manage concurrent media item fetch requests, ensuring accurate loading states.
- Updated upload summary messaging to include a note about the list being refreshed after uploads.
- Enhanced loading state management to prevent unnecessary updates when fetch requests are out of sync.
2026-05-07 22:02:18 +02:00
Lars cc4e621f95 feat: enhance media upload handling and MIME type resolution
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Expanded the allowed upload MIME types to include HEIC, HEIF, and QuickTime formats.
- Introduced a new function to resolve MIME types based on file content, filename extensions, and client-provided content types.
- Updated media upload logic in both the exercises and media assets routers to utilize the new MIME resolution function.
- Adjusted frontend file input accept attributes to allow broader media types, improving user experience.
- Enhanced media library components to handle HEIC/HEIF formats with appropriate fallback messaging for browser compatibility.
2026-05-07 21:55:22 +02:00
Lars d213746bd2 fix: update media card positioning and styles
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 28s
Test Suite / lint-backend (push) Successful in 1s
- Removed unnecessary positioning styles from media library card types.
- Added a new style for the thumbnail card type to adjust its position.
- Updated the MediaLibraryPage component to apply the new thumbnail style conditionally based on the compact view.
2026-05-07 21:42:10 +02:00
Lars f9e6e61244 feat: implement bulk upload functionality for media assets
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 29s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Added a new API endpoint for bulk uploading media assets, allowing users to upload multiple files in a single request.
- Implemented validation for file types and sizes during the upload process, ensuring compliance with allowed formats and limits.
- Enhanced the MediaLibraryPage component to support bulk file selection and visibility options, improving user experience.
- Updated CSS styles for the upload interface to enhance layout and accessibility.
- Added tests to verify the functionality of the new bulk upload feature and its integration with existing media asset management.
2026-05-07 21:36:35 +02:00
Lars 696cb09bf4 Merge pull request 'Medienmanager update 1' (#22) from develop into main
Test Suite / build-frontend (push) Successful in 7s
Deploy Production / deploy (push) Successful in 36s
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 4f64cb105b feat: enhance database migration handling and media asset tags
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (pull_request) Successful in 23s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 30s
Test Suite / pytest-backend (push) Successful in 29s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 23s
- Updated migration scripts to ensure idempotency and safe execution of SQL statements, preventing errors on repeated runs.
- Improved documentation in migration files to clarify the execution order and idempotent practices for database migrations.
- Added a comment in main.py to explain the migration process and its conditional execution based on the SKIP_DB_MIGRATE environment variable.
2026-05-07 16:28:25 +02:00
Lars a8667f4757 feat: increment version to 0.8.51 and update media assets handling
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated APP_VERSION to 0.8.51 and MODULE_VERSIONS for media_assets to 1.5.1.
- Added a new function to check for the presence of the 'training_unit_exercises' table, enhancing conditional handling in media asset queries.
- Updated changelog to reflect the latest changes, including improved handling of media links based on the existence of the training unit exercises table.
2026-05-07 16:24:05 +02:00
Lars 084ac38c2e feat: add support for media asset tags and conditional database handling
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 1s
- Introduced a function to check for the presence of the 'tags' column in the media_assets table, ensuring compatibility with database migrations.
- Updated media asset listing and patching functions to conditionally include tags based on the presence of the 'tags' column.
- Enhanced error handling for operations involving tags, providing clear feedback when the required database migration has not been performed.
- Improved search functionality to account for the presence of tags, optimizing queries based on available database schema.
2026-05-07 16:20:51 +02:00
Lars 1bc7ea95fb feat: increment version to 0.8.50 and enhance media asset features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 30s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated APP_VERSION to 0.8.50 and DB_SCHEMA_VERSION to 20260507046.
- Enhanced media assets with new tagging functionality, allowing users to filter and search by tags.
- Improved media library UI with new filters for media kind and uploader, enhancing user experience.
- Updated changelog to reflect the latest changes and improvements in media management.
2026-05-07 16:15:07 +02:00
Lars 33fedd5ec6 Merge pull request 'Medienmanager und Sicherheitsupdate' (#21) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 35s
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 3d321857ec feat: add media preview functionality to media library
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Failing after 1s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 39s
Test Suite / pytest-backend (push) Successful in 28s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 24s
- Introduced a preview feature for media assets, allowing users to view images and videos in a modal overlay.
- Updated the MediaLibraryPage component to handle media selection and display previews based on the media type.
- Enhanced CSS styles for media cards and preview modals to improve user experience and accessibility.
- Updated instructional text to guide users on how to access media previews.
2026-05-07 14:39:31 +02:00
Lars b8453f3f07 feat: enhance media asset lifecycle management and permissions
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 31s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new API endpoints for bulk lifecycle actions and bulk patching of media assets, allowing for more efficient management of multiple assets.
- Updated media lifecycle permissions to restrict actions based on user roles, ensuring that only superadmins can perform critical operations like purging and force lifecycle changes.
- Enhanced frontend components to support new bulk actions and improved user experience in the media library, including visibility and copyright management.
- Incremented version to 0.8.49, reflecting the latest improvements in media handling and governance.
2026-05-07 14:33:02 +02:00
Lars 0a1816e38b feat: enhance media library and lifecycle management
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
- Updated media library to include lifecycle filtering options (active, trash_soft, trash_hidden) and copyright management capabilities.
- Implemented new API endpoints for listing media assets with lifecycle states and patching copyright notices.
- Enhanced frontend components to support navigation to the media library and integration of media management features in the ExerciseFormPage.
- Incremented version to 0.8.48, reflecting the latest improvements in media handling and governance.
2026-05-07 14:10:26 +02:00
Lars 95f5b0b2d7 feat: implement official exercise media management and copyright validation
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 22s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced exercise update functionality to support the promotion of attached media assets to 'official' status, requiring active visibility and copyright validation.
- Updated backend API to handle new fields for promoting media and setting default copyright notices during exercise updates.
- Improved frontend error handling to prompt users for confirmation when promoting media assets, including checks for copyright compliance.
- Incremented version to 0.8.47, reflecting the latest changes in media management and governance.
2026-05-07 13:34:22 +02:00
Lars 88fb60e244 chore: increment version to 0.8.46 and update changelog
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 28s
Test Suite / lint-backend (push) Successful in 0s
- Updated APP_VERSION to 0.8.46 and MODULE_VERSIONS for exercises to 2.15.1.
- Added structured logging for media upload conflicts in the backend.
- Removed explanatory media hints from the ExerciseFormPage in the frontend to streamline the user interface.
2026-05-07 13:30:25 +02:00
Lars da368222e0 feat: implement media asset reactivation and enhance lifecycle management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 31s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Added a new action to the media asset lifecycle for reactivating assets from the trash, allowing users to restore previously deleted media.
- Updated the backend API to handle reactivation requests and ensure proper state transitions for media assets.
- Enhanced frontend error handling to prompt users for reactivation when attempting to upload media that matches an existing asset in the trash.
- Incremented version to 0.8.45, reflecting the latest changes in media lifecycle management and user experience improvements.
2026-05-07 13:25:42 +02:00
Lars e2964a077d feat: update media management and project status documentation
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated project status to reflect the latest media management milestones and version increment to 0.8.44.
- Enhanced MEDIA_ASSETS_AND_ARCHIVE_SPEC.md with new API details for media asset lifecycle and inline media integration.
- Improved exercise media handling in the frontend, including new preview features and user prompts for media deletion.
- Adjusted backend API to ensure proper handling of media asset deletions without removing files, maintaining governance and user experience.
2026-05-07 13:10:37 +02:00
Lars 631ba1cb43 feat: enhance media asset management and exercise integration
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Added new API endpoints for listing media assets and attaching existing archive media to exercises, improving media reuse and governance.
- Updated frontend components to support media asset selection from the archive, enhancing user experience and reducing duplication.
- Incremented version to 0.8.43, reflecting the latest changes in media handling and exercise integration.
2026-05-07 13:00:57 +02:00
Lars 8ac723eafe feat: enhance media lifecycle management and inline media integration
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Implemented media lifecycle management with new API endpoints for handling asset states (trash_soft, trash_hidden, recover, purge), improving media governance.
- Updated frontend components to filter and display media based on lifecycle states, enhancing user experience and visibility.
- Enhanced documentation in MEDIA_ASSETS_AND_ARCHIVE_SPEC.md to include guidelines for inline media references in exercise texts, establishing a clear implementation plan.
- Incremented version to 0.8.42, reflecting the latest changes in media handling and lifecycle management.
2026-05-07 12:55:50 +02:00
Lars ece08ec1a1 feat: enhance exercise editing permissions and media management
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Updated exercise editing permissions to allow platform admins and users with planning rights in clubs to edit exercises, improving governance.
- Refactored the `_assert_can_edit_exercise` function to utilize tenant context for permission checks.
- Enhanced frontend media management with new features for saving media metadata and reordering media items, improving user experience.
- Introduced state management for media fields in the ExerciseFormPage, allowing users to edit titles and contexts for media assets.
2026-05-07 12:46:59 +02:00
Lars 7284c577d7 feat: enhance media management and governance in the project
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
- Added new documentation for media assets and lifecycle management, establishing a single source of truth in MEDIA_ASSETS_AND_ARCHIVE_SPEC.md.
- Updated project status to reflect the addition of media archive and lifecycle governance.
- Introduced a new API endpoint for platform media storage, allowing superadmin access for media management.
- Enhanced exercise media handling with improved database integration for media assets, including deduplication and effective media root resolution.
- Updated frontend API utilities to support new media storage functionalities, ensuring seamless integration with the backend.
- Incremented version to 0.8.41, reflecting the latest changes and improvements in media handling.
2026-05-07 12:36:46 +02:00
Lars 161d520329 feat: implement CSP and security headers for API responses
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Added Content-Security-Policy header to nginx configuration for SPA, enhancing security against XSS attacks.
- Introduced middleware in FastAPI to set X-Content-Type-Options header, preventing MIME-sniffing vulnerabilities.
- Updated production readiness audit and access layer endpoint audit to reflect security enhancements and ongoing governance practices.
- Added tests to verify the presence of security headers in API responses, ensuring compliance with security standards.
2026-05-07 11:09:06 +02:00
Lars 9365125969 feat: enhance media file delivery with range support and inline display
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Added support for HTTP Range requests to enable partial downloads for media files, improving streaming capabilities.
- Implemented a new response function to handle binary media responses, including content disposition for inline display.
- Updated the media file download endpoint to utilize the new response handling, ensuring secure and efficient file delivery.
- Enhanced type hints and imports for better code clarity and maintainability.
2026-05-07 11:02:43 +02:00
Lars b752883392 feat: enhance media access and security for exercises
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Successful in 25s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Updated PostgreSQL binding in docker-compose to restrict access to localhost only.
- Implemented a new API endpoint for secure media file delivery, requiring authentication via token.
- Enhanced governance checks for exercise media access, ensuring only authorized users can retrieve files.
- Updated frontend components to utilize the new media file access method, improving user experience while maintaining security.
- Documented changes in production readiness audit and access layer endpoint audit for clarity on security enhancements.
2026-05-07 10:52:14 +02:00
Lars c2d9eac151 feat: enhance API and profile management with environment configurations
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
- Added functions to determine production environment and OpenAPI exposure settings, improving API documentation control.
- Updated FastAPI initialization to conditionally set OpenAPI and documentation URLs based on environment variables.
- Refactored health check response to limit detail exposure in production environments, enhancing security.
- Streamlined profile management by removing legacy ID retrieval and ensuring session-based profile access for security improvements.
2026-05-07 10:40:10 +02:00
Lars c8a08f8a94 Merge pull request 'pre-Prod Alpha' (#18) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #18
2026-05-07 10:37:21 +02:00
Lars 18fa4de055 feat: add system information page and update account settings
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (pull_request) Successful in 5s
Test Suite / lint-backend (pull_request) Successful in 1s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 23s
- Introduced a new SettingsSystemInfoPage to display technical system information.
- Updated AccountSettingsPage to include a link to the new system information page, enhancing user access to app version, build, environment, and database schema details.
- Removed unused version state from Dashboard component to streamline data handling.
2026-05-07 10:29:14 +02:00
Lars fe703ca414 feat: add club visibility queue for training exercises
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Implemented a new API endpoint to retrieve exercises in training units that are not yet visible to the target club, enhancing visibility management for trainers.
- Introduced a new widget in the Dashboard to display these exercises, improving user access to relevant training information.
- Added helper functions to determine exercise visibility based on club membership and status, streamlining the exercise promotion process.
2026-05-07 10:19:55 +02:00
Lars f9d518fb78 feat: implement exercise promotion logic for training units
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added functionality to promote private exercises used in training units to club visibility, allowing better access for trainers and members.
- Introduced helper functions to retrieve distinct exercise IDs and group club IDs for scheduled units.
- Updated the create, update, and quick create training unit methods to include exercise promotion logic, enhancing exercise management within clubs.
2026-05-07 10:09:25 +02:00
Lars c6a7d668c5 feat: add quick create draft functionality in ExercisePickerModal
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 22s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a quick create draft feature allowing users to create private exercise drafts directly from the ExercisePickerModal.
- Added state management for quick create inputs including title and summary, with validation for minimum title length.
- Updated the Dashboard to display a preview of private exercise drafts, enhancing user visibility of pending exercises.
- Enabled quick create functionality in TrainingFrameworkProgramEditPage and TrainingPlanningPage for streamlined exercise management.
2026-05-07 09:20:19 +02:00
Lars ff8fd78a31 feat: add debriefing functionality and enhance training unit filtering
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new filter option for listing training units to show only those with pending debriefs.
- Updated the dashboard to reflect changes in training unit statuses, renaming components for clarity.
- Enhanced the Training Planning Page to manage debrief completion status, including UI elements for user interaction.
- Improved API utility to support new filtering criteria for training units, ensuring accurate data retrieval.
2026-05-07 09:01:01 +02:00
Lars 40a3b4b8e6 feat: enhance dashboard and exercises list UI with new styles and filtering options
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Added responsive styles for dashboard KPI cards and exercise search actions, improving layout on smaller screens.
- Refactored the Dashboard component to streamline error handling and loading states for better user experience.
- Updated ExercisesListPage to include new filtering options for user-created exercises, enhancing data relevance.
- Improved overall CSS organization and introduced new classes for better styling consistency across components.
2026-05-07 08:47:01 +02:00
Lars 3bf0af001a feat: enhance dashboard and exercises list with new filtering and UI components
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added a new filter option in the list_exercises function to allow users to view exercises created by the current profile.
- Introduced new CSS styles for the dashboard, including KPI tiles and training previews, improving layout and user experience.
- Updated the Dashboard component to fetch and display statistics related to user-created exercises, enhancing visibility of personal metrics.
- Enhanced the ExercisesListPage to support filtering based on user-specific exercise creation, improving data relevance for users.
2026-05-07 08:33:50 +02:00
Lars 3210796139 feat: update dashboard smoke test for new UI elements
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 24s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Modified the dashboard smoke test to reflect changes in the main heading and greeting text.
- Updated expectations to check for the visibility of the new "Dashboard" heading and the greeting message, enhancing test accuracy.
2026-05-07 07:51:24 +02:00
Lars d04ebee1f6 Merge pull request 'UX - Filter' (#12) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #12
2026-05-06 21:25:56 +02:00
Lars b9d27b59b0 feat: enhance exercise filtering capabilities with new catalog rules
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (pull_request) Successful in 5s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 7s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (pull_request) Failing after 28s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new filtering options for style directions, training types, and target groups in the exercise list.
- Implemented catalog rule picker components to manage inclusion and exclusion of exercise attributes.
- Updated utility functions to handle new catalog rules for improved filtering logic.
- Enhanced the ExercisesListPage and ExercisePickerModal to support the new filtering features, improving user experience.
2026-05-06 21:20:19 +02:00
Lars 518918a6e5 feat: update version and enhance exercise filtering features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 45s
Test Suite / playwright-tests (push) Failing after 29s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.40 and updated module versions accordingly.
- Introduced new focus area filtering options in the ExercisesListPage, allowing users to include or exclude exercises based on specified focus areas.
- Added utility functions for deduplicating and merging focus area IDs to improve filtering logic.
- Enhanced the ExercisePickerModal and ExercisesListPage components to support new focus rules and improve user experience with focus area selections.
2026-05-06 17:15:44 +02:00
Lars cfd40889ac feat: add utility functions for exercise data sanitization
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 29s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Introduced `sanitizeExerciseRichText` and `coerceApiNameList` utility functions to enhance data handling in ExercisesListPage.
- Improved overall code organization by importing new utilities for better maintainability and readability.
2026-05-06 15:15:26 +02:00
Lars 585ee8c90d feat: enhance exercise management features and UI
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Failing after 27s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new function `club_admin_shares_club_with_creator` to check club admin permissions for shared clubs.
- Updated `can_manage_club_org` to incorporate new role checks.
- Enhanced exercise deletion logic to include checks for club admin roles and shared club memberships.
- Added new filters for exercise visibility and status in the ExercisesListPage, allowing users to exclude specific criteria.
- Implemented functionality to save user-specific exercise list preferences, improving user experience.
- Updated API interactions to support new filtering options and preferences for exercise management.
2026-05-06 13:52:24 +02:00
Lars 8eec145393 style: update navigation styles for improved layout and consistency
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 27s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 1s
- Adjusted the height and padding of the navigation bar for better alignment with design standards.
- Enhanced the bottom navigation with a new box shadow for improved visual separation.
- Updated nav-item dimensions and styles for better responsiveness and user interaction.
- Increased icon size in navigation items for better visibility and accessibility.
2026-05-06 12:52:35 +02:00
Lars db8af53652 refactor: update navigation components and styles for improved consistency
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Replaced legacy .capture-shell with .app-subnav-shell and integrated PageSectionNav for a unified navigation experience across multiple pages.
- Refactored AdminCatalogsPage, AdminMaturityModelsPage, ClubsPage, ExercisesListPage, MediaWikiImportPage, SkillsPage, and TrainingFrameworkProgramEditPage to utilize the new PageSectionNav component for tab navigation.
- Enhanced CSS styles for better responsiveness and visual clarity in navigation elements.
- Improved accessibility features with appropriate ARIA roles and attributes for better usability.
2026-05-06 12:49:35 +02:00
Lars 1e1fd80fb7 feat: enhance card layouts and UI components across multiple pages
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 40s
Test Suite / playwright-tests (push) Failing after 29s
Test Suite / pytest-backend (push) Successful in 10s
Test Suite / lint-backend (push) Successful in 0s
- Updated CSS styles to improve card spacing and layout consistency in grid formats.
- Introduced a new card-grid class for better handling of card arrangements in ClubsPage and TrainingFrameworkProgramsListPage.
- Added ExerciseCardScopeStatus component to display visibility and status icons in ExercisesListPage, enhancing user feedback.
- Refactored exercise card actions and footer for improved layout and accessibility.
- Enhanced overall responsiveness and visual clarity across various components.
2026-05-06 12:41:04 +02:00
Lars b9ef0395c1 feat: enhance app.css and AppSubnavShell for improved navigation and layout
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 31s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Updated CSS styles to refine card spacing in grid layouts, ensuring consistent margins.
- Enhanced the capture-shell component for better responsiveness and sticky navigation across all viewports.
- Improved sub-navigation structure for both mobile and desktop, promoting a unified user experience.
- Added detailed comments in CSS for better clarity on navigation layers and layout intentions.
2026-05-06 12:31:39 +02:00
Lars 5096eec16b feat: enhance Exercises and Clubs pages with improved UI and functionality
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added new utility functions for handling exercise focus areas, style directions, and training types, improving data presentation.
- Refactored ExercisesListPage to utilize new card layouts and improved visibility labels for exercises.
- Updated ClubsPage and SkillsPage to implement a consistent tab navigation style, enhancing user experience.
- Enhanced CSS styles for better responsiveness and visual consistency across various components.
- Improved loading states and accessibility features for better user feedback and interaction.
2026-05-06 12:20:22 +02:00
Lars 68923b0364 feat: enhance UI and functionality for Skills and Exercises pages
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 29s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for Skills and Exercises pages, improving layout and responsiveness.
- Refactored components to utilize new styles, enhancing visual consistency and user experience.
- Implemented horizontal scrollable navigation for exercises and skills tabs, improving usability on smaller screens.
- Updated button styles and introduced new class names for better maintainability and accessibility.
- Enhanced loading states and empty messages for improved user feedback during data fetching.
2026-05-06 11:24:44 +02:00
Lars 657f73d2c5 feat: enhance admin catalog UI and functionality
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 27s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for admin catalog sections, improving layout and responsiveness.
- Implemented icon support for catalog section titles, enhancing visual clarity.
- Refactored loading and error states for better user experience in the CatalogsTab and HierarchyTab components.
- Updated AdminCatalogsPage to utilize new styles and improve tab navigation.
- Enhanced accessibility with appropriate ARIA roles and attributes for better usability.
2026-05-06 11:12:59 +02:00
Lars 8b86021293 feat: update bulk metadata patch functionality for exercises
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 29s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Bumped the version of exercises to 2.8.0, reflecting new features in the bulk metadata patch.
- Enhanced the ExerciseBulkMetadataPatch model to include focus area, style direction, training type, and target group IDs.
- Updated the bulk patch endpoint to support replacing catalog associations for exercises.
- Improved the ExercisesListPage to handle new relation fields and updated UI for bulk operations.
- Adjusted API documentation to reflect changes in the bulk patch functionality.
2026-05-06 11:02:46 +02:00
Lars 35a3f6e18d feat: enhance mobile responsiveness and UI components in app.css
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for mobile layout adjustments, improving spacing and readability for various UI elements.
- Implemented horizontal scrollable navigation for main and admin top navigation, enhancing usability on smaller screens.
- Updated button and card styles for better visual consistency and compactness in mobile view.
- Enhanced tab and segment button styles to improve user interaction and accessibility.
2026-05-06 10:55:36 +02:00
Lars 18a58cb5a5 feat: enhance UI and functionality in Training Framework pages
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 53s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Added new CSS styles for segment buttons and admin assignment matrix, improving layout and responsiveness.
- Refactored AssignmentsTab component to utilize new styles and improve accessibility with aria-labels.
- Introduced collapsible details for framework edit introduction, enhancing user guidance.
- Updated TrainingPlanningPage to streamline button styling and improve visual consistency across components.
2026-05-06 10:46:40 +02:00
Lars 14884e6e55 UX. refactor: simplify AdminPageNav component by removing unused hooks and improving styling
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 28s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Removed the useLocation hook as it was unnecessary for the component's functionality.
- Updated the navigation styling to use CSS classes instead of inline styles, enhancing maintainability and readability.
- Improved accessibility by adding aria-labels to navigation elements.
2026-05-06 10:37:01 +02:00
Lars 2007f3f659 feat: enhance TrainingPlanningPage with new training unit creation UI
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 22s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new layout for creating training units within a card format, improving visual organization and user experience.
- Added CSS styles for various elements related to training unit creation, including titles, hints, and action buttons.
- Removed the quick template ID state and related functionality to streamline the creation process.
- Updated user prompts and hints to guide users more effectively in selecting training groups and creating new training units.
2026-05-06 08:44:15 +02:00
Lars d4b9db9520 refactor: update sectionsEditMode logic and remove refine option in TrainingPlanningPage
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 48s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Revised the sectionsEditMode state to clarify the editing modes available, focusing on 'planning' and 'debrief'.
- Removed the 'refine' option from the editing mode buttons to streamline the user interface.
- Updated related text descriptions to reflect the changes in editing modes, enhancing user guidance during the training planning process.
2026-05-06 08:00:27 +02:00
Lars 00b22a756f feat: refactor TrainingUnitSectionsEditor and enhance TrainingPlanningPage layout
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Replaced the tu-ex-run-block with a new tu-ex-debrief layout using CSS Grid for improved structure and responsiveness.
- Updated the TrainingUnitSectionsEditor component to utilize the new layout, enhancing the user experience for inputting modifications and actual durations.
- Introduced a sectionsEditMode state in TrainingPlanningPage to manage different editing modes (planning, refine, debrief) for better user guidance.
- Adjusted the visibility of execution extras based on the current editing mode, streamlining the interface for users.
2026-05-06 07:55:35 +02:00
Lars 56ea36ea25 feat: enhance TrainingPlanningPage with new utility functions and state management improvements
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added utility functions to normalize co-trainer IDs and filter directory entries, improving data handling for training groups.
- Updated state management to remove reliance on the user profile for club admin checks, enhancing performance and clarity.
- Improved session assignment logic to ensure effective lead trainers are excluded from assistant trainer lists.
- Enhanced form field updates to manage session assistant IDs more effectively, streamlining the assignment process.
2026-05-06 07:42:39 +02:00
Lars 9dbd3cbd5f feat: enhance TrainingPlanningPage with template application functionality
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Successful in 30s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Added a new function to apply selected training templates, improving user experience in the training planning process.
- Introduced modal display logic to enhance interaction when applying templates.
- Updated the state management to handle template ID selection more effectively.
2026-05-06 07:25:11 +02:00
Lars 9e759a28c6 feat: update application version to 0.8.38 and enhance training planning features
Test Suite / build-frontend (push) Failing after 2s
Deploy Development / deploy (push) Failing after 14s
Test Suite / playwright-tests (push) Successful in 29s
Test Suite / pytest-backend (push) Successful in 5s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.38 in both backend and frontend files.
- Updated training planning API to improve permission checks for trainer assignments, allowing club admins to manage training units more effectively.
- Enhanced the TrainingPlanningPage with new modal functionality for assigning trainers and improved loading of club member directories.
- Updated changelog to reflect the new version and changes made in this release.
2026-05-06 07:18:30 +02:00
Lars c778d21b26 feat: update application version to 0.8.37 and enhance training planning features
Test Suite / build-frontend (push) Failing after 2s
Deploy Development / deploy (push) Failing after 14s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 5s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.37 in both backend and frontend files.
- Updated training planning API to include new session assignment features, allowing for lead trainer and assistant trainer assignments.
- Enhanced the TrainingPlanningPage to support dynamic loading of club member directories based on selected groups.
- Improved validation for trainer assignments, ensuring only active club members can be assigned as trainers.
- Updated changelog to reflect the new version and changes made in this release.
2026-05-05 23:35:41 +02:00
Lars 0c1fbab0ef Merge pull request 'Mandantenfähigkeit V1.1' (#11) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 37s
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 14745b347d fix: update test workflow and improve smoke tests
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (pull_request) Successful in 8s
Test Suite / lint-backend (pull_request) Successful in 0s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / playwright-tests (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 22s
- Changed the artifact upload action in the CI workflow from v4 to v3 due to compatibility issues with Gitea.
- Enhanced the smoke test for the clubs page to check the URL and visibility of the primary heading, ensuring more robust validation.
- Updated session persistence test to verify the visibility of the dashboard heading after a page reload, improving test reliability.
2026-05-05 23:03:40 +02:00
Lars 35b14fe1a6 feat: update application version to 0.8.36 and enhance profile creation process
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 37s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.36 in both backend and frontend files.
- Updated the ProfileCreate model to require name and email fields, ensuring schema compliance.
- Implemented a new POST /api/profiles endpoint restricted to platform admins, utilizing a random PIN for user setup.
- Added integration tests for profile creation, including checks for unauthorized access and duplicate email handling.
- Enhanced changelog to reflect the new version and changes made in this release.
2026-05-05 23:01:14 +02:00
Lars caab9f2863 feat: update application version to 0.8.35 and enhance profile access controls
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 34s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.35 in both backend and frontend files.
- Updated profile retrieval and deletion endpoints to restrict access to the profile owner or platform admins, returning a 403 status for unauthorized access.
- Added integration tests to verify access control for profile retrieval.
- Enhanced changelog to reflect the new version and changes made in this release.
2026-05-05 22:57:42 +02:00
Lars f03330bf77 feat: update application version to 0.8.33 and enhance CI workflow
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / pytest-backend (push) Successful in 5s
Test Suite / lint-backend (push) Successful in 1s
- Bumped application version to 0.8.33 in both backend and frontend files.
- Refactored pytest-backend job in CI workflow to run tests within the deployed backend container, eliminating the need for a separate Python/Postgres service.
- Updated pytest.ini to include new test markers for smoke and slow tests, and adjusted default options for pytest execution.
- Enhanced changelog to reflect the new version and changes made in this release.
2026-05-05 22:51:59 +02:00
Lars 61e3b3a6b1 feat: update application version to 0.8.31 and enhance CI workflow
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 34s
Test Suite / pytest-backend (push) Failing after 3s
Test Suite / lint-backend (push) Successful in 1s
- Bumped application version to 0.8.31 in both backend and frontend files.
- Added pytest-backend job to the CI workflow for PostgreSQL integration testing, including database migrations and access layer checks.
- Updated test.yml to trigger on pull requests to main and develop branches in addition to pushes.
- Updated changelog to reflect the new version and changes made in this release.
2026-05-05 22:47:00 +02:00
Lars 347af0c36e feat: update application version to 0.8.30 and add integration test marker
Test Suite / build-frontend (push) Successful in 8s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 35s
Test Suite / lint-backend (push) Successful in 1s
- Bumped application version to 0.8.30 in both backend and frontend files.
- Added a new marker for integration tests in pytest.ini to facilitate PostgreSQL integration testing.
- Updated changelog to reflect the new version and changes made in this release.
2026-05-05 22:34:35 +02:00
Lars a7d68c0646 Merge pull request 'Mandantenfähigkeit V1' (#10) from develop into main
Test Suite / build-frontend (push) Successful in 7s
Deploy Production / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 46s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #10
2026-05-05 22:34:25 +02:00
Lars dc310b38eb feat: implement bulk metadata update for exercises
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 35s
Test Suite / lint-backend (push) Successful in 1s
- Introduced a new PATCH endpoint `/api/exercises/bulk-metadata` to allow bulk updates of visibility and status for exercises, supporting up to 500 IDs.
- Enhanced the ExercisesListPage to include a bulk update modal for managing exercise visibility and status.
- Updated frontend API utility to handle bulk patch requests.
- Bumped application version to 0.8.29 and updated changelog to reflect these changes.
2026-05-05 22:18:04 +02:00
Lars e0ecfe927f feat: update access layer governance and visibility checks
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 37s
Test Suite / lint-backend (push) Successful in 1s
- Enhanced ACCESS_LAYER_AND_GOVERNANCE_PLAN.md with additional details on heuristic checks and testing procedures for cross-tenant scenarios.
- Updated club_tenancy.py to recommend using `library_content_visible_to_profile` for exercise visibility checks.
- Refactored multiple routers to utilize `library_content_visible_to_profile`, improving consistency in access control across exercises and training planning.
- Bumped application version to 0.8.28 and updated changelog to reflect these changes.
2026-05-05 22:11:05 +02:00
Lars abee6171df feat: enhance access layer governance and visibility checks
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 34s
Test Suite / lint-backend (push) Successful in 0s
- Added new documentation references for access layer governance in CLAUDE.md, including multi-tenancy and endpoint audit guidelines.
- Updated ACCESS_LAYER_AND_GOVERNANCE_PLAN.md to include cursor and heuristic checks for access layer compliance.
- Enhanced ACCESS_LAYER_ENDPOINT_AUDIT.md to clarify endpoint visibility and governance requirements, including exemptions for certain routers.
- Introduced library_content_visible_to_profile function in club_tenancy.py to streamline visibility checks for library content.
- Updated exercise progression graphs router to utilize the new visibility function, improving access control.
- Bumped application version to 0.8.27 and updated changelog to reflect these changes.
2026-05-05 22:09:25 +02:00
Lars 5aee9c52fc feat: integrate tenant context across club-related APIs
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 34s
Test Suite / lint-backend (push) Successful in 0s
- Refactored club join requests, memberships, and clubs routers to utilize TenantContext for authentication and authorization, enhancing security and consistency.
- Updated session handling to replace direct session dictionary access with TenantContext, improving code clarity and maintainability.
- Ensured proper role and profile ID retrieval from TenantContext in various endpoints, streamlining access control for club management functionalities.
2026-05-05 22:05:10 +02:00
Lars 870a7611dc feat: enhance governance visibility checks and update login rate limit
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 34s
Test Suite / lint-backend (push) Successful in 0s
- Updated governance visibility logic in `assert_valid_governance_visibility` to enforce club membership checks for platform admins and ensure proper club existence validation.
- Increased login request limit from 5 to 30 per minute to improve user experience.
- Refactored exercise update logic to better handle visibility and club ID requirements, ensuring compliance with governance rules.
2026-05-05 21:57:55 +02:00
Lars 0181575962 feat: update exercises API to fully integrate tenant context and bump version to 0.8.24
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 43s
Test Suite / lint-backend (push) Successful in 0s
- Refactored exercises API endpoints to utilize tenant context for authentication and authorization, enhancing security and governance.
- Updated access layer documentation to reflect the complete integration of tenant context for exercises.
- Bumped application version to 0.8.24 in both backend and frontend files.
- Enhanced changelog to document the new version and changes made in this release.
2026-05-05 21:51:53 +02:00
Lars c919e02441 feat: enhance tenant context integration and update access layer endpoints
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Implemented `library_content_visibility_sql` for managing visibility of exercises, training planning, and framework programs based on tenant context.
- Updated access layer documentation to reflect changes in endpoint visibility and governance requirements.
- Bumped application version to 0.8.23 in both backend and frontend files.
- Enhanced changelog to document the new version and changes made in this release.
2026-05-05 21:46:41 +02:00
Lars 4b6fd49940 feat: implement tenant context resolution and update profiles API
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 52s
Test Suite / lint-backend (push) Successful in 0s
- Introduced tenant context resolution in the profiles API, allowing for effective club identification based on user memberships.
- Updated the `GET /profiles/me` endpoint to return `effective_club_id` and removed reliance on the deprecated `X-Active-Club-Id` header.
- Bumped application version to 0.8.22 in both backend and frontend files.
- Enhanced changelog to document the new version and changes made in this release.
2026-05-05 21:42:56 +02:00
Lars 413a096432 feat: enhance mobile and desktop sidebar with ActiveClubSwitcher component
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Integrated ActiveClubSwitcher into both mobile and desktop sidebar layouts, improving club selection functionality.
- Updated app header styles for better mobile responsiveness and layout.
- Adjusted desktop sidebar footer styles for improved alignment and spacing.
2026-05-05 21:23:16 +02:00
Lars f48b573a63 feat: register new club membership and join request routers
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 43s
Test Suite / lint-backend (push) Successful in 0s
- Added club_memberships and club_join_requests routers to the backend, improving API functionality for managing club memberships and join requests.
- Bumped application version to 0.8.21 in both backend and frontend files.
- Updated changelog to reflect the new version and changes made in this release.
2026-05-05 21:15:27 +02:00
Lars b661d0edb2 feat: update application version to 0.8.20 and enhance superadmin role management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.20 in both backend and frontend files.
- Introduced migration 041 to promote the oldest admin user to superadmin if no superadmin exists.
- Updated registration logic to assign the superadmin role to the first user and those in ADMIN_BOOTSTRAP_EMAILS.
- Enhanced changelog to document the new version and changes made in this release.
2026-05-05 21:10:19 +02:00
Lars 9afcd762d0 feat: enhance admin user management and profile updates
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Added role and tier fields to the ProfileUpdate model, allowing for better user role management.
- Implemented new API endpoint for listing admin users, accessible only to portal admins.
- Updated profile retrieval and update logic to handle role and tier changes, enforcing permissions for modifications.
- Enhanced frontend navigation and routing to include the new admin users page, improving admin interface usability.
- Bumped application version to 0.8.19 and updated changelog to reflect these changes.
2026-05-05 21:05:52 +02:00
Lars 0f08e8df58 feat: enhance club management features and member requests
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 50s
Test Suite / lint-backend (push) Successful in 1s
- Updated the backend to include a new `requested_club_id` field in the registration request model.
- Replaced the club memberships router with a new club join requests router for better management of membership applications.
- Added API endpoints for listing public clubs and managing club join requests, improving user experience during registration and membership processes.
- Enhanced the ClubsPage in the frontend to support member management and join requests, including new modals for adding members and handling requests.
- Updated API utility functions to accommodate new endpoints for club join requests and public club listings.
2026-05-05 16:40:49 +02:00
Lars 7d476268b8 feat: implement multi-tenancy governance and enhance club member management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.17, reflecting updates in both backend and frontend.
- Introduced governance visibility for training plan templates and framework programs, allowing access based on visibility settings (private, club, official).
- Added API endpoints for managing club members, including listing, adding, updating, and removing members.
- Updated changelog to document the new features and changes made in this release.
2026-05-05 16:29:11 +02:00
Lars c7bf7dcd9d chore: bump version to 0.8.15 and update changelog
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 48s
Test Suite / lint-backend (push) Successful in 0s
- Updated application version to 0.8.15 in both backend and frontend files.
- Enhanced database migration logic for co-trainer backfill using a subquery and CASE statement, improving robustness.
- Updated changelog to reflect the new version and changes made.
2026-05-05 16:20:16 +02:00
Lars e69aca51f6 fix: update logging messages for database operations and version bump
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
- Changed logging output for PostgreSQL readiness, schema loading, and migration status to a consistent format using [OK], [FAIL], and [WARN].
- Updated application version to 0.8.14 and modified changelog to reflect recent changes, including a fix for co-trainer backfill logic in the database migration.
- Enhanced error handling messages for better clarity during migration processes.
2026-05-05 16:18:42 +02:00
Lars 0c044249d9 Phase 0a Mandantenfähigkeit
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 3m38s
Test Suite / lint-backend (push) Successful in 0s
2026-05-05 16:12:17 +02:00
Lars a34dc19f5d Merge pull request 'Trainingsplanung und Rahmenplanung' (#9) from develop into main
Test Suite / build-frontend (push) Successful in 7s
Deploy Production / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 58s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #9
2026-05-05 16:05:01 +02:00
Lars 0748990328 feat: update version and enhance training unit management features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Bumped application version to 0.8.11 and updated database schema version.
- Added new API features for training units, including filtering by club and assigned trainer.
- Enhanced the TrainingPlanningPage with options to filter training units by club and assigned trainer, improving user experience.
- Implemented lead trainer assignment functionality, allowing users to take lead on training units.
- Updated changelog with new version details and changes.
2026-05-05 15:40:29 +02:00
Lars e69de82028 feat: enhance TrainingPlanningPage with improved view selection
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Added a new view selection component allowing users to toggle between list and calendar views for training planning.
- Updated styling and accessibility features for the view buttons, enhancing user experience.
- Removed the old view selection implementation to streamline the interface and improve maintainability.
2026-05-05 15:18:54 +02:00
Lars 7e8421bfde feat: implement data loading and management for training planning
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Added functions to load training plan templates and active training groups, enhancing data retrieval for the TrainingPlanningPage.
- Implemented error handling and loading states to improve user experience during data fetching.
- Refactored loadUnits function to dynamically fetch training units based on selected group and date range, supporting better planning capabilities.
2026-05-05 15:16:20 +02:00
Lars 1923feb5bb feat: enhance TrainingPlanningPage with calendar view and date handling
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 47s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a calendar view option for training planning, allowing users to switch between list and calendar layouts.
- Added functions for managing calendar grid ranges and enumerating ISO days, improving date handling.
- Updated state management to include calendar month and view type, enhancing user experience.
- Refactored loadUnits function to adapt to the selected view, ensuring accurate data loading based on the chosen layout.
2026-05-05 15:13:00 +02:00
Lars d774d60a15 feat: add API endpoint for creating training units from framework slots
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function `createTrainingUnitFromFrameworkSlot` in the API utility, enhancing the ability to create training units directly from framework slots.
- This addition supports improved integration with the training planning features, streamlining the process for users.
2026-05-05 15:06:34 +02:00
Lars 6dcbc8c610 feat: enhance training framework programs and planning features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 41s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Added aggregation of training type names and target group names in the training framework programs API response for improved data presentation.
- Implemented origin framework slot tracking in the training planning module, allowing users to import training units from framework programs.
- Enhanced the TrainingFrameworkProgramsListPage to display aggregated training type and target group information, improving user experience.
- Introduced a modal for importing framework programs into training planning, streamlining the process of managing training units.
2026-05-05 15:03:54 +02:00
Lars 86192df508 refactor: streamline exercise selection process in training pages
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 43s
Test Suite / lint-backend (push) Successful in 0s
- Simplified the exercise selection logic in TrainingUnitSectionsEditor, TrainingFrameworkProgramEditPage, and TrainingPlanningPage by removing the multi-select option.
- Updated the ExercisePickerModal to always enable multi-select, enhancing user experience when selecting exercises.
- Refactored the handling of selected exercises to improve clarity and maintainability of the code.
2026-05-05 14:52:19 +02:00
Lars 4080088d42 feat: enhance TrainingUnitSectionsEditor with heading accessory support
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Added a new `headingAccessory` prop to TrainingUnitSectionsEditor for customizable header content.
- Updated the component to conditionally render the heading and accessory in a flexible toolbar layout.
- Refactored TrainingFrameworkProgramEditPage and TrainingPlanningPage to utilize the new heading accessory feature, improving user interaction and layout consistency.
2026-05-05 14:47:38 +02:00
Lars 2bfe67879f feat: enhance exercise selection and training unit management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m8s
Test Suite / lint-backend (push) Successful in 1s
- Updated ExercisePeekModal to support exercise variants, improving user experience when selecting exercises.
- Enhanced ExercisePickerModal with multi-select functionality, allowing users to select multiple exercises at once.
- Introduced drag-and-drop support for reordering training unit sections in TrainingUnitSectionsEditor, enhancing organization and usability.
- Improved TrainingFrameworkProgramEditPage and TrainingPlanningPage to manage exercise selection and section movement across slots more effectively.
- Added new CSS styles in app.css for better visual feedback during drag-and-drop actions and improved layout consistency.
2026-05-05 14:42:46 +02:00
Lars 354216cb4f feat: implement drag-and-drop functionality for training unit items
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 43s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced TrainingUnitSectionsEditor to support drag-and-drop reordering of items, improving user interaction and organization.
- Introduced new CSS styles in app.css for item rows, including visual feedback for drag-and-drop actions.
- Added text editing capabilities for notes and exercise descriptions, allowing for inline updates.
- Improved overall layout and responsiveness of the training unit sections editor.
2026-05-05 14:29:17 +02:00
Lars 69adf1fde0 feat: enhance training framework UI and responsiveness
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Updated app.css to improve layout and responsiveness for mobile and desktop views, including new styles for session slots and chips.
- Modified TrainingUnitSectionsEditor to support a wider exercise grid for better usability.
- Enhanced TrainingFrameworkProgramEditPage with improved slot management and mobile navigation features.
- Introduced dynamic slot chip labels for better user interaction and clarity.
2026-05-05 14:22:37 +02:00
Lars c4fbabd8f6 chore: update versioning and enhance training framework features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Incremented APP_VERSION to 0.8.10 and DB_SCHEMA_VERSION to 20260505037.
- Updated project status and domain model documentation to reflect recent changes.
- Enhanced training framework program handling with new slot-blueprint structure.
- Introduced API endpoint for creating training units from framework slots.
- Improved documentation for training planning and governance concepts.
2026-05-05 13:39:30 +02:00
Lars 7e21b44604 chore: update versioning and enhance training unit features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Incremented APP_VERSION to 0.8.10 and DB_SCHEMA_VERSION to 20260505037.
- Added changelog entry for version 0.8.10 detailing database and API changes.
- Refactored training framework program handling to support cloning training units from framework slots.
- Improved permission checks for training units based on framework slot associations.
- Introduced new API endpoint for creating training units from framework slots.
2026-05-05 13:31:26 +02:00
Lars b4495e39c1 chore: update versioning and enhance Training Framework features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 44s
Test Suite / lint-backend (push) Successful in 0s
- Incremented APP_VERSION to 0.8.9 and DB_SCHEMA_VERSION to 20260505036.
- Added changelog entry for version 0.8.9 detailing database and API changes.
- Updated TrainingFrameworkProgramEditPage to manage focus areas, style directions, training types, and target groups.
- Enhanced TrainingFrameworkProgramsListPage with context teasers for better user information.
- Improved CSS styles for framework catalog checkgrid and check components for better layout and usability.
2026-05-05 13:11:17 +02:00
Lars 8f32a6df29 feat: enhance TrainingFrameworkProgramEditPage with goal management and UI improvements
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new goal chip components for better visual representation and interaction.
- Added hover tooltips for goal chips to display additional information.
- Implemented state management for editing goals and goal menu visibility.
- Updated styles in app.css to support new goal chip design and improve layout consistency.
- Incremented version of TrainingFrameworkProgramEditPage to 1.4.0 to reflect the latest enhancements.
2026-05-05 12:52:51 +02:00
Lars 0971f35402 refactor: improve sidebar and layout responsiveness in app.css
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a CSS variable for the desktop sidebar width to enhance maintainability and responsiveness.
- Updated sidebar and app shell styles to utilize the new variable, ensuring consistent layout across different screen sizes.
- Adjusted margin and width properties to prevent overflow and improve overall user experience on various devices.
2026-05-05 12:45:00 +02:00
Lars 8c9c97bedb refactor: simplify page layout for improved responsiveness
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Removed constrained width classes from multiple pages to allow full-width layout, enhancing adaptability on larger screens.
- Updated app.css to eliminate unnecessary max-width properties, ensuring a more fluid design across various components.
- Adjusted styles in Navigation and other pages for consistent full-width presentation, improving user experience on diverse devices.
2026-05-05 12:41:59 +02:00
Lars 83ee300192 refactor: enhance layout and responsiveness across multiple pages
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 1s
- Updated app.css to improve responsive design, introducing new classes for consistent page widths and grid layouts.
- Refactored various page components to utilize the new layout classes, ensuring better adaptability on different screen sizes.
- Adjusted padding and margin properties for improved visual consistency and user experience across the application.
2026-05-05 12:39:15 +02:00
Lars b1af59b134 refactor: enhance responsive design and layout in app.css
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Improved mobile and web-app layout by adjusting overflow properties and widths to prevent horizontal scrolling.
- Updated .app-shell and .app-main styles for better adaptability on various screen sizes.
- Refined card dimensions in the framework slots to ensure consistent sizing and scrolling behavior across devices.
2026-05-05 12:33:09 +02:00
Lars 6c87989863 feat: update PWA support and enhance responsive design
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 32s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Added PWA meta tags for improved iOS web app compatibility in index.html.
- Updated app.css to refine responsive design, ensuring better layout handling on mobile devices.
- Adjusted padding and height properties to accommodate safe area insets for a more polished user experience.
2026-05-05 12:26:49 +02:00
Lars 44f224e5d1 feat: enhance TrainingFrameworkProgramEditPage with drag-and-drop functionality and layout improvements
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 39s
Test Suite / lint-backend (push) Successful in 0s
- Updated app.css to refine responsive design for mobile and desktop views, ensuring better usability.
- Implemented drag-and-drop features for exercises and slots in TrainingFrameworkProgramEditPage, enhancing user interaction.
- Adjusted tab management and layout visibility based on screen size, improving overall user experience.
- Incremented version of TrainingFrameworkProgramEditPage to 1.3.0 to reflect the latest enhancements.
2026-05-05 12:19:03 +02:00
Lars 88fc9d9ba5 feat: update layout and styles for TrainingFrameworkProgramEditPage
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 41s
Test Suite / lint-backend (push) Successful in 0s
- Adjusted responsive design breakpoints for mobile and desktop views in app.css.
- Introduced a new horizontal layout for slots in the framework editor, enhancing usability on wider screens.
- Updated versioning for TrainingFrameworkProgramEditPage to 1.2.0 to reflect recent changes.
- Improved tab visibility and layout management based on screen size in TrainingFrameworkProgramEditPage.jsx.
- Enhanced user guidance in TrainingFrameworkProgramsListPage with additional context on layout behavior.
2026-05-05 12:08:03 +02:00
Lars eade9af2fe feat: implement mobile and desktop layouts for framework editing
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Added responsive design for the framework editing page, including mobile tabs and a grid layout for goals and slots on desktop.
- Introduced state management for tab selection and layout detection based on screen size.
- Enhanced user interface with a tabbed navigation system for better organization of content.
- Updated styles in app.css to support new layout features and improve overall aesthetics.
2026-05-05 11:53:45 +02:00
Lars 17f0513821 fix: update versioning and improve routing in TrainingFrameworkProgramEditPage
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 51s
Test Suite / lint-backend (push) Successful in 0s
- Incremented version of TrainingFrameworkProgramEditPage to 1.0.1.
- Refactored variable names for clarity in TrainingFrameworkProgramEditPage.
- Enhanced routing logic to handle new program creation more effectively.
- Updated button text and messages in TrainingFrameworkProgramsListPage for better user guidance.
2026-05-05 11:11:52 +02:00
Lars 8328e7e0d3 feat: add training framework program management and update versioning
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 1s
- Introduced new pages for managing training framework programs, including listing and editing functionalities.
- Updated routing in App.jsx to accommodate new training framework program pages.
- Enhanced API with CRUD operations for training framework programs.
- Incremented application version to 0.5.1 and updated relevant page versions.
- Added informational link in TrainingPlanningPage to guide users to training framework programs.
2026-05-05 09:02:13 +02:00
Lars b054c642a3 chore: update training framework specifications and versioning
Test Suite / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 0s
- Incremented version to 0.8.8 and updated database schema version to 20260505035.
- Added new entity `training_framework_programs` to manage training frameworks, including goals and slots.
- Enhanced `training_plan_templates` with a visibility attribute and backfilled existing data.
- Updated API to support CRUD operations for training frameworks, ensuring proper authorization similar to existing planning libraries.
- Revised documentation in DOMAIN_MODEL.md, TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md, and TRAINING_FRAMEWORK_SPEC.md to reflect these changes.
2026-05-05 08:41:43 +02:00
Lars f5895b6637 chore: update documentation and enhance exercise progression graph details
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 41s
Test Suite / lint-backend (push) Successful in 0s
- Updated CLAUDE.md to reflect the addition of exercise_progression_graphs in the backend routers.
- Revised PROJECT_STATUS.md to document the current project status and recent milestones, including the implementation of the exercise progression graph feature.
- Incremented versioning in DOMAIN_MODEL.md and DATABASE_SCHEMA.md to align with the latest migration updates.
- Enhanced technical specifications in TRAINING_FRAMEWORK_SPEC.md to clarify the implementation details of the exercise progression graph and its integration with the training framework.
2026-05-05 08:30:48 +02:00
Lars ae6c089366 chore: update versioning and enhance exercise progression graph functionality
Test Suite / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 41s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.8.7 and updated database schema version to 20260430034.
- Enhanced exercise progression graph functionality by adding support for exercise variants as node endpoints and bulk creation of progression sequences.
- Updated changelog to reflect new features and improvements related to progression graphs and API enhancements.
2026-05-03 18:07:52 +02:00
Lars 1b7a0405e9 feat: add exercise progression graph functionality and update versioning
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 41s
Test Suite / lint-backend (push) Successful in 0s
- Integrated exercise progression graphs into the backend and frontend, allowing users to visualize relationships between exercises.
- Updated API endpoints for managing exercise progression graphs and edges, enhancing the exercise management capabilities.
- Added a new tab in the ExercisesListPage for displaying progression graphs and included a panel in the ExerciseFormPage for editing.
- Incremented application version to 0.8.6 and updated changelog to reflect new features and improvements.
2026-04-30 11:47:50 +02:00
Lars 9227b98431 Merge pull request 'feat: enhance MediaWiki integration and error handling in SMW client' (#8) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 39s
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 362eb4145f feat: enhance MediaWiki integration and error handling in SMW client
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 46s
Test Suite / lint-backend (push) Successful in 1s
- Added MediaWiki API configuration options to docker-compose.yml for production environment.
- Improved error handling in the SMW client by introducing a response parsing method to manage API errors more effectively.
- Updated methods in the SMW client to ensure robust handling of API responses, preventing potential crashes due to unexpected data structures.
- Enhanced the import functionality to handle last imported timestamps more gracefully.
2026-04-29 13:50:54 +02:00
Lars 390b0ecb73 Merge pull request 'chore: clean up docker-compose files and enhance SQL migration for skills' (#7) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 36s
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 07b1cd8209 chore: clean up docker-compose files and enhance SQL migration for skills
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 40s
Test Suite / lint-backend (push) Successful in 1s
- Removed version specification from docker-compose.dev-env.yml and docker-compose.yml for consistency.
- Added a unique constraint to the skills table in the SQL migration to prevent duplicate entries, ensuring data integrity during imports.
- Updated test cases in dev-smoke-test.spec.js to improve locator strategies and enhance viewport handling for mobile navigation.
2026-04-29 13:41:17 +02:00
Lars 7e7adfab54 Merge pull request 'bug fixes' (#6) from develop into main
Test Suite / build-frontend (push) Successful in 7s
Deploy Production / deploy (push) Successful in 35s
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 fe86d763ad refactor: enhance environment configuration and CI workflow for improved flexibility
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m29s
Test Suite / lint-backend (push) Successful in 0s
- Updated .env.example to provide clearer instructions and examples for production and development environments.
- Refactored docker-compose files to utilize environment variables for database and application settings, improving configurability.
- Enhanced .gitea/workflows/test.yml to streamline E2E testing setup, ensuring consistent handling of environment variables across different stages.
2026-04-29 13:33:28 +02:00
Lars f4a86f9726 refactor: update docker-compose and CI workflow for improved E2E testing
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 6s
Test Suite / lint-backend (push) Successful in 0s
- Removed fixed container names in docker-compose.dev-env.yml to prevent conflicts during redeploys.
- Enhanced playwright.config.js comments for clarity on base URL usage in different environments.
- Updated .gitea/workflows/test.yml to streamline E2E testing setup, including conditional logic for local and production environments, and improved health check handling after deployment.
2026-04-29 13:12:05 +02:00
Lars bce235b9f6 Merge pull request 'feat: enhance Playwright configuration and CI workflow for E2E testing' (#5) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 4s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #5
2026-04-29 12:37:28 +02:00
Lars 50b8ff12cd feat: enhance Playwright configuration and CI workflow for E2E testing
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 10s
Test Suite / lint-backend (push) Successful in 0s
- Updated playwright.config.js to allow dynamic base URL configuration via environment variables, improving flexibility for different environments.
- Modified .gitea/workflows/test.yml to include steps for starting a development stack, seeding test data, and stopping the stack after tests, enhancing the CI process for end-to-end testing.
- Refactored login test in dev-smoke-test.spec.js to use a dedicated function for submitting the login form, improving code clarity and maintainability.
2026-04-29 12:35:30 +02:00
Lars 5334836207 Merge pull request 'feat: enhance database migration handling and health check endpoint' (#4) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 37s
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 1f2c8ea0f1 feat: enhance database migration handling and health check endpoint
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Updated migration logic in main.py to allow skipping migrations during local development with SKIP_DB_MIGRATE environment variable.
- Improved error handling for migration failures, ensuring the application does not start if migrations are incomplete.
- Added a new health check endpoint (/api/health/ready) to verify database connection and essential tables, aiding in production debugging.
- Enhanced run_migrations.py to support ordered execution of migration files and improved transaction handling.
- Updated requirements.txt to include sqlparse for SQL statement parsing when psql is unavailable.
2026-04-29 12:29:39 +02:00
Lars 38d78abc3b Merge pull request 'bug fix' (#3) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 38s
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 159ac8fb71 feat: add utility function for verification link expiration check
Test Suite / build-frontend (push) Successful in 11s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 26s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new function to determine if a verification link has expired, improving error handling in the email verification process.
- Updated the email verification logic to utilize the new function, enhancing clarity and maintainability of the code.
2026-04-29 11:51:41 +02:00
Lars a748f4607d refactor: improve email verification handling in components
Test Suite / build-frontend (push) Successful in 15s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 2m3s
Test Suite / lint-backend (push) Successful in 0s
- Introduced a utility function to standardize email verification checks across EmailVerificationBanner and AccountSettingsPage.
- Updated conditional logic to enhance clarity and maintainability regarding email verification status.
- Ensured consistent treatment of various representations of email verification status in user profiles.
2026-04-29 11:48:04 +02:00
Lars 2646bc776a feat: implement email verification flow and enhance user experience
Test Suite / build-frontend (push) Failing after 1s
Deploy Development / deploy (push) Failing after 12s
Test Suite / playwright-tests (push) Has been skipped
Test Suite / lint-backend (push) Successful in 0s
- Added EmailVerificationBanner component to notify users about unverified email status and provide a resend verification option.
- Introduced VerifyPage for handling email verification via a token in the URL, including success and error handling.
- Updated LoginPage and AccountSettingsPage to allow users to resend verification emails directly from these pages.
- Enhanced API utility with new functions for verifying emails and resending verification requests.
- Updated routing to include the new verification page and improved link structure for verification links.
2026-04-29 11:37:54 +02:00
Lars c6569abe1a feat: enhance email configuration and registration logic
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Added SMTP_SSL and SMTP_STARTTLS options to .env.example and docker-compose.yml for improved email sending configuration.
- Updated password reset email logic to utilize a new send_email helper function with SSL and STARTTLS support.
- Implemented role assignment for the first registered user or based on ADMIN_BOOTSTRAP_EMAILS during registration, enhancing user management capabilities.
2026-04-29 11:28:07 +02:00
Lars a143532486 Merge pull request 'Version 0.1' (#2) from develop into main
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m53s
Test Suite / lint-backend (push) Successful in 0s
Reviewed-on: #2
2026-04-29 11:20:41 +02:00
Lars fae673670a feat: update authentication and profile management features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Enhanced login response to include additional user information such as email, tier, and role.
- Updated profile update logic to restrict access based on user roles and ensure only authorized users can modify profiles.
- Replaced ProfilePage with AccountSettingsPage in routing and updated related components to reflect this change.
- Added new API functions for updating profiles and changing passwords to improve user account management.
2026-04-29 11:19:05 +02:00
Lars d9d2d9e506 fix: correct profile creation logic in registration process
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m57s
Test Suite / lint-backend (push) Successful in 0s
- Removed the profile ID from the INSERT statement to align with the database schema, which uses SERIAL for IDs.
- Updated comments for clarity regarding the profile creation process and verification status.
2026-04-29 10:46:37 +02:00
Lars e6a8931da8 feat: update environment configuration and enhance development setup
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 39s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Added optional DEV_APP_URL and DEV_ALLOWED_ORIGINS to docker-compose.dev-env.yml for improved local development flexibility.
- Updated .env.example to reflect new environment variables for development.
- Modified backend main.py to support rate limiting on authentication routes and improved CORS handling.
- Enhanced deploy-dev.yml to include health checks for the frontend service, ensuring better monitoring during development.
2026-04-29 09:57:36 +02:00
Lars d67026e25a feat: enhance Nginx configuration and API error handling
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Updated Nginx configuration to improve service dependency resolution and proxying for API and media requests.
- Added a resolver directive to mitigate sporadic 502 errors related to backend container IP changes.
- Enhanced error handling in the API utility to provide clearer feedback for various HTTP errors, including specific guidance for 502 Bad Gateway responses.
2026-04-29 09:18:22 +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
Test Suite / build-frontend (push) Successful in 6s
Deploy Production / deploy (push) Successful in 37s
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
Lars 60132e97e8 feat: update docker-compose and Nginx configuration for improved service dependencies and API routing
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 44s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Added 'depends_on' for the frontend service to ensure it starts after the backend service.
- Updated Nginx configuration to proxy API and media requests to the backend, enhancing client access under the same host URL.
- Included health check endpoint for backend service in Nginx configuration to monitor service status.
2026-04-29 08:51:47 +02:00
Lars 5215a2adc5 feat: update TrainingCoachPage with additional useEffect hooks for state management
Test Suite / build-frontend (push) Successful in 44s
Deploy Development / deploy (push) Successful in 34s
Deploy Production / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 1s
- Added a new useEffect to handle updates for deltas and idNum, improving state synchronization.
- Introduced another useEffect to manage session storage for coach debrief phase, enhancing user experience during training sessions.
- Implemented a timer functionality with setInterval to track pulse updates, ensuring real-time feedback during training.
2026-04-29 08:16:33 +02:00
Lars 0dfc08459e feat: enhance training unit update functionality and improve UI controls
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 2m5s
Test Suite / lint-backend (push) Successful in 0s
- Added logic to retrieve existing trainer notes if not provided during the update of training units.
- Updated the TrainingCoachPage to include new controls for managing training sessions, including timer functionalities and navigation enhancements.
- Improved user experience with clearer button labels and conditional rendering based on the training session state.
2026-04-29 08:09:11 +02:00
Lars 6fd316e985 feat: enhance TrainingCoachPage with exercise details and navigation
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Replaced ExercisePeekModal with ExerciseFullContent for improved exercise visibility.
- Added CoachStepNavBar component for better navigation between training steps.
- Implemented loading and error handling for fetching exercise details based on the current step.
- Updated UI elements for a more cohesive layout and improved user experience.
2026-04-29 07:58:28 +02:00
Lars af3476b833 fix: improve step management in TrainingCoachPage
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Refactored step clamping logic to ensure it correctly handles edge cases when the timeline is empty or when the unit changes.
- Updated useEffect to reset the step to 0 when the timeline is empty, enhancing user experience during training sessions.
2026-04-29 06:54:41 +02:00
Lars 3673053fe2 feat: add TrainingCoachPage and enhance training planning features
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Introduced TrainingCoachPage for coaching-related training sessions.
- Updated app routing to include a new route for the TrainingCoachPage.
- Enhanced TrainingPlanningPage with a link to navigate to the new coaching page.
- Incremented version numbers for TrainingPlanningPage, TrainingUnitRunPage, and added version for TrainingCoachPage.
- Integrated ExercisePeekModal for improved exercise selection and visibility in both TrainingPlanningPage and TrainingUnitRunPage.
2026-04-29 06:49:16 +02:00
Lars 8debdae397 feat: add TrainingUnitRunPage and enhance training planning features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m57s
Test Suite / lint-backend (push) Successful in 0s
- Introduced TrainingUnitRunPage for displaying and printing training plans.
- Updated app routing to include a new route for the TrainingUnitRunPage.
- Enhanced the TrainingPlanningPage with a link to navigate to the new training run page.
- Updated CSS styles for print layout and improved visibility of completed training items.
2026-04-29 06:37:52 +02:00
Lars 23d4281058 feat: refine exercise focus area retrieval in training planning
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m56s
Test Suite / lint-backend (push) Successful in 0s
- Updated the SQL query in the training planning module to fetch the primary exercise focus area more efficiently.
- Enhanced error handling in the API utility to provide clearer feedback on potential issues, including CORS and URL errors, improving debugging for developers.
2026-04-29 06:33:23 +02:00
Lars 131b7d591d feat: enhance training planning page with exercise variant support
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 2m3s
Test Suite / lint-backend (push) Successful in 0s
- Introduced ExercisePickerModal for selecting exercises and their variants.
- Updated state management to handle exercise titles and variants in training units.
- Implemented enrichSectionsWithVariants function to fetch and integrate exercise details from the server.
- Improved loading logic for training units to include exercise variant data, enhancing user experience in planning sessions.
2026-04-29 06:15:26 +02:00
Lars 69b26fc928 feat: enhance role permissions and UI for clubs and training planning
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Updated role permissions to allow trainers and users to create clubs and training groups.
- Modified database insertion logic to reflect the correct role for trainers during registration.
- Enhanced frontend components to display appropriate messages and buttons based on user roles.
- Improved user guidance in the Clubs and Training Planning pages, emphasizing the need for clubs and groups before planning training sessions.
2026-04-28 19:46:09 +02:00
Lars 1f2a4595cd feat: update version to 0.7.9 in changelog
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m56s
Test Suite / lint-backend (push) Successful in 0s
- Added new version entry for 0.7.9 in the changelog, documenting the release date and changes related to exercise variants API enhancements.
2026-04-28 16:34:27 +02:00
Lars d7e1a82a37 feat: update version to 0.8.0 and enhance training planning features
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.8.0 and updated database schema version to 20260428031.
- Introduced support for training plan templates, allowing users to create and manage reusable training structures.
- Enhanced the Training Planning UI to include sections and exercises, improving the organization of training units.
- Updated API endpoints for training plan templates, enabling CRUD operations for better integration with the frontend.
- Improved validation and permission checks for creating training units, ensuring proper access control.
2026-04-28 16:31:45 +02:00
Lars 7134fd1a25 feat: update version to 0.7.9 and enhance project documentation
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.9 and updated database schema version to 20260427030.
- Revised project status documentation to reflect recent milestones and changes, including detailed logs of implemented features and next steps.
- Enhanced API specifications for exercises, including support for exercise variants and improved query parameters.
- Updated frontend routing to streamline exercise variant management within the ExerciseFormPage.
- Implemented role-based media upload limits and refined search/filter specifications for better user experience.
2026-04-28 16:18:25 +02:00
Lars d5fbc2cd5c refactor: update loading state management and enhance search functionality in ExercisesListPage
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Replaced loading state with listFetching for clearer intent in managing exercise list fetching.
- Introduced search title suggestions for improved user experience during exercise searches.
- Updated UI elements to reflect changes in loading states and added datalist for search inputs, enhancing usability.
- Adjusted text for loading indicators to provide a more localized experience.
2026-04-28 15:24:05 +02:00
Lars 756263bad4 feat: implement dynamic upload limits for exercise media
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 1s
- Introduced role-based upload limits for exercise media, allowing users to upload up to 1 MB while admins and superadmins can upload up to 1024 MB.
- Updated the media upload logic to enforce these limits, enhancing the flexibility and control over media management in the application.
2026-04-28 13:56:26 +02:00
Lars 91b3fec5cc feat: enhance RichTextEditor and exercise variant management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Added support for saving and restoring text selection in the RichTextEditor, improving user experience during formatting.
- Updated CSS styles for the RichTextEditor to enhance list formatting and overall appearance.
- Introduced new ExerciseVariantFields component to streamline the editing of exercise variants, including fields for variant name, description, execution changes, and more.
- Enhanced ExerciseFormPage to manage exercise variants more effectively, including improved state handling and UI updates for variant selection.
2026-04-28 13:09:42 +02:00
Lars 1ee1a2f2d9 feat: update version to 0.7.9 and enhance exercise variant management
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 2m0s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.9 and updated changelog to reflect new features.
- Added support for creating, updating, and deleting exercise variants via new API endpoints.
- Implemented functionality for reordering exercise variants, improving user experience in managing exercise options.
- Enhanced frontend components to display and manage exercise variants, including detailed information and editing capabilities.
2026-04-28 10:59:09 +02:00
Lars cf9f95377c feat: update version to 0.7.8 and enhance exercise variant handling
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m57s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.8 and updated database schema version to 20260427030.
- Added support for including exercise variants in the exercise listing API, improving training planning capabilities.
- Enhanced training unit creation and update logic to validate exercise variant IDs, ensuring proper associations.
- Updated frontend components to support exercise variant selection, improving user experience in training planning.
2026-04-28 09:30:33 +02:00
Lars 2c831d6cea refactor: enhance filtering logic and UI for ExercisesListPage
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 2m1s
Test Suite / lint-backend (push) Successful in 0s
- Removed the countActiveFilterGroups function and replaced it with a more comprehensive filterChips implementation to manage active filters.
- Improved the rendering of active filters with dynamic chips that allow users to remove individual filters.
- Updated the UI to reflect the new filtering logic, enhancing user experience and interaction with the filter options.
- Adjusted the layout and styling for better visibility and usability of the filter components.
2026-04-28 08:58:17 +02:00
Lars 0d4ad9a2c8 feat: implement exercise filter modal and enhance filtering logic
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 2m3s
Test Suite / lint-backend (push) Successful in 0s
- Added a new exercise filter modal with improved layout and styling for better user experience.
- Introduced initial filter state and logic to count active filter groups, enhancing the filtering capabilities on the ExercisesListPage.
- Updated CSS styles to support the new modal and improve overall UI consistency.
- Implemented keyboard accessibility for closing the filter modal, enhancing usability.
2026-04-28 08:21:55 +02:00
Lars fd2009294b feat: enhance exercise filtering and UI components
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 32s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Introduced multi-select functionality for filtering exercises by focus areas, style directions, training types, target groups, and skills, allowing users to select multiple options.
- Updated the ExercisesListPage to utilize the new multi-select component, improving the user experience for filtering exercises.
- Enhanced backend filtering logic to support new array-based query parameters, ensuring efficient handling of multiple filter criteria.
- Adjusted CSS styles for better layout and usability of the exercise filters.
2026-04-28 08:02:08 +02:00
Lars 025b161d2f feat: enhance exercise mapping and filtering capabilities
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m56s
Test Suite / lint-backend (push) Successful in 0s
- Added support for style direction mappings in the backend, allowing for improved categorization of exercises.
- Introduced a new function to normalize property synonyms, enhancing the mapping of exercise properties.
- Updated the exercise catalog assignment logic to include style directions, ensuring proper database entries.
- Enhanced the ExercisesListPage with new filtering options for style directions, improving user experience and search capabilities.
2026-04-28 07:25:33 +02:00
Lars 76098f5244 feat: update capability levels and enhance exercise filtering
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 1s
- Updated capability level mappings in the backend to reflect new terminology (e.g., "einsteiger" to "basis" and "experte" to "optimierung").
- Refactored the exercise management logic to normalize skill levels using canonical slugs, improving consistency across the application.
- Enhanced the ExercisesListPage with additional filtering options for style direction, training type, and target group, along with AI search capabilities.
- Incremented application version to 0.7.7 and updated changelog to document these changes.
2026-04-27 18:25:23 +02:00
Lars c6d20e4dec feat: add listTrainingStyles to API utility functions
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 1s
- Introduced listTrainingStyles function to the API utility, enhancing the capabilities for managing training styles.
- This addition supports improved data retrieval for training-related features in the application.
2026-04-27 15:03:48 +02:00
Lars 0ad096e483 feat: enhance SQL query handling and UI components for exercise management
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
- Introduced a new utility function to streamline SQL query construction for active status filtering, improving code reusability across multiple endpoints.
- Updated existing query logic in the catalogs and skills routers to utilize the new utility function, ensuring consistent handling of active status.
- Refactored the ExerciseFormPage to remove deprecated age group handling, simplifying the form structure.
- Enhanced the RichTextEditor component with improved link handling and formatting options for better user experience.
- Updated API utility functions to support new AI features for exercise suggestions and regeneration, expanding the capabilities of the exercise management system.
2026-04-27 15:01:47 +02:00
Lars d8f439a3e5 feat: enhance exercise management with training types and rich text support
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m58s
Test Suite / lint-backend (push) Successful in 1s
- Added support for training types in exercise creation and updates, allowing for better categorization of exercises.
- Implemented a rich text editor for exercise descriptions, improving content formatting capabilities.
- Updated the ExerciseDetailPage to display training types and enhanced the layout for better user experience.
- Refactored ExerciseFormPage to accommodate new multi-association fields for training styles, types, and target groups.
- Improved API payload handling to include training types and ensure proper data structure for exercise management.
- Enhanced the ExercisesListPage with improved loading and filtering functionalities for better performance.
2026-04-27 14:48:46 +02:00
Lars cb11e39201 feat: enhance exercise management and media handling
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Introduced new API endpoints for managing exercise media, including upload, update, delete, and reorder functionalities.
- Updated the exercise creation and update logic to ensure goal and execution fields are validated and normalized.
- Refactored frontend components to support the new exercise media features, including a dedicated import section for complete stack files.
- Removed the deprecated ExercisesPage component and replaced it with a more modular structure for exercise management.
- Incremented database schema version to 20260427028 and updated changelog to reflect these changes.
2026-04-27 14:27:25 +02:00
Lars 2452b5e2e8 feat: update version to 0.7.6 and add matrix stack bundle functionality
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.6 and updated maturity models version to 1.4.0.
- Introduced new API endpoints for exporting and importing matrix stack bundles, enhancing the capabilities for managing maturity models and context bindings.
- Updated frontend components to support the new matrix stack export and import features, including UI elements for stack management.
- Documented changes in the changelog for version 0.7.6, detailing the new matrix stack functionality and its usage.
2026-04-27 13:13:36 +02:00
Lars 863535aa26 feat: update version to 0.7.5 and enhance maturity model binding logic
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.5 and updated maturity model version to 1.3.1.
- Improved binding logic to ensure that only relevant entries are considered based on the presence of context bindings.
- Updated documentation to clarify the behavior of binding resolution and its impact on legacy model resolution.
- Documented changes in the changelog for version 0.7.5, detailing the new binding resolution rules.
2026-04-27 13:05:18 +02:00
Lars f2c007cc68 feat: update version to 0.7.4 and enhance maturity model functionality
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m59s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.4 and updated database schema version to 20260427027.
- Enhanced maturity model context bindings to support new filtering options for training styles.
- Introduced new API endpoints for importing and exporting maturity model bundles.
- Updated frontend components to include a matrix view and improved admin UI for managing maturity models.
- Documented changes in the changelog for version 0.7.4, detailing new features and improvements.
2026-04-27 12:48:22 +02:00
Lars 3397b2094d feat: update version to 0.7.3 and enhance maturity model context bindings
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.3 and updated database schema version to 20260427026.
- Enhanced maturity model context bindings with new hierarchical resolution logic for focus areas, style directions, and training types.
- Added new API endpoints for managing maturity model context bindings.
- Updated frontend components to support the new context binding functionality and improved admin UI for better user experience.
- Documented changes in the changelog for version 0.7.3, including new features and improvements.
2026-04-27 12:35:48 +02:00
Lars 469ec93074 feat: enhance admin UI for maturity models and skills catalog
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Added new styles and layout for the maturity models admin panel, improving user experience.
- Removed unused multi-selection component for focus areas, style directions, and target groups.
- Updated skills catalog functionality to support editing and sorting of main categories and skills.
- Introduced a modal for editing main categories, categories, and skills with improved accessibility.
- Enhanced responsiveness and visual consistency across admin components.
2026-04-27 12:19:22 +02:00
Lars e8b7e62832 feat: add skill main categories and enhance skills catalog functionality
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 48s
Test Suite / playwright-tests (push) Failing after 1m57s
Test Suite / lint-backend (push) Successful in 0s
- Introduced endpoints for managing skill main categories, including CRUD operations.
- Enhanced skills catalog endpoint to support hierarchical sorting by main category and category.
- Updated frontend API utility functions to include new skill main category operations.
- Improved admin interface for skills management with new layout and styles.
- Documented changes in the changelog for better tracking of new features and updates.
2026-04-27 11:53:25 +02:00
Lars f1ee1eec7e feat: update maturity models and version to 0.7.2
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Incremented application version to 0.7.2 and updated database schema version to 20260427025.
- Enhanced maturity models functionality to support M:N relationships for focus areas, style directions, and target groups.
- Updated frontend to allow multi-selection for focus areas, style directions, and target groups.
- Documented changes in the changelog for version 0.7.2, including new migration details and UI improvements.
2026-04-27 11:42:03 +02:00
Lars 5277f4f4cf feat: add maturity models functionality and update version
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 1s
- Introduced new maturity models feature with CRUD operations in the API.
- Added routes and frontend components for managing maturity models.
- Updated version to 0.7.1 with corresponding build date and schema version.
- Enhanced admin navigation to include maturity models section.
- Documented changes in the changelog for version 0.7.1.
2026-04-27 11:32:30 +02:00
Lars 5626be792f docs: Dokumentation aktualisiert für Skills-Import Complete
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Updates:
- DATABASE_SCHEMA.md v0.4.0 (Migration 022+023, Skills-Hierarchie)
- DOMAIN_MODEL.md v0.4.0 (Fähigkeiten-Domäne, Fokusbereich-Zuordnung)
- MEDIAWIKI_IMPORT_SPEC.md v1.1 (Skills via Migration statt API)
- PROJECT_STATUS.md (NEU - Projekt-Übersicht & Deployment-Status)

Änderungen:
- 69 Skills mit Kategorisierung dokumentiert
- Haupt-/Unterkategorien (KARATE/ALLGEMEINE)
- Fokusbereich-Zuordnung (karate/universal)
- Level-Definitionen-Schema
- Migration 021 als DEPRECATED markiert
- Deployment-Status aktualisiert
- Lessons Learned dokumentiert
2026-04-27 11:18:49 +02:00
Lars e8eba57b3a feat: Migration 022+023 - Vollständiger Skills-Import
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Migration 022: Schema-Erweiterung
  - skill_main_categories (KARATE / ALLGEMEINE)
  - skills.main_category_id + focus_areas JSONB
  - skill_level_definitions Tabelle
  - Indizes für Performance

- Migration 023: Produktionsreifer Skills-Import
  - 69 Skills mit vollständiger Kategorisierung
  - 2 Haupt-Kategorien, 9 Unterkategorien
  - KARATE: 32 Skills (karate focus)
  - ALLGEMEINE: 37 Skills (universal focus)
  - Duplikat-Bereinigung (Timing, Antizipation, etc.)

- Scripts:
  - parse_matrix.py: Extrahiert Skills aus Fähigkeitsmatrix
  - generate_migration_023_direct.py: Generiert Migration direkt aus Matrix

Source: https://karatetrainer.net/index.php?title=Fähigkeitsmatrix

Verified auf Dev: 69 Skills importiert, korrekte Kategorisierung
2026-04-27 10:58:33 +02:00
Lars 97c1bb0c8b feat: import 18 base skills from Fähigkeitsmatrix
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 2m10s
Test Suite / lint-backend (push) Successful in 1s
Imported from https://karatetrainer.net/index.php?title=Fähigkeitsmatrix
- 9 skill categories (Kihon, Kumite, Kata, etc.)
- 18 core skills with descriptions

This enables skill-level assignments for imported exercises.
2026-04-27 10:26:10 +02:00
Lars 1ddbd76e36 fix: add UNIQUE constraint to exercise_skills table
Test Suite / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Failing after 28s
Test Suite / playwright-tests (push) Failing after 2m2s
Test Suite / lint-backend (push) Successful in 0s
Fixes: 'no unique or exclusion constraint matching the ON CONFLICT specification'
ON CONFLICT (exercise_id, skill_id) requires UNIQUE constraint.

This was causing 91 import failures.
2026-04-27 10:00:02 +02:00
Lars a02df32ce2 fix: set created_by automatically on MediaWiki import
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m58s
Test Suite / lint-backend (push) Successful in 0s
- Added imported_by parameter to _run_import and _upsert_exercise
- Exercises now automatically get created_by set to importing user
- Fixes visibility issue where imported exercises were invisible

Related: Wiki import - exercise visibility fix
2026-04-27 09:52:18 +02:00
Lars e6ce7e241c fix: convert skill target_level to INTEGER instead of string
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 54s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- build_skill_assignments() now returns INTEGER (1-5) for target_level
- Previously returned string names ('einsteiger', 'grundlagen', etc.)
- Caused 91/95 import failures with 'invalid input syntax for type integer'
- Remaining 4 failures are wiki pages missing both goal AND execution (invalid data)

Issue: Wiki import - dict-cursor fixes phase 2
2026-04-27 09:30:29 +02:00
Lars 97a7fe7cba fix: reimport dict-cursor bug + add admin cleanup endpoint
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 54s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
Problem 1: Reimport fails completely (all exercises fail)
Root cause: Line 465 existing[0] instead of existing['id']
Fix: Changed to existing['id'] for dict-cursor compatibility

Problem 2: 221 exercises skipped, only 2 in database
Root cause: Orphaned wiki_import_references from failed imports
Fix: New admin endpoint to manually cleanup orphaned references

New endpoints:
- DELETE /api/import/mediawiki/admin/cleanup-orphaned-references
  Deletes all references where local_id doesn't exist in target table
  Returns count of deleted references per type

- GET /api/import/mediawiki/admin/stats
  Shows references vs. actual count + orphaned count
  Helps diagnose import state issues

Usage:
1. Call cleanup endpoint to remove orphaned references
2. Run normal import (reimport=false)
3. Should import all previously failed exercises
2026-04-27 08:52:05 +02:00
Lars 3a4160fd1c fix: detect and cleanup orphaned import references
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Problem: 221 exercises skipped, but only 2 actually in database
Root cause: Failed imports created wiki_import_references entries,
but exercises were never saved (due to earlier bugs)

Duplicate check only verified references existed, not actual data.
Result: All subsequent imports skipped 'already imported' items.

Solution:
- Enhanced duplicate check to verify BOTH reference AND actual entity
- If reference exists but entity is missing → delete orphaned reference
- Item will be re-imported on same run (no manual cleanup needed)

Check logic:
1. Find reference in wiki_import_references
2. Check if exercises/skills/methods table has matching local_id
3. If both exist → skip (true duplicate)
4. If reference exists but entity missing → delete reference + re-import

This auto-heals broken state from previous failed imports.
2026-04-27 08:45:27 +02:00
Lars 1a0708f152 fix: correct remaining dict cursor access (row[0] → row['id'])
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m57s
Test Suite / lint-backend (push) Successful in 0s
Error: 100 exercises failed with error '0' (TypeError suppressed)
Root cause: More row[0] dict access in catalog assignment functions

Previous fix only covered fetchone()[0] in RETURNING clauses.
Missed 6 more locations in SELECT queries where row is dict-like.

Fixed locations:
- Line 511: focus_area_id in exercise_focus_areas INSERT
- Line 524: style_direction_id in exercise_training_styles INSERT
- Line 535: target_group_id in exercise_target_groups INSERT
- Line 546: skill_id in exercise_skills INSERT
- Line 568: skill_id in exercise_skills INSERT (with levels)
- Line 589: category_id assignment in _upsert_skill

All changed from row[0] to row['id'] for RealDictCursor compatibility.

This should fix the remaining 100 import failures.
2026-04-27 08:24:35 +02:00
Lars bcc7d61d07 fix: make exercise goal and execution optional (at least one required)
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Error: 224/225 exercises failed with NOT NULL constraint violations
Root cause: exercises table requires BOTH goal AND execution (NOT NULL)
Reality: Many wiki exercises have only ONE of these fields

Migration 019:
- ALTER COLUMN goal DROP NOT NULL
- ALTER COLUMN execution DROP NOT NULL
- ADD CHECK constraint: (goal IS NOT NULL OR execution IS NOT NULL)

This allows:
✓ Exercises with only goal
✓ Exercises with only execution
✓ Exercises with both
✗ Exercises with neither (CHECK constraint fails)

Import validation already correct (line 312):
required_ok = bool(mapped.get('goal') or mapped.get('execution'))

DB schema was blocking valid exercises.
2026-04-24 20:42:21 +02:00
Lars a37400bb22 fix: correct dict cursor access in MediaWiki import
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 2m2s
Test Suite / lint-backend (push) Successful in 0s
Error: 500 Internal Server Error on execute import
Root cause: Using fetchone()[0] with RealDictCursor (dict-like rows)

PostgreSQL RealDictCursor returns dict-like objects, not tuples.
Accessing [0] on a dict throws TypeError.

Fix: Changed all fetchone()[0] to fetchone()['id']
Locations:
- Line 163: log_id after INSERT INTO wiki_import_log
- Line 485: ex_id after INSERT INTO exercises
- Line 599: skill_id after INSERT INTO skills
- Line 616: method_id after INSERT INTO training_methods

This matches the pattern used in other routers (exercises.py, etc.)
2026-04-24 20:37:31 +02:00
Lars 8b51864b53 feat: add recursive subcategory search for MediaWiki import
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 2m2s
Test Suite / lint-backend (push) Successful in 0s
Issue: Only 2 exercises found instead of 200+
Root cause: Exercises likely organized in subcategories

Solution:
- Added recursive parameter to get_category_members()
- New _get_subcategories() helper method
- Recursively traverses all subcategories
- Logs subcategory counts for debugging

Behavior:
- get_category_members('Übungen') now finds:
  1. All pages directly in 'Kategorie:Übungen'
  2. All subcategories (e.g. 'Kihon', 'Kata', 'Kumite')
  3. All pages in those subcategories (recursive)

Example structure:
Kategorie:Übungen
├─ Seite: Übung A (2 direkte)
├─ Kategorie:Kihon
│  ├─ Seite: Mae-Geri
│  └─ Seite: Gyaku-Zuki
└─ Kategorie:Kata
   └─ Seite: Heian Shodan
2026-04-24 17:53:11 +02:00
Lars 9d041aaf4f fix: add MediaWiki credentials to docker-compose
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 1s
Error: MediaWiki Login fehlgeschlagen: The supplied credentials could not be authenticated
Root cause: MEDIAWIKI_USER and MEDIAWIKI_PASSWORD were empty in container

Fix:
- Set MEDIAWIKI_USER: Jinkendo
- Set MEDIAWIKI_PASSWORD: Jinkendo6970
- karatetrainer.net requires authentication for API access

Note: Credentials are for read-only access to public training wiki
Local .env file also updated (not committed, in .gitignore)
2026-04-24 17:42:28 +02:00
Lars f54d8b2e03 fix: add MediaWiki environment variables to docker-compose
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Error: 500 Internal Server Error on MediaWiki import
Root cause: MEDIAWIKI_API_URL not configured in container

Fix:
- Added MEDIAWIKI_API_URL: https://karatetrainer.net/api.php
- Added MEDIAWIKI_USER, MEDIAWIKI_PASSWORD (optional, uses .env)
- Added category name overrides (4 categories)

Public wiki access (read-only) does not require authentication.
User/password only needed for write operations.

Note: .env file created locally but not committed (in .gitignore)
Users should copy .env.example and set their credentials if needed.
2026-04-24 17:18:47 +02:00
Lars c738f1234b fix: MediaWiki import - increase limit to 500 and add validation
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Error: 422 Unprocessable Entity when limit > 100
Root cause: Backend enforced max=100, frontend allowed any value

Backend fix:
- Increased preview limit from 100 to 500 (consistent with execute)
- import_wiki.py line 64: le=100 → le=500

Frontend fix:
- Added Math.min/max validation to both limit inputs
- Preview limit: max 500 with auto-clamp
- Execute limit: max 500 with auto-clamp
- Updated placeholder: 'Kein Limit (max 500)'

Prevents 422 errors from invalid limit values
2026-04-24 17:15:17 +02:00
Lars 89055ddbc4 feat: Admin page navigation with MediaWiki Import link
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- New AdminPageNav component with horizontal navigation
- Links to Hierarchie / Kataloge / Wiki-Import
- Integrated in all 3 admin pages
- Uses lucide-react icons (TreePine, FolderTree, Download)
- Active state tracking via useLocation
- Mobile-friendly with flexbox layout

Navigation flow:
/admin/hierarchy → /admin/catalogs → /admin/mediawiki-import
2026-04-24 17:03:13 +02:00
Lars df569bbf6e fix: auth register - correct column name created_at
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 38s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Error: column 'created' of relation 'profiles' does not exist
Fix: Changed 'created' to 'created_at' in INSERT statement
Line: backend/routers/auth.py:247
2026-04-24 16:07:13 +02:00
Lars 46d000d6b3 feat: SMW-Importer Frontend (Phase 2 complete)
Test Suite / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Test Suite / playwright-tests (push) Blocked by required conditions
Test Suite / lint-backend (push) Waiting to run
Phase 2A: API Functions
- 5 MediaWiki import functions in api.js
- previewMediaWikiImport, executeMediaWikiImport
- getMediaWikiImportStatus, listMediaWikiImportLogs
- deleteMediaWikiImportReference

Phase 2B: UI Component
- MediaWikiImportPage.jsx (3-tab interface)
- Preview Tab: Category selection, preview with accordions
- Execute Tab: Import form with status polling
- History Tab: Import log list with refresh

Phase 2C: Routing
- Added /admin/mediawiki-import route in App.jsx
- Import and ProtectedRoute wrapper

Issue: SMW-Importer Frontend (Option C from handover)
Related: backend/routers/csv_import.py (MediaWiki endpoints)
2026-04-24 16:06:49 +02:00
Lars a67cc5f812 fix: exercises.py - use direct VARCHAR for age_groups (no catalog table in Shinkan)
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 2m0s
Test Suite / lint-backend (push) Successful in 1s
2026-04-24 15:27:11 +02:00
Lars a6ea5b95eb fix: exercises.py - correct table name exercise_style_directions (all 3 occurrences)
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 1s
2026-04-24 15:25:17 +02:00
Lars b617b5a2d8 fix: exercises.py - handle dict rows in fetchone() for INSERT RETURNING
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
2026-04-24 15:23:00 +02:00
Lars e80c8e01e1 fix: add listTrainingStyles alias for backward-compatibility (references listStyleDirections)
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Has been cancelled
Test Suite / lint-backend (push) Successful in 0s
2026-04-24 15:20:39 +02:00
Lars 711bdc99cb fix: Migration 014 - correct table name exercise_style_directions (not exercise_training_styles)
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 1s
2026-04-24 15:10:26 +02:00
Lars 01ed5509f8 feat: Exercises v2.0 + Migrations 014/016/017 (Clean-Room Rebuild)
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
BREAKING CHANGES:
- exercises.py komplett neu gebaut (kein Legacy-Code)
- Legacy-Felder entfernt: age_groups, focus_area, secondary_areas, training_character
- Nur M:N Relations, keine JSONB-Kataloge

Migrations:
- Migration 014: Variant Progression + Search Vector + Legacy DROP
  - exercise_variants: progression_level, sequence_order, prerequisite_variant_id
  - exercises: search_vector (tsvector für Volltext-Suche)
  - DROP age_groups, focus_area, secondary_areas, training_character
  - Helper: update_timestamp() Funktion für Triggers
- Migration 016: Saved Exercise Searches
  - saved_exercise_searches (profile_id, name, filters JSONB)
- Migration 017: Exercise Blocks + Template Blocks
  - exercise_blocks (name, description, goal, is_template)
  - exercise_block_items (exercise_id, variant_id, sequence_order, is_placeholder, placeholder_criteria)

Backend (exercises.py v2.0):
- GET /exercises: Volltext-Suche via tsvector, M:N Joins
- GET /exercises/{id}: enrich_exercise_detail() mit allen M:N Relations
- POST /exercises: M:N Relations (focus_areas_multi, training_styles_multi, target_groups_multi, age_groups, skills)
- PUT /exercises: Partial Update + M:N Relations
- DELETE /exercises: Cascade-Check für exercise_block_items

Architecture:
- Issue #53 konform: Import = Feld-Zuordnung, keine fachliche Interpretation
- Helper: enrich_exercise_detail() für vollständige Objekte
- Helper: assign_exercise_relations() für M:N Management (DELETE+INSERT Pattern)

Docs:
- SMW_IMPORTER_GAP_ANALYSIS.md: Vollständige Gap-Analyse + Umsetzungsplan

Version: 0.7.0
Module: exercises 2.0.0
Schema: 20260424002
2026-04-24 15:04:27 +02:00
Lars 6801c60604 feat: Add MediaWiki import functionality with tracking and mapping
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Implemented a new SQL migration for wiki import tracking tables.
- Created an import router for handling MediaWiki imports of exercises, skills, and methods.
- Developed a Semantic MediaWiki API client for direct API interactions.
- Added a mapper to convert SMW properties to local database fields.
- Introduced background tasks for asynchronous import processing.
- Implemented logging and error handling for import operations.
- Added endpoints for previewing imports, checking import status, and managing import references.
2026-04-24 14:41:52 +02:00
Lars 0e0b709768 refactor: split AdminHierarchyPage into modular components
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 2m0s
Test Suite / lint-backend (push) Successful in 0s
Split 1200+ line file into clean modular architecture:
- FocusAreaNode.jsx - Tree nodes with nested style directions + training types
- HierarchyTab.jsx - Tab 1 with tree view and detail panel
- CatalogsTab.jsx - Tab 2 with global catalogs (Target Groups, Skill Categories, Training Characters)
- AssignmentsTab.jsx - Tab 3 with M:N checkbox matrix (Style Directions ↔ Target Groups)
- DetailPanel.jsx - All edit forms (Focus Area, Style Direction, Training Type) + create forms

Fixes ESBuild parser error from large file size.
Implements full CRUD: create, edit, delete, reassign focus areas.
Responsive design with mobile/desktop layouts.
2026-04-24 09:08:12 +02:00
Lars 9ec1cf7781 fix: temporarily use simple admin hierarchy to fix build
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 2m2s
Test Suite / lint-backend (push) Successful in 0s
Large AdminHierarchyPage.jsx (1200+ lines) causes ESBuild parser error.
Using simplified version temporarily while investigating the issue.

Broken version saved as AdminHierarchyPage.broken.jsx for debugging.
Will split into modules and restore full functionality.
2026-04-24 08:57:13 +02:00
Lars af2fc31f70 fix: build error - remove dynamic template from style tag
Test Suite / build-frontend (push) Failing after 2s
Deploy Development / deploy (push) Failing after 31s
Test Suite / playwright-tests (push) Has been skipped
Test Suite / lint-backend (push) Successful in 0s
2026-04-24 08:52:12 +02:00
LarsandClaude Sonnet 4.5 3fda149049 feat: complete admin system - global catalogs + M:N assignments
Test Suite / build-frontend (push) Failing after 2s
Deploy Development / deploy (push) Failing after 10s
Test Suite / playwright-tests (push) Has been skipped
Test Suite / lint-backend (push) Successful in 0s
Tab System:
- Tab 1: Hierarchie (Fokusbereich → Stilrichtung/Trainingstyp)
- Tab 2: Kataloge (Zielgruppen, Fähigkeiten, Trainingscharakter)
- Tab 3: Zuordnungen (Matrix Stilrichtungen ↔ Zielgruppen)

Global Catalogs (Tab 2):
- Zielgruppen: CRUD mit Altersangaben (zentral verwaltet)
- Fähigkeitskategorien: CRUD (global)
- Trainingscharakter: CRUD (global)
- Reusable CatalogSection component with dynamic fields
- Create/Edit/Delete für alle Kataloge
- Inline editing + validation

M:N Assignments Matrix (Tab 3):
- Checkbox-Grid: Stilrichtungen (Zeilen) × Zielgruppen (Spalten)
- Grouped by Focus Area for clarity
- Toggle assignments with immediate save
- Shows empty states with helpful messages
- Fully responsive table with horizontal scroll

Architecture:
- Trainingstypen: Context-specific per focus area (create new)
- Zielgruppen: Global catalog (assign via matrix)
- Clean separation of concerns
- Proper loading states + error handling

Mobile responsive across all tabs.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-24 08:46:32 +02:00
LarsandClaude Sonnet 4.5 80986735b5 feat: complete admin hierarchy - create + reassign functions
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Create Functions:
- '+ Neu' buttons for Style Directions and Training Types
- Create forms with focus area context
- Auto-assigns to parent focus area
- Loading states + validation

Reassignment:
- Focus area dropdown in edit forms
- Move style directions between focus areas
- Move training types between focus areas
- Updates hierarchy immediately after save

Full CRUD now complete:
- Create: new elements under focus area
- Read: tree view with nested elements
- Update: edit + reassign to different focus area
- Delete: with confirmation dialogs

Mobile + Desktop responsive design maintained.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-24 08:39:48 +02:00
LarsandClaude Sonnet 4.5 af89546022 feat: complete admin hierarchy - edit/delete + responsive design
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Features:
- Edit forms for Style Directions and Training Types (working)
- Delete functions with confirmation dialogs
- Responsive layout: mobile (stacked), tablet/desktop (side-by-side)
- Back button on mobile to return to tree view
- Full CRUD except create (can use old catalogs page for now)

Mobile UX:
- Tree view fills screen
- Click item → detail panel replaces tree
- Back button → return to tree
- Safe bottom padding for navigation

Desktop UX:
- 400px tree + fluid detail panel
- Both always visible
- No back button (not needed)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-24 08:33:11 +02:00
Lars 599d696321 fix: add getAdminHierarchy to api export object
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 2m0s
Test Suite / lint-backend (push) Successful in 0s
2026-04-24 08:25:03 +02:00
LarsandClaude Sonnet 4.5 7314ae1436 feat: Hierarchical Admin UI - Tree View for Catalogs
Test Suite / build-frontend (push) Successful in 7s
Deploy Development / deploy (push) Successful in 1m2s
Test Suite / playwright-tests (push) Failing after 1m56s
Test Suite / lint-backend (push) Successful in 0s
Backend:
- New endpoint: GET /api/admin/hierarchy
- Returns hierarchical structure: Focus Areas with nested Style Directions + Training Types
- Style Directions include target_groups assignments (M:N)
- JSON aggregation for efficient data loading

Frontend:
- New page: AdminHierarchyPage.jsx with Tree + Detail Panel layout
- Tree View: Expandable/collapsible nodes (Focus Areas → Stilrichtungen/Trainingstypen)
- Detail Panel: Shows selected item details, inline editing
- Visual hierarchy: Icons, indentation, color coding
- Responsive layout: Fixed 400px tree, fluid detail panel

Routes:
- /admin now redirects to /admin/hierarchy (new default)
- /admin/hierarchy: Tree-based catalog management
- /admin/catalogs: Legacy flat UI (still available)

UX Improvements:
- Visual hierarchy instead of flat tabs
- M:N relationships visible (target groups per style)
- Better navigation: Click to select, expand/collapse sections
- Cleaner layout: Two-column design

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-24 07:51:40 +02:00
Lars 0be9fd840c fix: remove incompatible schema_migrations tracking from migrations 012-013
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
The db_init.py system uses (filename, applied_at) schema, not (version, description).
Removing manual INSERT statements - db_init.py handles tracking automatically.
2026-04-23 16:17:35 +02:00
LarsandClaude Sonnet 4.5 fe5d29e40e feat: Training Types → Focus Area Hierarchie
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
Migration 013:
- Adds focus_area_id to training_types (context-specific types)
- Migrates existing data to Karate focus area
- Seeds focus-area-specific training types:
  * Karate: Dan-Vorbereitung
  * Gewaltschutz: Präventivkurse, Intensivtraining, Spezialkurse
  * Fitness: Gesundheitssport, Funktionelles Training
- Updates unique constraint to (name, focus_area_id)

Backend (catalogs.py):
- list_training_types: Added focus_area_id filter, LEFT JOIN focus_areas
- create_training_type: Added focus_area_id parameter
- update_training_type: Added focus_area_id parameter
- Enriched responses with focus_area_name and focus_area_icon

Frontend (AdminCatalogsPage):
- Added Fokusbereich dropdown to create form
- Added Fokusbereich dropdown to edit form
- Display shows focus_area_icon and focus_area_name
- Training types now context-specific to focus areas

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 15:29:23 +02:00
LarsandClaude Sonnet 4.5 9f44cff77b fix: Stilrichtungen → Fokusbereich Zuordnung (focus_area_id)
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
Problem: Stilrichtungen-Tab zeigte falsches Feld 'Übergeordneter Stil' (parent_style_id)
Lösung: Fokusbereich-Dropdown (focus_area_id) für Hierarchie

Backend (catalogs.py):
- INSERT: focus_area_id Parameter hinzugefügt
- UPDATE: focus_area_id Parameter hinzugefügt
- SELECT: LEFT JOIN focus_areas für focus_area_name + icon
- Response enriched mit focus_area_name/icon

Frontend (AdminCatalogsPage.jsx):
- newTS State: parent_style_id → focus_area_id
- Create Form: Fokusbereich-Dropdown statt 'Übergeordneter Stil'
- Edit Form: Fokusbereich-Dropdown mit focusAreas
- Display: Zeigt Fokusbereich-Icon + Name (accent color)
- parent_style_id bleibt für optionale Stil-Hierarchien

Jetzt kann Hierarchie korrekt angelegt werden:
✅ Karate → Goju-Ryu
✅ Karate → Shotokan
✅ Gewaltschutz → (eigene Stilrichtungen)

version: 0.5.0
module: catalogs 1.5.0, AdminCatalogsPage 2.2.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 14:36:02 +02:00
LarsandClaude Sonnet 4.5 377f365473 feat: Add TrainerContextsPage to navigation
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 34s
Test Suite / playwright-tests (push) Failing after 1m54s
Test Suite / lint-backend (push) Successful in 0s
- Import TrainerContextsPage in App.jsx
- Add route /trainer-contexts
- Add 'Meine Bereiche' to main navigation (appNav.js)
- Icon: Target (Zielscheibe) für Trainer-Bereiche
- Visible in both desktop sidebar and mobile bottom nav

version: 0.5.0
module: TrainerContextsPage 1.0.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 14:26:10 +02:00
LarsandClaude Sonnet 4.5 5e2820c63c feat: Trainer-Kontext-System & Exercise Training Characters (v0.5.0)
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 33s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
Migration 012:
- exercise_training_characters (M:N junction table)
- trainer_contexts (Fokussierte Trainer-Ansichten)
- Indizes für Performance
- Example seed data

Backend (catalogs.py):
- GET /api/trainer-contexts (list own contexts)
- POST /api/trainer-contexts (create context)
- PUT /api/trainer-contexts/{id} (update own context)
- DELETE /api/trainer-contexts/{id} (delete own context)
- Enriched responses mit focus_area_name, style_direction_name, training_type_name
- Ownership-Validation (nur eigene Kontexte)

Frontend:
- TrainerContextsPage.jsx (vollständige CRUD-UI)
- Kaskadierende Dropdowns (Fokusbereich → Stilrichtung)
- is_style_independent Flag für stilunabhängige Kontexte
- api.js erweitert (listTrainerContexts, create, update, delete)

Architektur:
- Flat Catalogs mit M:N überall
- NULL = 'für alles geeignet'
- Trainer-Kontexte für fokussierte Ansichten
- Vorbereitung für 1000+ Übungen mit flexibler KI-Filterung

version: 0.5.0 (backend + frontend)
module: exercises 0.5.0, catalogs 1.5.0
page: TrainerContextsPage 1.0.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 14:22:17 +02:00
LarsandClaude Sonnet 4.5 9ab2bd31fa fix: Update onClick handlers to use renamed functions
Test Suite / build-frontend (push) Successful in 5s
Deploy Development / deploy (push) Successful in 37s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- createTrainingStyle → createStyleDirection
- updateTrainingStyle → updateStyleDirection
- deleteTrainingStyle → deleteStyleDirection

Fixes: Stilrichtungen tab showed blank screen due to undefined function calls

version: 0.4.0 (frontend)
module: AdminCatalogsPage 2.2.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 12:57:23 +02:00
LarsandClaude Sonnet 4.5 426efd4b83 fix: Frontend API Calls & Field Names für renamed tables
Test Suite / build-frontend (push) Successful in 6s
Deploy Development / deploy (push) Successful in 36s
Test Suite / playwright-tests (push) Failing after 1m55s
Test Suite / lint-backend (push) Successful in 0s
- Updated api.js function names:
  - listTrainingStyles → listStyleDirections
  - createTrainingStyle → createStyleDirection
  - updateTrainingStyle → updateStyleDirection
  - deleteTrainingStyle → deleteStyleDirection
  - listTrainingStyleTargetGroups → listStyleDirectionTargetGroups
  - createTrainingStyleTargetGroup → createStyleDirectionTargetGroup
  - updateTrainingStyleTargetGroup → updateStyleDirectionTargetGroup
  - deleteTrainingStyleTargetGroup → deleteStyleDirectionTargetGroup
  - getTrainingStylesHierarchy → getStyleDirectionsHierarchy
- Updated AdminCatalogsPage.jsx:
  - loadData() uses renamed API functions
  - CRUD functions renamed (createStyleDirection, etc.)
  - Matrix uses style_direction_id parameter
  - Hierarchy renders style_directions array
- Fixes data binding between frontend and backend after table rename

version: 0.4.0 (frontend)
module: AdminCatalogsPage 2.2.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 12:27:09 +02:00
LarsandClaude Sonnet 4.5 155c21f018 fix: Backend SQL Queries für renamed tables (Migration 010+011)
- Updated all SQL queries in catalogs.py to use renamed tables:
  - training_styles → style_directions
  - training_style_target_groups → style_direction_target_groups
  - exercise_styles → exercise_style_directions
- Updated API parameter names: training_style_id → style_direction_id
- Updated response field names: training_style_name → style_direction_name
- Updated array field names: training_styles → style_directions
- Fixes 'failed to fetch' errors on Stilrichtungen, Hierarchie, Zuordnungen tabs

version: 0.4.0 (backend)
module: catalogs 1.4.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-23 12:24:50 +02:00
228 changed files with 63936 additions and 3632 deletions

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
# Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-08
**Version (Code):** 0.8.64 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260508049` (`backend/version.py`, DB_SCHEMA_VERSION)
**Branch:** develop
---
## Executive Summary
**Aktueller Meilenstein (Medien):** Das **Medien-Archiv** (`media_assets` + `exercise_media.media_asset_id`) ist **produktiv nutzbar**: zentrale Bibliothek **`/media`** (Kacheln/Liste, Filter inkl. Lifecycle, Suche/Tags, Copyright, Bulk-Lifecycle und Bulk-PATCH), **Verknüpfung aus dem Archiv** in der Übungsbearbeitung (`POST …/media/from-asset`), **deduplizierter Speicher** unter **`library/…`** (Vereinsordner aus Name, Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeitsänderung), **Papierkorb & Lifecycle** (Reaktivierung, Soft-Trash, Superadmin-Purge), plus **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop mit Auto-Scroll, Vorschau-/Rückweg-UX). **Governance:** Sichtbarkeit **`official`** nur noch **Superadmin** (Übungen und Medien); Plattform-Admin wie Trainer für Vereins-/Private-Inhalte. **Vereinsübungen** mit Datei-Assets: **Copyright-Pflicht** (API/UI). **Aktiver Verein:** Dropdown, Profilfeld `active_club_id`, Header `X-Active-Club-Id` und `effective_club_id` sind nach **0.8.59** synchronisiert (inkl. Plattform-Admin ohne Header beim ersten Request).
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) §12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **§11 Inline-Medien**, umgesetzt)
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
1. ~~**Übung → `official` Promotion** inkl. Medien-Anhebung + **Copyright-Pflicht** bei `official` (Spec §4.2)~~ — umgesetzt (0.8.47).
2. ~~**Eigenständige Medienmanager-Seite**~~ — **Basis umgesetzt** (`/media`); Ausbau nach Bedarf: Quotas, feinere Bulk-Workflows, Sichtbarkeits-PATCH in der UI vereinheitlichen.
3. **Tests & Observability:** gezielte pytest-Abdeckung für Archiv/Verknüpfen/Lifecycle; Retention-Job (`scripts/media_retention_job.py`) in Betrieb/Doku verankern.
4. **S3 / externes Backend** hinter Speicher-Abstraktion (Spec §7) — nach stabiler Nutzung lokaler/NAS-Pfade.
5. **Inline-Medien im Fließtext (Spec §11)** — **Basis umgesetzt (0.8.60–0.8.64)**: Platzhalter-Syntax, zentraler Renderer, Modal-Picker, Drag&Drop + Auto-Scroll; offen: weitere UX-Politur und ggf. strategischer Umbau auf reine Asset-Referenz (separat zu entscheiden).
**Inline:** verbindliche Leitplanken **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11**; Umsetzung aktiv im Produktpfad (RTE + Anzeige).
---
**Nächste Schritte (Auszug — Planung/Rahmen):**
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**).
---
## Deployed Migrations (Dev / Zielstand)
| Migration | Beschreibung | Dev | Prod |
|-----------|--------------|-----|------|
| 001–017 | Initial Schema + Exercise System | ✅ | ✅ |
| 018 | Wiki Import Tracking | ✅ | ✅ |
| 019 | Exercises Optional Fields | ✅ | ✅ |
| 020 | Exercise Skills UNIQUE Constraint | ✅ | 🔲 |
| 021 | ~~Import Skills from Matrix~~ (DEPRECATED) | ⚠️ | ❌ |
| 022 | Skills Schema Complete | ✅ | 🔲 |
| 023 | Skills Complete Import (69 Skills) | ✅ | 🔲 |
| 028–029 | exercise_media / skills Stufen | ✅ | 🔲 |
| **030** | **training_unit_exercises.exercise_variant_id** | ✅ | 🔲 |
| **032–034** | **Progressionsgraph Übung→Übung** | ✅ | 🔲 |
| **035–037** | **Rahmenprogramm, Bibliothek‑Kopf, Slot‑Blueprint‑Units** | ✅ | 🔲 |
| **040–046** | **u. a. Mitgliedschaften, Übungs-Governance, `media_assets` (046 z. B. Tags/GIN), Plattform-Speicherpfad** | ✅ Dev | 🔲 Prod |
---
## Aktuelle Datenbank-Stats (Dev, Richtwerte)
Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übungen-Importe aus früheren Meilensteinen bleiben die Datenbasis.
---
## Feature-Status
### ✅ Deployed Features (Dev)
**Kern-System:**
- [x] Auth & Profile Management
- [x] Organisation (Clubs, Divisions, Groups)
- [x] Kataloge (Focus Areas, Styles, Target Groups – M:N)
**Übungen:**
- [x] CRUD (Create, Read, Update, Delete)
- [x] M:N Beziehungen (Focus Areas, Styles, Target Groups, Skills)
- [x] **Varianten** (CRUD, Reorder, Voraussetzung) + Anzeige im Detail
- [x] **Progressionsgraph zwischen Übungen** (Bibliotheks-Container, Kanten, Sequenz-Bulk, Varianten-Knoten — Zwischenstand, siehe TRAINING_FRAMEWORK_SPEC §4)
- [x] Medien (Upload/Embed, rollenabhängige Größenlimits)
- [x] Suche & Filter (Multi-Filter, Chips, Fokus beim Suchen)
- [x] Exercise Blocks (Bausteine)
- [x] Saved Searches (wo implementiert)
**Trainingsplanung:**
- [x] Training Units / strukturierter Ablauf (Sektionen + Items)
- [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)
- [ ] Kalender-View / erweiterte Roadmap (Backlog)
**MediaWiki Import:**
- [x] Import-Tracking, Übungs-Import, Skills-Migration (siehe ältere Session-Docs)
**Skills-System:**
- [x] Hierarchisches Schema, Fokusbereich-Zuordnung, Exercise-Skill mit Levels
**Admin-UI:**
- [x] Katalog-CRUD, Matrix/Import je nach Rolle
### 🔲 In Arbeit / Backlog
- [x] **Medien:** Papierkorb (§5), Retention-Job, Archiv-API, „Aus Archiv verknüpfen“, Picker/Vorschau in Übungsbearbeitung (0.8.42 ff.)
- [x] **Medien:** Promotion Übung↔Medien + Copyright-Pflicht `official` / Vereins-Copyright-Regeln (Spec §4.2, Übungen+Assets)
- [x] **Medien:** Medienbibliothek `/media` (Filter, Tags, Copyright, Bulk-Lifecycle/PATCH, Lesemodus für eingeschränkte Rollen bei `official`)
- [x] **Medien:** Speicherpfad-Konvention `library/…`, Plattform-Speicher-Konfiguration (`platform_media_storage`), Mandanten-/Governance-Umzug bei Asset-Änderungen
- [x] **Medien:** Inline im Fließtext — Spec §11 (Platzhalter, Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll, Rückweg aus Vorschau)
- [ ] Admin-UI für Skill-Kategorien (CRUD) – falls noch offen
- [ ] Responsive Design / Dark Mode / PWA
- [ ] KI-Suche (`ai_search`) über reine Volltextsuche hinaus
### 📋 Geplant (Backlog)
- Trainingsplan-Generator, Bulk-Export, Review-Workflow (unverändert strategisch geplant)
---
## Technische Schulden
| Bereich | Issue | Priorität |
|---------|-------|-----------|
| Skills | Migration 021 bereinigen (falls noch referenziert) | Niedrig |
| Import | Reimport-Flag / DNS – je nach Prod-Realität prüfen | Mittel |
---
## Lessons Learned (Auszug)
- **Listen-UX:** Bedingtes Rendern der **gesamten Seite** bei `loading` zerstört Fokus und Scroll – separates `listFetching` für die Trefferliste.
- **Upload-Limits:** Vergleich immer in **MB** vor Umrechnung in Bytes; Admin-Limit nie unter Nutzer-Limit.
---
## Deployment-Status
### Dev
Branch `develop`; Migrations bis mindestens **046** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
### Prod
Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozess.
---
## Dokumentation-Status
| Dokument | Pfad | Stand | Status |
|----------|------|-------|--------|
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-08 | ✅ Aktualisiert (§12 Medien inkl. Inline 0.8.60–0.8.64) |
| Trainingsrahmen + Graph | `technical/TRAINING_FRAMEWORK_SPEC.md` | 2026-05-05 | ✅ §2 Blueprint |
| Anforderungen (Index) | `functional/SHINKAN_REQUIREMENTS.md` | 2026-04-27 | ✅ Neu |
| Database Schema | `technical/DATABASE_SCHEMA.md` | 2026-05-07 | ✅ Hinweis 040–046 Medien (Kurz) |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-07 | ✅ Abschnitt Medien-Archiv |
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-05-08 | ✅ Medien/Inline-Workflow ergänzt |
| Frontend Routing | `technical/EXERCISES_FRONTEND_ROUTING.md` | 2026-04-30 | ✅ Ergänzt UI-Hinweise |
| Search & Filter | `technical/SEARCH_FILTER_SPEC.md` | 2026-04-27 | ✅ Aktualisiert (Liste UX) |
| Media Upload | `technical/MEDIA_UPLOAD_SPEC.md` | 2026-05-07 | ✅ Verweis Archiv/Inline |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` | 2026-05-08 | ✅ Ist-Changelog + §11 Inline erweitert |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-08 | ✅ auf 0.8.64 aktualisiert |
---
## Team & Kontakte
**Product Owner:** Lars
**Wiki (Datenquelle):** https://karatetrainer.net
---
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
@@ -0,0 +1,599 @@
# Review Prompt: Exercises System Specifications
**Zweck:** Vollständiger Review der erstellten Spezifikationen gegen ursprüngliche Anforderungen und User-Ergänzungen
**Reviewer:** Plan Agent (oder anderer spezialisierter Agent)
**Status:** ✅ Review abgeschlossen + Fixes implementiert
**Datum:** 2026-04-24
**Review-Datum:** 2026-04-24
**Ergebnis:** APPROVED WITH CHANGES – alle BLOCKER und MAJOR Issues behoben
---
## 1. Kontext & Auftrag
Du bist ein Plan Agent, der die erstellten Spezifikationen für das Exercise System in Shinkan Jinkendo reviewt. Deine Aufgabe ist es, die 7 Core-Specs gegen die ursprünglichen Anforderungen und User-Ergänzungen zu prüfen und sicherzustellen, dass **keine Anforderungen vergessen** wurden und **keine architektonischen Drifts** entstanden sind.
---
## 2. Zu reviewende Spezifikationen
### 2.1 Core Specs (Phase 0 Foundation)
**Lokation:** `c:/Dev/shinkan-jinkendo/.claude/docs/technical/`
1. **EXERCISES_ARCHITECTURE.md** (ca. 800 Zeilen)
- Architektur-Entscheidungen
- Exercise/Variant/Block/Series Definitionen
- Media-Strategie
- API-Konventionen
- DB-Konventionen
- Decision Log
2. **UI_COMPONENTS_SPEC.md** (ca. 600 Zeilen)
- Base Components (Chip, MultiSelect, Accordion, DragDropList)
- Exercise Components (Card, QuickInfo, VariantCard, MediaGallery, MediaUploader)
- Layout Patterns
- Responsive Breakpoints
- Accessibility
3. **EXERCISES_API_SPEC.md** (ca. 574 Zeilen)
- Alle Endpoints (Exercises, Variants, Media)
- Request/Response Beispiele
- Validierung Rules
- Error Format
- HTTP Status Codes
4. **EXERCISES_FRONTEND_ROUTING.md** (ca. 400 Zeilen)
- Route-Struktur
- Navigation Patterns
- State Management (URL, Local, Context)
- Deep Linking
- Navigation Guards
- Performance (Lazy Loading, Prefetching)
5. **MEDIA_UPLOAD_SPEC.md** (ca. 500 Zeilen)
- Hybrid Upload-Strategie (Lokal + Embeds)
- Upload-Flow (Client + Server)
- Embed-Parsing (YouTube, Vimeo, Instagram, TikTok)
- Media-Galerie
- Drag & Drop Reordering
- Security & Performance
6. **SEARCH_FILTER_SPEC.md** (ca. 450 Zeilen)
- Multi-Layer Search (Keyword, Katalog, Meta)
- Volltext-Suche (tsvector)
- Frontend Filter-UI
- Erweiterte Filter (Multi-Select, Range, Equipment)
- Faceted Search
- Saved Searches
- Sortierung
7. **EXERCISES_DATABASE_FINAL.md** (ca. 600 Zeilen)
- Migration 014 (Variant Progression + Search Vector)
- Migration 015 (Semantic Matching - Optional)
- Migration 016 (Saved Searches)
- Vollständige Tabellenstruktur
- Indizes
- Constraints & Business Rules
- Trigger-Funktionen
---
## 3. Ursprüngliche Anforderungen
### 3.1 User-Anforderungen (Initial Message)
**Quelle:** Erste User-Message in Session
**Kern-Anforderungen:**
1. **Formatierte Ausgabe:** Übungen mit Embedded Videos, Zeichnungen, optimiert für verschiedene Use Cases
2. **Varianten:** Mehrere Varianten mit progressiven Schwierigkeitsstufen
3. **Exercise Series:** Progression durch Varianten derselben Übung
4. **Exercise Blocks:** Sammlungen verschiedener Übungen
5. **Multi-dimensionale Kategorisierung:** Stil, Fokus, Zielgruppe, Fähigkeiten-Matrix mit Levels
6. **Trainingsplan-Integration:** Muss mit Trainingsplan-System integrieren
7. **MediaWiki-Import:** Direct API Integration (NICHT export-basiert)
8. **Robustheit:** Kein ständiger Drift, skalierbar, umfassend
**Spec-First Approach gewählt:** Alle Specs VOR Implementation
### 3.2 User-Ergänzungen (Follow-up)
**Quelle:** Zweite User-Message mit 5 Klarstellungen
**Präzisierungen:**
1. **Priorisierung OK:** Spec-First Ansatz bestätigt
2. **Web + Mobile Priorität (NICHT Print/PDF):**
- Kurze vs. detaillierte Beschreibungen für Trainingspläne
3. **Media-Strategie:** Lokaler Upload + YouTube/Instagram Embeds
4. **Exercise Series vs. Blocks Klarstellung:**
- **Series:** Progressive Varianten derselben Übung (via Variant-Metadata)
- **Blocks:** Gruppierung VERSCHIEDENER Übungen (neue Entity)
- **Template Blocks:** Blocks mit Platzhaltern (gefüllt beim Planen)
5. **MediaWiki Import:** Via Direct API (NICHT Export)
### 3.3 Referenz-Dokumente
**Quelle:** Zu lesende Dokumente vor Spec-Erstellung
1. **shinkan_anforderungsdokument_entwurf.md** (1425 Zeilen)
- Fachliche Anforderungen
- Reifegradmodelle
- Übungen & Methoden
- Trainingsplanung
- MVP Scope: Trainer-fokussiert
2. **DOMAIN_MODEL.md** (Version 0.3.4)
- Hierarchische Struktur: Fokusbereich → Stil → Zielgruppen (M:N)
- Primary/Secondary Pattern für M:N
- Migration 009 deployed (Zielgruppen M:N Refactoring)
3. **DATABASE_SCHEMA.md** (Version 0.3.4)
- Existierende M:N Tabellen
- Migrations 001-013 deployed
4. **backend/routers/exercises.py** (454 Zeilen)
- Existierendes CRUD
- Enrichment-Pattern für M:N Relations
- Filter-Support
5. **backend/migrations/005_exercises.sql**
- Base exercises table
- exercise_skills, exercise_variants, exercise_media
6. **backend/migrations/008_mn_exercise_relations.sql**
- M:N Migration (focus_areas, styles, target_groups, age_groups)
7. **frontend/src/pages/ExercisesPage.jsx** (609 Zeilen)
- Existierende UI (Grid, Filters, Modal)
- Limitation: Nutzt M:N Backend-Daten NICHT
---
## 4. Review-Kriterien
### 4.1 Vollständigkeit (Completeness)
**Prüfe gegen ursprüngliche Anforderungen:**
- [ ] **Formatierte Ausgabe:** Sind Embedded Videos, Zeichnungen, verschiedene Use Cases abgedeckt?
- [ ] **Varianten mit Progression:** Sind progressive Schwierigkeitsstufen spezifiziert?
- [ ] **Exercise Series:** Ist Progression durch Varianten klar definiert (OHNE separate Entity)?
- [ ] **Exercise Blocks:** Ist Gruppierung verschiedener Übungen spezifiziert?
- [ ] **Template Blocks:** Sind Platzhalter-Blocks für Planung definiert?
- [ ] **Multi-dimensionale Kategorisierung:** Sind Stil, Fokus, Zielgruppe, Skills mit Levels abgedeckt?
- [ ] **Trainingsplan-Integration:** Ist Integration mit Training Plan System spezifiziert?
- [ ] **MediaWiki-Import:** Ist Direct API Integration (NICHT Export) spezifiziert?
- [ ] **Kurz vs. Detail:** Sind verschiedene Beschreibungslängen für Trainingspläne definiert?
### 4.2 Konsistenz (Consistency)
**Prüfe gegen Referenz-Dokumente:**
- [ ] **DOMAIN_MODEL.md:** Folgen Specs der hierarchischen Struktur (Fokusbereich → Stil → Zielgruppen)?
- [ ] **M:N Pattern:** Wird `is_primary` Flag korrekt genutzt?
- [ ] **DATABASE_SCHEMA.md:** Bauen Migrationen 014-016 auf 001-013 auf?
- [ ] **Existierender Code:** Sind Specs kompatibel mit `backend/routers/exercises.py`?
- [ ] **Migration-Pattern:** Folgen neue Migrationen dem idempotenten DO $$ Pattern?
### 4.3 Architektonische Korrektheit (No Drift)
**Prüfe gegen User-Ergänzungen:**
- [ ] **Series vs. Blocks:** Ist die Unterscheidung klar und korrekt umgesetzt?
- Series = Progression durch Varianten (Metadata in `exercise_variants`)
- Blocks = Neue Entity für Gruppierung verschiedener Übungen
- [ ] **Media-Strategie:** Hybrid (Lokal + Embeds) korrekt spezifiziert?
- [ ] **Keine Cloud-Only Annahme:** Lokaler Upload vorhanden?
- [ ] **Direct API statt Export:** MediaWiki-Import via API spezifiziert?
### 4.4 Technische Machbarkeit (Feasibility)
- [ ] **Performance:** Sind Performance-Targets realistisch (<50ms List, <150ms Search)?
- [ ] **Skalierbarkeit:** DB-Schema skaliert auf 5.000+ Übungen?
- [ ] **Security:** File-Upload-Validierung mit python-magic (nicht nur Extension)?
- [ ] **UX:** Mobile-Optimierung (Filter-Drawer, Sticky Search, Bottom-Nav) vorhanden?
### 4.5 Gaps & Fehlende Features
**Prüfe auf vergessene Features:**
- [ ] **Trainingscharakter (M:N):** Ist `exercise_training_characters` spezifiziert?
- [ ] **Fähigkeiten-Levels:** Sind `required_level` und `target_level` in `exercise_skills` definiert?
- [ ] **Visibility-Workflow:** Ist `private → club → official` Status-Flow spezifiziert?
- [ ] **Permissions:** Sind Owner-Checks (nur Ersteller darf bearbeiten) definiert?
- [ ] **Pagination:** Ist Pagination in List-Endpoints spezifiziert?
- [ ] **Reordering:** Ist Drag & Drop Reordering für Variants + Media definiert?
---
## 5. Review-Prozess
### 5.1 Schritt-für-Schritt Anleitung
**Schritt 1: Dokumente lesen**
1. Lies alle 7 Core-Specs vollständig durch
2. Mache dir Notizen zu Auffälligkeiten
3. Markiere unklare oder widersprüchliche Stellen
**Schritt 2: Checkliste durchgehen**
1. Gehe durch Abschnitt 4.1 (Vollständigkeit) - jede Anforderung einzeln prüfen
2. Gehe durch Abschnitt 4.2 (Konsistenz) - gegen Referenz-Docs prüfen
3. Gehe durch Abschnitt 4.3 (Architektur) - gegen User-Ergänzungen prüfen
4. Gehe durch Abschnitt 4.4 (Machbarkeit) - technische Risiken bewerten
5. Gehe durch Abschnitt 4.5 (Gaps) - fehlende Features identifizieren
**Schritt 3: Cross-Check zwischen Specs**
1. ARCHITECTURE.md ↔ API_SPEC.md: Sind Decisions in API umgesetzt?
2. API_SPEC.md ↔ DATABASE_FINAL.md: Matchen Endpoints zur DB-Struktur?
3. UI_COMPONENTS_SPEC.md ↔ FRONTEND_ROUTING.md: Passen Komponenten zu Routes?
4. MEDIA_UPLOAD_SPEC.md ↔ DATABASE_FINAL.md: Passt `exercise_media` Tabelle?
5. SEARCH_FILTER_SPEC.md ↔ DATABASE_FINAL.md: Ist `search_vector` definiert?
**Schritt 4: Gap-Analyse**
1. Erstelle Liste aller **fehlenden** Anforderungen
2. Erstelle Liste aller **widersprüchlichen** Definitionen
3. Erstelle Liste aller **unklaren** Spezifikationen
4. Erstelle Liste aller **technischen Risiken**
**Schritt 5: Review-Report erstellen**
1. Folge Template in Abschnitt 6
2. Fülle alle Abschnitte vollständig aus
3. Sei konkret: Datei + Zeile + Problem + Lösungsvorschlag
---
## 6. Review-Report Template
**Nutze dieses Template für deinen Review-Report:**
```markdown
# Exercise System Specs - Review Report
**Reviewer:** [Dein Agent-Name]
**Review-Datum:** [Datum]
**Review-Dauer:** [ca. X Minuten]
**Gesamtbewertung:** [APPROVED / APPROVED WITH CHANGES / REJECTED]
---
## 1. Executive Summary
[2-3 Sätze: Sind die Specs bereit für Implementation? Größte Probleme?]
---
## 2. Vollständigkeit (Completeness)
### 2.1 Erfüllte Anforderungen ✅
- [x] Formatierte Ausgabe: Abgedeckt in MEDIA_UPLOAD_SPEC.md (Abschnitt 4)
- [x] Varianten mit Progression: Abgedeckt in EXERCISES_DATABASE_FINAL.md (Migration 014)
- [... weitere ...]
### 2.2 Fehlende Anforderungen ❌
| Anforderung | Wo fehlt es? | Kritikalität | Lösungsvorschlag |
|-------------|--------------|--------------|------------------|
| Exercise Blocks Entity | EXERCISES_ARCHITECTURE.md erwähnt, aber nicht in DATABASE_FINAL.md | HIGH | Migration 017 für `exercise_blocks` Tabelle hinzufügen |
| Template Blocks Platzhalter | Nirgendwo spezifiziert | MEDIUM | Erweitere `exercise_blocks` um `is_template` + `placeholders` JSONB |
| ... | ... | ... | ... |
---
## 3. Konsistenz (Consistency)
### 3.1 Inkonsistenzen zwischen Specs
| Problem | Betroffene Dateien | Impact | Fix |
|---------|-------------------|--------|-----|
| API_SPEC.md definiert `age_groups_catalog` als JSONB, aber DOMAIN_MODEL.md sagt M:N | API_SPEC.md Zeile 104, DOMAIN_MODEL.md Abschnitt 3 | MEDIUM | Entscheide: JSONB ODER M:N (empfohlen: M:N für Konsistenz) |
| ... | ... | ... | ... |
### 3.2 Inkonsistenzen mit Referenz-Dokumenten
| Problem | Spec-Datei | Referenz-Dokument | Fix |
|---------|-----------|-------------------|-----|
| DOMAIN_MODEL.md sagt Zielgruppen sind global (M:N), aber API_SPEC.md zeigt `target_group_id` als FK | API_SPEC.md Zeile 267 | DOMAIN_MODEL.md Abschnitt 3.3 | Korrigiere API_SPEC zu M:N Array |
| ... | ... | ... | ... |
---
## 4. Architektur-Drift
### 4.1 Abweichungen von User-Ergänzungen
| User-Anforderung | Spec-Umsetzung | Konform? | Problem / Fix |
|-----------------|----------------|----------|---------------|
| "Series = Varianten-Progression OHNE separate Entity" | EXERCISES_ARCHITECTURE.md Abschnitt 2.2 definiert Series korrekt als Metadata | ✅ JA | - |
| "Blocks = neue Entity für verschiedene Übungen" | EXERCISES_ARCHITECTURE.md erwähnt, DATABASE_FINAL.md fehlt Migration | ❌ NEIN | Migration 017 fehlt |
| "Direct API statt Export" | Nirgendwo spezifiziert | ❌ NEIN | Neue Spec MEDIAWIKI_IMPORT_SPEC.md nötig |
| ... | ... | ... | ... |
---
## 5. Technische Risiken
| Risiko | Betroffene Spec | Wahrscheinlichkeit | Impact | Mitigation |
|--------|----------------|-------------------|--------|------------|
| tsvector auf großen Texten langsam | SEARCH_FILTER_SPEC.md | MEDIUM | HIGH | Teste Performance mit 10.000 Zeichen Execution-Text |
| 50MB File-Upload blockiert Server | MEDIA_UPLOAD_SPEC.md | HIGH | MEDIUM | Chunk-Upload oder separater Upload-Worker |
| pgvector Extension nicht verfügbar | DATABASE_FINAL.md Migration 015 | LOW | LOW | Migration 015 ist optional (Phase 2) |
| ... | ... | ... | ... | ... |
---
## 6. Gap-Analyse
### 6.1 Komplett fehlende Features
1. **Exercise Blocks Implementation**
- Wo benötigt: DATABASE_FINAL.md, API_SPEC.md, UI_COMPONENTS_SPEC.md
- Kritikalität: HIGH (User-Anforderung #4)
- Aufwand: 1 Migration + 3 Endpoints + 2 Komponenten
2. **Template Blocks mit Platzhaltern**
- Wo benötigt: DATABASE_FINAL.md, API_SPEC.md
- Kritikalität: MEDIUM (User-Anforderung #4 Teil 2)
- Aufwand: Erweitere Blocks-Tabelle + 1 Endpoint
3. **MediaWiki Direct API Import**
- Wo benötigt: Neue Spec MEDIAWIKI_IMPORT_SPEC.md
- Kritikalität: HIGH (User-Anforderung #7)
- Aufwand: Neue Spec + Backend-Integration
4. [... weitere ...]
### 6.2 Unvollständig spezifizierte Features
1. **Trainingsplan-Integration**
- Status: Erwähnt in ARCHITECTURE.md, aber keine konkreten Endpoints
- Fehlende Details: Wie werden Übungen in Pläne eingefügt? API-Struktur?
- Fix: Erweitere API_SPEC.md um `/training-plans/{id}/exercises` Endpoints
2. [... weitere ...]
---
## 7. Kritische Findings (Must-Fix vor Implementation)
### 🔴 BLOCKER (Implementation NICHT starten ohne Fix)
1. **Exercise Blocks fehlen komplett**
- Impact: Kern-Anforderung #4 nicht erfüllt
- Fix: Migration 017 + API-Endpoints + UI-Komponenten spezifizieren
2. **MediaWiki-Import nicht spezifiziert**
- Impact: Kern-Anforderung #7 nicht erfüllt
- Fix: Neue Spec MEDIAWIKI_IMPORT_SPEC.md erstellen
### 🟠 MAJOR (Fix vor Phase 1 Abschluss)
1. **age_groups: JSONB vs. M:N Inkonsistenz**
- Impact: Daten-Modell unklar, spätere Migration schwierig
- Fix: Entscheide für M:N (Konsistenz) oder JSONB (Einfachheit)
2. [... weitere ...]
### 🟡 MINOR (Fix in Phase 2 akzeptabel)
1. **Semantic Matching (Migration 015) optional**
- Impact: Nice-to-have Feature, kein MVP-Blocker
- Fix: Kein Fix nötig, als Phase 2 markieren
2. [... weitere ...]
---
## 8. Empfehlungen
### 8.1 Vor Implementation starten
1. **Fixe alle BLOCKER:** Exercise Blocks + MediaWiki-Import spezifizieren
2. **Kläre MAJOR Issues:** age_groups Inkonsistenz auflösen
3. **Ergänze Extended Specs:** VARIANTS_PROGRESSION_SPEC.md, EXERCISE_BLOCKS_SPEC.md, PERMISSIONS_VISIBILITY_SPEC.md
4. **User-Review:** Zeige Specs dem User, hole Feedback zu Blocks/Template-Blocks
### 8.2 Implementation-Reihenfolge (falls APPROVED)
**Phase 1A - Foundation:**
1. Migration 014 (Search Vector + Variant Progression)
2. Migration 016 (Saved Searches)
3. Backend: GET/POST/PUT/DELETE `/exercises` + `/exercises/{id}/variants`
4. Frontend: ExercisesListPage + ExerciseDetailPage (ohne Blocks)
**Phase 1B - Media:**
1. Backend: `/exercises/{id}/media` Endpoints
2. Frontend: MediaUploader + MediaGallery Komponenten
**Phase 1C - Search:**
1. Backend: Search + Filter in GET `/exercises`
2. Frontend: SearchFilterBar Komponente
**Phase 2 - Blocks (nach BLOCKER-Fix):**
1. Migration 017 (Exercise Blocks)
2. Backend: `/exercise-blocks` Endpoints
3. Frontend: BlockEditor Komponente
**Phase 3 - Import:**
1. MEDIAWIKI_IMPORT_SPEC.md erstellen
2. Backend: MediaWiki API Connector
3. Frontend: Import-UI
---
## 9. Positive Findings ✅
[Was ist gut gelaufen? Was ist besonders gut spezifiziert?]
1. **Sehr detaillierte API-Spec:** Alle Request/Response-Beispiele vorhanden
2. **Konsistentes M:N Pattern:** is_primary Flag durchgängig genutzt
3. **Performance-bewusst:** Indizes, Caching, Lazy Loading spezifiziert
4. **Accessibility:** ARIA, Keyboard-Nav, Skip-Links definiert
5. [... weitere ...]
---
## 10. Nächste Schritte
### Für Spec-Autor (Original Agent):
1. [ ] Fixe BLOCKER #1: Exercise Blocks spezifizieren
2. [ ] Fixe BLOCKER #2: MediaWiki-Import spezifizieren
3. [ ] Kläre MAJOR Issue: age_groups JSONB vs. M:N
4. [ ] Aktualisiere betroffene Specs (siehe Abschnitt 7)
### Für User:
1. [ ] Lese Executive Summary + Kritische Findings
2. [ ] Entscheide über Blocks/Template-Blocks Umsetzung
3. [ ] Priorisiere MediaWiki-Import (jetzt oder später?)
4. [ ] Gib Feedback zu age_groups Entscheidung
### Für Implementation:
- **WARTE** bis alle BLOCKER gefixt sind
- **DANACH:** Starte mit Phase 1A (Foundation)
---
**Review abgeschlossen:** [Datum/Uhrzeit]
**Nächster Review:** [Nach BLOCKER-Fixes]
```
---
## 7. Wichtige Hinweise für Reviewer
### 7.1 Sei konkret
❌ **SCHLECHT:** "Die API-Spec ist inkonsistent"
✅ **GUT:** "API_SPEC.md Zeile 267 zeigt `target_group_id` als FK, aber DOMAIN_MODEL.md Abschnitt 3.3 definiert Zielgruppen als M:N"
### 7.2 Priorisiere nach Impact
- **BLOCKER:** Verhindert Implementation-Start
- **MAJOR:** Muss vor Phase 1 Abschluss gefixt werden
- **MINOR:** Kann in Phase 2 gefixt werden
### 7.3 Schlage Lösungen vor
Nicht nur Probleme nennen, sondern auch:
- Konkrete Fix-Vorschläge
- Alternative Ansätze
- Trade-offs aufzeigen
### 7.4 Sei fair
- Lobe gute Spezifikationen
- Erkenne schwierige Trade-offs an
- Berücksichtige MVP-Scope (nicht alles muss perfekt sein)
---
## 8. Erfolgs-Kriterien für APPROVED
Specs sind **APPROVED**, wenn:
1. ✅ Alle User-Anforderungen (1-8) spezifiziert sind
2. ✅ Alle User-Ergänzungen (1-5) korrekt umgesetzt sind
3. ✅ Keine architektonischen Widersprüche existieren
4. ✅ Specs konsistent mit Referenz-Dokumenten sind
5. ✅ Keine BLOCKER-Issues offen sind
6. ✅ Technische Machbarkeit gegeben ist
7. ✅ Implementation-Reihenfolge klar definiert ist
Specs sind **APPROVED WITH CHANGES**, wenn:
- 1-2 MAJOR Issues existieren (aber klar, wie zu fixen)
- Mehrere MINOR Issues existieren
- Implementation kann starten, während Fixes parallel gemacht werden
Specs sind **REJECTED**, wenn:
- 3+ BLOCKER Issues existieren
- Fundamentale architektonische Probleme vorhanden
- Große Teile der Anforderungen fehlen
---
## 9. Beispiel-Review-Snippet
**So sollte ein gutes Review-Finding aussehen:**
```markdown
### 🔴 BLOCKER #1: Exercise Blocks fehlen in DB-Schema
**Problem:**
- EXERCISES_ARCHITECTURE.md Abschnitt 2.3 definiert Exercise Blocks als "Gruppierung verschiedener Übungen"
- EXERCISES_DATABASE_FINAL.md (Migration 014-016) enthält KEINE `exercise_blocks` Tabelle
- API_SPEC.md spezifiziert KEINE `/exercise-blocks` Endpoints
**Impact:**
- User-Anforderung #4 ("Exercise Blocks: Sammlungen verschiedener Übungen") NICHT erfüllt
- Trainingsplan-Integration (Anforderung #6) ohne Blocks schwierig
**Betroffene Dateien:**
- EXERCISES_DATABASE_FINAL.md (fehlt Migration 017)
- EXERCISES_API_SPEC.md (fehlt Abschnitt "Exercise Blocks")
- UI_COMPONENTS_SPEC.md (fehlt "BlockEditor" Komponente)
**Lösungsvorschlag:**
1. **Migration 017: Exercise Blocks**
```sql
CREATE TABLE exercise_blocks (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
is_template BOOLEAN DEFAULT FALSE,
placeholders JSONB, -- für Template-Blocks
created_by INT REFERENCES profiles(id),
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE exercise_block_items (
id SERIAL PRIMARY KEY,
block_id INT REFERENCES exercise_blocks(id) ON DELETE CASCADE,
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE,
sequence_order INT NOT NULL,
notes TEXT,
UNIQUE(block_id, sequence_order)
);
```
2. **API-Endpoints ergänzen:**
- `GET /exercise-blocks` - List blocks
- `POST /exercise-blocks` - Create block
- `PUT /exercise-blocks/{id}` - Update block
- `POST /exercise-blocks/{id}/items` - Add exercise to block
- `PUT /exercise-blocks/{id}/items/reorder` - Reorder exercises
3. **UI-Komponente spezifizieren:**
- BlockEditor mit Drag & Drop für Exercise-Reihenfolge
- Template-Modus mit Platzhalter-UI
**Aufwand:** ~4-6h (1 Migration + 5 Endpoints + 1 Komponente spezifizieren)
**Kritikalität:** BLOCKER - Implementation kann ohne Blocks NICHT User-Anforderungen erfüllen
```
---
## 10. Review starten
**Bereit? Dann:**
1. Lies alle 7 Spec-Dokumente gründlich
2. Gehe die Checkliste durch (Abschnitt 4)
3. Erstelle deinen Review-Report (Template Abschnitt 6)
4. Sei konkret, fair und konstruktiv
5. Priorisiere nach Impact (BLOCKER > MAJOR > MINOR)
**Viel Erfolg beim Review! 🚀**
---
**Letzte Aktualisierung:** 2026-04-24
**Version:** 1.0
**Autor:** Claude Code (Spec-Ersteller)
+261 -20
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Fachliches Domänenmodell
**Version:** 0.3.4
**Stand:** 2026-04-23 (Migration 009: Target Groups M:N Refactoring)
**Basis:** `shinkan_anforderungsdokument_entwurf.md`
**Version:** 0.4.4
**Stand:** 2026-05-08 (Medien-Archiv **`media_assets`** / Bibliothek **`/media`** im Ist; **Inline-Medien** im Fließtext umgesetzt — `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11)
**Basis:** `shinkan_anforderungsdokument_entwurf.md` + Fähigkeitsmatrix
---
@@ -27,6 +27,27 @@ Dieses Dokument beschreibt die **fachliche Datenstruktur** von Shinkan Jinkendo.
**Konsequenz:** Ein globaler Katalog, aber kontextabhängige Ausprägung über Reifegradmodelle.
**🆕 Hierarchische Struktur (ab Migration 022):**
```
Haupt-Kategorie (KARATE / ALLGEMEINE)
└─ Unter-Kategorie (Kihon, Kumite, Kondition, etc.)
└─ Fähigkeit
└─ Level-Definitionen (1-5)
```
**🆕 Fokusbereich-Zuordnung (ab Migration 022):**
- **Karate-spezifisch** (`focus_areas: ["karate"]`)
- Beispiele: Kata Ablauf, Kihon, Bunkai, Dachi Waza
- Nur relevant für Karate-Training
- **Universal** (`focus_areas: ["universal"]`)
- Beispiele: Maximalkraft, Konzentration, Deeskalation, Flexibilität
- Relevant für ALLE Trainingsbereiche (Karate, Selbstverteidigung, Gewaltschutz)
**Später möglich:** Mehrfachzuordnung
- `["karate", "selbstverteidigung"]` - Fähigkeit in beiden Bereichen relevant
- `["karate", "gewaltschutz"]` - etc.
### 2. Mehrfachzuordnung von Übungen (§10.7)
**Prinzip:** Eine Übung kann mehreren Bereichen GLEICHZEITIG zugeordnet sein.
@@ -188,6 +209,161 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
---
## Fähigkeiten-Domäne (§8.3, erweitert ab Migration 022+023)
### Fähigkeiten-Hierarchie
**🆕 3-Ebenen-Struktur (ab Migration 022):**
```
Haupt-Kategorie (2 Stück)
├─ KARATE Fähigkeiten
│ ├─ Kihon (Unterkategorie)
│ │ ├─ Dachi Waza (Fähigkeit, Level 1-5)
│ │ ├─ Uke Waza
│ │ └─ ...
│ ├─ Kumite
│ ├─ Kata
│ └─ Selbstverteidigung
│
└─ ALLGEMEINE sportliche Fähigkeiten
├─ Koordination (Unterkategorie)
│ ├─ Orientierung (Fähigkeit, Level 1-5)
│ └─ ...
├─ Kondition
├─ Kognition
├─ Soziale Fähigkeiten
└─ Psychische Fähigkeiten
```
### Haupt-Kategorien
**1. KARATE Fähigkeiten** (`focus_areas: ["karate"]`)
- **Anzahl:** 32 Skills
- **Bedeutung:** Karate-spezifische Techniken und Fähigkeiten
- **Verwendung:** Nur für Karate-Training relevant
- **Unterkategorien:** Kihon, Kumite, Kata, Selbstverteidigung
**2. ALLGEMEINE sportliche Fähigkeiten** (`focus_areas: ["universal"]`)
- **Anzahl:** 37 Skills
- **Bedeutung:** Universelle sportliche und mentale Fähigkeiten
- **Verwendung:** Für ALLE Trainingsbereiche einsetzbar
- **Unterkategorien:** Koordination, Kondition, Kognition, Soziale Fähigkeiten, Psychische Fähigkeiten
### Unterkategorien
#### KARATE Fähigkeiten
**Kihon (Grundtechniken) - 10 Skills:**
- Dachi Waza (Standtechniken)
- Uke Waza (Blocktechniken)
- Zuki Waza (Stoßtechniken)
- Uchi Waza (Schlagtechniken)
- Geri Waza (Tritttechniken)
- Nage Waza (Wurftechniken)
- Nukite Waza (Fingerstichtechniken)
- Ken Waza (Fausttechniken)
- Hüfteinsatz
- Kime (Fokussierung)
**Kumite (Kampf) - 10 Skills:**
- Beinarbeit
- Distanzkontrolle
- Angriff
- Abwehr Konter
- Präzision
- Antizipation
- Timing
- Taktik
- Fokus
- Mentale Stärke
**Kata (Formen) - 8 Skills:**
- Technik Kombination
- Kata Ablauf
- Bunkai (Anwendung)
- Oyo (Variation)
- Henka (Veränderung)
- Kakushi (Versteckte Techniken)
- Kata Atmung
- Kata Rhythmus
**Selbstverteidigung - 4 Skills:**
- Gefahrenbewustsein
- Selbstbehauptung
- Selbstschutz
- Gefahrenabwehr
#### ALLGEMEINE sportliche Fähigkeiten
**Koordination - 7 Skills:**
- Orientierung
- Differenzierung
- Kopplung
- Gleichgewicht
- Rhythmisierung
- Reaktion
- Umstellung
**Kondition - 15 Skills:**
- Kraftfähigkeiten: Maximalkraft, Schnellkraft, Reaktivkraft, Kraftausdauer, Muskelaufbau
- Schnelligkeitsfähigkeiten: Reaktionsschnelligkeit, Bewegungsschnelligkeit, Handlungsschnelligkeit, Schnelligkeitsausdauer
- Ausdauerfähigkeiten: Grundlagenausdauer, Aerobe Ausdauer, Anaerobe Ausdauer
- Regenerationsfähigkeiten: Regenerationsfähigkeit, Ermüdungswiderstandsfähigkeit
- Beweglichkeit: Flexibilität
**Kognition - 5 Skills:**
- Aufmerksamkeit
- Wahrnehmung
- Urteilsvermögen
- Merkfähigkeit
- Lernfähigkeit
**Psychische Fähigkeiten - 6 Skills:**
- Selbstvertrauen
- Konzentration
- Emotionale Kontrolle
- Motivation
- Stressresistenz
- Stressregulation
**Soziale Fähigkeiten - 4 Skills:**
- Deeskalation
- Selbstdisziplin
- Toleranz
- Fairness
### Level-Definitionen (Reifegradmodell)
**Konzept:** Jede Fähigkeit hat 5 Stufen mit konkreten Beschreibungen.
**Struktur (noch nicht vollständig implementiert):**
- **Level 1:** Einsteiger - Grundlegende Ausführung
- **Level 2:** Grundlagen - Kontrollierte Ausführung
- **Level 3:** Aufbau - Sichere Anwendung
- **Level 4:** Fortgeschritten - Variable Anwendung
- **Level 5:** Experte - Meisterhafte Beherrschung
**Beispiel (Dachi Waza - Standtechniken):**
- Level 1: Stabiler Stand mit Schwerpunkt und richtiger Ausrichtung
- Level 2: Korrekter Stand mit guter Balance in verschiedenen Positionen
- Level 3: Fließender Wechsel zwischen Ständen mit Kontrolle
- Level 4: Dynamische Stand-Variationen unter Belastung
- Level 5: Perfekte Stand-Technik in allen Kampfsituationen
**Datenbankstruktur:**
```sql
skill_level_definitions (
skill_id,
level (1-5),
description (Text aus Fähigkeitsmatrix)
)
```
**Status:** Schema vorhanden (Migration 022), Daten noch nicht importiert (optional für spätere Phase).
---
## Übungs-Zuordnungslogik (§10)
### Primäre vs. Sekundäre Zuordnung
@@ -223,19 +399,23 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
**Beispiel:** "Kumite-Drill"
**Hauptfähigkeiten:**
- Distanzgefühl (Intensität: hoch)
- Timing (Intensität: hoch)
- Distanzkontrolle (Kumite, target_level: 3, intensity: hoch)
- Timing (Kumite, target_level: 3, intensity: hoch)
**Nebenfähigkeiten:**
- Beinarbeit (Intensität: mittel)
- Reaktionsfähigkeit (Intensität: mittel)
- Beinarbeit (Kumite, target_level: 2, intensity: mittel)
- Reaktion (Koordination, target_level: 2, intensity: mittel)
**Attribute pro Fähigkeitsbezug:**
- is_primary (Haupt- oder Nebenfähigkeit)
- intensity (niedrig/mittel/hoch)
- development_contribution (Entwicklungsbeitrag)
- required_level (Voraussetzung)
- target_level (Ziel-Level)
- required_level (Voraussetzung, 1-5)
- target_level (Ziel-Level, 1-5)
**🆕 Fokusbereich-Filterung:**
- Bei Übungen mit Fokusbereich "Karate" sollten primär KARATE-Fähigkeiten zugeordnet werden
- ALLGEMEINE Fähigkeiten können als Nebenfähigkeiten hinzugefügt werden
- Bei universellen Übungen (Selbstverteidigung, Gewaltschutz) bevorzugt ALLGEMEINE Fähigkeiten
### Trainingscharakter (§10.7)
@@ -276,6 +456,34 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
- Abweichende Zielgruppen
- Eigener Medienbezug
**Umsetzung (Trainingsplanung):** Ein Eintrag in `training_unit_exercises` kann optional eine konkrete Varianten-ID (`exercise_variant_id`, Migration 030) tragen; Bindung wird gegen die gewählte Übung validiert. Varianten werden über die Übungs-API verwaltet (`technical/EXERCISES_API_SPEC.md`).
### Progressionsgraph zwischen Übungen (Zwischenstand, CURR‑002 Stufe 1)
**Abgrenzung:** Zusätzlich zur Varianten-Reihe **innerhalb** einer Übung gibt es optional einen **Bibliotheks-Progressionsgraphen**: gerichtete Kanten zwischen **Übungen** (Knoten optional auf konkrete **Varianten** eingegrenzt). Gemeinsamer Kontainer pro Graph (`exercise_progression_graphs`); Kanten mit Typ z. B. Nachfolger oder Schwester.
**Rolle:** **unterstützend** für Planung und spätere Rahmenprogramme — keine Pflicht, jeden Trainingsablauf als Graph zu modellieren (**CURR‑013**).
**Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4.
### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009)
**Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**).
**Bibliothek only (036):** Kein Kopf‑`plan_mode`/keine Kopf‑`group_id`; Zuordnung zu Gruppe und Datum erfolgt nur über **kopierte** Kalender‑`training_units` (Instanz).
**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**).
---
## 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.
---
## Methodenbezug (§11.5)
@@ -314,12 +522,45 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
- Offiziell (Standardinhalte)
**Zusätzlich:** Thematische Einschränkungen
- Karate-Inhalte
- Karate-Inhalte (nur Übungen mit `focus_areas: ["karate"]`)
- Selbstverteidigungs-Inhalte
- Gewaltschutz-Inhalte
---
## MediaWiki Import (ab Migration 018)
### Import-Typen
**1. Übungen** (`import_type: exercise`)
- Quelle: https://karatetrainer.net `Kategorie:Übungen`
- Import-Modus: Vollständig mit Skill-Zuordnungen
- Status: ✅ Produktiv (221 Übungen importiert)
**2. Fähigkeiten** (`import_type: skill`)
- Quelle: https://karatetrainer.net `Kategorie:Fähigkeitsbeschreibung`
- Import-Modus: DEPRECATED - Nutze Migration 023 stattdessen
- Status: ⚠️ Migration 021 fehlerhaft, ersetzt durch Migration 023
**3. Trainingsmethoden** (`import_type: method`)
- Quelle: https://karatetrainer.net `Kategorie:Methodenbeschreibung`
- Import-Modus: Vollständig
- Status: 🔲 Noch nicht implementiert
### Import-Tracking
**Duplikat-Erkennung:**
- Über `wiki_import_references` Tabelle
- Verknüpfung `wiki_page_id` → `local_id`
- Reimport aktualisiert bestehende Einträge
**Import-Metadaten:**
- `import_source = 'mediawiki'`
- `import_id` = Wiki-Seitentitel
- `wiki_page_id` = MediaWiki interne Page-ID
---
## Admin-Workflows
### Fokusbereich anlegen
@@ -344,7 +585,7 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
- Ziel-Fokusbereich existiert
- Keine Namenskonflikte
5. System aktualisiert:
- `training_styles.focus_area_id`
- `style_directions.focus_area_id`
- Alle abhängigen Zielgruppen bleiben erhalten
6. System loggt Änderung
7. Erfolg-Meldung
@@ -358,7 +599,7 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
2. Klickt "Löschen"
3. System prüft Abhängigkeiten:
```sql
SELECT COUNT(*) FROM training_styles WHERE focus_area_id = :id
SELECT COUNT(*) FROM style_directions WHERE focus_area_id = :id
SELECT COUNT(*) FROM exercise_focus_areas WHERE focus_area_id = :id
```
4. **Falls verwendet:**
@@ -396,15 +637,15 @@ Jede Kombination (Fokusbereich + Stil + Zielgruppe) kann ein eigenes Reifegradmo
## Nächste Schritte
- [ ] Hierarchie-UI Wireframes erstellen
- [ ] Admin-CRUD-Endpoints spezifizieren
- [ ] Cascade-Logik detaillieren
- [ ] Umrouten-Workflows implementieren
- [ ] Migration 008 Entwurf finalisieren
- [ ] Tests für alle Admin-Operationen
- [ ] Level-Definitionen aus Fähigkeitsmatrix extrahieren (optional)
- [ ] Skills-Beschreibungen aus Wiki importieren (Migration 024)
- [ ] Admin-UI für Fähigkeiten-Kategorien (CRUD)
- [ ] Skill-Filter in Übungssuche integrieren
- [ ] Reifegradmodelle definieren (Kombination Fokusbereich + Stil + Zielgruppe)
- [ ] KI-Unterstützung für Trainingsplanung (basierend auf Fähigkeiten-Level)
---
**Letzte Aktualisierung:** 2026-04-23
**Letzte Aktualisierung:** 2026-04-27
**Verantwortlich:** Claude Code
**Review:** Pending
@@ -0,0 +1,14 @@
# Shinkan Jinkendo – Anforderungen (Index)
Ausführliche fachliche Inhalte:
| Dokument | Inhalt |
|----------|--------|
| [shinkan_anforderungsdokument_entwurf.md](./shinkan_anforderungsdokument_entwurf.md) | Gesamtentwurf Anforderungen |
| [DOMAIN_MODEL.md](./DOMAIN_MODEL.md) | Domänenmodell, Variantenlogik (§11.2), **Medien-Archiv** (Abschnitt 2026-05) |
| [MEDIA_ASSETS_AND_ARCHIVE_SPEC.md](../technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) | Medien-Archiv, Lifecycle, **geplante Inline-Medien §11** |
| [MULTI_TENANCY_RBAC_ARCHITECTURE.md](../technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md) | Zielarchitektur Mandanten/Rollen/Membership & Umsetzungsplan |
**Lieferstand & Umsetzung (Stand Code):** [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md), [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md) §12, Repo-Root **`docs/HANDOVER.md`**.
`CLAUDE.md` (Repo-Root) verweist hierher als Einstieg.
@@ -0,0 +1,225 @@
# Konzept: Trainingsplanung über Einheiten hinweg, Kurspläne, Governance, Assessments
**Status:** Arbeitspapier (lebend)
**Stand:** 2026-05-05 (Rahmen‑Bibliothek **036**, Slot‑Blueprint **037** / API `from-framework-slot`; CURR‑002 Stufe 1 Graph unverändert 032–034)
**Zweck:** Erkenntnisse und **getroffene Entscheidungen** festhalten, um Spec- und Implementierungsdrift zu vermeiden.
**Kanons:** Bei Widersprüchen mit produktiven Specs zuerst diese Datei mit dem Team abstimmen; technische Details ergänzen später in `technical/`.
---
## 1. Kurz-Zielbild (Problem)
- **Heute:** Planung denkt stark pro **einer** Trainingseinheit (Struktur + Übungen).
- **Gewünscht:**
- **Trainingsrahmenprogramm** (über **mehrere** Session-Slots): **mehrere** **Entwicklungsziele** über denselben Zeitraum sowie **Zuordnung von Übungen** zu Sessions; unterstützt **manuelle** Verteilung (ohne Pflicht-Progressionsgraph) und optional **persistente Progressionsbäume** (v. a. Verwalter) — siehe CURR‑010, CURR‑011, CURR‑013.
- **Mehrwöchige / periodische Planung** (z. B. Monat) mit **Entwicklungszielen** und Verteilung aufbauender Elemente über **mehrere Einheiten** – auch **ohne** vollständiges „Kursprogramm“-Produkt.
- **Standard-Kurs-/Stufenpläne** (zeitlos, mehrschrittig) als Basis für konkrete Durchführung; Instanzen **editierbar ohne** Änderung der Vorlage.
- **Governance** einheitlich über Domänen (Übungen, Verein, Trainingspläne, Kurspläne …), ohne spätere Modellbrüche.
- **Nachvollziehbarkeit:** real durchgeführte Einheiten an Pläne/Vorlagen zurückführen; **Feedback** zur Verbesserung von Standardplänen.
- **Assessments** als Spezialfall eines Plans (Tests, z. B. Gürtel), später ggf. Teilnehmerbezug und Erwartungsniveau.
---
## 2. Geführte Konzepterstellung (Arbeitsschritte)
**Konzept-Arbeit:** Ziele klären → Optionen → **Entscheidung** in §5 → Glossar §4 pflegen.
### 2.a Umsetzungs-Reihenfolge „Rahmenprogramm“ (product / binding laut CURR-001–002)
| Stufe | Inhalt | Status |
|--------|--------|--------|
| **1** | **Progressionsbezüge** zwischen Übungen **persistent speicherbar** (Progressionsbaum / -graph zwischen Übungseinheiten, nicht nur UI) | ✅ **Zwischenstand im Produkt** (Migrationen 032–034, UI/API); UX für **parallele gleichwertige Alternativ‑Pakete** noch kein Erstklass‑Fall — siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4 |
| **2** | **Planungs-/Rahmenmodus:** Übungen auf **mehrere** Session-Slots verteilen; **mehrere Ziele**; speicherbare Rahmen-Vorlage (CURR‑002 (2) i. V. m. **CURR‑010–013**) | **in Arbeit**: Bibliotheks‑Backend + Slot‑Blueprint + Kopie‑API (**037**); **UI Kalender**/Bulk folgt (**CURR‑012**) |
| **3** | **Konkrete Einheit:** aus Rahmen-/Verteilungsplan **Vorschläge** beim Ausarbeiten laden; Bezug zur Idee **„Warenkorb“** bei der Übungsplanung | folgt nach 2 |
### 2.b Übrige Konzept-Schritte (noch durchzuarbeiten)
| Schritt | Thema | Status |
|--------|--------|--------|
| **A** | Scope & Reihenfolge relativ zu Kursprogramm, Backlog-Themen | ✅ siehe §5 CURR-001–004 |
| **B** | **Governance-Muster** (einheitliche Sichtbarkeit; Bibliothek vs. Instanz) | ✅ Leitplan §2.c; Entscheidungen §5 CURR-005–007 |
| **C** | **Rahmenprogramm** — §2.d (**C1–C4** ✅ · **C5** Leitplan) | ✅ Kern i. V. m. **CURR‑009–013** |
| **D** | **Kurs-/Stufenprogramm:** nach Rahmenprogramm; plantechnisch ähnlich | 📌 zeitlich nachgelagert (CURR-003) |
| **E** | **Lineage & Feedback** (Einheit ↔ Vorlage/Rahmen; Issues zur Nachbesserung) | ➕ **teilweise:** `training_units.origin_framework_slot_id`; vollständiges Konzept/UX offen |
| **F** | **Assessments** | 📌 Backlog (CURR-003) |
| **G** | **Progressions-Automatik** (KI, komplexe Vorschläge) | 📌 Backlog (CURR-003) |
**Aktueller Fokus:** **Kalender-/Planungs‑UI** an **`POST /api/training-units/from-framework-slot`** und Visibility für geteilte Rahmen; weiteres Lineage (**Schritt E**) ergänzend zu **`origin_framework_slot_id`**.
---
### 2.c Schritt B – Governance-Muster (Leitplan)
#### B.1 Ziel
Ein **wiedererkennbares Muster** für alle **Bibliotheksobjekte** (Übung, Trainingsplan-Vorlage, Übungsblock, künftig Rahmen-/Kurs-Vorlage, Progressions-Paket …), damit **CURR-004** (spätere Rechte nach Rolle/Zugehörigkeit) **ohne Modellbruch** nachrüstbar ist.
#### B.2 Ist-Stand im Produkt (kurz, Stand Code-Review)
| Objekt | Relevante Felder / Muster |
|--------|---------------------------|
| `exercises`, `exercise_blocks` | `visibility` ∈ `private` \| `club` \| `official`, `club_id`, `created_by` — **Referenzmuster** |
| `training_plan_templates` | `club_id`, `created_by`, **`visibility`** seit **035** (Backfill **`club`**); Referenz‑Muster an Übung angleichen (**CURR‑007** erledigt für dieses Feld) |
| `training_framework_programs` | `visibility`, `club_id`, `created_by`; Kontext `focus_area_id`, `style_direction_id`; keine Kopf‑`group_id`; Slot‑Inhalt über **Blueprint‑`training_units`** (**036–037**) |
| `training_units` | `group_id`, `created_by`, `plan_template_id` — **Instanz** oder **Blueprint** (`framework_slot_id`); Lineage‑Light **`origin_framework_slot_id`** |
#### B.3 Prinzipien (binding mit §5)
1. **Bibliothek vs. Instanz**
- **Bibliothek:** zeitlose Objekte (Übung, Vorlage, Rahmen-Template, Graph-Definition …). Tragen **Sichtbarkeits-Metadaten** nach gemeinsamem Muster.
- **Instanz:** z. B. `training_unit` am Termin; **inhaltliche** Bearbeitung **entkoppelt** von der Vorlage (**Kopie** der Struktur, nicht „Live-Link“ zur Überschreibung der Vorlage).
- Zugriff auf Instanzen: primär über **Trainingsgruppe / Rolle** (Trainer, Co-Trainer); **nicht** zwingend über `visibility` der Vorlage dublett führen in Phase 1.
2. **Einheitlicher Governance-Kern für neue & nachzuziehende Bibliothekstypen**
- Minimal: **`visibility`** (gleiche Semantik wie bei Übungen), **`club_id`** (optional, NULL = nicht vereinsgebunden / global nutzbar je nach Policy), **`created_by`**.
- **Sparte (`division`):** optional später **`division_id`** oder M:N — **nicht** im MVP-Kern erzwingen, damit keine parallele „Rights-Welt“ pro Objekttyp entsteht.
3. **Policy vs. Speicherung**
- DB-Felder beschreiben **„wem gehört es / welche Lesestufe“** intentionell; **durchsetzende** Filter in API/UI folgen schrittweise (CURR-004).
- Vermeiden: Objekttypen mit völlig anderen Spaltennamen für dieselbe Idee (`owner` vs `created_by` ohne Konvention).
4. **Herkunft / Lineage (nur Metadaten)**
- Wo sinnvoll: `plan_template_id`, später `framework_program_template_id`, optional `forked_from_*` für **Nachvollziehbarkeit** ohne Kopplung für Writes.
- Detail Arbeitspaket **Schritt E**; nicht mit Governance-Kern vermischen.
5. **Progressionsgraph**
- Als eigener Bibliotheks-**Kontainer** oder als **Annotion** an Übung(en): gleicher Governance-Kern; **Ausnahmen** nicht vorwegnahmen ohne technische Spec (§6 offene Fragen).
#### B.4 Bewusste Nicht-Ziele in diesem Schritt
- Keine endgültige **Matrix** „Welche Rolle sieht welches `official`“.
- Keine Pflicht-Anbindung Sportler/Lehrender außerhalb bestehender Gruppenmitgliedschaft.
---
### 2.d Schritt C – Trainingsrahmenprogramm (Ausarbeitung · Status **Kern geklärt**)
#### Checkliste — Abgleich Produktfeedback 2026‑04‑29
| Check | Ergebnis | Verweis |
|-------|----------|---------|
| **C1** | ✅ **Eigene Rahmen-Entität** (C1a) — nicht die Einheitenvorlage überladen | **CURR‑009** |
| **C2** | ✅ Slots erlauben **beliebige Übungen** über Trainings-/Slots zu verteilen; **persistenter Progressionsgraph** ist **unterstützend**, **Pflicht‑Pflege** im Graph gilt **nicht** (Admin‑Aufwand; v. a. global) | **CURR‑010**, **CURR‑013** |
| **C3** | ✅ Über denselben Planungszeitraum **mehrere** gleichzeitige **Entwicklungsziele** (nicht nur ein Sammelfeld) | **CURR‑011** |
| **C4** | ✅ **Zwei Nutzungsbilder**, kein „entweder C4a oder C4b global“ — siehe Ausführungen unten zu **Konkret** vs. **Bibliothek** | **CURR‑012** |
| **C5** | ✅ `training_plan_template` bleibt **eine‑Einheit‑Mikrovorlage**; Rahmen adressiert **n** Sessions; pro Slot weiterhin möglich: **optional** `training_plan_template_id` (Technical Spec entscheidet MVP‑Pflicht) | Glossar |
---
#### C4 verständlich: **„Materialisierung“** = zwei echte Situationen
| Nutzungsbild | Kontext | Gruppe / Datum | Typische Persistenz‑Schicht |
|--------------|---------|----------------|----------------------------|
| **A – Kurzfrist‑ / Basisplanung („nächste Wochen“)** | Konkret für **eine Trainingsgruppe** geplant | **Immer:** Gruppe + Termin(e) wie heute beim Training | Existierende oder neu angelegte **`training_units`**; Rahmen fungiert als **Planhilfe**/Vorlage **über mehrere dieser Einheiten** |
| **B – Kursprogramm-/Lehrplan‑Bibliothek** | Übergeordnete **Struktur** ohne laufenden Kurs | **In der Bibliotheksvorlage selbst oft:** keine Gruppe/Zeit | Rahmen-/Kurs‑Vorlage **zeit‑ und gruppenlos** gespeichert; **Übertrag** (`Instanziierung`) erst bei „wir machen einen Kurs daraus“: dann Wahl **Gruppe + Zeitraum** → Anlegen oder Befüllen von **`training_units`** |
**Klartext zur früheren Frage „C4a vs. C4b“:** Bei **Modus A** passen **automatisches Anlegen n Einheiten** (früheres C4a) **oder** Zuordnung zu **bereits geplanten** Einheiten (C4b) — je nach Produkt/UI. Bei **Modus B** existieren erst bei der Übernahme überhaupt Gruppe/Zeiten; die Bibliotheksvorlage bleibt **neutral**.
**Stand Code 036–037:** Am Rahmenkopf gibt es **keine** **`plan_mode`/`group_id`** mehr — die Bibliothek ist immer „Modus B“; konkrete Gruppe/Zeit entstehen **nur** in **`training_units`** (Kalender‑Zeilen oder Übernahme‑API **`from-framework-slot`**).
---
#### C2 (Klärung fürs Team)
„**C2**“ im Entwurf bezog sich auf „**wie** weiß ich pro Slot welche Übungen (nur Progression oder auch Mikro‑Vorlage)?“ — **aktueller Beschluss:**
Pro Slot: **Zuordnung von Übung(en)** als **Teil des vollständigen Ablaufs** (wie geplante Einheit: **Sektionen und Items**, **037**) ist **tragend**; **Progressionsgraph** liefert **Vorschläge / Pakete**, wenn Admins sie pflegen — **Trainer** können **ohne** Graph planen.
---
#### C1/Erinnerung Checkbox (historisch)
- **`[x] C1a`** eigene Rahmen‑Entität bestätigt (Chat 2026‑04‑29).
---
*Konkretisierung technischer Felder (ein Objekt zwei Modi vs. zwei Typen) → **Technical Spec**; keine neuen Contradicts zu CURR‑001 ohne expliziten Beschluss.*
---
## 3. Richtungen aus Diskussion (nicht-binding, wenn nicht in §5)
| Thema | Richtung |
|--------|----------|
| Assessments als Plantyp | **Spezielle Form eines Trainingsplans**; Test-Übungen; später **Sportlerbezug**/Erwartungsniveau (Gürtel) — aktuell **Backlog**, siehe CURR-003. |
| Bibliothek vs. Durchführung | Konkrete Pläne/Einheiten editierbar **ohne** Änderung am Standard-/Rahmen-Template (**Kopien / Instanzen**). |
*Scope-Reihenfolge und Governance-Startpunkt sind ab 2026-04-29 in §5 festgehalten (CURR-001 bis CURR-004).*
---
## 4. Glossar (wird ergänzt)
| Begriff | Bedeutung (vorläufig) |
|---------|------------------------|
| **Bibliotheksobjekt** | Zeitlose Vorlage (Übung, Trainingsplan-Vorlage, Kursrahmen, später Assessment-Vorlage …) |
| **Governance-Kern** | Einheitliches Minimalset an Metadaten für Bibliotheksobjekte: v. a. `visibility`, `club_id`, `created_by` (siehe §2.c) |
| **Instanz (Training)** | `training_unit` o. Ä.; Zugriff über Gruppe/Rolle; Inhalt als **Kopie** aus Vorlagen, nicht schreibend an Vorlage gekoppelt |
| **Trainingsrahmenprogramm** | Über **mehrere Session-Slots**: **mehrere gleichzeitige Entwicklungsziele** und **Zuordnung von Übungen** zu Slots/Einheiten; **manuelle** Zuordnung + optional **Progression** (**CURR‑010**, **CURR‑011**, **CURR‑013**) |
| **Progressionsbaum / -graph** | Optionale gerichtete Beziehungen **zwischen Übungen** zur **Unterstützung** beim Planen (**CURR‑010** — **kein Pflicht‑Pflegeschritt für jede Zuordnung**); v. a. für globale Pflege |
| **Rahmen-Vorlage** („Framework“) | Bibliothekskontainer mit **ordered Slots**, **zeitlos möglich** (Modus B) oder im Konkretkontext an Gruppe geknüpfte Planung (**CURR‑012**); eigene Entität (**CURR‑009**) |
| **Slot** | Position in der Reihenfolge eines Rahmens; trägt **Übungszuweisungen** („Stückliste“), optional Hinweise/Text; Datum optional bis Materialisierung |
| **Materialisierung / Instanziierung** | Überführung aus (ggf. zeit‑/gruppenloser) **Rahmen-Bibliothek** in konkrete **`training_units`** mit Gruppe/Zeitraum — **CURR‑012 Modus B**. Modus A bleibt nahe bestehender Einheiten-Planung |
| **Konkret-Planung (Modus A)** | Mehr‑Wochen für **bekannte** Trainingsgruppe + Terminen — **`training_units`** |
| **Bibliotheks-Rahmen (Modus B)** | Strukturierte Vorlage ohne Gruppe/Uhrzeit („Kursprogramm“‑Wurzel bis zum Import in einen Kurs) |
| **Kursprogramm** | Wie Curriculum-/Stufen-Standard; **planerisch nachgelagert** an Rahmenprogramm (CURR-003) |
---
## 5. Entscheidungsprotokoll (binding)
| ID | Datum | Entscheidung | Begründung / Kontext |
|----|--------|---------------|---------------------|
| **CURR-013** | 2026-04-29 | Präzisierung zu **CURR‑002 (1)+(2)**: **Persistenter Progressionsgraph** ist **unterstützend**, **nicht** die alleinige Quelle für Slot‑geplante Übungen. Der Planungsmodus **muss beliebige Übungen** auf Slots verteilen **ohne** Pflicht zur Graph‑Pflege im Alltag. Reichhaltiges Pflegen von Progressionsbezügen v. a. durch **globale Verwalter** erwünscht, nicht verpflichtend pro Übungszuordnung. | Chat C2 |
| **CURR-012** | 2026-04-29 | **Zwei Nutzungsbilder:** **Modus A (Konkret)** — Mehr‑Wochenplan für **bekannte Trainingsgruppe + Termine** → bestehende/neue **`training_units`**; Rahmen als Planhilfe über mehrere Einheiten. **Modus B (Bibliothek)** — **Kurs-/Stufen‑Struktur ohne** Gruppe/Uhrzeit bis zur **Übernahme**; dann Zuordnung von Gruppe+Zeitraum und **Instanziierung** in **`training_units`**. Bulk‑Anlegen (**C4a**) und Verknüpfen existierender (**C4b**) sind **Modus‑A‑Alternativen**. | Chat C4 |
| **CURR-011** | 2026-04-29 | **Mehrere parallele Entwicklungsziele** im selben Planungszeitraum → Datenmodell: **Zielliste mit ≥1 Einträgen** auf Rahmen‑Ebene (Details Technical Spec). **Nicht** nur ein einziges Sammelziel‑Feld. | Chat C3 |
| **CURR-010** | 2026-04-29 | **Slot‑Inhalt:** tragend **direkte Zuordnung beliebiger Übungen** („Stückliste“); Option **Graph** für Vorschläge/Anreicherung. **`training_plan_template_id` pro Slot** weiterhin **optional** (MVP offen). | Chat C2 |
| **CURR-009** | 2026-04-29 | **C1a:** **Neue eigene Bibliotheks‑Entität** für Mehr‑Slot‑Rahmen (**Framework**/`training_framework_*`-Arbeitscode); **`training_plan_template`** bleibt **eine Einheit**‑Mikrovorlage (**C5**). | Chat C1 |
| **CURR-008** | 2026-04-29 | **Migration / Backfill (Early-Installation):** Migrationen betreffen aktuell nur **frühe Systeme ohne weitere Nutzer**. Vereins‑Zuordnung für Bestands-/Default‑Zeilen erfolgt beim Backfill mit dem **Standard‑Verein der Installation** (konkret: Club‑ID bzw. Konvention im Migrate‑Skript dokumentieren — z. B. erster Verein oder `DEFAULT_CLUB_ID` in Env). **`visibility`**-Default beim Hinzufügen der Spalte: **`club`**, wenn fachlich alles diesem Vereinskontext zugeordnet wird; anderenfalls bei Multi‑Tenant eigene Migrate‑Anweisung. | Nutzerfestlegung; pragmatisches Backfill ohne Mehr‑Mandanten‑Heuristik; §6 entsprechend vereinfacht. |
| **CURR-007** | 2026-04-29 | **`training_plan_templates`** weichen aktuell vom Übungs-Muster ab (**kein** `visibility`). **Festlegung:** Bei der nächsten sinnvollen Migration auf den **gemeinsamen Governance-Kern** angleichen (**`visibility`** zusätzlich zu `club_id` / `created_by`), Semantik **analog zu Übungen** im Vereinskontext; von dieser Linie nur abweichen, wenn ausdrücklich anders dokumentiert. | Bekannte Schulden bis Migration vermeiden; neue Objekttypen sollen CURR-005 folgen; Zuordnung/Backfill **CURR‑008**. |
| **CURR-006** | 2026-04-29 | **Instanz-Ebene (`training_unit` u. Ä.):** In der Rahmenprogramm-Phase **keine** neue parallele `visibility`-Schicht auf der Einheit; **Zugriff** über **`group_id`** und bestehende Trainer-/Mitgliedschaftslogik. **Lineage** zu Vorlagen/Rahmen nur als **optionale Metadaten-FKs** (`plan_template_id`, spätere Erweiterungen), ohne dass Schreiben in der Einheit die Vorlage ändert. | CURR-004-kompatibel: API-Policy später ergänzbar ohne Instanz-Umbau. |
| **CURR-005** | 2026-04-29 | **Governance-Kern für Bibliotheksobjekte** (Übung, neue/alte Vorlagen, künftig Rahmen-/Kurs-/Progressions-Container): **`visibility`** im Sinne von `exercises` (`private` \| `club` \| `official`), **`club_id`** optional (NULL wenn nicht vereinsspezifisch), **`created_by`**. Sparte später optional **`division_id`** oder Verknüpfungstabelle — **nicht** Blocker für ersten Progressions-/Rahmen-Entwurf. | Einheitliche Semantik; Altabweichungen gezielt nachziehen (CURR-007). |
| **CURR-004** | 2026-04-29 | **Sichtbarkeit:** Aktuell **globale Nutzungs-/Planungssicht** für alle; Architektur und Datenmodell aber **von Anfang an** so gestalten, dass **spätere** Einschränkungen nach Rollen und Zugehörigkeiten (Verein, Gruppe, Sparte …) ohne Bruch eingeführt werden können. | Vorbereitung einheitlicher Governance; siehe CURR-005/006 für Konkretisierung. |
| **CURR-003** | 2026-04-29 | **Nachgelagert / explizites Backlog (nicht Phase Rahmenprogramm):** **Kursprogramm** kommt nach dem Rahmenprogramm (planerisch ähnlich); **Assessments**, **Sportlerakte**, **KI-Optimierungen** ebenfalls zurückgestellt bis Rahmenkern steht. | Priorität liegt auf Persistenz Progression → Multi-Einheiten-Planung → Einheitenvorschläge. |
| **CURR-002** | 2026-04-29 | **Umsetzungsreihenfolge Rahmenprogramm:** **(1)** Progressionsbezüge **zwischen Übungen** müssen als **persistierter Graph/Baum** modellierbar sein. **(2)** **Planungsmodus**, der **Übungen** (u. a. aus Progression, **auch manuell**, **CURR‑010**) **auf mehrere Trainingseinheiten verteilt**, **mehrere Ziele** (**CURR‑011**) enthält und als **speicherbares Rahmen‑Template** dient. **(3)** **Warenkorb**-Idee beim Ausarbeiten einer **einzelnen** Einheit. | Reihenfolge vom Datenkern zur UX; Zuordnung/Graph **CURR‑013** |
| **CURR-001** | 2026-04-29 | Vor dem separaten Produkt **„Kursprogramm“** wird das **„Trainingsrahmenprogramm“** (Ziele + Progression über mehrere Einheiten) angegangen — **nicht** umgekehrt. | Kursprogramm baut auf derselben Planungslogik auf; erst gemeinsamen Kern liefern. |
*Format:* Neue Zeile **oben** einfügen (neueste zuerst).
---
## 6. Offene Fragen (Backlog)
- **Minimal-UI** Rahmenprogramm vs. bestehende Kalender/Liste `training_units`?
- ~~Governance Migrate Default~~ → **CURR‑008**
- ~~Slots / C4 generisch~~ → **CURR‑012** (Modi A/B)
- ~~Relation zwei Vorlagenfamilien~~ → **CURR‑009** (**Rahmen** neu, **Einheit** bleibt `training_plan_template`)
- **Technical:** ~~gleiche DB‑Entität mit `plan_mode` (**A \| B**) vs. **konsequente Teilung** zweier Objekttypen?~~ → **Festgelegt:** eine Entität **`training_framework_programs`** + **`plan_mode`**; siehe **`technical/TRAINING_FRAMEWORK_SPEC.md` §2.0**.
- **Progressionsgraph:** Kantentypen (nächste Übung vs. **Variante** vs. Level innerhalb gleicher Übung); optional **Skills**-Anbindung
---
## 7. Produkt-Backlog (explizit, nicht aktuelle Phase)
Siehe **CURR-003:** Kurs-/Stufenprogramm (nach Rahmenkern), Assessments (Plantyp/Testübungen/Sportler), Sportlerakte, KI-/optimierungsunterstützte Planung.
---
## 8. Nächste Aktion (für dich / Team)
1. ~~**Schritt C**~~ · siehe §2.d · **CURR‑009 bis CURR‑013**
2. ~~Progressionsgraph Stufe 1~~ ✅ siehe **`technical/TRAINING_FRAMEWORK_SPEC.md`** §3–§4 · **Jetzt:** **`TRAINING_FRAMEWORK_SPEC.md`** §2 (Checkliste) mit **DDL-/API-Abschnitt Rahmen** ergänzen (**CURR‑002 (2)**); Modus A/B siehe Funktionskonzept §6
3. **Migrate** weiter **CURR‑007 / CURR‑008** (ideal parallel oder vor erster Rahmen‑Migration mit neuem Bibliothekstyp)
4. Konzeptpaket optional **Schritt E** Lineage vor Implementierung Großrelease
---
## 9. Changelog dieser Datei
| Datum | Änderung |
|-------|-----------|
| 2026-04-30 | §8 Punkt 2 angepasst (Graph ✅; nächster Fokus Rahmen‑Spec **CURR‑002 (2)**). |
| 2026-04-28 | Technische Ausarbeitung gebündelt: neue Datei **`technical/TRAINING_FRAMEWORK_SPEC.md`** (Stub); Verweis §8. |
| 2026-04-29 | **CURR‑009–013**, **CURR‑002** präzisiert; Glossar Modi A/B Slot; §2.d C geklärt; §6‑Backlog gekürzt. |
| 2026-04-29 | CURR‑008 (Migration Standard‑Verein); **§2.d Schritt C** Checkpoints C1–C5; Glossar/§6 angepasst. |
| 2026-04-29 | CURR-001–004; Umsetzungsreihenfolge §2.a; Glossar Rahmenprogramm/Progressionsgraph; Scope-Backlog. |
| 2026-04-28 | Erstanlage aus Konzept-Arbeitsphase Chat; Schritttabelle und Protokollstruktur. |
@@ -0,0 +1,173 @@
# Gelieferte Features & technische Basis (Q2 2026)
**Stand:** 2026-05-08
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.64**, **DB_SCHEMA_VERSION** siehe dort
Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren** Funktionen und die zugehörigen **technischen Artefakte**. Trainingsrahmen‑Bibliothek + Slot‑Blueprint: **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2. **Progressionsgraph zwischen Übungen** (Zwischenstand, Grenzen): **§§3–4**. **Medien-Archiv & Bibliothek:** Abschnitt **12** unten + **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
---
## 1. Datenbank-Migrationen (Auswahl)
| Migration | Inhalt |
|-----------|--------|
| **032–034** | **Progressionsgraph Übung→Übung:** Container `exercise_progression_graphs`, Kanten `exercise_progression_edges`; **`notes`** (033); optionale Varianten-Endpunkte + Constraints (034) |
| **028** | `exercise_media` erweitert (Embed/Metadaten), `exercise_skills` Level-Felder (VARCHAR); Medien-API |
| **029** | Kanonische Fähigkeitsstufen (basis–optimierung), `model_levels`-Namen |
| **030** | `training_unit_exercises.exercise_variant_id` → FK `exercise_variants(id)` ON DELETE SET NULL |
| **035** | **`training_framework_programs`** + Ziele, Slots (+ frühere Slot‑Übungstabelle, heute entfallen nach **037**); **`training_plan_templates.visibility`** |
| **036** | Rahmen nur Bibliothek: Kontext + M:N Trainingsarten/Zielgruppen; keine Modus-Spalten / keine Kopf‑`group_id` |
| **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
---
## 2. Backend – Progressionsgraphen (`routers/exercise_progression_graphs.py`)
- REST unter **`/api/exercise-progression-graphs`** inkl. Kanten-CRUD, **`POST …/edges/sequence`** (Reihe auf einmal), **`POST …/edges/delete-batch`**.
- AuthZ wie Trainingsvorlagen: Admin/Superadmin oder Graph‑Ersteller; Anlegen mit Trainings-/Planungsrolle (`_has_planning_role`).
- Listenresponses mit Übungstiteln und Variantennamen (JOIN).
---
## 3. Backend – Übungen (`routers/exercises.py`)
### 3.1 Liste & Suche
- `GET /api/exercises` mit Filtern u. a.: Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeiten, **Skill-Stufe min/max**, `visibility_any`, `status_any`, `search`, **`ai_search`** (Platzhalter, derzeit gleiche Volltextlogik wie `search`).
- Optional: **`include_variants=true`** — liefert pro Übung ein kompaktes **`variants`**-JSON (id, variant_name, sequence_order) für Planung/UI.
### 3.2 Übungsvarianten (CRUD)
Implementiert gemäß **`EXERCISES_API_SPEC.md`** (Varianten-Abschnitt):
- `POST /api/exercises/{id}/variants`
- `PUT /api/exercises/{id}/variants/{variant_id}`
- `DELETE /api/exercises/{id}/variants/{variant_id}` (409, wenn andere Varianten diese als Voraussetzung nutzen)
- `PUT /api/exercises/{id}/variants/reorder` — `sequence_order` 1…n
Sortierung der Varianten im Detail: **`sequence_order`**, dann **`progression_level`**, dann **`id`**.
### 3.3 Medien-Upload – Größenlimits
- Standard: **50 MB** pro Datei (`EXERCISE_MEDIA_MAX_UPLOAD_MB`, Default 50).
- **`admin`** / **`superadmin`**: **1024 MB** Default (`EXERCISE_MEDIA_ADMIN_MAX_UPLOAD_MB`), nie unter dem Nutzer-Limit (in MB verglichen).
Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
---
## 4. Backend – Trainingsplanung (`routers/training_planning.py`)
- Strukturierte Einheiten: **`training_unit_sections`** + **`training_unit_section_items`** (Migration **031**) — Hauptpfad beim Lesen/Schreiben von Einheiten.
- **`training_unit_exercises`:** Legacy-/Nebenpfad; weiterhin **`exercise_variant_id`** (Migration **030**) mit Validierung gegen die gewählte **`exercise_id`**; JOINs liefern u. a. **`exercise_variant_name`**.
- **Blueprint‑Zeilen (`framework_slot_id` gesetzt):** **`GET /api/training-units`** listet diese **nicht**; **`PUT`** mit eingeschränkten Regeln (**kein** `plan_template_id` / kein Reset aus Vorlage über diesen Kopf wie bei Kalender‑Einheit).
- Übernahme aus Rahmen: **`POST /api/training-units/from-framework-slot`** ({ `framework_slot_id`, `group_id`, `planned_date` }) — tiefe Kopie inkl. Sektionen/Items; **`origin_framework_slot_id`** setzt Lineage‑Light.
---
## 5. Frontend – Übungsliste (`ExercisesListPage.jsx`)
- Tabs **Liste** · **Progressionsgraphen** (`ExerciseProgressionGraphPanel`): Graphen anlegen/bearbeiten, Kanten inkl. Sequenz-Bulk und Tabellenansicht.
- **Filter-Modal** (Fokus, Stilrichtung, Trainingsstil, Zielgruppe, Fähigkeit + Stufen von/bis, Sichtbarkeit, Status).
- **Filter-Chips** unter der Suchleiste; Klick entfernt einen Filter; Badge am Filter-Button = Anzahl Chips.
- **Kein Vollbild-Spinner** bei jeder Suche: nur noch **`listFetching`** — Suchfelder bleiben im DOM (**Fokus/Cursor** bleiben erhalten); Liste zeigt optional „Aktualisiere Treffer…“.
- **`<datalist>`** mit Titeln der aktuellen Treffer; **`autoComplete="on"`** für Browser-Vorschläge.
- **`api.listExercises`**: Booleans (z. B. `include_variants`) werden als Query übergeben.
---
## 6. Frontend – Übung bearbeiten (`ExerciseFormPage.jsx`)
- **Varianten-Editor**: eingeklappter Bereich (`<details>`), **eine Variante zur Zeit** über Dropdown oder „Neue Variante“; Felder über **`ExerciseVariantFields`**; Reihenfolge Nach oben/unten; Speichern/Löschen pro Variante.
- **Medien:** Upload/Embed, **Archiv verknüpfen** (`from-asset`), Medienliste mit Vorschau, Reaktivierung bei Archiv-Konflikt — Details **§12**.
- Block **Progressionsgraph** (Edit): Kanten mit Bezug zur aktuellen Übung.
Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Bearbeitung erfolgt unter **`/exercises/:id/edit`** (Routing-Doku ggf. anpassen).
---
## 7. Frontend – Übung Detail (`ExerciseDetailPage.jsx`)
- Varianten-Abschnitt mit **Meta** (Dauer, Schwierigkeit, Material, Progressionsstufe) wo vorhanden.
---
## 8. Frontend – Trainingsplanung (`TrainingPlanningPage.jsx`)
- `listExercises({ include_variants: true })`.
- Pro Zeile: Übung + **Variante** (optional), Dauer, Reihenfolge.
---
## 9. Rich-Text (`RichTextEditor.jsx` + CSS)
- **Selection Save/Restore** vor Toolbar-Klicks (`insertUnorderedList` / `insertOrderedList` zuverlässiger bei Mehrzeilen-Markierung).
- **`styleWithCSS` false** vor Formatbefehlen.
- **Listen-Styling** für `.rich-text-editor ul/ol/li` (Einzüge sichtbar).
---
## 10. Admin – Matrix / Reifegrad (Kontext)
- Bereits dokumentiert in **`CHANGELOG`** / Module **`maturity_models`**: Matrix-Stack-Bundle Export/Import, Kontext-Bindings — siehe `version.py` und Admin-UI-Pfade.
---
## 11. Trainingsrahmen: Bibliothek + Slot‑Blueprint (DB **036–037**)
- **036:** `training_framework_programs` nur Bibliothek — `focus_area_id`, `style_direction_id`, M:N `training_framework_program_training_types` / `_target_groups`; Entfall `plan_mode`, `group_id`; Slot‑Verknüpfungen zu Kalender‑Einheiten geleert.
- **037:** Pro Slot genau eine **`training_units`**‑Zeile mit **`framework_slot_id`**; Ablauf über **`training_unit_sections`** / **`training_unit_section_items`** (wie Planung); Legacy **`training_framework_slot_exercises`** Datenmigration + **`DROP` TABLE**; geplante Kopien können **`origin_framework_slot_id`** tragen.
- **Router `training_framework_programs.py`:** CRUD **`/api/training-framework-programs`**, Slots im Speichern mit neuen Blueprint‑`training_units`, Hydration **`sections`/`exercises`/`blueprint_training_unit_id`**; siehe **`TRAINING_FRAMEWORK_SPEC.md`** §2.3.
- **Frontend:** **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** (`api.js`).
- **Doku:** **`technical/TRAINING_FRAMEWORK_SPEC.md`** §2; **`technical/DATABASE_SCHEMA.md`**; **`functional/DOMAIN_MODEL.md`** (Trainingsrahmen‑Abschnitt).
---
## 12. 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:
### 12.1 Datenbank & Router
- **`media_assets`**, **`platform_media_storage`**, **`exercise_media.media_asset_id`** (Dedupe `sha256` + Sichtbarkeit + `club_id` je nach Policy).
- Router **`media_assets.py`**: Listen, PATCH, Lifecycle, Dateiauslieferung, Bulk; Integration in **`exercises.py`** (Upload, `from-asset`, Promotion/Copyright-Regeln bei `official` / Vereinsübungen).
### 12.2 Funktional (Ist)
- Zentrale **Medienbibliothek** Frontend **`/media`**: Filter (Lifecycle, Medientyp, Verein für Admins), Suche, Tags, Copyright bearbeiten (rollengerecht), Kacheln/Liste, Nutzungs-Hinweise (Übungen/Planung wo implementiert).
- **Papierkorb** mehrstufig (`trash_soft` / `trash_hidden`), Recovery, Superadmin-Purge; strukturierte Fehlercodes bei Governance (u. a. Übung **`CLUB_MEDIA_*`**).
- **Speicher:** Pfadkonvention **`library/{vereinssegment}/…`** mit Medienkind-Unterordnern; Umzug bei Sichtbarkeits-/Vereinsänderung; effektives Wurzelverzeichnis `MEDIA_ROOT` + Superadmin-`local_relative_root`.
- **Governance:** **`visibility=official`** für Übungen und schützenswerte Medien-Operationen im Wesentlichen **Superadmin**; Plattform-Admin entspricht nicht automatisch Superadmin.
- **Mandant:** aktiver Verein über Profil + **`X-Active-Club-Id`**; Sync UI nach **0.8.59** (siehe `tenant_context` / `AuthContext` / `activeClub.js`).
### 12.3 Inline-Medien im Fließtext (geliefert in 0.8.60–0.8.64)
- Platzhalter-Syntax: `{{exerciseMedia:id}}` (normalisiert auf `data-shinkan-exercise-media`), Validierung gegen `exercise_media` der aktuellen Übung.
- Zentraler Anzeigepfad über `ExerciseRichTextBlock` inkl. Sanitize und Lifecycle-Hinweisen.
- RTE-Workflow: Modal „Medien im Text“ (Mediathek + Upload), separates „Embed im Text“-Modal, Größenwahl (`small|medium|full`) und sprechende Platzhalter-Captions.
- Bearbeiten: kompakte Medien-Kacheln + Drag&Drop in Textfelder; Auto-Scroll beim Drag aktiv.
- UX-Schutz: Warnung bei Wechsel „Ansehen“ mit ungespeicherten Änderungen; Detailseite bietet Rückweg zur Bearbeitung.
---
## 13. 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).
- Serverseitige **Suchvorschläge** (Autocomplete-Endpoint), falls datalist nicht reicht.
- Optional: Streaming/chunked Upload für sehr große Videos (RAM-Thema).
- **Medien:** Retention-Job-Betrieb; pytest-Abdeckung Archiv; S3-Adapter (Spec §7); ggf. strategischer Entscheid „exercise_media-Verknüpfung vs. reine Asset-Referenz“.
---
## 14. Verweise
| Thema | Dokument |
|--------|----------|
| Rahmenprogramm / Progressionsgraph | `technical/TRAINING_FRAMEWORK_SPEC.md` |
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
| Medien Upload (Limits, MIME) | `technical/MEDIA_UPLOAD_SPEC.md` |
| Medien-Archiv & Lifecycle | `technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
| Projektstatus-Kachel | `../PROJECT_STATUS.md` |
@@ -0,0 +1,126 @@
# Einheitliche Zugriffsschicht & Governance – Umsetzungsplan
**Status:** verbindliche Umsetzungsreihenfolge (nachgelagert zum Zielbild in `MULTI_TENANCY_RBAC_ARCHITECTURE.md`)
**Stand:** 2026-05-06
**Zweck:** Drift vermeiden – eine nachvollziehbare Schicht für Mandanten-Kontext, Sichtbarkeit und Berechtigungen, auf die alle inhaltsbezogenen Module konsistent aufbauen.
**Explizit zurückgestellt (wie vereinbart):** kostenpflichtiges Vereins-Membership / Tier-Limits pro Verein (`club_subscriptions` o. Ä.) – kommt nach stabiler Zugriffs- und Datenisolationsbasis.
**Separates späteres Konzept:** durch Vereinsadmins definierbare Rollen mit feingranularen Rechten (Capability-Bundles in DB/UI); dieser Plan bereitet nur die **Capability-Idee** und **Erweiterungspunkte** vor.
---
## 1. Leitprinzipien
1. **Ein Mandant für Datenisolierung:** `club_id` ist die Grenze für „vereinsgeteilte“ Inhalte. Nur Ausnahmen: explizit **plattformweite/offizielle** Objekte und **privat**e Objekte des Erstellers.
2. **Ein Kontext pro HTTP-Request:** Mitgliedschaft und gewählter aktiver Verein werden einmal aufgelöst und validiert; Folgelogik nutzt nur noch dieses Objekt (kein verteiltes erneutes „Rates“ aus Headers).
3. **Eine fachliche Sichtbarkeits-Semantik** über alle Bibliotheks- und Planungsartefakte (Übungen, Vorlagen, Rahmenprogramme, …): gleiche Enums, gleiche Leseprüfung, angepasste Listenfilter.
4. **Sparte optional verschärfen:** `division_id` auf Objekten und später auf Rollenzuweisung ausgewertet – ohne Vereinsgrenze zu sprengen.
5. **Community später additive:** neue Freigabeebene oder Flags ergänzen die bestehende Semantik, ohne `club`-Isolation zu ersetzen.
---
## 2. Architektur der Zugriffsschicht (Schichtenmodell)
| Schicht | Verantwortung |
|---------|----------------|
| **Authentifizierung** | Session / Token → `profile_id`, globale `role` (`require_auth`, bestehend). |
| **TenantContext** (neu, zentral) | Aus `profile_id` + Header `X-Active-Club-Id` (optional) + DB `profiles.active_club_id`: effektive **`effective_club_id`** nur wenn Mitgliedschaft aktiv existiert; sonch klaren Fehler (403/400 nach Konvention). Optional: Cache der Mitgliedschaftszeilen/Rollen **einmal pro Request**. |
| **Governance / Objekt contra Account** | Für jedes geschützte Objekt: `visibility`, `club_id`, `division_id` (nullable), `created_by` → **eine** zentrale Entscheidung `can_read` / `can_write` (interne Module, keine Copy-Paste-Logik pro Router). |
| **Funktions-/Feature-Rechte** | „Darf dieser Nutzer im Verein X Trainergruppe anlegen?“ → Capability-Checks (`can_manage_club_org`, `can_plan_in_club`, …); später durch dynamische Rollen → gleiche Capability-Namen. |
**Ziel:** Router werden dünn: laden Daten nur noch durch Hilfen, die **TenantContext** und **Governance** bereits berücksichtigen oder explizit prüfen.
---
## 3. Scope- und Sichtbarkeitsmodell (einheitlich)
Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
**Zielbild (phasenweise DB/API-Anpassung):**
| Wert | Lesende Regel (kurz) |
|------|----------------------|
| `private` | Nur `created_by` (+ Plattform-Admin nach Policy); keine Vereinsliste ohne Ownership. |
| `club` | Nur aktive Mitglieder des Objekt-`club_id`; **Cross-Verein nie**. |
| `division` *(optional neue Stufe oder `club` + Pflicht `division_id`)* | Nur Mitglieder, die dieser Sparte zugeordnet sind (Regeln gesondert spezifizieren: Mitgliedschaft vs. Gruppe vs. Rolle `division_lead`). |
| `official` | Plattform-weit lesbar (Superadmin publiziert/pflegt); weiterhin strikt von `club`-Daten getrennt. |
| `community` *(reserviert)* | Noch nicht implementieren; Design nur additive Felder/Enum-Einträge dokumentieren, wenn erste Stories starten. |
**Trainer-Flow:** „Privat anlegen, dann im Verein teilen“ = Transition von `private` zu `club` (oder Kopie + neue Visibility – Produktentscheidung; technisch muss `club_id` gesetzt und Mitgliedschaft geprüft werden).
---
## 4. Roadmap (verbindliche Reihenfolge)
### Stufe A – Foundations & Audit
- **Router-Inventar:** Liste aller Endpoints mit Zugriff auf `club_id`, `visibility`, organisationalem Bezug oder Listenfiltern (Excel/Markdown-Tabelle im Repo oder unter `.claude/docs/working/`).
- **Definition of Done je Endpoint:** „Default deny“ für tenant-sensitive Listen wenn Kontext fehlt/ungültig.
- TenantContext-Spezifikation festhalten (Feldnamen, HTTP-Fehlercodes, Superadmin-Ausnahmen).
### Stufe B – TenantContext (Backend zentral)
- FastAPI-Dependency z. B. `get_tenant_context(session, x_active_club_id)` → Objekt mit `profile_id`, `global_role`, `effective_club_id`, `club_memberships` (optional gekürzt).
- Alle neuen und bestehenden sicherheitsrelevanten Änderungen **nur** über diese Dependency oder darauf aufbauende Helfer.
- Abgleich mit Frontend: `X-Active-Club-Id` und Persistenz `active_club_id` (bereits vorhanden) als einzige variabler Vereinskontext-Quellen.
### Stufe C – Governance vereinheitlichen
- **Eine** interne API-Stilebene (auch wenn mehrere Python-Funktionen):
`content_readable(...)`, `content_writable(...)` oder zweischichtig „Governance“ vs „Org-Rechte“.
- Module angleichen: **Übungen**, **Trainingsplanung**, **Rahmenprogramme**, **Vorlagen** – gleiche Regeln für `club`/`official`/`private`; **`division`** dort einführen, wo fachlich nötig (einheitliche Filter-Chips in UI).
- Regressionstests: **zwei Vereine, zwei Nutzer**, kein Kreuzzugriff auf `club`-Objekte; Superadmin/Global-Path weiterhin getrennt testen.
### Stufe D – Sparten-Durchsetzung
- `division_lead` und optional `division_id` auf Mitgliedschaft/Rolle auswerten bei Schreib-/Lesevorgängen für Objekte mit `division_id`.
- Dokumentieren: Was gilt für Objekte mit `division_id=NULL` innerhalb eines Vereins (vereinsweit vs. nur „ohne Sparte“).
### Stufe E – Capabilities dokumentieren (ohne UI für Custom Roles)
- Markdown-Tabelle **Capability-Fingerprint**: Kennungen wie `content.share_club`, `planning.edit_unit`, `org.manage_members`, … mit Zuordnung zu den **heutigen** festen Vereinsrollen.
- Ziel: später `club_custom_roles` nur noch andere Kombination derselben Kennungen – keine zweite Philosophie.
### Stufe F – Community (eigenes Epic)
- Konzept: Freigabe **additiv** (Flag oder Enum), Moderation, Sichtbarkeit „öffentlich außerhalb meines Vereins“ ohne bestehende `club`-Isolation zu brechen.
### Zurückgestellt – Vereinsabo / Limits
- Wiederöffnen wenn ACCESS_LAYER Stufe C/D stabil; dann Enforcement vor ausgewählten Writes an einen Billing-Stripe binden.
---
## 5. Drift vermeiden (Arbeitsdisziplin)
| Mechanismus | Inhalt |
|-------------|--------|
| **Cursor / IDE** | Projektregel `.cursor/rules/access-layer.mdc` (Router); Agents sollen nicht auf „nur require_auth“ ausweichen. |
| **Heuristik-Check** | `python backend/scripts/check_access_layer_hints.py`; CI optional mit `ACCESS_LAYER_STRICT=1`. Optional danach: `cd backend && pytest tests/` (nach `pip install -r requirements-dev.txt`). |
| **PR-Checkliste** | Neuer/changed Endpoint: TenantContext verwendet? Governance für Listen + Detail? Tests für zweiten Verein? |
| **Single Source of Truth** | Sichtbarkeitsregeln nur in Zugriffsmodul(en), nicht in Routers dupliziert. |
| **Änderungen am Enum** | Nur zusammen mit Migration + Kurzbeschreibung in diesem Dokument (Datum/Changelog-Zeile). |
| **Beziehung zu MULTI_TENANCY-Doc** | Zielbild und Gap-Analyse §3 dort pflegen (**§3.0** = aktueller Umsetzungsstand); **operative Reihenfolge** hier. |
---
## 6. Nächste konkrete Artefakte (nach diesem Plan)
1. **TenantContext-Spezifikation** (ein Abschnitt in diesem Dokument oder Kurz-ADR): Request-Lebenszyklus, Fehlerbilder, Superadmin.
2. **Endpoint-Audit-Tabelle** (Working-Dokument, bei jedem Merge pflegen bis Stufe C abgeschlossen).
3. **Testplan „Cross-Tenant“** (manuell oder pytest): Minimalsetup zweier Vereine — Unit-Tests `backend/tests/test_access_layer.py`; Integration `backend/tests/test_access_layer_integration.py` bei `ACCESS_LAYER_INTEGRATION=1` / CI im Backend-Container.
**Audit-Tabelle (fortlaufend):** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
---
## 7. Referenzen
- `.claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md` – übergeordnetes Zielbild & Begriffe.
- `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` – verbindliche Domänenregeln für **Medien-Assets** (gleiche Sichtbarkeit wie Übungen, Promotion-Kopplung, Copyright, Papierkorb/Lebenszyklus, externer Speicher). Bei Widerspruch zur Sichtbarkeits-Tabelle in §3 dieses Dokuments: §3 für Enums/`library_content_*`-Semantik, Medien-Spez für Asset-spezifische Zusatzregeln.
- `backend/club_tenancy.py` – bestehende Bausteine (`assert_club_member`, `exercise_visible_to_profile`, …); Ziel ist Deren schrittweise Zusammenführung unter die neue Zugriffsschicht ohne Big-Bang.
---
**Letzte Aktualisierung:** 2026-05-07
@@ -0,0 +1,602 @@
# KI-Prompt-System – Universelle Admin-Konfiguration
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT
**Autor:** Claude Code
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
---
## 1. Konzept
### 1.1 Ziel
Alle KI-Aufrufe in Shinkan sind durch **admin-konfigurierbare Prompt-Templates**
steuerbar. Kein KI-Aufruf ist fest im Code verdrahtet.
**Admins können:**
- Prompt-Texte anpassen (ohne Code-Änderung)
- Neue Prompt-Typen hinzufügen
- Prompts aktivieren/deaktivieren
- Prompts testen (Preview mit aufgelösten Platzhaltern)
- Platzhalter-Katalog einsehen
### 1.2 Anwendungsfälle in Shinkan
| Prompt-Slug | Verwendung |
|-------------|-----------|
| `exercise_summary` | Generiert `exercises.summary` aus goal + execution |
| `exercise_skill_suggestions` | Empfiehlt Skills + Stufen für eine Übung |
| `exercise_category_suggestions` | Empfiehlt Fokusbereich, Stil, Zielgruppe |
| `model_skill_level_description` | Generiert Stufen-Beschreibung in der Fähigkeitsmatrix |
| `training_plan_notes` | Erzeugt Trainer-Notizen für Trainingseinheiten |
| `wiki_import_cleanup` | Bereinigt importierten Wikitext in lesbares Deutsch |
### 1.3 Architektur (aus Mitai übernommen, vereinfacht)
```
Admin konfiguriert Prompt-Template in DB (ai_prompts)
│
▼
KI-Aufruf: Backend lädt Template, löst {{Platzhalter}} auf
│
▼
OpenRouter API → Antwort
│
▼
Antwort wird dem Trainer als Vorschlag angeboten (nicht blind gespeichert)
```
---
## 2. Datenbank
### 2.1 Migration (020_ai_prompts.sql)
```sql
-- Migration 020: AI Prompt System (admin-konfigurierbar)
-- Basis: Mitai Jinkendo prompts system (vereinfacht für Shinkan MVP)
-- Autor: Claude Code
DO $$
BEGIN
-- ============================================================================
-- AI PROMPTS (Admin-verwaltete Prompt-Templates)
-- ============================================================================
CREATE TABLE IF NOT EXISTS ai_prompts (
id SERIAL PRIMARY KEY,
slug VARCHAR(100) NOT NULL UNIQUE, -- z.B. 'exercise_summary'
display_name VARCHAR(200) NOT NULL,
description TEXT,
-- Template mit {{Platzhalter}}-Syntax
template TEXT NOT NULL,
-- Kategorie: welcher Bereich der App nutzt diesen Prompt?
category VARCHAR(50) DEFAULT 'exercise'
CHECK (category IN ('exercise', 'training', 'matrix', 'import', 'admin')),
-- Output-Format: was gibt die KI zurück?
output_format VARCHAR(10) DEFAULT 'text'
CHECK (output_format IN ('text', 'json')),
-- JSON Schema für Validierung des KI-Outputs (nur wenn output_format='json')
output_schema JSONB,
-- System-Default: kann auf Original zurückgesetzt werden
is_system_default BOOLEAN DEFAULT false,
default_template TEXT, -- Backup des originalen Templates
-- Admin-Controls
active BOOLEAN DEFAULT true,
sort_order INT DEFAULT 0,
-- Meta
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_ai_prompts_slug ON ai_prompts(slug);
CREATE INDEX IF NOT EXISTS idx_ai_prompts_category ON ai_prompts(category);
CREATE INDEX IF NOT EXISTS idx_ai_prompts_active ON ai_prompts(active, sort_order);
-- ============================================================================
-- TRIGGER
-- ============================================================================
DROP TRIGGER IF EXISTS ai_prompts_update ON ai_prompts;
CREATE TRIGGER ai_prompts_update
BEFORE UPDATE ON ai_prompts
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
-- ============================================================================
-- SYSTEM-DEFAULT PROMPTS
-- ============================================================================
INSERT INTO ai_prompts (slug, display_name, description, template, category, output_format, is_system_default, default_template, sort_order) VALUES
-- 1. Exercise Summary
('exercise_summary',
'Übungs-Zusammenfassung',
'Generiert eine kurze Zusammenfassung (2-3 Sätze) einer Übung für Listen und Trainingspläne.',
$$Du bist Assistent für einen Kampfsport-Trainer.
Erstelle eine prägnante Zusammenfassung dieser Übung für die Anzeige in Listen und Trainingsplänen.
Die Zusammenfassung soll:
- 2-3 Sätze lang sein (maximal 200 Zeichen)
- Das Wesentliche: Was trainiert die Übung? Wie läuft sie ab?
- Sachlich und klar (keine Werbebotschaften)
- Auf Deutsch
Übung: {{exercise_title}}
Fokusbereich: {{exercise_focus_area}}
Ziel: {{exercise_goal}}
Durchführung: {{exercise_execution}}
Antworte NUR mit dem Zusammenfassungstext, ohne Anführungszeichen.$$,
'exercise', 'text', true,
$$Du bist Assistent für einen Kampfsport-Trainer.
Erstelle eine prägnante Zusammenfassung dieser Übung für die Anzeige in Listen und Trainingsplänen.
Die Zusammenfassung soll:
- 2-3 Sätze lang sein (maximal 200 Zeichen)
- Das Wesentliche: Was trainiert die Übung? Wie läuft sie ab?
- Sachlich und klar (keine Werbebotschaften)
- Auf Deutsch
Übung: {{exercise_title}}
Fokusbereich: {{exercise_focus_area}}
Ziel: {{exercise_goal}}
Durchführung: {{exercise_execution}}
Antworte NUR mit dem Zusammenfassungstext, ohne Anführungszeichen.$$,
1),
-- 2. Skill Suggestions
('exercise_skill_suggestions',
'Fähigkeiten-Empfehlungen',
'Empfiehlt passende Fähigkeiten + Stufen aus dem Katalog für eine Übung.',
$$Du bist Assistent für einen Kampfsport-Trainer.
Analysiere diese Übung und empfehle passende Fähigkeiten aus dem Katalog.
Übung: {{exercise_title}}
Fokusbereich: {{exercise_focus_area}}
Ziel: {{exercise_goal}}
Durchführung: {{exercise_execution}}
Verfügbare Fähigkeiten:
{{skills_catalog}}
Wähle maximal 5 passende Fähigkeiten. Für jede gib an:
- skill_id (aus der Liste)
- required_level: Voraussetzung (einsteiger|grundlagen|aufbau|fortgeschritten|experte)
- target_level: Ziel nach regelmäßigem Training (gleiche Werte)
- intensity: Trainingsintensität (niedrig|mittel|hoch)
- is_primary: true wenn Hauptfähigkeit
Antworte NUR als JSON-Array:
[{"skill_id": 1, "required_level": "grundlagen", "target_level": "aufbau", "intensity": "hoch", "is_primary": true}]
Wenn keine Fähigkeit passt, antworte mit [].$$,
'exercise', 'json', true, NULL, 2),
-- 3. Category Suggestions
('exercise_category_suggestions',
'Kategorie-Empfehlungen',
'Empfiehlt Fokusbereich, Stilrichtung und Zielgruppe für eine Übung.',
$$Du bist Assistent für einen Kampfsport-Trainer.
Ordne diese Übung in die Katalog-Struktur ein.
Übung: {{exercise_title}}
Beschreibung: {{exercise_goal}}
Durchführung: {{exercise_execution}}
Verfügbare Fokusbereiche: {{focus_areas_catalog}}
Verfügbare Stilrichtungen: {{style_directions_catalog}}
Verfügbare Zielgruppen: {{target_groups_catalog}}
Wähle die passendsten Zuordnungen. Antworte NUR als JSON:
{
"focus_areas": [{"id": 1, "is_primary": true}],
"style_directions": [{"id": 2, "is_primary": true}],
"target_groups": [{"id": 5, "is_primary": true}]
}$$,
'exercise', 'json', true, NULL, 3),
-- 4. Matrix Level Description
('model_skill_level_description',
'Fähigkeitsmatrix-Stufenbeschreibung',
'Generiert Beschreibungen für Stufen in der Fähigkeitsmatrix.',
$$Du bist Fachexperte für {{focus_area}} und erstellst Lernziel-Beschreibungen.
Modell: {{model_name}}
Fokusbereich: {{focus_area}}
Zielgruppe: {{target_group}}
Fähigkeit: {{skill_name}}
Stufenanzahl: {{level_count}}
Stufen: {{level_names}}
Beschreibe für JEDE Stufe konkret und beobachtbar, was ein Schüler auf dieser Stufe
der Fähigkeit "{{skill_name}}" können soll.
Antworte NUR als JSON-Array ({{level_count}} Einträge):
[
{"level_number": 1, "description": "...", "observable_criteria": "..."},
{"level_number": 2, "description": "...", "observable_criteria": "..."}
]$$,
'matrix', 'json', true, NULL, 4),
-- 5. Wiki Import Cleanup
('wiki_import_cleanup',
'Wiki-Text-Bereinigung',
'Bereinigt importierten Wikitext in lesbares, strukturiertes Deutsch.',
$$Bereinige folgenden Text aus einem Trainings-Wiki für die Darstellung in einer modernen App.
Original-Text:
{{wiki_raw_text}}
Regeln:
- Entferne alle Wiki-Markup-Syntax ([[Links]], {{Templates}}, ==Überschriften==)
- Behalte den fachlichen Inhalt vollständig
- Schreibe in klarem, professionellem Deutsch
- Strukturiere mit Absätzen (nicht mit Wiki-Markup)
- Maximal 1000 Zeichen
Antworte NUR mit dem bereinigten Text.$$,
'import', 'text', true, NULL, 5)
ON CONFLICT (slug) DO NOTHING;
RAISE NOTICE 'Migration 020 completed successfully (AI Prompt System)';
END $$;
```
---
## 3. Platzhalter-Katalog
### 3.1 Verfügbare Platzhalter
Alle `{{Platzhalter}}` werden vom Backend-Service `prompt_resolver.py` aufgelöst.
**Kontext: exercise** (für exercise_summary, skill_suggestions, category_suggestions)
| Platzhalter | Beschreibung | Beispielwert |
|-------------|--------------|--------------|
| `{{exercise_title}}` | Titel der Übung | "Maai - Distanzübung" |
| `{{exercise_goal}}` | Ziel (erste 500 Zeichen) | "Distanzgefühl entwickeln..." |
| `{{exercise_execution}}` | Durchführung (erste 500 Zeichen) | "1. Partnerwahl..." |
| `{{exercise_preparation}}` | Vorbereitung | "Matten auslegen..." |
| `{{exercise_focus_area}}` | Primärer Fokusbereich | "Karate" |
| `{{exercise_duration}}` | Dauer | "15-20 min" |
| `{{exercise_group_size}}` | Gruppengröße | "8-12 Personen" |
| `{{skills_catalog}}` | Liste aller Skills: "ID Name (Kategorie)" | "- ID 1: Dachi Waza (Kihon)\n..." |
| `{{focus_areas_catalog}}` | Liste aller Fokusbereiche | "- ID 1: Karate\n..." |
| `{{style_directions_catalog}}` | Liste aller Stilrichtungen | "- ID 1: Shotokan\n..." |
| `{{target_groups_catalog}}` | Liste aller Zielgruppen | "- ID 1: Breitensportler\n..." |
**Kontext: matrix** (für model_skill_level_description)
| Platzhalter | Beschreibung | Beispielwert |
|-------------|--------------|--------------|
| `{{model_name}}` | Name des Reifegradmodells | "Karate Shotokan Breitensport" |
| `{{focus_area}}` | Fokusbereich des Modells | "Karate" |
| `{{style_direction}}` | Stilrichtung | "Shotokan" |
| `{{target_group}}` | Zielgruppe | "Breitensportler" |
| `{{skill_name}}` | Fähigkeitsname | "Distanzgefühl" |
| `{{skill_description}}` | Fähigkeitsbeschreibung | "Kontrolle der Kampfdistanz..." |
| `{{level_count}}` | Anzahl der Stufen | "5" |
| `{{level_names}}` | Stufen-Namen kommagetrennt | "Einsteiger, Grundlagen, Aufbau, Fortgeschritten, Experte" |
**Kontext: import**
| Platzhalter | Beschreibung |
|-------------|--------------|
| `{{wiki_raw_text}}` | Roher Wikitext aus MediaWiki |
### 3.2 Platzhalter-Auflösung (Backend)
```python
# backend/prompt_resolver.py
class ExercisePromptContext:
"""Kontext für exercise-bezogene Prompts."""
def resolve(self, template: str, exercise_data: dict, db) -> str:
variables = {
"exercise_title": exercise_data.get("title", ""),
"exercise_goal": exercise_data.get("goal", "")[:500],
"exercise_execution": exercise_data.get("execution", "")[:500],
"exercise_preparation": exercise_data.get("preparation", ""),
"exercise_focus_area": self._get_primary_focus_area(exercise_data, db),
"exercise_duration": self._format_duration(exercise_data),
"exercise_group_size": self._format_group_size(exercise_data),
"skills_catalog": self._format_skills_catalog(db),
"focus_areas_catalog": self._format_catalog(db, "focus_areas"),
"style_directions_catalog":self._format_catalog(db, "style_directions"),
"target_groups_catalog": self._format_catalog(db, "target_groups"),
}
return self._replace_placeholders(template, variables)
```
### 3.3 Unbekannte Platzhalter
Wenn ein Platzhalter nicht aufgelöst werden kann:
- `{{unknown_key}}` → bleibt als `[NICHT VERFÜGBAR]` im Template
- Warnung im API-Response
- Kein Abbruch des KI-Aufrufs
---
## 4. API-Endpoints
### 4.1 Übersicht
| Method | Endpoint | Beschreibung |
|--------|----------|--------------|
| GET | `/admin/ai-prompts` | Liste aller Prompts (Admin) |
| GET | `/admin/ai-prompts/{id}` | Prompt-Detail |
| POST | `/admin/ai-prompts` | Neuen Prompt anlegen |
| PUT | `/admin/ai-prompts/{id}` | Prompt bearbeiten |
| DELETE | `/admin/ai-prompts/{id}` | Prompt löschen (nur custom, nicht system) |
| POST | `/admin/ai-prompts/{id}/reset` | Auf System-Default zurücksetzen |
| POST | `/admin/ai-prompts/{id}/preview` | Platzhalter auflösen ohne KI-Call |
| GET | `/admin/ai-prompts/placeholders` | Platzhalter-Katalog mit Beschreibungen |
| POST | `/admin/ai-prompts/test` | Prompt mit Beispiel-Daten testen (echter KI-Call) |
### 4.2 `GET /admin/ai-prompts`
**Response:** `200 OK`
```json
[
{
"id": 1,
"slug": "exercise_summary",
"display_name": "Übungs-Zusammenfassung",
"description": "Generiert eine kurze Zusammenfassung...",
"category": "exercise",
"output_format": "text",
"active": true,
"is_system_default": true,
"is_modified": false,
"sort_order": 1
}
]
```
`is_modified`: true wenn `template != default_template`
---
### 4.3 `PUT /admin/ai-prompts/{id}`
**Request Body:**
```json
{
"template": "Du bist ein erfahrener Karate-Trainer...\n{{exercise_title}}...",
"active": true,
"display_name": "Übungs-Zusammenfassung (angepasst)"
}
```
**Response:** `200 OK` (Prompt-Objekt)
**Constraints:**
- Nur `template`, `display_name`, `description`, `active`, `sort_order` änderbar
- `slug`, `output_format`, `category` nicht änderbar (würde Code brechen)
- System-Default-Backup bleibt immer erhalten
---
### 4.4 `POST /admin/ai-prompts/{id}/preview`
Löst Platzhalter auf und zeigt das finale Prompt – **OHNE KI-Call**.
**Request Body:**
```json
{
"context": "exercise",
"example_data": {
"exercise_id": 42
}
}
```
**Response:** `200 OK`
```json
{
"resolved_template": "Du bist Assistent für einen Kampfsport-Trainer.\nÜbung: Maai - Distanzübung\n...",
"placeholders_resolved": ["exercise_title", "exercise_goal"],
"placeholders_missing": [],
"estimated_tokens": 320
}
```
---
### 4.5 `GET /admin/ai-prompts/placeholders`
Liefert den vollständigen Platzhalter-Katalog.
**Response:** `200 OK`
```json
{
"categories": {
"exercise": [
{
"key": "exercise_title",
"placeholder": "{{exercise_title}}",
"description": "Titel der Übung",
"example": "Maai - Distanzübung",
"required_context": "exercise_id oder title direkt"
}
],
"matrix": [...],
"import": [...]
}
}
```
---
## 5. Verwendung in Backend-Code
### 5.1 Standard-Pattern für KI-Aufrufe
```python
# backend/services/ai_service.py
async def run_ai_prompt(
slug: str,
context_data: dict,
db,
openrouter_key: str
) -> dict:
"""
Lädt Prompt aus DB, löst Platzhalter auf, ruft KI auf.
Wirft AiNotConfiguredError wenn key fehlt oder Prompt inaktiv.
"""
# 1. Prompt laden
prompt = db.fetchrow("SELECT * FROM ai_prompts WHERE slug=$1 AND active=true", slug)
if not prompt:
raise AiNotConfiguredError(f"Prompt '{slug}' nicht gefunden oder inaktiv")
# 2. Platzhalter auflösen
resolved = resolve_placeholders(
template=prompt["template"],
context=context_data,
db=db
)
# 3. KI-Call
response = await call_openrouter(
prompt=resolved,
model=settings.openrouter_model,
api_key=openrouter_key
)
# 4. JSON validieren (wenn output_format='json')
if prompt["output_format"] == "json":
response = parse_and_validate_json(response, prompt["output_schema"])
return {
"output": response,
"prompt_slug": slug,
"ai_generated": True,
"model": settings.openrouter_model
}
```
### 5.2 Aufruf in exercises Router
```python
# backend/routers/exercises.py
@router.post("/exercises/ai/suggest")
async def suggest_for_exercise(data: ExerciseSuggestRequest, session=Depends(require_auth)):
result = {}
# Summary
try:
summary = await ai_service.run_ai_prompt(
slug="exercise_summary",
context_data={"exercise": data.dict()},
db=db,
openrouter_key=settings.openrouter_api_key
)
result["summary"] = summary
except AiNotConfiguredError:
result["summary"] = None
# Skills
try:
skills = await ai_service.run_ai_prompt(
slug="exercise_skill_suggestions",
context_data={"exercise": data.dict()},
db=db,
openrouter_key=settings.openrouter_api_key
)
result["skills"] = skills
except AiNotConfiguredError:
result["skills"] = None
return result
```
---
## 6. Frontend: Admin-UI
### 6.1 Route
```
/admin/ai-prompts → AdminAiPromptsPage (Liste)
/admin/ai-prompts/{id} → AdminAiPromptDetailPage (Edit)
```
### 6.2 Layout (Prompt-Editor)
```
┌───────────────────────────────────────────────┐
│ ✨ KI-Prompts [+ Neu] │
│ ───────────────────────────────────────────── │
│ exercise_summary [Aktiv] [Bearbeiten] │
│ exercise_skill_suggestions [Aktiv] [Bearbeiten]│
│ model_skill_level_description [Aktiv] │
└───────────────────────────────────────────────┘
── Detailansicht ──────────────────────────────────
┌───────────────────────────────────────────────┐
│ Übungs-Zusammenfassung │
│ slug: exercise_summary · Kategorie: exercise │
│ ───────────────────────────────────────────── │
│ Template: │
│ ┌────────────────────────────────────────────┐ │
│ │ Du bist Assistent für einen Kampfsport- │ │
│ │ Trainer. ... │ │
│ │ {{exercise_title}} │ │ ← Syntaxhighlight
│ │ {{exercise_goal}} │ │
│ └────────────────────────────────────────────┘ │
│ [Verfügbare Platzhalter ▼] [Vorschau] │
│ ───────────────────────────────────────────── │
│ [Mit Beispiel testen] [Original wiederherstellen]│
│ [Speichern] │
└───────────────────────────────────────────────┘
```
**Syntax-Highlighting:** `{{placeholder}}` in Farbe hervorheben.
**Platzhalter-Panel:** Ausklappbare Liste aller verfügbaren Platzhalter (aus `/admin/ai-prompts/placeholders`).
---
## 7. Zusammenspiel KI_FEATURES_SPEC ↔ AI_PROMPT_SYSTEM_SPEC
Die `KI_FEATURES_SPEC.md` beschreibt die **User-Flows** (wann wird KI angeboten,
wie sieht die Bestätigung aus).
Die `AI_PROMPT_SYSTEM_SPEC.md` (diese Datei) beschreibt die **technische Basis**
(DB-Schema, Platzhalter-System, Admin-UI).
```
KI_FEATURES_SPEC: POST /exercises/ai/suggest
│
▼
AI_PROMPT_SYSTEM_SPEC: ai_service.run_ai_prompt("exercise_summary", ...)
│
▼
DB: ai_prompts WHERE slug='exercise_summary'
│
▼
Template + {{Platzhalter}} auflösen
│
▼
OpenRouter API
```
---
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT
+340 -189
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
**Version:** 0.3.4
**Stand:** 2026-04-23
**Aktuell deployed:** Migration 009 (Target Groups M:N Refactoring)
**Version:** 0.5.3
**Stand:** 2026-05-07
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints) und für Medien-Archiv bis **045+** (`media_assets`, …) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`) und **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
---
@@ -26,55 +26,146 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
| 006 | 2026-04-21 | Training Planning | ✅ Deployed |
| 007 | 2026-04-22 | Exercise Catalogs (idempotent) | ✅ Deployed |
| 008 | 2026-04-23 | M:N Exercise Relations + Hierarchical Catalogs | ✅ Deployed |
| 009 | 2026-04-23 | **Target Groups M:N Refactoring** (BREAKING) | ✅ Deployed |
| 009 | 2026-04-23 | Target Groups M:N Refactoring (BREAKING) | ✅ Deployed |
| 010 | 2026-04-23 | Rename training_styles to style_directions | ✅ Deployed |
| 011 | 2026-04-23 | Create Training Types | ✅ Deployed |
| 012 | 2026-04-23 | Exercise Training Characters + Trainer Contexts | ✅ Deployed |
| 013 | 2026-04-23 | Training Types Focus Area | ✅ Deployed |
| 014 | 2026-04-24 | Variant Progression Search Legacy | ✅ Deployed |
| 016 | 2026-04-24 | Saved Searches | ✅ Deployed |
| 017 | 2026-04-24 | Exercise Blocks | ✅ Deployed |
| 018 | 2026-04-24 | Wiki Import Tracking | ✅ Deployed |
| 019 | 2026-04-24 | Exercises Optional Fields (goal/execution nullable) | ✅ Deployed |
| 020 | 2026-04-27 | Exercise Skills UNIQUE Constraint | ✅ Deployed |
| 021 | 2026-04-27 | ~~Import Skills from Matrix~~ (DEPRECATED) | ⚠️ Faulty |
| **022** | **2026-04-27** | **Skills Schema Complete (BREAKING)** | ✅ Deployed |
| **023** | **2026-04-27** | **Skills Complete Import (69 Skills)** | ✅ Deployed |
| 024–031 | *versch.* | Reifegradmodelle, Medien, Planvorlagen/Sektionen u. a. — siehe `backend/migrations/` | ✅ je Umgebung |
| **032** | **2026-04-30** | **Progressionsgraph Übung→Übung:** `exercise_progression_graphs`, `exercise_progression_edges` | ✅ |
| **033** | **2026-04-30** | **`exercise_progression_edges.notes`** | ✅ |
| **034** | **2026-04-30** | **Kanten-Endpunkte optional `exercise_variants`; UNIQUE/CHECK** | ✅ |
| **035** | **2026-05-05** | **Rahmenprogramm:** `training_framework_programs` (+ Ziele, Slots, früher `training_framework_slot_exercises`); **`training_plan_templates.visibility`** (Backfill `club`) — siehe `TRAINING_FRAMEWORK_SPEC.md` | ✅ |
| **036** | **2026-05-05** | **Rahmen nur Bibliothek:** Kopf mit `focus_area_id`, `style_direction_id`, M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`, `group_id`; Slot‑`training_unit_id` geleert — siehe `036_framework_program_context_only_library.sql` | ✅ |
| **037** | **2026-05-05** | **Slot‑Blueprint:** `training_units.framework_slot_id` (+ CHECK Blueprint vs. Kalender), `origin_framework_slot_id`; Migration Slot‑Übungen → `training_unit_sections`/`training_unit_section_items`; **`DROP training_framework_slot_exercises`** | ✅ |
| **040–046** | **2026-05** | **Mitgliedschaft/Anträge, Übungs-Governance-Erweiterungen, `media_assets`, `platform_media_storage`, `exercise_media.media_asset_id`, Tags/GIN u. a.** — exakte Nummern: `backend/migrations/`; fachliche Norm Medien: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** | ✅ je Umgebung |
---
## Migration 022: Skills Schema Complete (BREAKING CHANGE)
## Migration 009: Target Groups M:N Refactoring (BREAKING CHANGE)
**Problem:** Skills hatten keine Kategorisierung (Haupt-/Unterkategorie, Fokusbereich).
**Lösung:** Vollständiges hierarchisches Schema für produktionsreifen Import.
**Problem:** Zielgruppen waren hierarchisch an Trainingsstile gebunden (1:N via FK `training_style_id`).
**Lösung:** M:N Beziehung über Junction-Tabelle `training_style_target_groups`.
**Änderungen:**
- ❌ **Entfernt:** `target_groups.training_style_id` (FK constraint + column)
- ✅ **Neu:** `training_style_target_groups` Junction-Tabelle
- ✅ **Migriert:** Alte Zuordnungen zu M:N (alle mit `is_primary = true`)
- ✅ **Architektur:** Eine Zielgruppe kann mehreren Stilen zugeordnet sein
**Neue Struktur:**
**Neue Tabellen:**
```sql
-- Global unabhängige Zielgruppen (KEINE training_style_id mehr)
target_groups (
id, name, description, min_age, max_age,
sort_order, status, created_at, updated_at
-- Haupt-Kategorien (KARATE / ALLGEMEINE)
skill_main_categories (
id SERIAL PRIMARY KEY,
name VARCHAR(200) UNIQUE NOT NULL, -- "KARATE Fähigkeiten" / "ALLGEMEINE sportliche Fähigkeiten"
slug VARCHAR(50) UNIQUE NOT NULL, -- "karate" / "allgemeine"
description TEXT,
sort_order INT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
)
-- M:N Junction-Tabelle
training_style_target_groups (
-- Level-Definitionen (1-5 Beschreibungen aus Fähigkeitsmatrix)
skill_level_definitions (
id SERIAL PRIMARY KEY,
training_style_id INT REFERENCES training_styles(id) ON DELETE CASCADE,
target_group_id INT REFERENCES target_groups(id) ON DELETE CASCADE,
is_primary BOOLEAN DEFAULT false,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
level INT NOT NULL CHECK (level BETWEEN 1 AND 5),
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(training_style_id, target_group_id)
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE (skill_id, level)
)
```
**Backend API:** 5 neue Endpoints:
- `GET /api/training-style-target-groups` (Liste mit Filtern + Enrichment)
- `POST /api/training-style-target-groups` (Upsert-Logik)
- `PUT /api/training-style-target-groups/{id}` (is_primary Flag)
- `DELETE /api/training-style-target-groups/{id}`
- `GET /api/training-styles/hierarchy` (Hierarchische Struktur für Tree-View)
**Erweiterte Tabellen:**
```sql
-- skill_categories erweitert
ALTER TABLE skill_categories ADD COLUMN slug VARCHAR(50);
ALTER TABLE skill_categories ADD COLUMN main_category_id INT REFERENCES skill_main_categories(id);
ALTER TABLE skill_categories ADD CONSTRAINT skill_categories_slug_unique UNIQUE (slug);
**Frontend:**
- Admin-UI Tab "Hierarchie" (Tree-View: Fokusbereich → Stil → Zielgruppen)
- Admin-UI Tab "Zuordnungen" (Checkbox-Matrix für M:N)
- Tab "Zielgruppen" überarbeitet (global, ohne training_style_id Dropdown)
-- skills erweitert
ALTER TABLE skills ADD COLUMN main_category_id INT REFERENCES skill_main_categories(id);
ALTER TABLE skills ADD COLUMN focus_areas JSONB DEFAULT '[]'::jsonb;
```
**Indizes:**
- `idx_skills_main_category_id`
- `idx_skills_category_id`
- `idx_skill_categories_main_category_id`
- `idx_skill_level_definitions_skill_id`
**Struktur:**
```
skill_main_categories (Hauptkategorie)
└─ skill_categories (Unterkategorie)
└─ skills (Fähigkeit)
└─ skill_level_definitions (Level 1-5 Beschreibungen)
```
---
## Kern-Entitäten (Stand Migration 007)
## Migration 023: Skills Complete Import
**Quelle:** Fähigkeitsmatrix (https://karatetrainer.net/index.php?title=Fähigkeitsmatrix)
**Importiert:**
- **69 Skills** mit vollständiger Kategorisierung
- **2 Haupt-Kategorien:** KARATE Fähigkeiten, ALLGEMEINE sportliche Fähigkeiten
- **9 Unterkategorien:** Kihon, Kumite, Kata, Selbstverteidigung, Koordination, Kondition, Kognition, Soziale Fähigkeiten, Psychische Fähigkeiten
**Skills-Verteilung:**
```
KARATE Fähigkeiten (32 Skills, focus_areas: ["karate"]):
├─ Kata (8): Technik Kombination, Kata Ablauf, Bunkai, Oyo, Henka, Kakushi, Kata Atmung, Kata Rhythmus
├─ Kihon (10): Dachi Waza, Uke Waza, Zuki Waza, Uchi Waza, Geri Waza, Nage Waza, Nukite Waza, Ken Waza, Hüfteinsatz, Kime
├─ Kumite (10): Beinarbeit, Distanzkontrolle, Angriff, Abwehr Konter, Präzision, Antizipation, Timing, Taktik, Fokus, Mentale Stärke
└─ Selbstverteidigung (4): Gefahrenbewustsein, Selbstbehauptung, Selbstschutz, Gefahrenabwehr
ALLGEMEINE sportliche Fähigkeiten (37 Skills, focus_areas: ["universal"]):
├─ Kognition (5): Aufmerksamkeit, Wahrnehmung, Urteilsvermögen, Merkfähigkeit, Lernfähigkeit
├─ Kondition (15): Maximalkraft, Schnellkraft, Reaktivkraft, Kraftausdauer, Muskelaufbau,
│ Reaktionsschnelligkeit, Bewegungsschnelligkeit, Handlungsschnelligkeit,
│ Schnelligkeitsausdauer, Grundlagenausdauer, Aerobe Ausdauer, Anaerobe Ausdauer,
│ Regenerationsfähigkeit, Ermüdungswiderstandsfähigkeit, Flexibilität
├─ Koordination (7): Orientierung, Differenzierung, Kopplung, Gleichgewicht, Rhythmisierung, Reaktion, Umstellung
├─ Psychische Fähigkeiten (6): Selbstvertrauen, Konzentration, Emotionale Kontrolle, Motivation, Stressresistenz, Stressregulation
└─ Soziale Fähigkeiten (4): Deeskalation, Selbstdisziplin, Toleranz, Fairness
```
**Duplikat-Handling:**
Einige Skills kommen in der Matrix doppelt vor (Kumite + Kondition/Koordination):
- **Behalten in Kondition:** Anaerobe Ausdauer, Bewegungsschnelligkeit, Flexibilität, Reaktionsschnelligkeit, Schnelligkeitsausdauer (konditionelle Primärfähigkeiten)
- **Behalten in Kumite:** Antizipation, Timing (kampfspezifisch)
**Cleanup:**
- DELETE FROM exercise_skills (M:N Beziehungen)
- DELETE FROM skills (alte Daten)
- DELETE FROM skill_categories
- DELETE FROM skill_main_categories
**Verifikation:**
```sql
-- Sollte 69 ergeben
SELECT COUNT(*) FROM skills;
-- Zeigt Verteilung
SELECT
mc.name AS hauptkategorie,
sc.name AS unterkategorie,
COUNT(s.id) AS anzahl_skills
FROM skills s
JOIN skill_categories sc ON s.category_id = sc.id
JOIN skill_main_categories mc ON s.main_category_id = mc.id
GROUP BY mc.name, sc.name, mc.sort_order, sc.sort_order
ORDER BY mc.sort_order, sc.sort_order;
```
---
## Kern-Entitäten
### Auth & Profile
@@ -91,151 +182,233 @@ divisions (id, club_id, name, description, ...)
training_groups (id, division_id, name, description, focus_area, level, ...)
```
### Kataloge (Einfache FK-Struktur - zu refactoren)
### Kataloge
**ACHTUNG:** Aktuell 1:1 Beziehungen - fachlich inkorrekt!
#### Fokusbereiche & Stile (M:N mit Zielgruppen)
```sql
focus_areas (id, name, abbreviation, description, color, icon, ...)
training_styles (id, name, abbreviation, description, parent_style_id, ...)
training_characters (id, name, description, ...)
skill_categories (id, name, description, parent_category_id, ...)
style_directions (id, focus_area_id, name, abbreviation, description, parent_style_id, ...)
target_groups (id, name, description, min_age, max_age, ...) -- Global, NICHT gebunden an Stil
training_style_target_groups (style_direction_id, target_group_id, is_primary) -- M:N Junction
```
### Übungen (Aktuell - zu refactoren)
#### Fähigkeiten (Hierarchisches Schema ab Migration 022)
```sql
-- Haupt-Kategorien (2: KARATE, ALLGEMEINE)
skill_main_categories (
id, name, slug, description, sort_order, created_at, updated_at
)
-- Unterkategorien (9: Kihon, Kumite, Kata, Selbstverteidigung, Koordination, Kondition, ...)
skill_categories (
id, name, slug, description, sort_order,
main_category_id REFERENCES skill_main_categories(id),
parent_category_id, -- Optional: Hierarchie
created_at, updated_at
)
-- Fähigkeiten (69 Skills)
skills (
id, name, description,
category_id REFERENCES skill_categories(id),
main_category_id REFERENCES skill_main_categories(id),
focus_areas JSONB, -- ["karate"] oder ["universal"]
created_at, updated_at
)
-- Level-Definitionen (optional, noch nicht gefüllt)
skill_level_definitions (
id, skill_id, level, description,
created_at, updated_at,
UNIQUE (skill_id, level)
)
```
**Focus Areas Bedeutung:**
- `["karate"]` - Skill ist spezifisch für Karate (z.B. Kata Ablauf, Kihon)
- `["universal"]` - Skill ist universell einsetzbar (z.B. Maximalkraft, Konzentration, Deeskalation)
- Später möglich: `["karate", "selbstverteidigung"]` - Mehrfachzuordnung
#### Trainingscharakter
```sql
training_characters (id, name, description, ...)
trainer_contexts (id, name, description, ...) -- Neue Dimension (Migration 012)
```
### Übungen (M:N Beziehungen ab Migration 008)
```sql
exercises (
id, title, summary, goal, execution, preparation, trainer_notes,
focus_area_id, -- ❌ 1:1 - sollte M:N sein
training_style_id, -- ❌ 1:1 - sollte M:N sein
training_character_id, -- ❌ 1:1 - sollte M:N sein
visibility, status, created_by, club_id, ...
duration_min, duration_max,
group_size_min, group_size_max,
equipment JSONB,
visibility, status, created_by, club_id,
import_source, import_id, wiki_page_id, -- MediaWiki Import (Migration 018)
created_at, updated_at
)
exercise_skills (exercise_id, skill_id, is_primary, intensity, ...)
-- M:N Beziehungen
exercise_focus_areas (exercise_id, focus_area_id, is_primary)
exercise_style_directions (exercise_id, style_direction_id, is_primary)
exercise_target_groups (exercise_id, target_group_id, is_primary)
exercise_age_groups (exercise_id, age_group) -- Enum: Minis, Kinder, Schüler, Teenager, Erwachsene
-- Fähigkeiten-Zuordnung (mit Level)
exercise_skills (
exercise_id, skill_id,
is_primary, intensity,
required_level INT, -- Voraussetzung (1-5)
target_level INT, -- Ziel (1-5)
UNIQUE (exercise_id, skill_id) -- Migration 020
)
-- Varianten & Medien (028+ Embed/Datei; 045+ optional media_asset_id → media_assets)
exercise_variants (id, exercise_id, name, description, ...)
exercise_media (id, exercise_id, type, url, title, description, ...)
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
platform_media_storage (id, local_relative_root, …)
```
### Training Planning
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
Kopf ohne Gruppenbindung (`training_framework_programs`), Ziele, Slots. Slot‑spezifischer Ablauf liegt nach **037** nicht mehr in eigener Übungstabelle, sondern in **`training_units`** mit **`framework_slot_id`** — siehe nächster Abschnitt.
```sql
training_units (id, group_id, date, title, description, ...)
training_unit_exercises (training_unit_id, exercise_id, sort_order, ...)
training_framework_programs (… focus_area_id, style_direction_id, visibility, club_id, created_by …)
training_framework_goals (framework_program_id, sort_order, title, notes)
training_framework_slots (framework_program_id, sort_order, title, notes, training_unit_id -- ungenutzt)
training_framework_program_training_types (framework_program_id, training_type_id)
training_framework_program_target_groups (framework_program_id, target_group_id)
```
### Training Planning & Rahmen‑Blueprint (Migrationen 006, 031, **037**)
Geplante Einheit und **Rahmen‑Slot‑Blueprint** teilen sich **`training_units`** und den strukturierten Ablauf über **Sektionen** (031). Blueprint‑Zeilen haben **`framework_slot_id`** gesetzt (genau eine Zeile pro Slot); Kalender‑Zeilen haben **`framework_slot_id IS NULL`** und **`group_id` / `planned_date`** gesetzt. Kopien aus dem Rahmen können **`origin_framework_slot_id`** setzen.
```sql
training_units (
id,
group_id INT NULL REFERENCES training_groups(id), -- Pflicht für Kalender‑Zeilen (CHECK)
planned_date DATE NULL, -- Pflicht für Kalender‑Zeilen (CHECK)
planned_time_start, planned_time_end, planned_focus,
actual_date, actual_time_start, actual_time_end, attendance_count,
status, notes, trainer_notes,
created_by, plan_template_id REFERENCES training_plan_templates(id),
framework_slot_id INT NULL REFERENCES training_framework_slots(id) ON DELETE CASCADE,
origin_framework_slot_id INT NULL REFERENCES training_framework_slots(id) ON DELETE SET NULL,
…
)
training_unit_sections (
training_unit_id, order_index, title, guidance_notes,
source_template_section_id REFERENCES training_plan_template_sections(id)
)
training_unit_section_items (
section_id, order_index, item_type CHECK ('exercise'|'note'),
exercise_id, exercise_variant_id, planned_duration_min, actual_duration_min,
notes, modifications, note_body
)
```
**Legacy (Migration 006, für ältere Codepfade noch referenzierbar):** `training_unit_exercises`; produktiver Standardablauf liegt in **Sections/Items**.
**Trainingsvorlagen (031):** `training_plan_templates`, `training_plan_template_sections`.
```sql
exercise_blocks (id, name, description, created_by, club_id, ...) -- Migration 017
```
### Progressionsgraph Übung → Übung (Migrationen 032–034)
Separater gerichteter Graph **zwischen** Übungen (nicht zu verwechseln mit Varianten-Reihen **innerhalb** einer Übung, Migration 014). Detail-DDL und REST siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §3.
```sql
exercise_progression_graphs (
id, name, description, visibility, club_id, created_by,
created_at, updated_at
)
exercise_progression_edges (
id, graph_id,
from_exercise_id, to_exercise_id,
from_exercise_variant_id, -- nullable (Migration 034)
to_exercise_variant_id,
edge_type, -- z. B. next_exercise, sibling
notes, -- Migration 033
created_at
)
```
### MediaWiki Import (Migration 018)
```sql
wiki_import_log (
id, category, import_type, import_status,
items_total, items_imported, items_skipped, items_failed,
error_log JSONB,
started_at, finished_at,
imported_by
)
wiki_import_references (
id, wiki_page_id, entity_type, local_id,
created_at, updated_at
)
```
**Import-Typen:**
- `exercise` - Übungen aus `Kategorie:Übungen`
- `skill` - Fähigkeiten aus `Kategorie:Fähigkeitsbeschreibung` (veraltet, nutze Migration 023)
- `method` - Trainingsmethoden aus `Kategorie:Methodenbeschreibung`
---
## Indizes
### Performance-Indizes
```sql
-- Hierarchie-Lookups
CREATE INDEX idx_style_directions_focus_area ON style_directions(focus_area_id);
CREATE INDEX idx_skill_categories_main_category ON skill_categories(main_category_id);
CREATE INDEX idx_skills_category ON skills(category_id);
CREATE INDEX idx_skills_main_category ON skills(main_category_id);
-- M:N Joins
CREATE INDEX idx_exercise_focus_areas_exercise ON exercise_focus_areas(exercise_id);
CREATE INDEX idx_exercise_focus_areas_focus ON exercise_focus_areas(focus_area_id);
CREATE INDEX idx_exercise_style_directions_exercise ON exercise_style_directions(exercise_id);
CREATE INDEX idx_exercise_style_directions_style ON exercise_style_directions(style_direction_id);
CREATE INDEX idx_exercise_target_groups_exercise ON exercise_target_groups(exercise_id);
CREATE INDEX idx_exercise_target_groups_target ON exercise_target_groups(target_group_id);
CREATE INDEX idx_exercise_skills_exercise ON exercise_skills(exercise_id);
CREATE INDEX idx_exercise_skills_skill ON exercise_skills(skill_id);
-- Import-Tracking
CREATE INDEX idx_wiki_import_references_wiki_page ON wiki_import_references(wiki_page_id);
CREATE INDEX idx_wiki_import_references_entity ON wiki_import_references(entity_type, local_id);
```
---
## Geplante Änderungen (Migration 008)
### Hierarchische Katalog-Struktur
**Fachliche Anforderung (§8.1 Anforderungsdokument):**
```
Fokusbereich → Stil → Zielgruppe
```
**Neue Struktur:**
```sql
-- Level 1: Fokusbereiche (Root)
focus_areas (
id SERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL,
abbreviation VARCHAR(20),
description TEXT,
color VARCHAR(20),
icon VARCHAR(50),
sort_order INT,
status VARCHAR(50) DEFAULT 'active'
)
-- Level 2: Trainingsstile (untergeordnet zu Fokusbereich)
training_styles (
id SERIAL PRIMARY KEY,
focus_area_id INT REFERENCES focus_areas(id), -- Hierarchie-Link
name VARCHAR(100) NOT NULL,
abbreviation VARCHAR(20),
description TEXT,
parent_style_id INT REFERENCES training_styles(id), -- Optional: Sub-Stile
sort_order INT,
status VARCHAR(50) DEFAULT 'active'
)
-- Level 3: Zielgruppen (untergeordnet zu Stil)
target_groups (
id SERIAL PRIMARY KEY,
training_style_id INT REFERENCES training_styles(id), -- Hierarchie-Link
name VARCHAR(100) NOT NULL,
description TEXT,
min_age INT,
max_age INT,
sort_order INT,
status VARCHAR(50) DEFAULT 'active'
)
```
### M:N Übungs-Zuordnungen
```sql
-- Übung → Fokusbereiche (M:N)
exercise_focus_areas (
id SERIAL PRIMARY KEY,
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE,
focus_area_id INT REFERENCES focus_areas(id),
is_primary BOOLEAN DEFAULT false,
UNIQUE(exercise_id, focus_area_id)
)
-- Übung → Stile (M:N)
exercise_styles (
id SERIAL PRIMARY KEY,
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE,
training_style_id INT REFERENCES training_styles(id),
is_primary BOOLEAN DEFAULT false,
UNIQUE(exercise_id, training_style_id)
)
-- Übung → Zielgruppen (M:N)
exercise_target_groups (
id SERIAL PRIMARY KEY,
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE,
target_group_id INT REFERENCES target_groups(id),
is_primary BOOLEAN DEFAULT false,
UNIQUE(exercise_id, target_group_id)
)
-- Übung → Altersgruppen (M:N - separate Dimension)
exercise_age_groups (
id SERIAL PRIMARY KEY,
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE,
age_group VARCHAR(50) NOT NULL, -- 'Minis', 'Kinder', 'Schüler', 'Teenager', 'Erwachsene'
UNIQUE(exercise_id, age_group)
)
```
---
## Kaskadier-Regeln (Geplant)
## Kaskadier-Regeln
### Fokusbereich löschen
**Verhalten:** `RESTRICT` (Löschen verweigern wenn verwendet)
**Alternativen:**
1. **Umrouten:** Alle abhängigen Stile auf neuen Fokusbereich setzen
2. **Archivieren:** Status auf 'archived' setzen statt löschen
**Implementierung:**
**Prüfung:**
```sql
-- Prüfung vor Löschen:
SELECT COUNT(*) FROM training_styles WHERE focus_area_id = :id
SELECT COUNT(*) FROM style_directions WHERE focus_area_id = :id
SELECT COUNT(*) FROM exercise_focus_areas WHERE focus_area_id = :id
-- Falls verwendet → HTTP 409 Conflict mit Hinweis
```
**Alternativen:**
1. Umrouten: Alle abhängigen Stile auf neuen Fokusbereich setzen
2. Archivieren: Status auf 'archived' setzen statt löschen
### Stil löschen
**Verhalten:** `RESTRICT` wenn Zielgruppen oder Übungen zugeordnet
@@ -243,63 +416,41 @@ SELECT COUNT(*) FROM exercise_focus_areas WHERE focus_area_id = :id
**Umrouten-Workflow:**
1. Admin wählt Ziel-Stil
2. System aktualisiert:
- `target_groups.training_style_id`
- `exercise_styles.training_style_id`
- `training_style_target_groups.style_direction_id`
- `exercise_style_directions.style_direction_id`
3. Löschen erlaubt
### Zielgruppe löschen
**Verhalten:** `SET NULL` oder `CASCADE` in `exercise_target_groups`
---
## Indizes (Geplant)
**Prüfung:**
```sql
-- Hierarchie-Lookups
CREATE INDEX idx_training_styles_focus_area ON training_styles(focus_area_id);
CREATE INDEX idx_target_groups_style ON target_groups(training_style_id);
-- M:N Joins
CREATE INDEX idx_exercise_focus_areas_exercise ON exercise_focus_areas(exercise_id);
CREATE INDEX idx_exercise_focus_areas_focus ON exercise_focus_areas(focus_area_id);
CREATE INDEX idx_exercise_styles_exercise ON exercise_styles(exercise_id);
CREATE INDEX idx_exercise_styles_style ON exercise_styles(training_style_id);
CREATE INDEX idx_exercise_target_groups_exercise ON exercise_target_groups(exercise_id);
CREATE INDEX idx_exercise_target_groups_target ON exercise_target_groups(target_group_id);
SELECT COUNT(*) FROM training_style_target_groups WHERE target_group_id = :id
SELECT COUNT(*) FROM exercise_target_groups WHERE target_group_id = :id
```
---
### Skill löschen
## Deprecation-Pfad (Migration 008)
**Verhalten:** `CASCADE` zu `skill_level_definitions`, `RESTRICT` wenn in `exercise_skills`
**Legacy-Spalten in `exercises`:**
**Prüfung:**
```sql
-- Werden in Migration 008 deprecated:
exercises.focus_area_id → Migriert zu exercise_focus_areas (is_primary=true)
exercises.training_style_id → Migriert zu exercise_styles (is_primary=true)
exercises.training_character_id → Bleibt vorerst (separate Dimension)
-- Spalten bleiben zur Rückwärtskompatibilität, aber:
-- 1. Daten migriert
-- 2. Neue Übungen nutzen M:N-Tabellen
-- 3. API liefert enriched data aus M:N
-- 4. Später: Spalten droppen nach Stabilisierung
SELECT COUNT(*) FROM exercise_skills WHERE skill_id = :id
```
---
## Nächste Schritte
- [ ] Migration 008 Entwurf erstellen
- [ ] Migrations-Strategie für Altdaten dokumentieren
- [ ] Admin-UI für Baum-Verwaltung planen
- [ ] API-Endpoints für hierarchische Navigation
- [ ] Cascade-Logik implementieren
- [ ] Tests für Löschen/Umrouten
- [ ] Level-Definitionen aus Fähigkeitsmatrix extrahieren (optional)
- [ ] Skills-Import testen mit Übungs-Import
- [ ] Migration 024: Skills-Beschreibungen aus Wiki importieren
- [ ] Admin-UI für Skill-Kategorien (CRUD)
- [ ] Skill-Filter in Übungssuche integrieren
---
**Letzte Aktualisierung:** 2026-04-23
**Letzte Aktualisierung:** 2026-04-27
**Verantwortlich:** Claude Code
**Review:** Pending
@@ -0,0 +1,956 @@
# Exercises API Specification
**Version:** 1.5
**Datum:** 2026-05-08
**Status:** Teilweise implementiert (Liste mit Filtern + Varianten + Medienlimits + Progressionsgraphen siehe Code)
**Autor:** Claude Code
**Änderungen v1.4:** Endpoints **`/exercise-progression-graphs`** inkl. Kanten, **`POST …/edges/sequence`**, **`POST …/edges/delete-batch`** — Detailtabellen siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3.3
**Änderungen v1.5:** Medien-/Inline-Workflow aktualisiert (Modal-Picker, Drag&Drop UX im Frontend), Klarstellung zu `context` (legacy/optional), Hinweise zu Platzhaltern in Rich-Text-Feldern.
**Änderungen v1.3:** `GET /exercises` erweiterte Query-Parameter (`include_variants`, Multi-Filter, `ai_search`-Platzhalter); Dokumentation angepasst
**Änderungen v1.2:** KI-Assistenz Endpoints, Skill-Level-System (benannte Stufen), intensity als low/medium/high
**Änderungen v1.1:** Exercise Blocks Endpoints, Permissions dokumentiert, age_groups korrigiert
---
## Base URL
```
Production: https://shinkan.jinkendo.de/api
Development: https://dev.shinkan.jinkendo.de/api
```
---
## Authentication
**Header:** `X-Auth-Token: <token>`
**Alle Endpoints** (außer `/auth/*`) erfordern Authentication.
---
## Endpoints Overview
| Method | Endpoint | Beschreibung |
|--------|----------|--------------|
| **Exercises** |
| GET | `/exercises` | List exercises mit Filtern |
| GET | `/exercises/{id}` | Exercise Detail mit Enrichment |
| POST | `/exercises` | Create exercise |
| PUT | `/exercises/{id}` | Update exercise |
| DELETE | `/exercises/{id}` | Delete exercise |
| **Variants** |
| POST | `/exercises/{id}/variants` | Create variant |
| PUT | `/exercises/{id}/variants/{variant_id}` | Update variant |
| DELETE | `/exercises/{id}/variants/{variant_id}` | Delete variant |
| PUT | `/exercises/{id}/variants/reorder` | Reorder variants (DnD) |
| **Media** |
| POST | `/exercises/{id}/media` | Upload/Embed media |
| PUT | `/exercises/{id}/media/{media_id}` | Update media metadata |
| DELETE | `/exercises/{id}/media/{media_id}` | Delete media |
| PUT | `/exercises/{id}/media/reorder` | Reorder media (DnD) |
| **KI-Assistenz** |
| POST | `/exercises/ai/suggest` | KI-Vorschläge (Summary + Skills) für neues Formular |
| POST | `/exercises/{id}/ai/regenerate` | KI-Vorschläge neu generieren für bestehende Übung |
| **Exercise Blocks** |
| GET | `/exercise-blocks` | List blocks (mit Filtern) |
| GET | `/exercise-blocks/{id}` | Block Detail mit Items |
| POST | `/exercise-blocks` | Create block |
| PUT | `/exercise-blocks/{id}` | Update block |
| DELETE | `/exercise-blocks/{id}` | Delete block |
| POST | `/exercise-blocks/{id}/items` | Add item to block |
| PUT | `/exercise-blocks/{id}/items/{item_id}` | Update item |
| DELETE | `/exercise-blocks/{id}/items/{item_id}` | Remove item |
| PUT | `/exercise-blocks/{id}/items/reorder` | Reorder items (DnD) |
| **Progressionsgraphen** (Übung→Übung) |
| GET | `/exercise-progression-graphs` | Liste Graphen |
| GET | `/exercise-progression-graphs/{id}` | Detail; Query `include_edges` |
| POST | `/exercise-progression-graphs` | Graph anlegen |
| PUT | `/exercise-progression-graphs/{id}` | Metadaten |
| DELETE | `/exercise-progression-graphs/{id}` | Graph + Kanten |
| GET | `/exercise-progression-graphs/{id}/edges` | Kantenliste |
| POST | `/exercise-progression-graphs/{id}/edges` | Einzelkante |
| POST | `/exercise-progression-graphs/{id}/edges/sequence` | Reihe (`steps`) in einer Transaktion |
| PUT | `/exercise-progression-graphs/{id}/edges/{edge_id}` | z. B. Notiz |
| DELETE | `/exercise-progression-graphs/{id}/edges/{edge_id}` | Kante löschen |
| POST | `/exercise-progression-graphs/{id}/edges/delete-batch` | `{ edge_ids }` |
Vollständige Pfadtabelle, Auth und Feldgrenzen: **`TRAINING_FRAMEWORK_SPEC.md`** §3.
---
## Exercises
### `GET /exercises`
**Query Parameters (Auswahl):**
| Parameter | Beschreibung |
|-----------|----------------|
| `focus_area_ids[]`, `focus_area` | Fokusbereiche (ODER über Liste oder Legacy Einzel-ID) |
| `visibility_any[]`, `visibility` | Sichtbarkeit(en) |
| `status_any[]`, `status` | Status |
| `skill_ids[]`, `skill_id` | Fähigkeit(en) |
| `skill_min_level`, `skill_max_level` | Stufe 1–5 auf Übung↔Skill-Zuordnung |
| `style_direction_ids[]`, `style_direction_id` | Stilrichtung(en) |
| `training_type_ids[]`, `training_type_id` | Trainingsstil(e) |
| `target_group_ids[]`, `target_group_id` | Zielgruppe(n) |
| `search`, `ai_search` | Volltext (aktuell gleiche Logik; `ai_search` Platzhalter für spätere KI-Suche) |
| `include_variants` | `true`: jedes Listenelement enthält optional kompaktes **`variants`** für UI/Planung |
| `limit` | Default 50, max 100 |
| `offset` | Default 0 |
**Response:** `200 OK`
Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
```json
{
"id": 1,
"title": "Maai - Distanzübung",
"variants": [
{ "id": 10, "variant_name": "Basis", "sequence_order": 1 }
]
}
```
**Errors:**
- `401` - Unauthorized
- `403` - Forbidden
---
### `GET /exercises/{id}`
**Path Parameters:**
- `id` (int, required)
**Response:** `200 OK`
```json
{
"id": 1,
"title": "Maai - Distanzübung",
"summary": "Kurzbeschreibung...",
"goal": "Distanzgefühl entwickeln durch Partnerübungen...",
"execution": "1. Partnerwahl\n2. Ausgangsstellung Zenkutsu Dachi...",
"preparation": "Matten auslegen, Pratzen bereitlegen",
"trainer_notes": "Auf korrekten Abstand achten!",
"equipment": ["Matten", "Pratzen"],
"duration_min": 15,
"duration_max": 20,
"group_size_min": 8,
"group_size_max": 12,
"focus_areas": [
{
"id": 1,
"focus_area_id": 1,
"name": "Karate",
"abbreviation": "KAR",
"color": "#E63946",
"icon": "🥋",
"is_primary": true
}
],
"training_styles": [
{
"id": 1,
"training_style_id": 2,
"name": "Shotokan",
"abbreviation": "SKA",
"is_primary": true
},
{
"id": 2,
"training_style_id": 3,
"name": "Goju-Ryu",
"abbreviation": "GJR",
"is_primary": false
}
],
"target_groups": [
{
"id": 1,
"target_group_id": 5,
"name": "Breitensportler",
"description": "Karate für Freizeit und Fitness",
"is_primary": true
}
],
"age_groups": ["Kinder", "Teenager"],
"skills": [
{
"id": 1,
"skill_id": 10,
"skill_name": "Distanzgefühl",
"skill_category": "Kumite",
"is_primary": true,
"intensity": "hoch",
"required_level": "grundlagen",
"target_level": "aufbau",
"ai_suggested": false
}
],
"variants": [
{
"id": 1,
"variant_name": "Ohne Partner",
"description": "Solo-Variante mit Schattenboxen",
"execution_changes": "Stelle dir einen imaginären Partner vor...",
"duration_min": 10,
"duration_max": 15,
"equipment_changes": [],
"difficulty_adjustment": "easier",
"progression_level": 1,
"sequence_order": 1,
"prerequisite_variant_id": null
},
{
"id": 2,
"variant_name": "Mit Pratzen",
"description": "Fortgeschrittene Variante mit Pratzen-Training",
"execution_changes": "Partner hält Pratzen, Ausführung wie Haupt...",
"duration_min": 15,
"duration_max": 25,
"equipment_changes": ["+ Pratzen"],
"difficulty_adjustment": "harder",
"progression_level": 3,
"sequence_order": 3,
"prerequisite_variant_id": 1
}
],
"media": [
{
"id": 1,
"media_type": "video",
"file_path": "/media/exercises/a1b2c3d4_demo.mp4",
"file_size": 5242880,
"mime_type": "video/mp4",
"original_filename": "demo.mp4",
"embed_url": null,
"embed_platform": null,
"title": "Durchführung Demo",
"description": "Zeigt korrekten Abstand",
"sort_order": 1,
"is_primary": true,
"context": "ablauf"
},
{
"id": 2,
"media_type": "video",
"file_path": null,
"file_size": null,
"mime_type": null,
"original_filename": null,
"embed_url": "https://www.youtube.com/watch?v=abc123",
"embed_platform": "youtube",
"title": "Erweiterte Techniken",
"description": "YouTube-Tutorial von Sensei XY",
"sort_order": 2,
"is_primary": false,
"context": "detail"
}
],
"visibility": "club",
"status": "approved",
"created_by": 1,
"creator_name": "Lars",
"club_id": 1,
"club_name": "Dojo Berlin",
"import_source": null,
"import_id": null,
"created_at": "2026-04-20T10:00:00Z",
"updated_at": "2026-04-22T14:30:00Z"
}
```
**Errors:**
- `401` - Unauthorized
- `403` - Forbidden (private + not owner)
- `404` - Not found
---
### `POST /exercises`
**Request Body:**
```json
{
"title": "Neue Übung",
"summary": "Kurzbeschreibung...",
"goal": "Ziel der Übung...",
"execution": "Durchführung Schritt für Schritt...",
"preparation": "Aufbau und Vorbereitung...",
"trainer_notes": "Hinweise für Trainer...",
"equipment": ["Matten", "Pratzen"],
"duration_min": 15,
"duration_max": 20,
"group_size_min": 8,
"group_size_max": 12,
"focus_areas_multi": [
{"focus_area_id": 1, "is_primary": true},
{"focus_area_id": 2, "is_primary": false}
],
"training_styles_multi": [
{"training_style_id": 2, "is_primary": true}
],
"target_groups_multi": [
{"target_group_id": 5, "is_primary": true}
],
"age_groups": ["Kinder", "Teenager"],
"skills": [
{
"skill_id": 10,
"is_primary": true,
"intensity": "hoch",
"required_level": "grundlagen",
"target_level": "aufbau"
}
],
"visibility": "private",
"status": "draft",
"club_id": 1
}
```
**Required Fields:**
- `title` (3-300 chars)
- `goal` (10-5000 chars)
- `execution` (10-10000 chars)
**Response:** `201 Created` (full exercise object wie GET)
**Errors:**
- `400` - Bad Request (validation error)
- `401` - Unauthorized
- `403` - Forbidden
---
### `PUT /exercises/{id}`
**Request Body:** Same as POST (all fields optional except id)
**Inline-Hinweis:** Rich-Text-Felder (`summary`, `goal`, `execution`, `preparation`, `trainer_notes` sowie `execution_changes` bei Varianten) unterstützen Platzhalter `{{exerciseMedia:id}}`, die serverseitig auf kanonisches Span-Markup normalisiert werden. Beim erstmaligen Anlegen ohne vorhandene `exercise_media` wird dies mit 400 abgelehnt.
**Response:** `200 OK` (full exercise object)
**Errors:**
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden (not owner)
- `404` - Not found
---
### `DELETE /exercises/{id}`
**Response:** `200 OK`
```json
{"ok": true}
```
**Errors:**
- `401` - Unauthorized
- `403` - Forbidden (not owner or admin)
- `404` - Not found
- `409` - Conflict (used in training units)
---
## Variants
### `POST /exercises/{id}/variants`
**Request Body:**
```json
{
"variant_name": "Mit Pratzen",
"description": "Fortgeschrittene Variante...",
"execution_changes": "Statt freier Distanz mit Pratzen...",
"duration_min": 15,
"duration_max": 25,
"equipment_changes": ["+ Pratzen"],
"difficulty_adjustment": "harder",
"progression_level": 3,
"sequence_order": 3,
"prerequisite_variant_id": 1
}
```
**Required Fields:**
- `variant_name` (3-200 chars)
**Response:** `201 Created`
```json
{
"id": 2,
"exercise_id": 1,
"variant_name": "Mit Pratzen",
"description": "...",
"progression_level": 3,
"sequence_order": 3,
"prerequisite_variant_id": 1,
"created_at": "2026-04-24T10:00:00Z"
}
```
**Errors:**
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden (not owner)
- `404` - Exercise not found
- `409` - Conflict (prerequisite_variant_id nicht zur gleichen Übung)
---
### `PUT /exercises/{id}/variants/{variant_id}`
**Request Body:** Same as POST
**Response:** `200 OK` (variant object)
---
### `DELETE /exercises/{id}/variants/{variant_id}`
**Response:** `200 OK`
```json
{"ok": true}
```
**Errors:**
- `409` - Conflict (andere Varianten referenzieren diese als Prerequisite)
---
### `PUT /exercises/{id}/variants/reorder`
**Request Body:**
```json
{
"variant_ids": [3, 1, 2]
}
```
**Response:** `200 OK`
```json
{"ok": true, "reordered": 3}
```
**Errors:**
- `400` - variant_ids nicht vollständig oder falsche Exercise
---
## Media
### `POST /exercises/{id}/media`
**Content-Type:** `multipart/form-data`
**Form Fields:**
- `file` (File, optional) - Image/Video file
- `embed_url` (string, optional) - YouTube/Instagram/Vimeo URL
- `media_type` (enum, required) - `image | video | document | sketch`
- `title` (string, optional)
- `description` (string, optional)
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
**Entweder `file` ODER `embed_url` (nicht beides).**
**Response:** `201 Created`
```json
{
"id": 5,
"exercise_id": 1,
"media_type": "video",
"file_path": "/media/exercises/a1b2c3d4_demo.mp4",
"file_size": 5242880,
"mime_type": "video/mp4",
"original_filename": "demo.mp4",
"embed_url": null,
"embed_platform": null,
"title": "Demo",
"description": null,
"sort_order": 3,
"is_primary": false,
"context": "ablauf",
"created_at": "2026-04-24T10:00:00Z"
}
```
**Errors:**
- `400` - Bad Request (invalid file type, missing file/embed_url)
- `401` - Unauthorized
- `403` - Forbidden
- `413` - File too large (> 50MB)
**Supported Formats:**
- **Images:** `image/jpeg`, `image/png`, `image/gif`
- **Videos:** `video/mp4`
- **Documents:** `application/pdf`
- **Embeds:** `youtube.com`, `youtu.be`, `instagram.com`, `vimeo.com`
---
### `PUT /exercises/{id}/media/{media_id}`
**Request Body:**
```json
{
"title": "Neuer Titel",
"description": "Neue Beschreibung",
"is_primary": true
}
```
`context` bleibt backendseitig kompatibel, wird in aktuellen Bearbeitungsflüssen jedoch nicht mehr aktiv zur UI-Zuordnung verwendet (Inline-Platzhalter priorisiert).
**Response:** `200 OK` (media object)
---
### `DELETE /exercises/{id}/media/{media_id}`
**Response:** `200 OK`
```json
{"ok": true}
```
**Deletes:** DB-Eintrag + Datei (wenn `file_path` gesetzt)
---
### `PUT /exercises/{id}/media/reorder`
**Request Body:**
```json
{
"media_ids": [2, 1, 3]
}
```
**Response:** `200 OK`
```json
{"ok": true, "reordered": 3}
```
---
## KI-Assistenz
### `POST /exercises/ai/suggest`
Generiert KI-Vorschläge für eine **noch nicht gespeicherte** Übung.
Wird beim Klick auf „✨ KI-Vorschlag" im Formular aufgerufen.
**Request Body:**
```json
{
"title": "Maai - Distanzübung",
"goal": "Distanzgefühl entwickeln...",
"execution": "1. Partnerwahl\n2. Ausgangsstellung..."
}
```
**Mindestanforderung:** `goal` oder `execution` muss vorhanden sein (min. 50 Zeichen)
**Response:** `200 OK`
```json
{
"summary": {
"text": "Partnerübung zur Entwicklung des Distanzgefühls. Trainiert räumliche Wahrnehmung und reaktives Verhalten.",
"ai_generated": true,
"model": "anthropic/claude-sonnet-4"
},
"skills": [
{
"skill_id": 10,
"skill_name": "Distanzgefühl",
"skill_category": "Kumite",
"required_level": "grundlagen",
"target_level": "aufbau",
"intensity": "hoch",
"is_primary": true,
"confidence": 0.92
},
{
"skill_id": 15,
"skill_name": "Reaktionsschnelligkeit",
"skill_category": "Athletik",
"required_level": "einsteiger",
"target_level": "grundlagen",
"intensity": "mittel",
"is_primary": false,
"confidence": 0.74
}
]
}
```
**Errors:**
- `400` - Zu wenig Text (< 50 Zeichen)
- `503` - KI nicht verfügbar (OPENROUTER_API_KEY nicht konfiguriert)
---
### `POST /exercises/{id}/ai/regenerate`
Generiert Vorschläge für eine **bestehende** Übung neu.
**Request Body:**
```json
{
"regenerate": ["summary", "skills"]
}
```
**Response:** `200 OK` (gleiche Struktur wie `/ai/suggest`)
**Hinweis:** Gibt nur Vorschläge zurück – nichts wird automatisch gespeichert.
Trainer muss im Frontend aktiv übernehmen.
---
## Permissions
### Sichtbarkeits-Workflow
| Von → Nach | Wer darf das? |
|-----------|---------------|
| `draft → in_review` | Ersteller, Club-Admin |
| `in_review → approved` | Club-Admin, Super-Admin |
| `approved → archived` | Club-Admin, Super-Admin |
| `* → draft` | Super-Admin |
### Sichtbarkeit (`visibility`)
| Änderung | Wer darf das? |
|----------|---------------|
| `private → club` | Ersteller, Club-Admin |
| `club → official` | Club-Admin, Super-Admin |
| `official → club` | Super-Admin |
### Owner-Checks
- **Bearbeiten** (PUT): Nur Ersteller oder Club-Admin
- **Löschen** (DELETE): Nur Ersteller oder Super-Admin
- **Lesen** (`private`): Nur Ersteller
**403 Fehler-Beispiel:**
```json
{"detail": "Keine Berechtigung. Nur der Ersteller oder ein Admin kann diese Übung bearbeiten."}
```
---
## Exercise Blocks
### `GET /exercise-blocks`
**Query Parameters:**
- `is_template` (bool, optional) - nur Templates oder nur reguläre Blocks
- `visibility` (enum, optional) - `private | club | official`
- `club_id` (int, optional) - Filter nach Verein
- `search` (string, optional) - Suche in name
- `limit` (int, optional, default: 50)
- `offset` (int, optional, default: 0)
**Response:** `200 OK`
```json
[
{
"id": 1,
"name": "Aufwärmblock Kumite",
"description": "Standard-Aufwärmprogramm für Kumite",
"is_template": false,
"item_count": 4,
"club_id": 1,
"club_name": "Dojo Berlin",
"created_by": 1,
"creator_name": "Lars",
"visibility": "club",
"created_at": "2026-04-20T10:00:00Z"
}
]
```
---
### `GET /exercise-blocks/{id}`
**Response:** `200 OK`
```json
{
"id": 1,
"name": "Aufwärmblock Kumite",
"description": "Standard-Aufwärmprogramm für Kumite",
"goal": "Sportler auf Kumite-Training vorbereiten",
"is_template": false,
"club_id": 1,
"club_name": "Dojo Berlin",
"created_by": 1,
"creator_name": "Lars",
"visibility": "club",
"items": [
{
"id": 1,
"sequence_order": 1,
"is_placeholder": false,
"exercise_id": 5,
"exercise_title": "Maai - Distanzübung",
"exercise_summary": "Distanzgefühl entwickeln...",
"variant_id": null,
"variant_name": null,
"notes": "Leicht anfangen, nur 5min",
"placeholder_criteria": null,
"placeholder_label": null
},
{
"id": 2,
"sequence_order": 2,
"is_placeholder": true,
"exercise_id": null,
"exercise_title": null,
"variant_id": null,
"notes": "Hier eine Schlag-Übung einsetzen",
"placeholder_criteria": {"focus_area_id": 1, "max_duration": 10},
"placeholder_label": "Schlag-Übung (max. 10 min)"
}
],
"created_at": "2026-04-20T10:00:00Z",
"updated_at": "2026-04-22T14:30:00Z"
}
```
**Errors:**
- `403` - Forbidden (private Block, nicht Ersteller)
- `404` - Not found
---
### `POST /exercise-blocks`
**Request Body:**
```json
{
"name": "Aufwärmblock Kumite",
"description": "Standard-Aufwärmprogramm",
"goal": "Sportler vorbereiten",
"is_template": false,
"visibility": "private",
"club_id": 1
}
```
**Required Fields:**
- `name` (3-200 chars)
**Response:** `201 Created` (full block object wie GET)
---
### `PUT /exercise-blocks/{id}`
**Request Body:** Same as POST (all fields optional)
**Response:** `200 OK` (full block object)
**Errors:**
- `403` - Forbidden (nicht Ersteller/Admin)
- `404` - Not found
---
### `DELETE /exercise-blocks/{id}`
**Response:** `200 OK`
```json
{"ok": true}
```
**Errors:**
- `403` - Forbidden
- `404` - Not found
- `409` - Conflict (Block in Trainingsplan verwendet)
---
### `POST /exercise-blocks/{id}/items`
**Request Body (konkretes Exercise):**
```json
{
"exercise_id": 5,
"variant_id": null,
"sequence_order": 3,
"notes": "Leicht anfangen"
}
```
**Request Body (Platzhalter):**
```json
{
"is_placeholder": true,
"placeholder_label": "Schlag-Übung (max. 10 min)",
"placeholder_criteria": {
"focus_area_id": 1,
"max_duration": 10
},
"sequence_order": 4,
"notes": "Variabel je nach Gruppe"
}
```
**Response:** `201 Created`
```json
{
"id": 5,
"block_id": 1,
"sequence_order": 3,
"is_placeholder": false,
"exercise_id": 5,
"exercise_title": "Maai - Distanzübung",
"variant_id": null,
"notes": "Leicht anfangen",
"created_at": "2026-04-24T10:00:00Z"
}
```
**Errors:**
- `400` - Bad Request (weder exercise_id noch is_placeholder=true)
- `404` - Block oder Exercise nicht gefunden
- `409` - Conflict (sequence_order bereits vergeben)
---
### `PUT /exercise-blocks/{id}/items/{item_id}`
**Request Body:** Gleiche Felder wie POST, alle optional
**Response:** `200 OK` (item object)
---
### `DELETE /exercise-blocks/{id}/items/{item_id}`
**Response:** `200 OK`
```json
{"ok": true}
```
---
### `PUT /exercise-blocks/{id}/items/reorder`
**Request Body:**
```json
{
"item_ids": [3, 1, 2, 4]
}
```
**Response:** `200 OK`
```json
{
"ok": true,
"reordered": 4,
"items": [
{"id": 3, "sequence_order": 1},
{"id": 1, "sequence_order": 2},
{"id": 2, "sequence_order": 3},
{"id": 4, "sequence_order": 4}
]
}
```
**Errors:**
- `400` - item_ids unvollständig oder gehören nicht zu diesem Block
---
## Validation Rules
### Exercise
- `title`: 3-300 chars, unique per club
- `goal`: 10-5000 chars
- `execution`: 10-10000 chars
- `duration_min/max`: 0-480 (8 hours)
- `group_size_min/max`: 1-100
- `visibility`: enum (private, club, official)
- `status`: enum (draft, in_review, approved, archived)
### Variant
- `variant_name`: 3-200 chars
- `progression_level`: 1-10
- `prerequisite_variant_id`: must exist, must be same exercise
### Media
- File size: max 50MB
- Mime types: `image/jpeg, image/png, image/gif, video/mp4, application/pdf`
- Embed platforms: `youtube, instagram, vimeo`
- Inline-Rich-Text: `{{exerciseMedia:id}}` bzw. `data-shinkan-exercise-media="<id>"`; optional `data-shinkan-exercise-media-size="small|medium|full"` für Layout.
### Exercise Block
- `name`: 3-200 chars
### Exercise Skills
- `required_level`: enum – `einsteiger | grundlagen | aufbau | fortgeschritten | experte` (optional/nullable)
- `target_level`: enum – gleiche Werte (optional/nullable)
- `intensity`: enum – `niedrig | mittel | hoch` (optional/nullable)
- `target_level` sollte >= `required_level` sein (Warnung, kein Fehler)
### Exercise Block Item
- `sequence_order`: muss unique pro Block sein
- `exercise_id`: muss existieren und zugänglich sein (visibility check)
- `is_placeholder = true`: `exercise_id` muss NULL sein
- `placeholder_criteria`: bekannte Keys nur (focus_area_id, training_style_id, target_group_id, skill_ids, max_duration, min_duration, difficulty, visibility)
---
## Error Response Format
**Standard:**
```json
{
"detail": "Human-readable error message"
}
```
**Validation (detailliert):**
```json
{
"detail": "Validation failed",
"errors": [
{"field": "title", "message": "Titel muss mindestens 3 Zeichen lang sein"},
{"field": "goal", "message": "Ziel ist ein Pflichtfeld"}
]
}
```
---
## HTTP Status Codes
- `200 OK` - Erfolgreiche GET/PUT/DELETE
- `201 Created` - Erfolgreiche POST
- `400 Bad Request` - Validierung fehlgeschlagen
- `401 Unauthorized` - Kein/ungültiges Token
- `403 Forbidden` - Keine Berechtigung
- `404 Not Found` - Ressource nicht gefunden
- `409 Conflict` - Duplikat, Constraint
- `413 Payload Too Large` - Datei zu groß
- `500 Internal Server Error` - Server-Fehler
---
**Version:** 1.5
**Letzte Änderung:** 2026-05-08
**Status:** Living Spec
@@ -0,0 +1,643 @@
# Exercise System Architecture
**Version:** 1.1
**Datum:** 2026-04-30
**Status:** DRAFT - Awaiting Review
**Autor:** Claude Code
**Änderungen v1.1:** Progressionsgraph **zwischen** Übungen (Migration 032–034); Verweis `TRAINING_FRAMEWORK_SPEC.md`
---
## 1. Datenmodell-Entscheidungen
### 1.1 Übung vs. Variante vs. Block vs. Serie
**Definitionen:**
- **Übung (Exercise):** Atomare Trainingseinheit mit Ziel, Durchführung, Vorbereitung
- Tabelle: `exercises`
- Beispiel: "Maai - Distanzübung"
- **Variante (Variant):** Angepasste Ausführung EINER Übung
- Tabelle: `exercise_variants`
- Beispiel: "Maai - Ohne Partner", "Maai - Mit Pratzen"
- Beziehung: 1:N (eine Übung hat 0-n Varianten)
- **Serie (Series):** Progression durch Varianten derselben Übung
- **KEINE eigene Tabelle** - Progression via Metadata in `exercise_variants`
- Felder: `progression_level`, `sequence_order`, `prerequisite_variant_id`
- Beispiel: Liegestütz → Level 1 (Knie), Level 2 (Normal), Level 3 (Erhöht), Level 4 (Einarmig)
- **Block (Block):** Sammlung UNTERSCHIEDLICHER Übungen als zusammenhängender Trainingsabschnitt
- Tabelle: `exercise_blocks` + `exercise_block_items`
- Beispiel: "Zirkel Oberkörper" → Liegestütz + Klimmzüge + Dips + Planks
- Beziehung: M:N (ein Block enthält viele Übungen, eine Übung kann in vielen Blöcken sein)
- **Template-Block:** Block mit Platzhaltern für spätere Befüllung
- Flag: `is_template = true` in `exercise_blocks`
- Beispiel: "Zirkeltraining (6 Stationen)" → Station 1: [Platzhalter: Push-Übung], Station 2: [Platzhalter: Pull-Übung], etc.
**Architektur-Diagramm:**
```
Exercise (1) ──────┬──── (N) Variants
│ ├── progression_level
│ ├── sequence_order
│ └── prerequisite_variant_id
│
└──── (M:N) Skills
└──── (M:N) Focus Areas
└──── (M:N) Training Styles
└──── (M:N) Target Groups
└──── (1:N) Media
Exercise Block ──── (N) Block Items ──── (1) Exercise
└── (1) Variant (optional)
└── is_placeholder (for templates)
```
### 1.1b Progressionsgraph zwischen Übungen (nicht „Serie“)
**Abgrenzung:** Separates Konzept von der **Varianten-Serie** (§1.1): hier geht es um **gerichtete Kanten zwischen verschiedenen Übungen** (optional mit Varianten als Knoten-Endpunkten), gruppiert in Bibliotheks-Containern (`exercise_progression_graphs`). Schema, REST, Produktgrenzen und Backlog (parallele Alternativ-Pakete): **`TRAINING_FRAMEWORK_SPEC.md`** §3–§4.
---
### 1.2 Medien-Strategie
**Zwei Medien-Typen:**
1. **Lokale Medien** (eigene Uploads)
- Storage: `/app/media/exercises/{uuid}_{filename}`
- Unterstützte Formate:
- Bilder: `image/jpeg`, `image/png`, `image/gif`
- Videos: `video/mp4`
- Dokumente: `application/pdf` (für Skizzen)
- Max Size: **50MB pro Datei**
- Max Count: **10 Dateien pro Übung**
2. **Embeds** (externe Plattformen)
- Unterstützte Plattformen:
- YouTube: `youtube.com/watch?v=...`, `youtu.be/...`
- Instagram: `instagram.com/p/...`, `instagram.com/reel/...`
- Vimeo: `vimeo.com/...`
- Speicherung: Nur URL + Platform-Identifier
- Rendering: iframe-Embed im Frontend
**Medien-Felder:**
- `file_path` (lokale Medien) **XOR** `embed_url` (externe Medien)
- `mime_type` (nur bei lokalen Medien)
- `embed_platform` (nur bei Embeds: 'youtube', 'instagram', 'vimeo')
- `sort_order` (für Reorder via Drag & Drop)
- `is_primary` (Hauptmedium, z.B. Vorschau-Bild)
- `context` (Kontext: 'ablauf', 'detail', 'trainer_hint')
**Storage-Management:**
- Uploads via FastAPI `UploadFile`
- Speicherort: Docker Volume `/app/media/exercises/`
- Cleanup: Bei Exercise-Deletion automatisch via CASCADE + Cleanup-Job
---
### 1.3 M:N Beziehungen (Primary/Secondary Pattern)
**Regel:** Alle Katalog-Zuordnungen nutzen M:N mit `is_primary` Flag.
**Betroffene Relationen:**
- `exercise_focus_areas` (Übung ↔ Fokusbereiche)
- `exercise_styles` (Übung ↔ Trainingsstile)
- `exercise_target_groups` (Übung ↔ Zielgruppen)
- `exercise_training_characters` (Übung ↔ Trainingscharaktere)
- `exercise_skills` (Übung ↔ Fähigkeiten)
**Primary/Secondary Semantik:**
- **Primary:** Hauptzuordnung, entscheidend für Filter/Suche
- **Secondary:** Nebenzuordnung, zusätzlicher Kontext
- **Regel:** Genau EINE Primary-Zuordnung pro Dimension
- **UI:** Primary wird visuell hervorgehoben (z.B. fett, farbig)
**Legacy-Felder (DEPRECATED):**
- `exercises.focus_area` → Ignorieren, nutze `exercise_focus_areas`
- `exercises.training_style_id` → Ignorieren, nutze `exercise_styles`
- `exercises.training_character_id` → Ignorieren, nutze `exercise_training_characters`
- **NICHT löschen** (Rückwärtskompatibilität), aber **nicht verwenden**
---
### 1.4 Sichtbarkeit & Freigabe
**3 Sichtbarkeits-Ebenen:**
- `private` - Nur Ersteller sieht Übung
- `club` - Alle Vereinsmitglieder sehen Übung
- `official` - Alle Nutzer sehen Übung (globale Standards)
**4 Status-Stufen:**
- `draft` - Entwurf, in Bearbeitung
- `in_review` - Zur Prüfung eingereicht
- `approved` - Freigegeben, produktiv nutzbar
- `archived` - Archiviert, nicht mehr aktiv
**Berechtigungsmatrix:**
| Aktion | Private | Club | Official |
|--------|---------|------|----------|
| **Sehen** | Nur Owner | Alle Club-Member | Alle Nutzer |
| **Bearbeiten** | Nur Owner | Nur Owner | Nur Superadmin |
| **Löschen** | Nur Owner | Nur Owner + Club-Admin | Nur Superadmin |
| **Freigeben** | Owner → Club | Club-Admin → Official | Superadmin |
**Freigabe-Workflow (vereinfacht in Phase 1):**
1. Trainer erstellt Übung (`private`, `draft`)
2. Trainer setzt Status auf `in_review`
3. Club-Admin prüft, setzt `approved` + `visibility = 'club'`
4. Superadmin kann auf `visibility = 'official'` setzen
**Phase 2+:** Explizite Freigabe-Requests (`content_change_requests` Tabelle)
---
## 2. API-Konventionen
### 2.1 Naming
**URL-Struktur:**
- **Collections:** Plural (`/api/exercises`)
- **Items:** Singular + ID (`/api/exercises/{id}`)
- **Sub-Resources:** Nested (`/api/exercises/{id}/variants`, `/api/exercises/{id}/media`)
- **Actions:** HTTP-Verben (POST, PUT, DELETE, GET)
**HTTP-Methoden:**
- `GET` - Read (Liste oder Detail)
- `POST` - Create (neue Ressource)
- `PUT` - Update (bestehende Ressource)
- `DELETE` - Delete
**Query-Parameter:**
- Snake-case: `focus_area`, `skill_id`, `search`
- Optional Filter: `?focus_area=karate&status=approved`
- Pagination: `?limit=50&offset=0`
---
### 2.2 Response-Format
**Erfolgreiche Responses:**
```json
// Liste (Array)
[
{"id": 1, "title": "...", ...},
{"id": 2, "title": "...", ...}
]
// Detail (Object mit Enrichment)
{
"id": 1,
"title": "...",
"skills": [...], // enriched M:N
"variants": [...], // enriched 1:N
"media": [...], // enriched 1:N
"focus_areas": [...], // enriched M:N
"training_styles": [...], // enriched M:N
"target_groups": [...], // enriched M:N
"age_groups_catalog": ["Kinder", "Teenager"]
}
// Create/Update (Created Object)
{
"id": 42,
... // full object wie GET Detail
}
// Delete
{"ok": true}
```
**Fehler-Responses:**
```json
{
"detail": "Human-readable error message"
}
```
---
### 2.3 Error-Handling
**HTTP-Status-Codes:**
- `200 OK` - Erfolgreiche GET/PUT/DELETE
- `201 Created` - Erfolgreiche POST
- `400 Bad Request` - Validierung fehlgeschlagen, fehlende Pflichtfelder
- `401 Unauthorized` - Kein oder ungültiges Auth-Token
- `403 Forbidden` - Keine Berechtigung (Sichtbarkeit/Ownership)
- `404 Not Found` - Ressource nicht gefunden
- `409 Conflict` - Duplikat, Constraint-Verletzung
- `413 Payload Too Large` - Datei zu groß
- `500 Internal Server Error` - Server-Fehler
**Error-Detail-Format:**
```json
{
"detail": "Titel, Ziel und Durchführung sind Pflichtfelder"
}
```
**Validation Errors (detailliert):**
```json
{
"detail": "Validation failed",
"errors": [
{"field": "title", "message": "Titel muss mindestens 3 Zeichen lang sein"},
{"field": "goal", "message": "Ziel ist ein Pflichtfeld"}
]
}
```
---
## 3. Frontend-Architektur
### 3.1 Route-Struktur
**Übungen-Routes:**
- `/exercises` → Grid/List mit Filtern (ExercisesPage)
- `/exercises/:id` → Detail-Ansicht (ExerciseDetailPage)
- `/exercises/:id/edit` → Edit-Formular (ExerciseEditPage - eigene Route, kein Modal)
- `/exercises/new` → Create-Formular (ExerciseCreatePage - eigene Route, kein Modal)
**Rationale für eigene Routes statt Modals:**
- Bessere Deep-Linking (shareable URLs)
- Browser-Navigation (Back-Button)
- State-Management einfacher
- Mobile-freundlicher
---
### 3.2 Komponenten-Hierarchie
```
pages/
ExercisesPage.jsx (Grid + Filters)
ExerciseDetailPage.jsx (Formatted View)
ExerciseEditPage.jsx (Edit Form)
ExerciseCreatePage.jsx (Create Form)
components/
exercise/
ExerciseCard.jsx (Grid-Item)
ExerciseQuickInfo.jsx (Summary-Box)
ExerciseSection.jsx (Collapsible Section)
VariantsList.jsx (Varianten-Akkordeon)
VariantCard.jsx (Einzelne Variante)
MediaGallery.jsx (Medien-Display)
MediaUploader.jsx (Upload/Embed-UI)
SkillsList.jsx (Fähigkeiten-Chips)
CatalogAssignments.jsx (Zuordnungen-Display)
forms/
ExerciseForm.jsx (Haupt-Formular, wiederverwendbar)
VariantForm.jsx (Varianten-Formular)
MediaUploadForm.jsx (Upload/Embed-Tabs)
MultiSelect.jsx (M:N Auswahl mit Primary-Toggle)
SkillsSelector.jsx (Skills mit Intensity/Level)
common/
Chip.jsx (Badge/Tag)
Badge.jsx (Status/Visibility)
Accordion.jsx (Collapsible Section)
Modal.jsx (Generisches Modal)
DragDropList.jsx (Reorder-Support)
```
---
### 3.3 State-Management
**Strategie: Minimal, lokal, server-zentriert**
- **Local State:** `useState` für UI (filter open/close, modal visible)
- **Server State:** `useEffect` + API-Calls (keine globale Cache)
- **Kein Redux/Zustand:** Context nur für Auth + Profile
- **Optimistic Updates:** Nur bei unkritischen Actions (reorder)
**Beispiel (ExercisesPage):**
```jsx
const [exercises, setExercises] = useState([])
const [filters, setFilters] = useState({focus_area: '', status: ''})
const [loading, setLoading] = useState(true)
useEffect(() => {
loadExercises(filters)
}, [filters])
const loadExercises = async (filters) => {
setLoading(true)
try {
const data = await api.listExercises(filters)
setExercises(data)
} catch (err) {
alert(err.message)
} finally {
setLoading(false)
}
}
```
---
## 4. Datenbank-Konventionen
### 4.1 Naming
- **Tabellen:** Plural, snake_case (`exercises`, `exercise_variants`)
- **Spalten:** snake_case (`created_at`, `is_primary`)
- **IDs:** `{table}_id` (`exercise_id`, `skill_id`)
- **Flags:** `is_*`, `has_*` (`is_primary`, `is_template`, `has_media`)
- **Timestamps:** `created_at`, `updated_at`
---
### 4.2 Standard-Spalten (IMMER)
**Pflicht für alle Tabellen:**
```sql
id SERIAL PRIMARY KEY
created_at TIMESTAMP DEFAULT NOW()
updated_at TIMESTAMP DEFAULT NOW() -- nur bei mutablen Tabellen
```
**Mutable vs. Immutable:**
- **Mutable:** `exercises`, `exercise_variants`, `exercise_blocks` → haben `updated_at`
- **Immutable:** `exercise_skills`, `exercise_focus_areas` → kein `updated_at`
---
### 4.3 Foreign Keys
**Regeln:**
- **Immer mit ON DELETE:** `CASCADE` oder `RESTRICT` (nie ohne!)
- **Immer mit Index:** Für alle FK-Spalten
- **Naming:** `fk_{from_table}_{to_table}` (optional, für Debugging)
**Beispiele:**
```sql
-- CASCADE: Löschen der Parent-Ressource löscht auch Children
exercise_id INT REFERENCES exercises(id) ON DELETE CASCADE
-- RESTRICT: Löschen der Parent-Ressource verhindert wenn Children existieren
skill_id INT REFERENCES skills(id) ON DELETE RESTRICT
-- SET NULL: Löschen setzt FK auf NULL (für optionale Beziehungen)
prerequisite_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL
```
---
### 4.4 JSONB vs. Tabellen
**JSONB verwenden wenn:**
- Daten unstrukturiert
- Selten gefiltert/gesucht
- Flexible Schema-Änderungen nötig
**Beispiele:**
- `equipment` JSONB - Liste von Geräten (["Matten", "Pratzen"])
- `secondary_method_ids` JSONB - Liste von IDs ([2, 5, 7])
- `placeholder_criteria` JSONB - Filter-Kriterien für Platzhalter
**Tabelle verwenden wenn:**
- Daten strukturiert
- Oft gefiltert/gesucht
- Referentielle Integrität nötig (Foreign Keys)
**Beispiele:**
- `exercise_skills` - M:N Beziehung, oft gefiltert
- `exercise_variants` - Strukturierte Daten, oft einzeln abgerufen
- `exercise_media` - Referentielle Integrität (ON DELETE CASCADE)
---
## 5. Migrations-Strategie
### 5.1 Naming
**Format:** `{NNN}_{descriptive_name}.sql`
- NNN = laufende Nummer (3-stellig mit führenden Nullen)
- Beschreibend, nicht kryptisch
- Beispiele:
- `014_variants_progression.sql`
- `015_media_upload.sql`
- `016_exercise_blocks.sql`
---
### 5.2 Idempotenz
**Regel:** Migrationen müssen mehrfach ausführbar sein ohne Fehler.
**Immer verwenden:**
```sql
-- Tabellen
CREATE TABLE IF NOT EXISTS ...
-- Spalten
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name='...' AND column_name='...') THEN
ALTER TABLE ... ADD COLUMN ...;
END IF;
END $$;
-- Indizes
CREATE INDEX IF NOT EXISTS ...
-- Constraints
ALTER TABLE ... ADD CONSTRAINT ... IF NOT EXISTS ...
```
**Niemals:**
```sql
DROP TABLE ... -- ohne IF EXISTS
ALTER TABLE ... DROP COLUMN ... -- ohne Check
```
---
### 5.3 Data Migration
**Reihenfolge bei Schema-Änderungen:**
1. **Backup:** Alte Daten sichern (z.B. `_backup` Suffix)
2. **Schema-Änderung:** Neue Spalten/Tabellen hinzufügen
3. **Data-Migration:** Alte Daten in neues Schema überführen
4. **Validation:** Daten-Integrität prüfen
5. **Cleanup:** Alte Spalten/Tabellen als deprecated markieren (nicht sofort löschen!)
**Beispiel (Migration 008):**
```sql
-- 1. Backup (implizit via alte Spalten behalten)
-- 2. Schema
CREATE TABLE exercise_focus_areas ...
-- 3. Data Migration
INSERT INTO exercise_focus_areas (exercise_id, focus_area_id, is_primary)
SELECT id, focus_area_id, true
FROM exercises
WHERE focus_area_id IS NOT NULL
ON CONFLICT DO NOTHING;
-- 4. Validation (manuell via Query)
-- 5. Cleanup (später, wenn sicher)
-- ALTER TABLE exercises DROP COLUMN focus_area_id; -- NICHT JETZT!
```
---
### 5.4 Rollback-Plan
**Jede Migration braucht:**
- Dokumentierter Rollback-Plan (im Kommentar)
- Test auf Dev-System
- Validierung nach Ausführung
**Beispiel:**
```sql
-- Migration 014: Variants Progression
-- Rollback: DROP COLUMNS progression_level, sequence_order, prerequisite_variant_id
-- Risk: LOW (nur neue Spalten, kein Data Loss)
-- Validation: SELECT COUNT(*) FROM exercise_variants WHERE progression_level IS NOT NULL;
ALTER TABLE exercise_variants
ADD COLUMN IF NOT EXISTS progression_level INT;
```
---
## 6. Testing-Strategie (Phase 2)
### 6.1 Backend
**Unit-Tests:**
- Resolver-Funktionen (z.B. `get_exercise()`)
- Validation-Logik (z.B. `validate_exercise()`)
- Helper-Funktionen (z.B. `parse_embed_url()`)
**Integration-Tests:**
- API-Endpoints (Request → Response)
- DB-Transaktionen (Create → Read → Update → Delete)
- Permissions (Auth + Visibility)
**Migration-Tests:**
- Up/Down-Migrationen
- Data-Integrity nach Migration
---
### 6.2 Frontend
**Component-Tests (Jest + React Testing Library):**
- ExerciseCard rendert korrekt
- ExerciseForm validiert Inputs
- MultiSelect verhält sich korrekt
**E2E-Tests (Playwright):**
- User kann Übung erstellen
- User kann Übung bearbeiten
- User kann Varianten hinzufügen
- User kann Medien hochladen
**Visual Regression (optional):**
- Chromatic / Percy
- Screenshots vergleichen
---
## 7. Dokumentations-Konventionen
### 7.1 Code-Kommentare
**Python Docstrings:**
```python
def get_exercise(exercise_id: int, session: dict) -> dict:
"""
Get exercise by ID with all enriched data.
Args:
exercise_id: Exercise ID
session: Auth session from require_auth()
Returns:
dict: Exercise object with skills, variants, media, catalog assignments
Raises:
HTTPException: 404 if not found, 403 if forbidden
"""
```
**JSDoc (für komplexe Komponenten):**
```jsx
/**
* ExerciseCard - Grid item für Übungsdarstellung
*
* @param {Object} exercise - Exercise object from API
* @param {Function} onClick - Handler für Detail-Klick
* @param {Function} onEdit - Handler für Edit-Klick
* @param {Function} onDelete - Handler für Delete-Klick
* @param {boolean} compact - Kompakte Darstellung (optional)
*/
export function ExerciseCard({ exercise, onClick, onEdit, onDelete, compact = false }) {
// ...
}
```
**Inline-Kommentare:**
- Nur für nicht-offensichtliche Logik
- Warum, nicht Was
- Beispiel: `// Prerequisite muss zur gleichen Übung gehören`
---
### 7.2 Markdown-Docs
**Struktur:**
- `functional/` - Fachliche Specs (WAS soll gebaut werden)
- `technical/` - Technische Specs (WIE wird es gebaut)
- `working/` - Temporäre Analysen, Notizen (kann veraltet sein)
- `audit/` - Reviews, Matrizen, Checklisten
**Update-Regel:**
- Nach jedem Feature: Doku aktualisieren
- Version im Header erhöhen
- Änderungslog im Dokument
---
## 8. Entscheidungs-Log
| Datum | Entscheidung | Rationale | Impact |
|-------|--------------|-----------|--------|
| 2026-04-24 | M:N statt 1:1 für Katalog-Zuordnungen | Flexibilität, keine Duplikate, bessere Filter | Alle Übungen müssen migriert werden (Migration 008) |
| 2026-04-24 | Varianten für Progression statt eigene Serie-Tabelle | Einfacher, weniger Joins, direkte Beziehung | Variants-Tabelle erweitern (Migration 014) |
| 2026-04-24 | Lokale Medien + Embeds (nicht Cloud) | Kostenkontrolle, Datenschutz, keine Vendor-Lock-in | Storage-Management nötig, Backup-Strategie |
| 2026-04-24 | Eigene Routes statt Modals für Edit/Create | Deep-Linking, Browser-Navigation, Mobile-UX | Mehr Routes, aber bessere UX |
| 2026-04-24 | MediaWiki API statt Export | Live-Sync möglich, aktuellere Daten | API-Client implementieren, Semantic MediaWiki verstehen |
| 2026-04-24 | JSONB für Equipment, nicht eigene Tabelle | Flexibel, selten gefiltert, keine Overhead | Keine Referentielle Integrität, Full-Text-Suche schwieriger |
---
## 9. Offene Punkte / TODOs
**Für Review:**
- [ ] Sichtbarkeits-Matrix OK? (private/club/official)
- [ ] Freigabe-Workflow ausreichend einfach?
- [ ] Medien-Limits OK? (50MB, 10 Files)
- [ ] JSONB vs. Tabellen für Equipment richtig entschieden?
**Für Phase 2:**
- [ ] Explizite Freigabe-Requests (content_change_requests)
- [ ] Saved Searches
- [ ] Advanced Filters (Kombination mehrerer Kriterien)
- [ ] Batch-Operations (Multi-Select + Delete/Archive)
---
**Version:** 1.0
**Letzte Änderung:** 2026-04-24
**Status:** DRAFT - Awaiting Review
@@ -0,0 +1,912 @@
# Database Schema Final - Exercises System
**Version:** 1.2
**Datum:** 2026-04-24
**Status:** REVIEWED - Pending Implementation
**Autor:** Claude Code
**Änderungen v1.2:** Skill-Level auf benannte Stufen (einsteiger–experte), intensity auf niedrig/mittel/hoch, ai_suggested Felder, summary_ai_generated
**Änderungen v1.1:** age_groups JSONB entfernt, Legacy-DROP ergänzt, Migration 017 (Exercise Blocks)
---
## 1. Übersicht
**Neue Migrationen:**
- **Migration 014:** Variant Progression System + Search Vector + Legacy-Cleanup
- **Migration 015:** Semantic Matching (OPTIONAL - Phase 2)
- **Migration 016:** Saved Searches
- **Migration 017:** Exercise Blocks + Template Blocks
**Basis:** Migrationen 001-013 (bereits deployed)
**Progressionsgraph zwischen Übungen:** Migrationen **032–034** — nicht Bestandteil dieses „Exercise Catalog“-Schemas-Dokuments; siehe **`TRAINING_FRAMEWORK_SPEC.md`** §3 und **`DATABASE_SCHEMA.md`** (Migrationshistorie).
---
## 2. Migration 014: Variant Progression + Search
### 2.1 Vollständige Migration
```sql
-- Migration 014: Variant Progression System + Search Vector
-- Autor: Claude Code
-- Datum: 2026-04-24
DO $$
BEGIN
-- ============================================================================
-- VARIANT PROGRESSION
-- ============================================================================
-- Erweitere exercise_variants Tabelle
ALTER TABLE exercise_variants
ADD COLUMN IF NOT EXISTS progression_level INT DEFAULT 1 CHECK (progression_level BETWEEN 1 AND 10),
ADD COLUMN IF NOT EXISTS sequence_order INT,
ADD COLUMN IF NOT EXISTS prerequisite_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL;
-- Index für Prerequisites
CREATE INDEX IF NOT EXISTS idx_exercise_variants_prerequisite
ON exercise_variants(prerequisite_variant_id);
-- ============================================================================
-- SEARCH VECTOR (Volltext-Suche)
-- ============================================================================
-- Füge search_vector zu exercises hinzu
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS search_vector tsvector;
-- Index für Volltext-Suche
CREATE INDEX IF NOT EXISTS idx_exercises_search
ON exercises USING gin(search_vector);
-- Funktion für automatisches Update
CREATE OR REPLACE FUNCTION update_exercises_search_vector()
RETURNS trigger AS $func$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('german', COALESCE(NEW.title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(NEW.summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(NEW.trainer_notes, '')), 'D');
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
-- Trigger
DROP TRIGGER IF EXISTS exercises_search_update ON exercises;
CREATE TRIGGER exercises_search_update
BEFORE INSERT OR UPDATE ON exercises
FOR EACH ROW EXECUTE FUNCTION update_exercises_search_vector();
-- Initiales Befüllen (für existierende Zeilen)
UPDATE exercises SET search_vector = (
setweight(to_tsvector('german', COALESCE(title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(trainer_notes, '')), 'D')
) WHERE search_vector IS NULL;
-- ============================================================================
-- LEGACY COLUMN CLEANUP
-- Deprecated Felder aus exercises (ersetzt durch M:N Tabellen in Migration 008+)
-- ============================================================================
-- age_groups JSONB → ersetzt durch exercise_age_groups M:N (seit Migration 008)
ALTER TABLE exercises DROP COLUMN IF EXISTS age_groups;
-- focus_area VARCHAR → ersetzt durch exercise_focus_areas M:N (seit Migration 008)
ALTER TABLE exercises DROP COLUMN IF EXISTS focus_area;
-- secondary_areas JSONB → ersetzt durch exercise_focus_areas M:N
ALTER TABLE exercises DROP COLUMN IF EXISTS secondary_areas;
-- training_character VARCHAR → ersetzt durch exercise_training_characters M:N (seit Migration 012)
ALTER TABLE exercises DROP COLUMN IF EXISTS training_character;
-- ============================================================================
-- ADDITIONAL INDEXES (Performance)
-- ============================================================================
-- Häufige Filter
CREATE INDEX IF NOT EXISTS idx_exercises_visibility ON exercises(visibility);
CREATE INDEX IF NOT EXISTS idx_exercises_status ON exercises(status);
CREATE INDEX IF NOT EXISTS idx_exercises_created_at ON exercises(created_at DESC);
-- M:N Relations (falls noch nicht vorhanden)
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_focus
ON exercise_focus_areas(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_exercise_styles_style
ON exercise_training_styles(training_style_id);
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_group
ON exercise_target_groups(target_group_id);
CREATE INDEX IF NOT EXISTS idx_exercise_skills_skill
ON exercise_skills(skill_id);
RAISE NOTICE 'Migration 014 completed successfully';
END $$;
```
---
## 3. Migration 015: Semantic Matching (Optional Phase 2)
**Diese Migration ist optional für MVP Phase 1**
```sql
-- Migration 015: Semantic Exercise Matching (OPTIONAL - Phase 2)
-- Nutzt pgvector extension für Similarity-Matching
-- Autor: Claude Code
-- Datum: 2026-04-24
DO $$
BEGIN
-- ============================================================================
-- SEMANTIC EMBEDDINGS (Optional)
-- ============================================================================
-- Benötigt pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Erweitere exercises Tabelle
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS embedding vector(1536); -- OpenAI ada-002 embedding size
-- Index für Ähnlichkeitssuche
CREATE INDEX IF NOT EXISTS idx_exercises_embedding
ON exercises USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- Funktion für Similarity-Search
CREATE OR REPLACE FUNCTION find_similar_exercises(
query_embedding vector(1536),
limit_count INT DEFAULT 10
)
RETURNS TABLE (
exercise_id INT,
title VARCHAR,
similarity FLOAT
) AS $func$
BEGIN
RETURN QUERY
SELECT
id,
title,
1 - (embedding <=> query_embedding) AS similarity
FROM exercises
WHERE embedding IS NOT NULL
ORDER BY embedding <=> query_embedding
LIMIT limit_count;
END;
$func$ LANGUAGE plpgsql;
RAISE NOTICE 'Migration 015 completed successfully (Semantic Matching - OPTIONAL)';
END $$;
```
**Hinweis:** Embeddings werden über separaten Background-Job befüllt, nicht beim INSERT.
---
## 4. Migration 016: Saved Searches
```sql
-- Migration 016: Saved Exercise Searches
-- Autor: Claude Code
-- Datum: 2026-04-24
DO $$
BEGIN
-- ============================================================================
-- SAVED SEARCHES
-- ============================================================================
CREATE TABLE IF NOT EXISTS saved_exercise_searches (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
filters JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Index für User-Zugriff
CREATE INDEX IF NOT EXISTS idx_saved_searches_profile
ON saved_exercise_searches(profile_id);
-- Trigger für updated_at
CREATE OR REPLACE FUNCTION update_saved_searches_timestamp()
RETURNS trigger AS $func$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS saved_searches_update ON saved_exercise_searches;
CREATE TRIGGER saved_searches_update
BEFORE UPDATE ON saved_exercise_searches
FOR EACH ROW EXECUTE FUNCTION update_saved_searches_timestamp();
RAISE NOTICE 'Migration 016 completed successfully';
END $$;
```
---
## 5. Migration 017: Exercise Blocks + Template Blocks
```sql
-- Migration 017: Exercise Blocks + Template Blocks
-- Autor: Claude Code
-- Datum: 2026-04-24
-- Zweck: Gruppierung verschiedener Übungen in Blöcken (User-Anforderung #4)
-- Series = Varianten-Progression (via exercise_variants, KEINE eigene Tabelle)
-- Blocks = Verschiedene Übungen in Reihenfolge (DIESE Migration)
DO $$
BEGIN
-- ============================================================================
-- EXERCISE BLOCKS
-- Eine Sammlung verschiedener Übungen in definierter Reihenfolge
-- ============================================================================
CREATE TABLE IF NOT EXISTS exercise_blocks (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
goal TEXT,
-- Template-Modus: Block mit Platzhaltern für flexible Planung
is_template BOOLEAN DEFAULT false,
-- Ownership & Sichtbarkeit
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
visibility VARCHAR(20) DEFAULT 'private' CHECK (visibility IN ('private', 'club', 'official')),
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- ============================================================================
-- EXERCISE BLOCK ITEMS
-- Einzelne Positionen innerhalb eines Blocks
-- ============================================================================
CREATE TABLE IF NOT EXISTS exercise_block_items (
id SERIAL PRIMARY KEY,
block_id INT NOT NULL REFERENCES exercise_blocks(id) ON DELETE CASCADE,
-- Konkrete Übung (NULL wenn is_placeholder = true)
exercise_id INT REFERENCES exercises(id) ON DELETE RESTRICT,
-- Optionale Variante (kann NULL sein → Haupt-Übung wird genutzt)
variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
-- Reihenfolge innerhalb des Blocks
sequence_order INT NOT NULL,
-- Template-Modus: Platzhalter statt konkreter Übung
is_placeholder BOOLEAN DEFAULT false,
-- Kriterien für Platzhalter-Auflösung (nur relevant wenn is_placeholder = true)
-- Schema: {"focus_area_id": 1, "max_duration": 10, "skill_ids": [3, 7], "difficulty": "easier"}
-- Alle Felder optional, werden als AND-Filter bei der Übungssuche genutzt
placeholder_criteria JSONB,
-- Platzhalter-Beschriftung (für UX im Template-Modus)
placeholder_label VARCHAR(100), -- z.B. "Aufwärmübung Schlag", "Hauptübung Kumite"
-- Zusätzliche Notizen für diese Position
notes TEXT,
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
-- Constraints
UNIQUE(block_id, sequence_order),
-- Entweder exercise_id ODER is_placeholder=true
CHECK (
(is_placeholder = false AND exercise_id IS NOT NULL) OR
(is_placeholder = true AND exercise_id IS NULL)
)
);
-- ============================================================================
-- INDEXES
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_club ON exercise_blocks(club_id);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_creator ON exercise_blocks(created_by);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_visibility ON exercise_blocks(visibility);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_template ON exercise_blocks(is_template) WHERE is_template = true;
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_block ON exercise_block_items(block_id);
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_exercise ON exercise_block_items(exercise_id);
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_placeholder ON exercise_block_items(is_placeholder) WHERE is_placeholder = true;
-- ============================================================================
-- UPDATED_AT TRIGGER
-- ============================================================================
DROP TRIGGER IF EXISTS exercise_blocks_update ON exercise_blocks;
CREATE TRIGGER exercise_blocks_update
BEFORE UPDATE ON exercise_blocks
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
RAISE NOTICE 'Migration 017 completed successfully (Exercise Blocks)';
END $$;
```
### 5.0 Placeholder Criteria Schema
Das `placeholder_criteria` JSONB-Feld in `exercise_block_items` erlaubt folgende Schlüssel (alle optional, werden als AND-Filter kombiniert):
```json
{
"focus_area_id": 1, // INT: Fokusbereich-ID
"training_style_id": 2, // INT: Stil-ID
"target_group_id": 5, // INT: Zielgruppen-ID
"skill_ids": [3, 7], // INT[]: Mindestens eine dieser Fähigkeiten
"max_duration": 15, // INT: Maximale Dauer in Minuten
"min_duration": 5, // INT: Minimale Dauer in Minuten
"difficulty": "easier", // "easier" | "same" | "harder"
"visibility": "club" // "private" | "club" | "official"
}
```
**Validierung:** Backend prüft, dass alle vorhandenen Schlüssel bekannte Felder sind und die Werte dem erwarteten Typ entsprechen.
---
## 6. Vollständige Tabellenstruktur (Final State)
### 5.1 exercises (Kern-Tabelle)
```sql
CREATE TABLE exercises (
id SERIAL PRIMARY KEY,
-- Basis-Info
title VARCHAR(300) NOT NULL,
summary TEXT,
goal TEXT NOT NULL,
execution TEXT NOT NULL,
preparation TEXT,
trainer_notes TEXT,
-- Dauer & Gruppengröße
duration_min INT,
duration_max INT,
group_size_min INT,
group_size_max INT,
-- JSONB-Felder
equipment JSONB DEFAULT '[]'::jsonb,
-- HINWEIS: age_groups werden via exercise_age_groups M:N Tabelle verwaltet (nicht JSONB)
-- Suche
search_vector tsvector, -- NEU in Migration 014
-- Semantic Matching (optional)
embedding vector(1536), -- NEU in Migration 015 (optional)
-- Sichtbarkeit & Status
visibility VARCHAR(20) DEFAULT 'private' CHECK (visibility IN ('private', 'club', 'official')),
status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'in_review', 'approved', 'archived')),
-- Ownership
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
-- Import-Tracking
import_source VARCHAR(50), -- 'mediawiki', 'csv', etc.
import_id VARCHAR(100), -- Original-ID aus Quellsystem
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
### 5.2 exercise_variants
```sql
CREATE TABLE exercise_variants (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
-- Variant-Details
variant_name VARCHAR(200) NOT NULL,
description TEXT,
execution_changes TEXT,
-- Dauer (Override)
duration_min INT,
duration_max INT,
-- Equipment-Änderungen
equipment_changes JSONB DEFAULT '[]'::jsonb,
-- Schwierigkeit
difficulty_adjustment VARCHAR(20) CHECK (difficulty_adjustment IN ('easier', 'same', 'harder')),
-- Progression (NEU in Migration 014)
progression_level INT DEFAULT 1 CHECK (progression_level BETWEEN 1 AND 10),
sequence_order INT,
prerequisite_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
### 5.3 exercise_media
```sql
CREATE TABLE exercise_media (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
-- Media-Type
media_type VARCHAR(20) CHECK (media_type IN ('image', 'video', 'document', 'sketch')),
-- Lokale Datei (exklusiv mit embed_url)
file_path VARCHAR(500),
file_size INT,
mime_type VARCHAR(100),
original_filename VARCHAR(300),
-- Embed (exklusiv mit file_path)
embed_url TEXT,
embed_platform VARCHAR(50), -- 'youtube', 'vimeo', 'instagram', 'tiktok'
-- Metadata
title VARCHAR(200),
description TEXT,
sort_order INT DEFAULT 1,
is_primary BOOLEAN DEFAULT FALSE,
context VARCHAR(50) DEFAULT 'ablauf' CHECK (context IN ('ablauf', 'detail', 'trainer_hint')),
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Constraint: Entweder file_path ODER embed_url
CHECK (
(file_path IS NOT NULL AND embed_url IS NULL) OR
(file_path IS NULL AND embed_url IS NOT NULL)
)
);
```
### 5.4 M:N Relation Tables
**exercise_focus_areas:**
```sql
CREATE TABLE exercise_focus_areas (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, focus_area_id)
);
```
**exercise_training_styles:**
```sql
CREATE TABLE exercise_training_styles (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
training_style_id INT NOT NULL REFERENCES training_styles(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, training_style_id)
);
```
**exercise_target_groups:**
```sql
CREATE TABLE exercise_target_groups (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
target_group_id INT NOT NULL REFERENCES target_groups(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, target_group_id)
);
```
**exercise_age_groups:**
```sql
CREATE TABLE exercise_age_groups (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
age_group_name VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, age_group_name)
);
```
**exercise_skills:**
```sql
CREATE TABLE exercise_skills (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT FALSE,
-- Kompetenzmodell: benannte Stufen (nicht numerisch 1-10)
-- NULL = nicht definiert / nicht relevant
required_level VARCHAR(20) CHECK (required_level IN ('einsteiger', 'grundlagen', 'aufbau', 'fortgeschritten', 'experte')),
target_level VARCHAR(20) CHECK (target_level IN ('einsteiger', 'grundlagen', 'aufbau', 'fortgeschritten', 'experte')),
-- Trainingsintensität: Wie stark wird diese Fähigkeit in der Übung trainiert
intensity VARCHAR(10) CHECK (intensity IN ('niedrig', 'mittel', 'hoch')),
-- KI-generierte Zuordnung (false = manuell bestätigt)
ai_suggested BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, skill_id)
);
```
**Skill-Level-Definitionen (Kompetenzmodell):**
| Stufe | Wert | Beschreibung | Beispiel Distanzgefühl |
|-------|------|--------------|----------------------|
| 1 | `einsteiger` | Erste Berührung mit der Fähigkeit, kein Vorwissen nötig | Versteht das Konzept Distanz |
| 2 | `grundlagen` | Grundprinzipien bekannt, in einfachen Situationen anwendbar | Hält in ruhigen Übungen Distanz |
| 3 | `aufbau` | Sicher in Standard-Situationen, braucht noch Korrektur | Distanzkontrolle in Partnerübungen |
| 4 | `fortgeschritten` | Zuverlässig auch unter Druck, wenig Fehler | Stabile Distanz im Sparring |
| 5 | `experte` | Automatisiert, intuitiv, auch in komplexen Situationen | Feines Distanzgefühl im Wettkampf |
**Für Migration 014 ergänzen:**
```sql
-- In Migration 014 nach den Variant-Columns ergänzen:
-- Skill-Level auf VARCHAR umstellen (bestehende INT-Werte migrieren)
ALTER TABLE exercise_skills
ALTER COLUMN required_level TYPE VARCHAR(20) USING
CASE required_level
WHEN 0 THEN NULL
WHEN 1 THEN 'einsteiger'
WHEN 2 THEN 'grundlagen'
WHEN 3 THEN 'aufbau'
WHEN 4 THEN 'fortgeschritten'
WHEN 5 THEN 'experte'
ELSE NULL
END,
ALTER COLUMN target_level TYPE VARCHAR(20) USING
CASE target_level
WHEN 0 THEN NULL
WHEN 1 THEN 'einsteiger'
WHEN 2 THEN 'grundlagen'
WHEN 3 THEN 'aufbau'
WHEN 4 THEN 'fortgeschritten'
WHEN 5 THEN 'experte'
ELSE NULL
END,
ALTER COLUMN intensity TYPE VARCHAR(10) USING
CASE
WHEN intensity <= 3 THEN 'niedrig'
WHEN intensity <= 7 THEN 'mittel'
ELSE 'hoch'
END;
-- Neue Constraints hinzufügen
ALTER TABLE exercise_skills
ADD CONSTRAINT ck_required_level CHECK (required_level IN ('einsteiger', 'grundlagen', 'aufbau', 'fortgeschritten', 'experte')),
ADD CONSTRAINT ck_target_level CHECK (target_level IN ('einsteiger', 'grundlagen', 'aufbau', 'fortgeschritten', 'experte')),
ADD CONSTRAINT ck_intensity CHECK (intensity IN ('niedrig', 'mittel', 'hoch'));
-- KI-Tracking Feld
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS summary_ai_generated BOOLEAN DEFAULT false;
ALTER TABLE exercise_skills
ADD COLUMN IF NOT EXISTS ai_suggested BOOLEAN DEFAULT false;
```
**exercise_training_characters:**
```sql
CREATE TABLE exercise_training_characters (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
training_character_id INT NOT NULL REFERENCES training_characters(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, training_character_id)
);
```
### 6.5 Exercise Blocks (Migration 017)
```sql
CREATE TABLE exercise_blocks (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
goal TEXT,
is_template BOOLEAN DEFAULT false,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
visibility VARCHAR(20) DEFAULT 'private' CHECK (visibility IN ('private', 'club', 'official')),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE exercise_block_items (
id SERIAL PRIMARY KEY,
block_id INT NOT NULL REFERENCES exercise_blocks(id) ON DELETE CASCADE,
exercise_id INT REFERENCES exercises(id) ON DELETE RESTRICT,
variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
sequence_order INT NOT NULL,
is_placeholder BOOLEAN DEFAULT false,
placeholder_criteria JSONB,
placeholder_label VARCHAR(100),
notes TEXT,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(block_id, sequence_order),
CHECK (
(is_placeholder = false AND exercise_id IS NOT NULL) OR
(is_placeholder = true AND exercise_id IS NULL)
)
);
```
### 6.6 Saved Searches (Migration 016)
```sql
CREATE TABLE saved_exercise_searches (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
filters JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
---
## 6. Indizes (Komplett-Übersicht)
```sql
-- Volltext-Suche
CREATE INDEX idx_exercises_search ON exercises USING gin(search_vector);
-- Semantic Matching (optional)
CREATE INDEX idx_exercises_embedding ON exercises USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
-- Häufige Filter
CREATE INDEX idx_exercises_visibility ON exercises(visibility);
CREATE INDEX idx_exercises_status ON exercises(status);
CREATE INDEX idx_exercises_created_at ON exercises(created_at DESC);
CREATE INDEX idx_exercises_club ON exercises(club_id);
CREATE INDEX idx_exercises_creator ON exercises(created_by);
-- M:N Relations
CREATE INDEX idx_exercise_focus_areas_exercise ON exercise_focus_areas(exercise_id);
CREATE INDEX idx_exercise_focus_areas_focus ON exercise_focus_areas(focus_area_id);
CREATE INDEX idx_exercise_styles_exercise ON exercise_training_styles(exercise_id);
CREATE INDEX idx_exercise_styles_style ON exercise_training_styles(training_style_id);
CREATE INDEX idx_exercise_target_groups_exercise ON exercise_target_groups(exercise_id);
CREATE INDEX idx_exercise_target_groups_group ON exercise_target_groups(target_group_id);
CREATE INDEX idx_exercise_skills_exercise ON exercise_skills(exercise_id);
CREATE INDEX idx_exercise_skills_skill ON exercise_skills(skill_id);
CREATE INDEX idx_exercise_characters_exercise ON exercise_training_characters(exercise_id);
CREATE INDEX idx_exercise_characters_character ON exercise_training_characters(training_character_id);
-- Variants
CREATE INDEX idx_exercise_variants_exercise ON exercise_variants(exercise_id);
CREATE INDEX idx_exercise_variants_prerequisite ON exercise_variants(prerequisite_variant_id);
-- Media
CREATE INDEX idx_exercise_media_exercise ON exercise_media(exercise_id);
CREATE INDEX idx_exercise_media_primary ON exercise_media(is_primary) WHERE is_primary = true;
CREATE INDEX idx_exercise_media_context ON exercise_media(context);
-- Saved Searches
CREATE INDEX idx_saved_searches_profile ON saved_exercise_searches(profile_id);
-- Exercise Blocks
CREATE INDEX idx_exercise_blocks_club ON exercise_blocks(club_id);
CREATE INDEX idx_exercise_blocks_creator ON exercise_blocks(created_by);
CREATE INDEX idx_exercise_blocks_visibility ON exercise_blocks(visibility);
CREATE INDEX idx_exercise_blocks_template ON exercise_blocks(is_template) WHERE is_template = true;
CREATE INDEX idx_exercise_block_items_block ON exercise_block_items(block_id);
CREATE INDEX idx_exercise_block_items_exercise ON exercise_block_items(exercise_id);
CREATE INDEX idx_exercise_block_items_placeholder ON exercise_block_items(is_placeholder) WHERE is_placeholder = true;
```
---
## 7. Constraints & Business Rules
### 7.1 Data Integrity
**Exercises:**
- `title` mindestens 3 Zeichen
- `goal` mindestens 10 Zeichen
- `execution` mindestens 10 Zeichen
- `duration_min <= duration_max`
- `group_size_min <= group_size_max`
**Variants:**
- `variant_name` mindestens 3 Zeichen
- `prerequisite_variant_id` muss zum gleichen Exercise gehören
**Media:**
- Max. 50 MB per file (enforced in Backend)
- Max. 10 media items per exercise (enforced in Backend)
- Entweder `file_path` ODER `embed_url` (enforced in CHECK)
### 7.2 Cascading Delete
**ON DELETE CASCADE:**
- exercise → variants
- exercise → media
- exercise → M:N relations (focus_areas, styles, etc.)
- profile → saved searches
**ON DELETE RESTRICT:**
- focus_area → exercise_focus_areas (verhindert Löschen genutzter Katalog-Einträge)
- skill → exercise_skills
- target_group → exercise_target_groups
**ON DELETE SET NULL:**
- profile (creator) → exercises
- club → exercises
- variant (prerequisite) → variants
---
## 8. Trigger-Funktionen
### 8.1 Search Vector Auto-Update
```sql
CREATE OR REPLACE FUNCTION update_exercises_search_vector()
RETURNS trigger AS $$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('german', COALESCE(NEW.title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(NEW.summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(NEW.trainer_notes, '')), 'D');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER exercises_search_update
BEFORE INSERT OR UPDATE ON exercises
FOR EACH ROW EXECUTE FUNCTION update_exercises_search_vector();
```
### 8.2 Updated_At Timestamp
```sql
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS trigger AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger für alle relevanten Tabellen
CREATE TRIGGER exercises_update_timestamp
BEFORE UPDATE ON exercises
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
CREATE TRIGGER exercise_variants_update_timestamp
BEFORE UPDATE ON exercise_variants
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
CREATE TRIGGER exercise_media_update_timestamp
BEFORE UPDATE ON exercise_media
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
CREATE TRIGGER saved_searches_update_timestamp
BEFORE UPDATE ON saved_exercise_searches
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
```
---
## 9. Migrations-Tracking
**Tabelle: schema_migrations**
```sql
CREATE TABLE IF NOT EXISTS schema_migrations (
migration_id VARCHAR(50) PRIMARY KEY,
description TEXT,
applied_at TIMESTAMP DEFAULT NOW()
);
```
**Nach jeder Migration:**
```sql
INSERT INTO schema_migrations (migration_id, description) VALUES
('014', 'Variant Progression System + Search Vector + Legacy-Cleanup'),
('015', 'Semantic Exercise Matching (OPTIONAL)'),
('016', 'Saved Exercise Searches'),
('017', 'Exercise Blocks + Template Blocks');
```
---
## 10. Datenbank-Größenabschätzung
**Annahmen:**
- 5.000 Übungen
- Durchschnittlich 2 Varianten pro Übung
- Durchschnittlich 3 Media-Items pro Übung
- Durchschnittlich 5 M:N Zuordnungen pro Übung
**Geschätzte Zeilen:**
```
exercises: 5.000
exercise_variants: 10.000
exercise_media: 15.000
exercise_focus_areas: 10.000
exercise_training_styles: 10.000
exercise_target_groups: 10.000
exercise_skills: 25.000
exercise_blocks: 1.000
exercise_block_items: 5.000
─────────────────────────────────────
TOTAL: 101.000 Zeilen
```
**Speicherbedarf (ohne Media-Files):**
- exercises Tabelle: ~50 MB (mit search_vector + embedding)
- Alle M:N Tabellen: ~10 MB
- Variants + Media: ~5 MB
- **Total DB:** ~65 MB
**Media-Files (lokal gespeichert):**
- 15.000 Items × 5 MB Durchschnitt = ~75 GB
---
## 11. Performance-Benchmarks
**Target Query Performance:**
- List Exercises (ohne Filter): < 50ms
- List Exercises (mit 3 Filtern): < 100ms
- Volltext-Suche: < 150ms
- Exercise Detail (enriched): < 80ms
- Semantic Similarity: < 200ms (optional)
**Optimierungen:**
- GIN-Index für tsvector → 10x schnellere Suche
- IVFFlat-Index für Embeddings → 50x schnellere Similarity-Search
- Partial Index für `is_primary` Media → schnellere Primary-Lookups
---
**Version:** 1.0
**Letzte Änderung:** 2026-04-24
**Status:** DRAFT - Awaiting Review
@@ -0,0 +1,679 @@
# Frontend Routing & Navigation Specification
**Version:** 1.2
**Datum:** 2026-04-30
**Status:** DRAFT - Awaiting Review
**Autor:** Claude Code
**Änderungen v1.2:** Übersicht **Übungen**: Tabs Liste \| Progressionsgraphen auf `/exercises`; Progressions-Editor ohne neue Routen (Panel + Formularblock unter `/exercises/:id/edit`)
**Änderungen v1.1:** Übungsvarianten-Bearbeitung nur unter `/exercises/:id/edit` (keine VariantFormPage-Routen)
---
## 1. Route-Struktur
### 1.1 Route-Übersicht
```
/exercises → ExercisesListPage — Tabs: **Liste** \| **Progressionsgraphen** (`ExerciseProgressionGraphPanel`)
/exercises/new → ExerciseFormPage (Create)
/exercises/{id} → ExerciseDetailPage (Accordion-Layout)
/exercises/{id}/edit → ExerciseFormPage (Edit inkl. Varianten-Editor inline + Block Progressionsgraph)
/exercise-blocks → ExerciseBlocksListPage (Meine Blocks)
/exercise-blocks/new → ExerciseBlockFormPage (Create)
/exercise-blocks/{id} → ExerciseBlockDetailPage (mit BlockEditor)
/exercise-blocks/{id}/edit → ExerciseBlockFormPage (Edit)
/admin/exercises/catalog → AdminCatalogPage (Fokusbereiche, Stile, Zielgruppen, Altersgruppen)
/admin/exercises/skills → AdminSkillsPage (Fähigkeiten-Matrix)
/admin/exercises/methods → AdminMethodsPage (Methoden-Katalog)
```
**URL-Parameter-Konventionen:**
- IDs immer numerisch: `/exercises/42` (nicht `/exercises/uuid`)
- Query-Parameter für Filter: `/exercises?focus_area=1&visibility=club`
- Pagination: `/exercises?limit=50&offset=100`
- Sortierung: `/exercises?sort=created_at&order=desc`
---
## 2. Navigation-Patterns
### 2.1 Haupt-Navigation (Desktop + Tablet)
**Primäre Nav (Top-Level):**
```
┌─────────────────────────────────────────┐
│ Shinkan │ Übungen │ Planung │ Admin │
└─────────────────────────────────────────┘
```
**Übungen-Submenu (Dropdown):**
```
Übungen
├─ Alle Übungen → /exercises
├─ Neue Übung → /exercises/new
├─ Meine Blocks → /exercise-blocks
├─ Neuer Block → /exercise-blocks/new
└─ Katalog verwalten → /admin/exercises/catalog (nur Admin)
```
### 2.2 Mobile Navigation (Hamburger-Menu)
```
☰ Menu
├─ Übungen
│ ├─ Alle anzeigen
│ ├─ Neue Übung
│ └─ Filter & Suche
├─ Planung
└─ Admin
└─ Katalog
```
### 2.3 Breadcrumbs (Detail/Edit-Seiten)
**Pattern:**
```
Home → Übungen → [Übungsname] → Bearbeiten (Varianten im gleichen Formular)
```
**Implementation:**
- Breadcrumbs dynamisch aus Route-Parametern generiert
- Letztes Element (aktuelle Seite) nicht klickbar
- Max. 4 Ebenen, dann `...` für gekürzte Pfade
---
## 3. State Management
### 3.1 URL-State (Query-Parameter)
**Filter-State in URL persistieren:**
```javascript
// ExercisesListPage.jsx
const [filters, setFilters] = useState({
focus_area: parseInt(searchParams.get('focus_area')) || null,
visibility: searchParams.get('visibility') || null,
status: searchParams.get('status') || null,
search: searchParams.get('search') || '',
limit: parseInt(searchParams.get('limit')) || 50,
offset: parseInt(searchParams.get('offset')) || 0,
})
// Bei Filter-Änderung → URL aktualisieren
const updateFilters = (newFilters) => {
const params = new URLSearchParams()
Object.entries(newFilters).forEach(([key, val]) => {
if (val) params.set(key, val)
})
navigate(`/exercises?${params.toString()}`)
}
```
**Vorteile:**
- Sharable URLs (Filter-Zustand übertragbar)
- Browser-Back funktioniert korrekt
- Keine verlorenen Filter beim Reload
### 3.2 Local State (React useState)
**Form-State (nicht in URL):**
```javascript
// ExerciseFormPage.jsx
const [formData, setFormData] = useState({
title: '',
summary: '',
goal: '',
execution: '',
// ... weitere Felder
})
```
**UI-State (nicht in URL):**
```javascript
// ExerciseDetailPage.jsx
const [expandedSections, setExpandedSections] = useState({
basics: true,
execution: false,
variants: false,
media: false,
})
```
### 3.3 Context (Global State)
**Katalog-Daten (einmalig laden, global verfügbar):**
```javascript
// CatalogContext.jsx
const CatalogContext = createContext()
export function CatalogProvider({ children }) {
const [focusAreas, setFocusAreas] = useState([])
const [trainingStyles, setTrainingStyles] = useState([])
const [targetGroups, setTargetGroups] = useState([])
const [ageGroups, setAgeGroups] = useState([])
const [skills, setSkills] = useState([])
useEffect(() => {
// Kataloge einmalig beim App-Start laden
Promise.all([
api.getFocusAreas(),
api.getTrainingStyles(),
api.getTargetGroups(),
api.getAgeGroups(),
api.getSkills(),
]).then(([fa, ts, tg, ag, sk]) => {
setFocusAreas(fa)
setTrainingStyles(ts)
setTargetGroups(tg)
setAgeGroups(ag)
setSkills(sk)
})
}, [])
return (
<CatalogContext.Provider value={{
focusAreas, trainingStyles, targetGroups, ageGroups, skills
}}>
{children}
</CatalogContext.Provider>
)
}
export const useCatalog = () => useContext(CatalogContext)
```
**Usage in Komponenten:**
```javascript
// ExerciseFormPage.jsx
const { focusAreas, trainingStyles } = useCatalog()
```
---
## 4. Deep Linking
### 4.1 Detail-Seite mit Accordion-State
**Problem:** Link teilen → Empfänger soll direkt zur "Varianten"-Sektion springen
**Lösung:** Hash-Fragment in URL:
```
/exercises/42#variants
/exercises/42#media
```
**Implementation:**
```javascript
// ExerciseDetailPage.jsx
useEffect(() => {
const hash = window.location.hash.replace('#', '')
if (hash && expandedSections[hash] !== undefined) {
setExpandedSections(prev => ({ ...prev, [hash]: true }))
// Scroll zur Sektion
setTimeout(() => {
document.getElementById(hash)?.scrollIntoView({ behavior: 'smooth' })
}, 100)
}
}, [])
```
### 4.2 Externe Verknüpfung aus Trainingsplan
**Szenario:** Trainingsplan-Editor soll Übung verlinken
**URL-Format:**
```
/exercises/42?from=training_plan&plan_id=7
```
**Navigation-Logik:**
```javascript
// ExerciseDetailPage.jsx
const searchParams = useSearchParams()
const returnUrl = searchParams.get('from') === 'training_plan'
? `/training-plans/${searchParams.get('plan_id')}`
: '/exercises'
// "Zurück"-Button zeigt entsprechendes Ziel
<button onClick={() => navigate(returnUrl)}>
← {returnUrl.includes('training') ? 'Zum Trainingsplan' : 'Zur Übersicht'}
</button>
```
---
## 5. Navigation Guards
### 5.1 Unsaved Changes Warning
**Pattern:**
```javascript
// ExerciseFormPage.jsx
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
// Bei Form-Änderung
const handleChange = (field, value) => {
setFormData(prev => ({ ...prev, [field]: value }))
setHasUnsavedChanges(true)
}
// Browser-Warning bei Reload/Close
useEffect(() => {
const handleBeforeUnload = (e) => {
if (hasUnsavedChanges) {
e.preventDefault()
e.returnValue = ''
}
}
window.addEventListener('beforeunload', handleBeforeUnload)
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
}, [hasUnsavedChanges])
// React-Router Warning bei Navigation
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
hasUnsavedChanges &&
currentLocation.pathname !== nextLocation.pathname
)
useEffect(() => {
if (blocker.state === 'blocked') {
const confirmed = window.confirm(
'Du hast ungespeicherte Änderungen. Seite wirklich verlassen?'
)
if (confirmed) {
blocker.proceed()
} else {
blocker.reset()
}
}
}, [blocker])
```
### 5.2 Permission-Check (Admin-Routes)
**Pattern:**
```javascript
// ProtectedRoute.jsx
function ProtectedRoute({ children, requiredRole = 'admin' }) {
const { profile } = useAuth()
if (!profile) {
return <Navigate to="/login" />
}
if (profile.role !== requiredRole) {
return <Navigate to="/exercises" replace />
}
return children
}
// App.jsx
<Route path="/admin/exercises/*" element={
<ProtectedRoute requiredRole="admin">
<AdminExerciseRoutes />
</ProtectedRoute>
} />
```
---
## 6. Performance-Optimierung
### 6.1 Lazy Loading von Routen
**Pattern:**
```javascript
// App.jsx
const ExercisesListPage = lazy(() => import('./pages/ExercisesListPage'))
const ExerciseDetailPage = lazy(() => import('./pages/ExerciseDetailPage'))
const ExerciseFormPage = lazy(() => import('./pages/ExerciseFormPage'))
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/exercises" element={<ExercisesListPage />} />
<Route path="/exercises/:id" element={<ExerciseDetailPage />} />
<Route path="/exercises/:id/edit" element={<ExerciseFormPage />} />
</Routes>
</Suspense>
)
}
```
**Vorteil:** Initial Bundle kleiner, Routen nur bei Bedarf nachgeladen
### 6.2 Prefetching von Detail-Daten
**Pattern:**
```javascript
// ExercisesListPage.jsx - Hover-Prefetch
const handleCardHover = (exerciseId) => {
// Prefetch Detail-Daten beim Hover
queryClient.prefetchQuery(['exercise', exerciseId], () =>
api.getExercise(exerciseId)
)
}
<ExerciseCard
exercise={exercise}
onMouseEnter={() => handleCardHover(exercise.id)}
onClick={() => navigate(`/exercises/${exercise.id}`)}
/>
```
**Vorteil:** Detail-Seite lädt sofort, da Daten bereits im Cache
---
## 7. Error-Handling
### 7.1 404 - Exercise Not Found
**Pattern:**
```javascript
// ExerciseDetailPage.jsx
const { data: exercise, error, isLoading } = useQuery(
['exercise', exerciseId],
() => api.getExercise(exerciseId)
)
if (error?.response?.status === 404) {
return (
<NotFoundPage
title="Übung nicht gefunden"
message="Diese Übung existiert nicht oder wurde gelöscht."
backLink="/exercises"
backLabel="Zur Übersicht"
/>
)
}
```
### 7.2 403 - No Permission
**Pattern:**
```javascript
if (error?.response?.status === 403) {
return (
<ForbiddenPage
title="Keine Berechtigung"
message="Du hast keinen Zugriff auf diese Übung."
backLink="/exercises"
/>
)
}
```
### 7.3 Network Error
**Pattern:**
```javascript
if (error?.message === 'Network Error') {
return (
<ErrorPage
title="Verbindungsfehler"
message="Server nicht erreichbar. Bitte prüfe deine Internetverbindung."
retryAction={() => refetch()}
/>
)
}
```
---
## 8. Mobile-Spezifische Navigation
### 8.1 Bottom Navigation (Mobile)
**Pattern:**
```
┌─────────────────────────────────────┐
│ │
│ (Content Area) │
│ │
├─────────────────────────────────────┤
│ 🏠 Home │ 📋 Übungen │ 📅 Plan │
└─────────────────────────────────────┘
```
**Implementation:**
```javascript
// MobileBottomNav.jsx
<nav className="mobile-bottom-nav">
<NavLink to="/" className={({ isActive }) => isActive ? 'active' : ''}>
<Icon name="home" />
<span>Home</span>
</NavLink>
<NavLink to="/exercises">
<Icon name="list" />
<span>Übungen</span>
</NavLink>
<NavLink to="/training-plans">
<Icon name="calendar" />
<span>Pläne</span>
</NavLink>
</nav>
```
**CSS:**
```css
.mobile-bottom-nav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 60px;
background: var(--surface);
border-top: 1px solid var(--border);
display: flex;
justify-content: space-around;
z-index: 100;
}
@media (min-width: 768px) {
.mobile-bottom-nav {
display: none; /* Desktop nutzt Top-Nav */
}
}
```
### 8.2 Swipe-Navigation (Detail-Seite)
**Pattern:** Swipe left/right zwischen Übungen (gleicher Filter)
**Implementation:**
```javascript
// ExerciseDetailPage.jsx
const { exercises } = useExercisesList() // aus Context/Query
const currentIndex = exercises.findIndex(e => e.id === parseInt(exerciseId))
const swipeHandlers = useSwipeable({
onSwipedLeft: () => {
const nextExercise = exercises[currentIndex + 1]
if (nextExercise) navigate(`/exercises/${nextExercise.id}`)
},
onSwipedRight: () => {
const prevExercise = exercises[currentIndex - 1]
if (prevExercise) navigate(`/exercises/${prevExercise.id}`)
},
preventDefaultTouchmoveEvent: true,
trackMouse: false,
})
<div {...swipeHandlers}>
{/* Exercise Detail Content */}
</div>
```
---
## 9. Accessibility
### 9.1 Skip Links
**Pattern:**
```javascript
// App.jsx
<a href="#main-content" className="skip-link">
Zum Hauptinhalt springen
</a>
<main id="main-content">
{/* Content */}
</main>
```
**CSS:**
```css
.skip-link {
position: absolute;
top: -40px;
left: 0;
background: var(--accent);
color: white;
padding: 8px;
z-index: 1000;
}
.skip-link:focus {
top: 0;
}
```
### 9.2 Focus Management
**Pattern:** Bei Navigation → Focus auf Hauptüberschrift setzen
```javascript
// ExerciseDetailPage.jsx
const titleRef = useRef(null)
useEffect(() => {
titleRef.current?.focus()
}, [exerciseId])
<h1 ref={titleRef} tabIndex={-1}>
{exercise.title}
</h1>
```
### 9.3 ARIA Live-Region für Filter
**Pattern:**
```javascript
// ExercisesListPage.jsx
<div aria-live="polite" aria-atomic="true" className="sr-only">
{exercises.length} Übungen gefunden
</div>
```
---
## 10. Testing-Strategie
### 10.1 Route-Tests (Playwright)
```javascript
// exercises.routing.spec.js
test('Navigation zu Detail-Seite funktioniert', async ({ page }) => {
await page.goto('/exercises')
const firstCard = page.locator('.exercise-card').first()
await firstCard.click()
await expect(page).toHaveURL(/\/exercises\/\d+/)
await expect(page.locator('h1')).toBeVisible()
})
test('Filter-State bleibt in URL erhalten', async ({ page }) => {
await page.goto('/exercises?focus_area=1')
await page.reload()
const url = new URL(page.url())
expect(url.searchParams.get('focus_area')).toBe('1')
})
```
### 10.2 Navigation-Guard-Tests
```javascript
test('Unsaved Changes Warning', async ({ page }) => {
await page.goto('/exercises/new')
await page.fill('[name="title"]', 'Test Übung')
page.on('dialog', dialog => {
expect(dialog.message()).toContain('ungespeicherte')
dialog.accept()
})
await page.goto('/exercises')
})
```
---
## 11. Route-Konfiguration (React Router)
### 11.1 Vollständige Route-Definitionen
```javascript
// App.jsx
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
function App() {
return (
<BrowserRouter>
<CatalogProvider>
<Routes>
{/* Exercises Routes */}
<Route path="/exercises">
<Route index element={<ExercisesListPage />} />
<Route path="new" element={<ExerciseFormPage />} />
<Route path=":id" element={<ExerciseDetailPage />} />
<Route path=":id/edit" element={<ExerciseFormPage />} />
{/* Varianten: Bearbeitung inline in ExerciseFormPage, keine eigenen Routen */}
</Route>
{/* Exercise Blocks Routes */}
<Route path="/exercise-blocks">
<Route index element={<ExerciseBlocksListPage />} />
<Route path="new" element={<ExerciseBlockFormPage />} />
<Route path=":id" element={<ExerciseBlockDetailPage />} />
<Route path=":id/edit" element={<ExerciseBlockFormPage />} />
</Route>
{/* Admin Routes */}
<Route path="/admin/exercises" element={
<ProtectedRoute requiredRole="admin">
<Outlet />
</ProtectedRoute>
}>
<Route path="catalog" element={<AdminCatalogPage />} />
<Route path="skills" element={<AdminSkillsPage />} />
<Route path="methods" element={<AdminMethodsPage />} />
</Route>
{/* Redirects */}
<Route path="/" element={<Navigate to="/exercises" replace />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</CatalogProvider>
</BrowserRouter>
)
}
```
---
**Version:** 1.2
**Letzte Änderung:** 2026-04-30
**Status:** REVIEWED - Pending Implementation
**Review-Änderungen:** Progressionsgraphen-UI (Tabs, Formularblock); Exercise Blocks Routes + Navigation (früher)
+370
View File
@@ -0,0 +1,370 @@
# KI-Funktionen Specification – Exercises
**Version:** 1.1
**Datum:** 2026-04-24
**Status:** DRAFT
**Autor:** Claude Code
**Änderungen v1.1:** Prompts sind nicht hardcoded – sie werden aus der DB geladen (AI_PROMPT_SYSTEM_SPEC.md)
**Verwandte Specs:** AI_PROMPT_SYSTEM_SPEC.md (Prompt-DB + Platzhalter), SKILLS_MATRIX_SPEC.md (Fähigkeitsmatrix)
---
## 1. Übersicht
Zwei KI-gestützte Assistenzfunktionen beim Anlegen und Bearbeiten von Übungen:
| Funktion | Ziel |
|---------|------|
| **KI-Zusammenfassung** | Generiert `summary` aus `goal` + `execution` (für Listen + Trainingspläne) |
| **KI-Skill-Empfehlung** | Schlägt passende Fähigkeiten + Stufen vor (reduziert manuelle Zuordungsarbeit) |
**Abhängigkeit:** OpenRouter API (`OPENROUTER_API_KEY` in `.env`).
Ist der Key nicht gesetzt, sind alle KI-Funktionen deaktiviert – Formular funktioniert ohne KI normal.
---
## 2. UX-Prinzip: Manual First, Auto als Fallback
```
Trainer gibt goal + execution ein
│
├─► [KI-Vorschlag]-Button sichtbar
│ │
│ ▼ (Klick)
│ KI generiert sofort Vorschlag
│ → Trainer sieht Vorschlag inline
│ → Kann akzeptieren / bearbeiten / ablehnen
│
└─► Kein Klick bis zum Speichern?
│
▼ (automatisch beim POST/PUT)
KI läuft im Hintergrund
→ summary + skill_suggestions werden gesetzt
→ Trainer kann danach noch bearbeiten
```
**Regel:** Manuell generierte Werte (wo Trainer aktiv bestätigt hat) werden
beim Auto-Fallback NICHT überschrieben. Auto-generierte Werte werden als
`ai_generated: true` markiert und können jederzeit neu generiert oder überschrieben werden.
---
## 3. KI-Zusammenfassung (`summary`)
### 3.1 Was wird generiert
Aus `title` + `goal` + `execution` generiert die KI eine **kurze Zusammenfassung**
(2-4 Sätze, max. 200 Zeichen) für:
- Übungslisten (Karten-Ansicht)
- Trainingsplan-Darstellung (kompakte Anzeige)
- Export-Berichte
### 3.2 Prompt-Logik (Backend)
**Prompt ist NICHT hardcoded** – er wird aus der `ai_prompts` Tabelle geladen
(Slug: `exercise_summary`). Admins können das Template anpassen.
```python
# Aufruf via zentralem AI-Service (siehe AI_PROMPT_SYSTEM_SPEC.md)
result = await ai_service.run_ai_prompt(
slug="exercise_summary",
context_data={"exercise": exercise_data},
db=db,
openrouter_key=settings.openrouter_api_key
)
```
**Default-Template** (in Migration 020 als `default_template` gespeichert):
Siehe `AI_PROMPT_SYSTEM_SPEC.md` §2.1 – Prompt `exercise_summary`.
### 3.3 DB-Feld
Kein neues Feld nötig – `exercises.summary` nimmt den generierten Text auf.
Zusätzliches Tracking-Feld: `summary_ai_generated BOOLEAN DEFAULT false`
---
## 4. KI-Skill-Empfehlung
### 4.1 Was wird empfohlen
Aus `title` + `goal` + `execution` + Katalog aller verfügbaren Skills empfiehlt die KI:
- **Welche Skills** relevant sind (aus dem bestehenden Skill-Katalog)
- **Erforderliche Stufe** (`required_level`) – was der Trainierende mitbringen muss
- **Ziel-Stufe** (`target_level`) – was durch regelmäßige Ausführung erreicht wird
- **Intensität** (`intensity`) – wie stark diese Fähigkeit trainiert wird
### 4.2 Prompt-Logik (Backend)
**Prompt ist NICHT hardcoded** – Slug: `exercise_skill_suggestions`.
Der `{{skills_catalog}}`-Platzhalter wird vom Backend automatisch mit der aktuellen
Skill-Liste aus der DB aufgelöst.
Admins können den Prompt anpassen (z.B. die Anweisung zur Auswahl verschärfen oder
fachliche Hinweise ergänzen). Siehe `AI_PROMPT_SYSTEM_SPEC.md`.
### 4.3 Bestätigungsflow (UX)
```
KI gibt Vorschläge
│
▼
┌─────────────────────────────────────────┐
│ KI-Vorschläge (3 Fähigkeiten) │
│ ─────────────────────────────────────── │
│ ✓ Distanzgefühl │
│ Voraussetzung: Grundlagen │
│ Ziel: Aufbau · Intensität: Hoch │
│ [✓ Übernehmen] [Stufe ändern ▼] [✕] │
│ ─────────────────────────────────────── │
│ ✓ Reaktionsschnelligkeit │
│ Voraussetzung: Einsteiger │
│ Ziel: Grundlagen · Intensität: Mittel │
│ [✓ Übernehmen] [Stufe ändern ▼] [✕] │
│ ─────────────────────────────────────── │
│ ◦ Gleichgewicht (optional) │
│ Voraussetzung: Grundlagen │
│ Ziel: Grundlagen · Intensität: Niedrig│
│ [✓ Übernehmen] [Stufe ändern ▼] [✕] │
│ ─────────────────────────────────────── │
│ [Alle übernehmen] [Verwerfen] │
└─────────────────────────────────────────┘
```
- Jeder Vorschlag kann **einzeln** übernommen, angepasst oder abgelehnt werden
- „Alle übernehmen" nimmt alle aktuell angezeigten Vorschläge
- Stufen können per Dropdown direkt angepasst werden bevor sie übernommen werden
- Abgelehnte Vorschläge werden nicht gespeichert
---
## 5. API-Endpoints
### 5.1 Endpoints Overview
| Method | Endpoint | Beschreibung |
|--------|----------|--------------|
| POST | `/exercises/ai/suggest` | Vorschläge für neue Übung (vor dem Speichern) |
| POST | `/exercises/{id}/ai/regenerate` | Neu generieren für bestehende Übung |
---
### 5.2 `POST /exercises/ai/suggest`
Liefert KI-Vorschläge auf Basis von Eingabe-Text, **bevor** die Übung gespeichert wurde.
Wird beim Klick auf „KI-Vorschlag" im Formular aufgerufen.
**Request Body:**
```json
{
"title": "Maai - Distanzübung",
"goal": "Distanzgefühl entwickeln durch Partnerübungen...",
"execution": "1. Partnerwahl\n2. Ausgangsstellung..."
}
```
**Required Fields:** mindestens `goal` ODER `execution` (je länger, desto besser)
**Response:** `200 OK`
```json
{
"summary": {
"text": "Partnerübung zur Entwicklung des Distanzgefühls. Trainiert werden räumliche Wahrnehmung und reaktives Verhalten in der Kumite-Distanz.",
"ai_generated": true,
"model": "anthropic/claude-sonnet-4"
},
"skills": [
{
"skill_id": 10,
"skill_name": "Distanzgefühl",
"skill_category": "Kumite",
"required_level": "grundlagen",
"target_level": "aufbau",
"intensity": "hoch",
"is_primary": true,
"confidence": 0.92
},
{
"skill_id": 15,
"skill_name": "Reaktionsschnelligkeit",
"skill_category": "Athletik",
"required_level": "einsteiger",
"target_level": "grundlagen",
"intensity": "mittel",
"is_primary": false,
"confidence": 0.74
}
]
}
```
**Errors:**
- `400` - Zu wenig Text (goal und execution leer)
- `503` - KI nicht verfügbar (OPENROUTER_API_KEY fehlt)
---
### 5.3 `POST /exercises/{id}/ai/regenerate`
Generiert summary und/oder skill-Empfehlungen für eine bestehende Übung neu.
Verwendet die aktuellen gespeicherten Felder als Input.
**Request Body:**
```json
{
"regenerate": ["summary", "skills"]
}
```
**Werte:** `"summary"` | `"skills"` (oder beide)
**Response:** `200 OK` (gleiche Struktur wie `/ai/suggest`)
**Hinweis:** Regenerieren überschreibt NICHT Felder, die manuell gesetzt wurden
(`summary_ai_generated = false`). Es wird nur der Vorschlag zurückgegeben,
Trainer muss aktiv übernehmen.
---
## 6. Datenbank
### 6.1 Neues Feld: `summary_ai_generated`
```sql
-- Als Teil von Migration 014 ergänzen:
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS summary_ai_generated BOOLEAN DEFAULT false;
```
**Semantik:**
- `false` (default) = Zusammenfassung manuell geschrieben oder noch leer
- `true` = Zuletzt von KI generiert (kann überschrieben werden)
Beim manuellen Überschreiben durch den Trainer: `summary_ai_generated = false` setzen.
### 6.2 Kein Feld für Skill-Empfehlungen
Skill-Vorschläge der KI werden **nicht** persistent gespeichert – sie erscheinen
nur im Formular-UI und werden erst bei expliziter Bestätigung als reguläre
`exercise_skills`-Einträge gespeichert.
---
## 7. Integration in Speicher-Flow
### 7.1 Auto-Fallback beim Speichern (POST/PUT exercises)
```python
# In backend/routers/exercises.py
async def create_exercise(data, session):
# 1. Übung normal speichern
exercise_id = db.insert_exercise(data)
# 2. Auto-KI nur wenn:
# - OPENROUTER_API_KEY gesetzt
# - summary noch leer
# - goal oder execution vorhanden
if settings.openrouter_api_key and not data.summary and (data.goal or data.execution):
# Background Task (non-blocking)
background_tasks.add_task(
auto_generate_summary,
exercise_id=exercise_id,
title=data.title,
goal=data.goal,
execution=data.execution
)
return exercise_id
```
### 7.2 Skill-Auto-Suggestion
Skill-Empfehlungen werden beim Auto-Fallback **NICHT** automatisch gespeichert
(wegen Bestätigungs-Pflicht). Sie werden nur beim manuellen Trigger angeboten.
---
## 8. Frontend-Integration
### 8.1 ExerciseFormPage – KI-Buttons
```
┌──────────────────────────────────────┐
│ Ziel der Übung * │
│ ┌────────────────────────────────┐ │
│ │ Distanzgefühl entwickeln... │ │
│ └────────────────────────────────┘ │
│ │
│ Durchführung * │
│ ┌────────────────────────────────┐ │
│ │ 1. Partnerwahl... │ │
│ └────────────────────────────────┘ │
│ ↓ │
│ Zusammenfassung (für Listen) │
│ ┌────────────────────────────────┐ │
│ │ [Leer] │ │
│ └────────────────────────────────┘ │
│ [✨ KI-Vorschlag] ← Button │
│ │
│ ─────────────────────────────────── │
│ Fähigkeiten │
│ [Keine zugeordnet] │
│ [+ Manuell hinzufügen] │
│ [✨ KI-Empfehlungen] ← Button │
└──────────────────────────────────────┘
```
### 8.2 KI-Vorschlag für Summary (Inline)
Beim Klick auf „✨ KI-Vorschlag":
```
┌──────────────────────────────────────┐
│ ✨ KI-Vorschlag │
│ ─────────────────────────────────── │
│ "Partnerübung zur Entwicklung des │
│ Distanzgefühls. Trainiert räumliche │
│ Wahrnehmung und reaktives Verhalten."│
│ ─────────────────────────────────── │
│ [✓ Übernehmen] [✕ Verwerfen] │
└──────────────────────────────────────┘
```
Nach „Übernehmen": Text landet im Summary-Feld, Button zeigt „↺ Neu generieren".
### 8.3 Anzeige KI-generierter Inhalte
Felder die KI-generiert sind, werden mit einem kleinen Badge markiert:
```
Zusammenfassung ✨ KI-generiert [bearbeiten]
```
Nach manuellem Bearbeiten verschwindet der Badge.
---
## 9. Konfiguration
```env
OPENROUTER_API_KEY=sk-or-...
OPENROUTER_MODEL=anthropic/claude-sonnet-4 # Für Zusammenfassung
OPENROUTER_MODEL_FAST=anthropic/claude-haiku-4-5 # Für Skill-Empfehlungen (billiger)
```
---
## 10. Fehlerbehandlung
| Szenario | Verhalten |
|----------|-----------|
| OPENROUTER_API_KEY nicht gesetzt | KI-Buttons nicht anzeigen, kein Auto-Fallback |
| API-Timeout (> 10s) | Fehlermeldung inline: "KI momentan nicht verfügbar. Bitte manuell ausfüllen." |
| API-Fehler (5xx) | Gleiche Meldung, kein Absturz |
| Unbekannte Skills in Empfehlung | Backend filtert Skills die nicht im Katalog sind heraus |
| Summary zu lang generiert | Backend kürzt auf 200 Zeichen |
---
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT
@@ -0,0 +1,449 @@
# MediaWiki Import Specification
**Version:** 1.1
**Datum:** 2026-04-27
**Status:** DEPLOYED - Skills via Migration, Exercises via API
**Autor:** Claude Code
---
## 1. Übersicht
**Ziel:** Übungen aus dem Jinkendo MediaWiki-System direkt via API importieren
(NICHT über Export/XML-Dump – siehe Architektur-Entscheidung in EXERCISES_ARCHITECTURE.md §8).
**Importrichtung:** Einseitig (MediaWiki → Shinkan). Kein bidirektionaler Sync.
**Import-Reihenfolge:** Skills → Methods → Exercises (Abhängigkeiten zuerst)
**Import-Tracking:** Jeder Import wird geloggt, Duplikate werden via `wiki_page_title`
erkannt und nicht doppelt angelegt.
**⚠️ WICHTIG - Skills-Import (ab 2026-04-27):**
Skills werden NICHT mehr über die API importiert, sondern über **Migration 023**
(vollständiger Import aus Fähigkeitsmatrix mit Kategorisierung).
Siehe `.claude/handover/session-2026-04-27-skills-complete.md` für Details.
---
## 2. MediaWiki API-Zugriff
### 2.1 API-Endpoint
```
GET https://karatetrainer.net/api.php
```
**Benötigte Parameter:**
- `action=query` – Seiteninhalte abfragen
- `action=parse` – Einzelseite parsen (mit Semantic MediaWiki Properties)
- `prop=text|properties|categories` – Relevante Felder
- `format=json`
### 2.2 Authentifizierung
Aktuell: Kein Auth (wenn Wiki öffentlich zugänglich).
Bei privatem Wiki: `lgtoken` via `/api.php?action=login`.
### 2.3 Relevante API-Calls
**Alle Übungen einer Kategorie auflisten:**
```
GET /api.php?action=query&list=categorymembers&cmtitle=Kategorie:Übungen&cmlimit=500&format=json
```
**Einzelne Übung abrufen (mit SMW Properties):**
```
GET /api.php?action=parse&page=Übungsname&prop=text|properties&format=json
```
**SMW-Properties einer Seite:**
```
GET /api.php?action=browsebysubject&subject=Übungsname&format=json
```
---
## 3. Field-Mapping (MediaWiki → Exercises)
**Echte Property-Namen von karatetrainer.net** (via `discover_properties()` ermittelt, 2026-04-24)
### 3.1 Kern-Felder
| Wiki-Property (SMW) | Exercises-Feld | Transformation |
|---------------------|---------------|----------------|
| `Übungsbezeichnung` | `title` | Bevorzugt über Seitentitel |
| `Summary` | `summary` | Direkt |
| `Ziel` | `goal` | Direkt |
| `Durchführung` | `execution` | Wikitext → Plaintext |
| `Hinweise` | `trainer_notes` | Wikitext → Plaintext |
| `Plandauer` | `duration_min` = `duration_max` | Zahl in Minuten z.B. `"10"` |
| `Gruppengröße` | `group_size_min` | Zahl z.B. `"2"` |
| `Hilfsmittel` | `equipment` (JSONB) | Array von Strings |
### 3.2 Katalog-Mapping
| Wiki-Property | Exercises-Tabelle | Transformation |
|---------------|------------------|----------------|
| `Übungstyp` | `exercise_focus_areas` | z.B. `"Karate"` → focus_area Name → ID |
| `Zielgruppe` | `exercise_target_groups` | Name → ID Lookup |
| `Altersgruppe` | `exercise_age_groups` | Name → ID Lookup |
| `Trainingsmethode` | exercise method ref | Wiki-Seitenname → Label (Unterstriche → Leerzeichen) |
| `PrimaryCapability` | `exercise_skills` (Name) | Skill-Name → ID Lookup |
| `CapabilityLevel` | `exercise_skills` (target_level) | Integer → Named Level (1=einsteiger…5=experte) |
| `Schlüsselworte` | — | Keywords (für zukünftige Tag-Funktion) |
### 3.3 Skill-Level-Mapping (CapabilityLevel → INTEGER)
**🆕 ÄNDERUNG (2026-04-27):** `target_level` ist jetzt INTEGER (1-5), nicht mehr String.
| Wiki-Wert | Shinkan DB-Wert | Bedeutung |
|-----------|-----------------|-----------|
| "1" | 1 (INTEGER) | Einsteiger |
| "2" | 2 (INTEGER) | Grundlagen |
| "3" | 3 (INTEGER) | Aufbau |
| "4" | 4 (INTEGER) | Fortgeschritten |
| "5" | 5 (INTEGER) | Experte |
**Implementierung:** `smw_mapper.py` Zeile 271-299 `build_skill_assignments()`
konvertiert String → INTEGER via `int(level_str.strip())`.
### 3.4 Kategorien (karatetrainer.net)
| Import-Typ | Wiki-Kategorie | Status | Import-Methode |
|------------|---------------|--------|----------------|
| exercises | `Übungen` | ✅ Produktiv | API (`/api/import-wiki/execute`) |
| skills | `Fähigkeitsbeschreibung` | ⚠️ DEPRECATED | ~~API~~ → **Migration 023** |
| methods | `Methodenbeschreibung` | 🔲 Geplant | API (noch nicht implementiert) |
**⚠️ Skills-Import-Änderung (2026-04-27):**
Skills werden NICHT mehr über `import_type: skill` importiert, sondern über:
- **Migration 022:** Schema-Erweiterung (skill_main_categories, focus_areas, level_definitions)
- **Migration 023:** Vollständiger Import (69 Skills mit Kategorisierung aus Fähigkeitsmatrix)
**Grund:** API-Import lieferte nur skill_name, aber KEINE Kategorisierung
(Haupt-/Unterkategorie, Fokusbereich). Migration 023 importiert alle Skills
mit vollständiger Metadaten-Struktur.
**Quelle:** https://karatetrainer.net/index.php?title=Fähigkeitsmatrix
**Details:** `.claude/handover/session-2026-04-27-skills-complete.md`
**Unbekannte Katalog-Werte:** Warnmeldung im Import-Log, Übung wird ohne
diese Zuordnung importiert (kein Abbruch).
### 3.3 Import-Tracking-Felder
| Feld | Wert |
|------|------|
| `import_source` | `'mediawiki'` |
| `import_id` | Wiki-Seitenname (URL-kodiert) |
| `visibility` | `'private'` (Trainer prüft vor Veröffentlichung) |
| `status` | `'draft'` |
### 3.4 Wikitext-Bereinigung
Vor dem Speichern werden folgende Wikitext-Elemente in Plaintext umgewandelt:
- `[[Link|Text]]` → `Text`
- `[[Link]]` → `Link`
- `{{Template}}` → (entfernt)
- `'''Bold'''` → `Bold`
- `''Italic''` → `Italic`
- `==Überschrift==` → `\nÜberschrift\n`
- Wikitables → (entfernt, zu komplex für automatischen Import)
---
## 4. Tracking-Tabellen
```sql
-- Migration: wiki_import_tracking
-- (In eigene Migration auslagern: 018_wiki_import_tracking.sql)
CREATE TABLE IF NOT EXISTS wiki_import_log (
id SERIAL PRIMARY KEY,
import_type VARCHAR(50) NOT NULL, -- 'exercise', 'skill', 'method'
import_status VARCHAR(20) CHECK (import_status IN ('running', 'completed', 'failed')),
items_total INT DEFAULT 0,
items_imported INT DEFAULT 0,
items_skipped INT DEFAULT 0,
items_failed INT DEFAULT 0,
error_log JSONB DEFAULT '[]'::jsonb, -- Array von {item, error} Objekten
imported_by INT REFERENCES profiles(id),
started_at TIMESTAMP DEFAULT NOW(),
finished_at TIMESTAMP
);
CREATE TABLE IF NOT EXISTS wiki_import_references (
id SERIAL PRIMARY KEY,
wiki_page_title VARCHAR(500) NOT NULL,
wiki_page_id INT, -- MediaWiki interne ID
content_type VARCHAR(50) NOT NULL, -- 'exercise', 'skill', 'method'
local_id INT NOT NULL, -- ID in der lokalen DB
last_imported TIMESTAMP DEFAULT NOW(),
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(wiki_page_title, content_type)
);
CREATE INDEX IF NOT EXISTS idx_wiki_refs_title ON wiki_import_references(wiki_page_title);
CREATE INDEX IF NOT EXISTS idx_wiki_refs_type ON wiki_import_references(content_type);
```
---
## 5. API-Endpoints
### 5.1 Endpoints Overview
| Method | Endpoint | Beschreibung |
|--------|----------|--------------|
| GET | `/import/mediawiki/preview` | Vorschau: Was wird importiert? |
| POST | `/import/mediawiki/execute` | Import ausführen |
| GET | `/import/mediawiki/status/{log_id}` | Import-Status abrufen |
| GET | `/import/mediawiki/logs` | Alle Import-Logs |
| DELETE | `/import/mediawiki/references/{id}` | Referenz löschen (für Re-Import) |
### 5.2 `GET /import/mediawiki/preview`
**Query Parameters:**
- `category` (string, required) – Wiki-Kategorie z.B. `Übungen`
- `limit` (int, optional, default: 10) – Maximale Anzahl zum Voranschauen
**Response:** `200 OK`
```json
{
"category": "Übungen",
"total_found": 47,
"preview": [
{
"wiki_page_title": "Maai - Distanzübung",
"wiki_page_id": 1234,
"already_imported": false,
"last_imported_at": null,
"mapped_fields": {
"title": "Maai - Distanzübung",
"summary": "Distanzgefühl entwickeln...",
"goal": "Ziel...",
"focus_area": "Karate",
"focus_area_found": true
},
"warnings": [],
"errors": []
},
{
"wiki_page_title": "Kumite Grundtechniken",
"already_imported": true,
"last_imported_at": "2026-04-10T10:00:00Z",
"mapped_fields": {...},
"warnings": ["Feld 'Zielgruppe' hat unbekannten Wert 'Fortgeschrittene' - wird ignoriert"],
"errors": []
}
]
}
```
---
### 5.3 `POST /import/mediawiki/execute`
**Request Body:**
```json
{
"category": "Übungen",
"reimport_existing": false, // true: Bereits importierte Übungen überschreiben
"dry_run": false, // true: Nur simulieren, nichts speichern
"limit": null // null: alle importieren
}
```
**Response:** `202 Accepted` (Import läuft asynchron)
```json
{
"log_id": 5,
"status": "running",
"message": "Import gestartet. Verwende GET /import/mediawiki/status/5 für Status."
}
```
---
### 5.4 `GET /import/mediawiki/status/{log_id}`
**Response:** `200 OK`
```json
{
"id": 5,
"import_type": "exercise",
"import_status": "completed",
"items_total": 47,
"items_imported": 44,
"items_skipped": 2,
"items_failed": 1,
"error_log": [
{
"item": "Unvollständige Übung",
"error": "Pflichtfeld 'Durchführung' fehlt in Wiki-Seite"
}
],
"imported_by": 1,
"started_at": "2026-04-24T10:00:00Z",
"finished_at": "2026-04-24T10:02:30Z"
}
```
---
### 5.5 `GET /import/mediawiki/logs`
**Response:** `200 OK` – Array von Import-Log Objekten (ohne error_log Details)
---
## 6. Backend-Implementation
### 6.1 Router-Datei
`backend/routers/import_wiki.py`
### 6.2 Import-Prozess (Pseudocode)
```python
async def execute_wiki_import(category: str, reimport: bool, dry_run: bool):
# 1. Alle Seiten der Kategorie via MediaWiki API abrufen
pages = wiki_api.get_category_members(category)
for page_title in pages:
# 2. Duplikat-Check
existing_ref = db.get_wiki_ref(page_title, 'exercise')
if existing_ref and not reimport:
log.skip(page_title, "bereits importiert")
continue
# 3. Seite parsen
wiki_data = wiki_api.parse_page(page_title)
# 4. Field-Mapping
exercise_data = map_wiki_to_exercise(wiki_data)
# 5. Validierung
errors = validate_exercise(exercise_data)
if errors:
log.fail(page_title, errors)
continue
# 6. Katalog-IDs auflösen
exercise_data = resolve_catalog_ids(exercise_data)
if not dry_run:
# 7. Speichern
exercise_id = db.upsert_exercise(exercise_data)
# 8. Import-Referenz aktualisieren
db.upsert_wiki_ref(page_title, 'exercise', exercise_id)
log.success(page_title)
```
### 6.3 Wikitext Parser
```python
import re
def wikitext_to_plaintext(wikitext: str) -> str:
"""Konvertiert Wikitext in lesbares Plaintext."""
text = wikitext
# Links: [[Link|Text]] → Text, [[Link]] → Link
text = re.sub(r'\[\[([^|]+)\|([^\]]+)\]\]', r'\2', text)
text = re.sub(r'\[\[([^\]]+)\]\]', r'\1', text)
# Templates entfernen
text = re.sub(r'\{\{[^}]+\}\}', '', text)
# Formatierung
text = re.sub(r"'''(.+?)'''", r'\1', text)
text = re.sub(r"''(.+?)''", r'\1', text)
# Überschriften
text = re.sub(r'={2,6}\s*(.+?)\s*={2,6}', r'\n\1\n', text)
# Mehrfache Leerzeilen normalisieren
text = re.sub(r'\n{3,}', '\n\n', text)
return text.strip()
```
---
## 7. Frontend-Import-UI
### 7.1 Route
```
/admin/import/mediawiki → AdminWikiImportPage
```
### 7.2 Layout
```
┌─────────────────────────────────────────┐
│ MediaWiki Import │
│ ─────────────────────────────────────── │
│ Wiki-Kategorie: [Übungen ] │
│ [+ Vorschau anzeigen] │
│ ─────────────────────────────────────── │
│ Vorschau (10 von 47): │
│ │
│ ✅ Maai - Distanzübung (neu) │
│ ✅ Kizami-Zuki (neu) │
│ ⚠️ Kumite XY (bereits importiert) │
│ ❌ Defekte Seite (Pflichtfeld fehlt) │
│ ... │
│ ─────────────────────────────────────── │
│ ☐ Bereits importierte überschreiben │
│ ☐ Nur simulieren (dry run) │
│ ─────────────────────────────────────── │
│ [47 Übungen importieren] │
│ ─────────────────────────────────────── │
│ Letzter Import: 44/47 · 2026-04-10 │
│ [Import-Logs anzeigen] │
└─────────────────────────────────────────┘
```
---
## 8. Fehlerbehandlung
| Fehler | Verhalten |
|--------|-----------|
| Wiki-Seite nicht erreichbar | Import-Prozess abbricht, Log-Eintrag |
| Pflichtfeld (`goal`, `execution`) fehlt | Item wird übersprungen, Warnung im Log |
| Unbekannter Katalog-Wert (Fokusbereich etc.) | Item wird ohne diese Zuordnung importiert |
| Duplikat-Titel im selben Club | Item wird übersprungen (außer reimport=true) |
| Wiki-API Timeout | Retry 3x, dann fail mit Log-Eintrag |
---
## 9. Sicherheit
- Nur Super-Admin darf Import ausführen (`require_role('superadmin')`)
- MediaWiki-URL ist konfigurierbar via `.env` (kein Hardcoding)
- Rate-Limiting: max. 1 Import parallel, max. 10/Tag
- Importierte Übungen starten immer als `visibility='private'`, `status='draft'`
---
## 10. Konfiguration (`.env`)
```
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
MEDIAWIKI_USER=import-bot # optional, für privates Wiki
MEDIAWIKI_PASSWORD=... # optional
```
---
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT - Ready for Review
@@ -0,0 +1,246 @@
# Medien-Assets, Archiv & Lebenszyklus (Single Source of Truth)
**Status:** verbindlich für Design, API und DB-Migrationen zum Thema Medien
**Stand:** 2026-05-08 (Ist-Changelog Medien bis 0.8.64; §11 Inline umgesetzt und erweitert)
**ersetzt/ergänzt:** operatives Upload-Format/Größen siehe weiterhin `MEDIA_UPLOAD_SPEC.md`
**normative Governance:** Sichtbarkeit & Mandanten wie `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`; bei Abweichung zwischen Dokumenten hat der Zugriffsplan Vorrang, **außer** dieses Dokument präzisiert explizit nur den Medien-Domain.
---
## 1. Zweck und Abgrenzung
### 1.1 Zweck
- **Ein physisches Medium** („Datei-Asset“) wird **einmal** gespeichert und **mehrfach** mit Übungen verknüpft (Wiederverwendung, keine Dubletten auf der Platte).
- **Sichtbarkeit** von Datei-Assets folgt **derselben Semantik** wie bei Übungen (`private` \| `club` \| `official` – ggf. spätere Enum-Erweiterungen nur gemeinsam mit Migration + ACCESS_LAYER-Doku).
- **Superadmin** kann Medien **global** freigeben (fachlich: Stufe wie „offiziell“ / plattformweit lesbar gemäß `library_content_*`-Regeln).
- **Copyright:** pro Asset sind **Vermerke** vorgesehen und an `official` / Vereinsnutzung anzubinden (Validierungsstufen in Umsetzung festlegen).
- **Externer Speicher:** Speicherung darf **lokal/NAS** (Filesystem) oder **extern** (z. B. S3-kompatibler Dienst) erfolgen – die App arbeitet über eine **Speicher-Abstraktion** (Interface), nicht mit verstreuten `Path`-Annahmen.
- **Papierkorb & Retention:** mehrstufiger Lebenszyklus mit **automatischen** und **manuellen** Übergängen, siehe §5.
### 1.2 Abgrenzung
- **Embeds** (reine externe URL, kein Upload) bleiben pro **Verknüpfung zur Übung** möglich (`embed_url` o. Ä.); sie haben **keinen** physischen Lebenszyklus wie Datei-Assets (kein Papierkorb „Stufe 3 physische Löschung“). Trotzdem: UI kann „Link ungültig“ o. Ä. separat abbilden.
- **Übungs-Governance** (wer eine Übung bearbeiten darf) **bleibt maßgeblich** für **Anlegen/Entfernen/Umsortieren** von Medien **in dieser Übung**; Medien erzwingen **keine** schärfere Edit-Policy als die Übung selbst.
---
## 2. Begriffe
| Begriff | Bedeutung |
|--------|-----------|
| **Media Asset** | Logische Entität für eine **hochgeladene Datei** inkl. Metadaten, Sichtbarkeit, Copyright, Speicherreferenz, Lifecycle-Status. |
| **Übungs-Medium / Attachment** | Verknüpfung **Übung ↔ Asset** oder reines Embed; enthält u. a. `context` (Sektion), `sort_order`, übungsspezifischen Titel/Beschreibung, `is_primary`. |
| **Medienmanager / Archiv** | Verwaltungs-UI/API für Assets (Suche, Metadaten, Lifecycle, ggf. Superadmin-global). |
---
## 3. Zieldatenmodell (Überblick)
> Konkrete Tabellennamen/Migrationen beim Implementierungsstart festziehen; dieses Kapitel ist die **fachliche Norm**.
### 3.1 Tabelle `media_assets` (oder gleichwertiger Name)
**Pflichtidee:**
- Identität, technische Metadaten: `id`, `mime_type`, `byte_size`, `sha256` (vollständig), `original_filename`, `created_at`, `updated_at`.
- Mandant & Governance: `visibility`, `club_id` (nullable je nach Semantik wie bei Übungen), `uploaded_by_profile_id`.
- Copyright: mindestens `copyright_notice` (TEXT); optional `license`, `attribution`, `source_url`.
- Speicher: `storage_backend` (Enum/String: z. B. `local`, `s3`, …), `storage_key` (relativer oder bucket-key), optional `storage_url` nur für interne Zwecke – **keine** öffentlichen Secrets in der DB.
- Lifecycle: `lifecycle_state` (siehe §5), Timestamps für Übergänge und geplante Purge-Termine.
**Deduplizierung:** Innerhalb sinnvoller Grenze (z. B. **pro Verein** bei `club`, global nur mit Superadmin-Policy) über `sha256` + `club_id`/`visibility`; Konflikt bei Upload → bestehendes Asset verknüpfen oder expliziter Nutzerdialog (Umsetzungsdetail).
### 3.2 Verknüpfung (heute `exercise_media`)
- Erweiterung um **`media_asset_id`** (FK, nullable wenn reines Embed).
- Embed-Zeilen: `media_asset_id IS NULL`, `embed_url`/`embed_platform` gesetzt wie heute.
- Übungsspezifische Felder: `context` (`ablauf` \| `detail` \| `trainer_hint`), `sort_order`, `title`, `description`, `is_primary`.
### 3.3 Referenzen & physisches Löschen
- Vor **physischem** Löschen muss die Referenzanzahl aller aktiven/nicht-purged Links **0** sein (oder Quarantäne-Policy); siehe §5.3.
---
## 4. Sichtbarkeit, Lesen und Übungs-Promotion
### 4.1 Leseregel Datei-Asset
- Zentrale Entscheidung analog `library_content_visible_to_profile` / TenantContext: **Profil darf Asset lesen** nur wenn Visibility+`club_id`+`created_by` zum Objekt passen (gleiche Philosophie wie Übungen).
- **GET Download / Stream:** muss **Asset-Governance** prüfen; wenn der Aufruf **im Kontext einer Übung** erfolgt, zusätzlich (oder als Schnittmenge) **Übung lesbar** – verbindlich **ohne Seitenkanal** (kein Download nur mit Übungs-ID, wenn Asset für Nutzer unsichtbar wäre).
### 4.2 Promotion Übung → `official` (bzw. global)
Beim Speichern/Promoten einer Übung auf **`official`** (oder vergleichbare globale Stufe):
1. **Pflicht-Dialog:** Hinweis, dass **alle zugeordneten Datei-Assets**, die noch **nicht** diese Sichtbarkeit haben, **mit angehoben** werden (oder die Aktion schlägt fehl / erfordert Anpassung).
2. **Abbruch:** Nutzer kann abbrechen oder einzelne Assets vor Freigabe anpassen / entkoppeln.
3. **Copyright:** Für `official` sind leere oder unzureichende Copyright-Felder **nicht** akzeptabel (genaue Regel in Umsetzung + Validierung).
Superadmin kann Medien **explizit** global/offiziell machen (Archiv-Pfad), unabhängig von einer einzelnen Übung – konsistent zur Rolle.
### 4.3 Bearbeitung Medien in der Übung
Wer die Übung **bearbeiten** darf (bestehende oder künftig erweiterte Regel), darf für diese Übung:
- Medien **hinzufügen** (Upload neu oder Verknüpfung aus Archiv),
- **Reihenfolge** / **Sektion** / **Titel** ändern,
- **Verknüpfung** entfernen (Asset bleibt im Archiv, sofern nicht anderweitig gelöscht),
- Embeds pflegen.
Das widerspricht **nicht** dem Papierkorb: wer kein Recht hat, ein Asset **global** zu Trash/ Purge zu bewegen, darf trotzdem die **Verknüpfung** in „seiner“ Übung lösen, solange die Übungs-Edit-Policy das erlaubt.
---
## 5. Lebenszyklus (Papierkorb) – Norm
### 5.1 Zustände
| Zustand | Code (Beispiel) | Neue Zuordnung zu Übungen | Anzeige in Übung (Lesemodus) | Anzeige Bearbeiten |
|---------|-----------------|---------------------------|------------------------------|-------------------|
| Aktiv | `active` | ja | normal | normal |
| Stufe 1 – Papierkorb | `trash_soft` | **nein** | ja + **Warnhinweis** („wird abgeschafft“) | ja + Warnhinweis |
| Stufe 2 – Ausblendung | `trash_hidden` | nein | **nein** (Platzhalter/„nicht verfügbar“) | Recovery-Aktion sichtbar |
| Stufe 3 – purgiert | `purged` / Zeile entfernt | nein | nein | nur noch historischer Hinweis nach Policy |
**Default-Retention (automatisch):**
- Stufe 1 → Stufe 2: **ca. 30 Tage** nach Eintritt in Stufe 1 (konfigurierbar).
- Stufe 2 → Stufe 3 **physisches Löschen**: **ca. 90 Tage** (3 Monate) nach Eintritt in Stufe 2 (konfigurierbar).
**Manuell:** Berechtigte Rollen dürfen Übergänge **vorziehen** (Stufe 1 erzwingen, Stufe 2 erzwingen, Purge erzwingen) gemäß §5.2 – ggf. **Tier-Gates** (§6).
### 5.2 Wer darf Lifecycle-Transitionen?
| Aktion | Vereins-Asset (`club`, Owner-Verein) | Privates Asset (`private`, Uploader) | `official` / plattformweit |
|--------|--------------------------------------|--------------------------------------|-----------------------------|
| Stufe 1 (Papierkorb) | **Vereinsadmin** + **Superadmin** | **Uploader** + **Superadmin** | **Superadmin** |
| Stufe 2 vorziehen / erzwingen | Vereinsadmin + Superadmin | Uploader + Superadmin | Superadmin |
| Recovery Stufe 2 → 1 | wie Stufe 1-Eintritt, ggf. Tier | wie links | Superadmin |
| Physisches Löschen (3) | Vereinsadmin + Superadmin; Systemjob nach Frist | Uploader + Superadmin | Superadmin |
**Superadmin / Systemadmin** ist immer **Override** (Klarstellung zur „systemadmin“-Formulierung).
### 5.3 Konsistenz mit bestehenden Übungen
- In **Stufe 1** bleiben Verknüpfungen funktional für Anzeige bestehen; Nutzer sehen **Warnung**.
- In **Stufe 2** wird das Medium in der **öffentlichen Übungsansicht nicht gerendert**; im **Bearbeitungsmodus** gibt es einen **Recovery-Link**, der das Asset zurück auf **Stufe 1** setzt (Policy: nur wer nach §5.2 Stufe 1 setzen darf, oder erweiterte Regel – bei Konflikt ACCESS_LAYER + dieses Dokument anpassen).
- **Physisches Löschen:** nur nach Stufe 2-Frist oder manueller Purge-Aktion; Backend entfernt Datei über Speicher-Backend und markiert Asset endgültig.
### 5.4 Hintergrundjobs
- Geplanter Job (täglich o. Ä.): Transitionen 1→2 und 2→3 gemäß Timestamps.
- Alle Zeiten **konfigurierbar** (Umgebungsvariablen oder DB-Config), Defaults wie §5.1.
---
## 6. Tier & Features
- **Tier** kann erlauben oder verbieten: **manuelles** Vorziehen von Stufe 2 oder Purge, zusätzliche Speicherquoten, externes Backend, etc.
- Tier ändert **nicht** die Übungs-Sichtbarkeit an sich; es **limitiert** nur Medien-spezifische Aktionen (Löschstufen, Archiv-Größe, …). Konkrete Feature-Keys in Umsetzung in `features` / `tier_limits` ergänzen und hier im **Changelog** dieses Dokuments verlinken.
---
## 7. Externe Speicherung (Server / S3)
- Abstraktion **StorageAdapter**: `put`, `get`, `delete`, ggf. `exists`.
- Konfiguration über ENV (z. B. Endpoint, Bucket, Credentials) – nie im Frontend.
- **NAS / anderer Rechner als App-Host:** In der Praxis `MEDIA_ROOT` in Compose/ENV auf den **Mount-Punkt** des NAS (oder NFS/SMB) setzen – die App läuft z. B. auf dem Raspberry, die Bytes liegen auf dem Speichersystem. Kein »Mediaserver« mit eigener Geschäftslogik nötig.
- **Pfadkonvention** auf der Platte z. B. `clubs/{club_id}/…` für Mandantentrennung (Umsetzung schrittweise; neue Uploads können zuerst unter `exercises/{sha256}{ext}` liegen).
### 7.1 Konfiguration: Bootstrap vs. Superadmin (Laufzeit)
| Ebene | Inhalt | Wer / Wo |
|-------|--------|----------|
| **Bootstrap** | Basis-Verzeichnis `MEDIA_ROOT` (Container/Host), ggf. S3-Secrets | Deployment (`.env`, Docker Compose) – Container muss ohne UI starten können |
| **Laufzeit (nicht-geheim)** | Zusätzlicher **relativer Unterpfad** unter `MEDIA_ROOT` (`local_relative_root`), später: aktives Backend `local` \| `s3`, öffentlicher Endpoint/Bucket-Name | **Superadmin** über Tabelle `platform_media_storage` + API; keine Secrets für S3 im Klartext in der DB (Keys nur ENV/Vault) |
| **Effektives Wurzelverzeichnis** | `Path(MEDIA_ROOT) / local_relative_root` nach Normalisierung (kein `..`, kein absoluter Pfad im relativen Segment) | berechnet im Backend bei jedem Zugriff |
**Hinweis Beta:** Primär ein Verein, Videos auf separatem physischen System → typischerweise **ein NAS-Mount** als `MEDIA_ROOT`; Superadmin kann bei Bedarf einen **Unterordner** setzen, ohne neues Image zu bauen.
**Drift:** Jede Änderung an Speicher-Konfiguration oder Asset-Schema → Migration + Eintrag **§10 Changelog** + bei neuen Endpoints **ACCESS_LAYER_ENDPOINT_AUDIT.md**. Änderungen an **Inline-Platzhaltern** (§11) → ebenfalls Changelog + ggf. Frontend-Sanitize-Regeln dokumentieren.
---
## 8. Embeds & Streaming-Plattformen
- Embeds **bleiben** erste Klasse; bestehende Plattform-Erkennung erweiterbar (`embed_platform`).
- Roadmap: weitere Hosts (Player-Komponente, oEmbed, CSP) – **ohne** Änderung am Asset-Lifecycle-Modell.
---
## 9. Pflichten zur Drift-Vermeidung
| Änderung an … | Pflegepflicht |
|---------------|---------------|
| DB-Schema Medien | Neue Migration + **Abschnitt/Changelog in diesem Dokument** (Datum, Kurzbeschreibung) |
| Sichtbarkeit / Enums | Zuerst `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`, dann dieses Dokument synchron halten |
| Neue Endpoints Medien/Archiv | `ACCESS_LAYER_ENDPOINT_AUDIT.md` + `get_tenant_context`/Governance |
| **Inline-Referenzen** in Übungstexten (§11) | Renderer/Sanitizer-Regeln + dieses Dokument §11; kein zweites Rechtemodell |
| Implementierungs-Meilenstein | `backend/version.py` (`MODULE_VERSIONS` / Schema-Kommentar) und bei größerem Release `PROJECT_STATUS.md` |
---
## 10. Changelog
| Datum | Änderung |
|-------|----------|
| 2026-05-08 | **0.8.64:** Bearbeiten-UX erweitert: Drag&Drop mit Auto-Scroll in Richtung Rich-Text, Medienliste in Kachel-Grid, Warnhinweis vor Wechsel „Ansehen“ bei ungespeicherten Änderungen + Rückweg „Zurück zur Bearbeitung“, Katalogvorschau ohne separaten Anhangs-Medienstreifen. |
| 2026-05-08 | **0.8.63:** Inline-Medien-Picker als Modal (Mediathek/Upload + separates Embed-Modal), Größenwahl `small|medium|full`, Platzhalter-Caption (`data-shinkan-exercise-media-caption`), Wiederverwendung bereits verknüpfter Assets im Picker, kompakter Medienbereich mit Drag&Drop in Textfelder. |
| 2026-05-08 | **0.8.60 §11:** Inline in Übungstexten (`{{exerciseMedia:id}}` / `data-shinkan-exercise-media`); Server-Normalisierung + Validierung; Client-Sanitize und zentraler Block-Renderer (`ExerciseRichTextBlock`); CREATE ohne bestehende `exercise_media` lehnt Platzhalter ab. |
| 2026-05-07 | **0.8.59:** Dokumentation — Aktiver Verein (Profil/Header/`effective_club_id`) für Plattform-Admin und UI-Dropdown synchron; kein fachliches Archiv-Schema-Change. |
| 2026-05-07 | **0.8.58:** Medien **`official`:** Lifecycle schwerpunktmäßig **Superadmin** (nicht Plattform-Admin); Bearbeitungsdialog Bibliothek für andere Rollen **Lesemodus**; Superadmin-Upload: Vereinskontext folgt aktiv gesetztem Verein / `effective_club_id`. |
| 2026-05-07 | **0.8.47–0.8.57 (Auszug):** Übung **`official`** nur Superadmin; Vereinsübungen mit File-Assets: **Copyright-Pflicht**; Speicherpfade **`library/`** mit Vereinsordner (Name+c{id}), Medienkind-Unterordner, Governance-Umzug bei Sichtbarkeit; Bibliothek-GET mit Filtern/Tags/Nutzungs-Anzeige; Bulk-Lifecycle/PATCH; Lesemodus/Kacheln; Konflikt **409** bei Upload-Dedupe vs. Papierkorb + UI-Reaktivierung. |
| 2026-05-07 | **0.8.42–0.8.43:** Papierkorb-Lifecycle API, Retention-Skript; **`POST …/exercises/{id}/media/from-asset`**; Übungs-UI Archiv verknüpfen / Vorschau. |
| 2026-05-07 | Erstfassung als Single Source of Truth (verbindlich); Abstimmung Stakeholder: Promotion Übung↔Medien, Copyright, Papierkorb 3-stufig, externe Speicher, Embeds getrennt vom Asset-Lifecycle. |
| 2026-05-07 | §11 **Inline-Medien im Fließtext**: Leitplanken (Anker `exercise_media.id`, einheitlicher Render-Pfad, keine zweite Governance); Umsetzung **nach** tragfähigem Archiv — siehe **`docs/HANDOVER.md`** §5. |
| 2026-05-07 | **Medienmanager (Basis):** `GET /api/media-assets?lifecycle=…`, `copyright_notice` in Response; `PATCH` Copyright; `GET …/file` für Papierkorb-Zeilen bei Verwaltungsrecht; UI-Route `/media` (Medienbibliothek). |
---
## 11. Inline-Medien im Fließtext (Umsetzung & Leitplanken)
**Status:** Frontend-Renderer und API-Validierung/Normalisierung umgesetzt (App ≥ 0.8.60); verbindliche Leitplanken unten.
### 11.1 Ziel
- Medien (Player, Bild) sollen **an definierter Stelle** in Feldern wie Ablauf / Ziel / Notizen erscheinen können – zusätzlich oder statt reiner Zuordnung zu den Sektionen `ablauf` / `detail` / `trainer_hint`.
- **Keine zweite Sichtbarkeit:** Inline verweist immer auf dieselbe **Übungs-Medium-Zeile** (`exercise_media.id`) bzw. indirekt auf das gleiche Asset wie die Medienliste; **Lesen/Ausliefern** nur nach **bestehender** Übungs- + Medien-Governance (§4.1).
### 11.2 Platzhalter-Konvention (**festgelegt**)
- **Kanonisches Markup nach Speichern:** `<span data-shinkan-exercise-media="<numerische exercise_media.id>" class="shinkan-inline-media"></span>`.
- **Erweiterung (UI/Lesbarkeit):** optionales Attribut `data-shinkan-exercise-media-size="small|medium|full"` (Default `medium`) und optional `data-shinkan-exercise-media-caption="..."` für sprechende Platzhalter-Chips im Editor.
- **Kurzsyntax (Eingabe/Import):** `{{exerciseMedia:123}}` — Server normalisiert beim Speichern (PUT Übung / Varianten) in das kanonische `span`; **CREATE** ohne bestehende `exercise_media`-Zeilen verwirft Platzhalter mit **400**.
### 11.3 Rendering & Sicherheit
- **Ein zentraler Pfad** „Übungstext für Anzeige aufbereiten“: HTML sanitizen (Allowlist), erlaubte Platzhalter auflösen, **ID gehört zur aktuellen Übung** und Medium ist für den Nutzer **sichtbar** – sonst Platzhalter mit neutralem Hinweis oder ausblenden.
- **XSS/CSP:** keine rohen `iframe`/Skripte aus Nutzer-HTML ohne Kontrolle; eingebettete Player nur über kontrollierte Komponenten.
### 11.4 Koexistenz mit Sektions-Medien
- **Liste + Inline** dürfen dasselbe `exercise_media` referenzieren (ein Player an zwei Stellen).
- Stand 0.8.64: Katalog-/Vorschaupfade priorisieren Inline-Darstellung; ein zusätzlicher Anhangsblock wird dort nicht mehr parallel erzwungen.
- Import/Wiki: vor großen Content-Migrationen **Syntax festlegen**, damit nicht irreversibel „falsches“ HTML importiert wird.
### 11.5 Wann umsetzen (Reihenfolge)
1. ~~**Erledigt (Basis):** Medien-Archiv, `media_assets`, Upload/Dedupe, Speicherpfad, Papierkorb, Bibliothek `/media`, Verknüpfung `from-asset`, Governance `official`/Copyright.~~
2. **Umgesetzt (Stand 0.8.64):** Platzhalter/Kurzsyntax + zentraler Frontend-Render-Pfad + Server-Validierung gemäß §11.1–11.4; Editor-Einstieg „Medium einfügen“ inkl. Modal-Picker (Mediathek/Upload), separates Embed-Modal, Größenwahl und Drag&Drop aus der Medienliste.
3. **Editor:** kein Zwang zum vollen Block-Editor vorab; **Platzhalter im bestehenden RTE** ist der vorgesehene schlanke Einstieg.
### 11.6 Refactor-Vermeidung (jetzt schon)
- Neue Features **nicht** so bauen, dass HTML aus Übungstexten an **vielen** Stellen „roh“ gerendert wird – **ein** wiederverwendbarer Renderer vorbereiten (schrittweise einziehen).
- Medien immer über **stabile IDs** anbinden, nicht nur über Datei-URLs im Text.
---
## 12. Referenzen
- `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
- `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` (Limits, MIME, Embed-Typen im aktuellen Backend)
- `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
- `backend/routers/exercises.py` – Ist-Zustand `exercise_media` bis Refactor
+782
View File
@@ -0,0 +1,782 @@
# Media Upload & Embed Specification
**Version:** 1.2
**Datum:** 2026-05-07
**Status:** Aktuell für Upload-Limits, MIME, Embed — **zentraler Medien-Ist-Stand** inkl. Archiv, Lifecycle, Pfadkonvention: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**
> **Zielbild Medien-Archiv, Wiederverwendung, Papierkorb, Copyright, externe Speicherung, später Inline im Fließtext:**
> Verbindliche Single Source of Truth: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`** (§11 Leitplanken Inline, ohne Umsetzung).
> Dieses Dokument bleibt maßgeblich für **konkrete Upload-Limits, MIME-Liste und Embed-Hosting** des aktuellen Stands bis zum Refactor.
---
## 1. Upload-Strategie
### 1.1 Hybrid-Ansatz
**Zwei Medienquellen:**
1. **Lokale Uploads:** Datei-Upload auf Server (Images, Videos, PDFs, Sketches)
2. **Embeds:** Einbetten von YouTube, Instagram, Vimeo, TikTok
**Vorteile:**
- Lokale Kontrolle über kritische Inhalte
- Keine Abhängigkeit von Drittanbietern für Kern-Content
- Externe Plattformen für ergänzende Videos
**Limitierungen (implementiert):**
- Max. Dateigröße: **50 MB** Standardnutzer (`EXERCISE_MEDIA_MAX_UPLOAD_MB`, Default 50).
- **`admin` / `superadmin`**: höheres Limit (**1024 MB** Default `EXERCISE_MEDIA_ADMIN_MAX_UPLOAD_MB`; nie unter dem Nutzer-Limit in MB).
- Max. 10 Media-Items pro Übung (kombiniert Local + Embeds) — siehe Backend-Validierung
- Erlaubte Formate: JPEG, PNG, GIF, MP4, PDF
---
## 2. Upload-Flow (Lokale Dateien)
### 2.1 Frontend-Komponente: MediaUploader
**Props:**
```typescript
interface MediaUploaderProps {
exerciseId: number
existingMedia: Media[]
onUploadComplete: (media: Media) => void
maxFiles?: number // default: 10
maxSizeMB?: number // default: 50
}
```
**UI-Struktur:**
```jsx
<MediaUploader>
<div className="upload-zone">
{/* Drag & Drop Area */}
<input type="file" multiple accept="image/*,video/mp4,application/pdf" />
{/* Preview Grid */}
<div className="media-grid">
{uploadQueue.map(file => (
<div key={file.name} className="upload-preview">
<img src={file.preview} />
<ProgressBar percent={file.uploadProgress} />
<button onClick={() => removeFromQueue(file)}>×</button>
</div>
))}
</div>
{/* Metadata Form (per File) */}
<div className="upload-metadata">
<input name="title" placeholder="Titel (optional)" />
<textarea name="description" placeholder="Beschreibung" />
<select name="context">
<option value="ablauf">Ablauf</option>
<option value="detail">Detail</option>
<option value="trainer_hint">Trainer-Hinweis</option>
</select>
<label>
<input type="checkbox" name="is_primary" />
Als Hauptbild markieren
</label>
</div>
<button onClick={handleUpload}>
{uploadQueue.length} Dateien hochladen
</button>
</div>
</MediaUploader>
```
### 2.2 Client-seitige Validierung
**Vor Upload prüfen:**
```javascript
// MediaUploader.jsx
const validateFile = (file) => {
const errors = []
// Größe
const maxSize = 50 * 1024 * 1024 // 50 MB
if (file.size > maxSize) {
errors.push(`${file.name} ist zu groß (max. 50 MB)`)
}
// MIME-Type
const allowed = ['image/jpeg', 'image/png', 'image/gif', 'video/mp4', 'application/pdf']
if (!allowed.includes(file.type)) {
errors.push(`${file.name} hat ungültiges Format`)
}
// Video-spezifisch: Auflösung prüfen
if (file.type === 'video/mp4') {
const video = document.createElement('video')
video.src = URL.createObjectURL(file)
video.onloadedmetadata = () => {
if (video.videoWidth > 1920 || video.videoHeight > 1080) {
errors.push(`${file.name} Auflösung zu hoch (max. 1920x1080)`)
}
}
}
return errors
}
const handleFilesSelected = (files) => {
const validFiles = []
const errors = []
files.forEach(file => {
const fileErrors = validateFile(file)
if (fileErrors.length === 0) {
validFiles.push(file)
} else {
errors.push(...fileErrors)
}
})
if (errors.length > 0) {
setValidationErrors(errors)
}
setUploadQueue(prev => [...prev, ...validFiles])
}
```
### 2.3 Upload mit Progress
**multipart/form-data Upload:**
```javascript
const uploadFile = async (file, metadata) => {
const formData = new FormData()
formData.append('file', file)
formData.append('media_type', detectMediaType(file))
formData.append('title', metadata.title || '')
formData.append('description', metadata.description || '')
formData.append('context', metadata.context || 'ablauf')
formData.append('is_primary', metadata.is_primary || false)
return axios.post(
`/api/exercises/${exerciseId}/media`,
formData,
{
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const percent = (progressEvent.loaded / progressEvent.total) * 100
setUploadProgress(file.name, percent)
}
}
)
}
const detectMediaType = (file) => {
if (file.type.startsWith('image/')) return 'image'
if (file.type === 'video/mp4') return 'video'
if (file.type === 'application/pdf') return 'document'
return 'sketch' // Fallback
}
```
### 2.4 Backend-Verarbeitung
**Endpoint:** `POST /api/exercises/{exercise_id}/media`
```python
from fastapi import UploadFile, File, Form
import magic # python-magic für MIME-Detection
import hashlib
import os
@router.post("/exercises/{exercise_id}/media")
async def upload_media(
exercise_id: int,
file: UploadFile = File(...),
media_type: str = Form(...),
title: str = Form(default=""),
description: str = Form(default=""),
context: str = Form(default="ablauf"),
is_primary: bool = Form(default=False),
session: dict = Depends(require_auth)
):
profile_id = session['profile_id']
# 1. Berechtigung prüfen
check_exercise_permission(exercise_id, profile_id)
# 2. Datei-Validierung
max_size = 50 * 1024 * 1024 # 50 MB
file_content = await file.read()
if len(file_content) > max_size:
raise HTTPException(413, "Datei zu groß (max. 50 MB)")
# 3. MIME-Type verifizieren (nicht nur Extension!)
mime = magic.from_buffer(file_content, mime=True)
allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'video/mp4', 'application/pdf']
if mime not in allowed_mimes:
raise HTTPException(400, f"Ungültiger Dateityp: {mime}")
# 4. Eindeutigen Dateinamen generieren
file_hash = hashlib.sha256(file_content).hexdigest()[:12]
file_ext = os.path.splitext(file.filename)[1]
safe_filename = f"{file_hash}_{exercise_id}{file_ext}"
# 5. Speichern
file_path = f"/app/media/exercises/{safe_filename}"
with open(file_path, 'wb') as f:
f.write(file_content)
# 6. DB-Eintrag
cur = get_db_cursor()
cur.execute("""
INSERT INTO exercise_media (
exercise_id, media_type, file_path, file_size, mime_type,
original_filename, title, description, context, is_primary, sort_order
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
COALESCE((SELECT MAX(sort_order) + 1 FROM exercise_media WHERE exercise_id = %s), 1)
)
RETURNING id, sort_order, created_at
""", (
exercise_id, media_type, file_path, len(file_content), mime,
file.filename, title, description, context, is_primary, exercise_id
))
result = cur.fetchone()
return {
"id": result['id'],
"exercise_id": exercise_id,
"media_type": media_type,
"file_path": file_path,
"file_size": len(file_content),
"mime_type": mime,
"original_filename": file.filename,
"title": title,
"description": description,
"context": context,
"is_primary": is_primary,
"sort_order": result['sort_order'],
"created_at": result['created_at'].isoformat(),
}
```
---
## 3. Embed-Flow (YouTube, Instagram, Vimeo)
### 3.1 Frontend-Komponente: EmbedInput
**UI:**
```jsx
<div className="embed-input">
<input
type="url"
placeholder="YouTube, Instagram oder Vimeo URL einfügen"
value={embedUrl}
onChange={(e) => setEmbedUrl(e.target.value)}
onBlur={handleEmbedParse}
/>
{preview && (
<div className="embed-preview">
<iframe src={preview.embedUrl} />
<div className="embed-metadata">
<strong>{preview.platform}</strong> • {preview.title}
</div>
</div>
)}
<div className="embed-metadata-form">
<input name="title" placeholder="Titel (optional)" />
<textarea name="description" />
<select name="context">
<option value="ablauf">Ablauf</option>
<option value="detail">Detail</option>
</select>
</div>
<button onClick={handleEmbedSave}>Embed hinzufügen</button>
</div>
```
### 3.2 URL-Parsing (Client-Side)
**Unterstützte Formate:**
```javascript
const parseEmbedUrl = (url) => {
// YouTube
if (url.includes('youtube.com/watch?v=')) {
const videoId = new URL(url).searchParams.get('v')
return {
platform: 'youtube',
videoId,
embedUrl: `https://www.youtube-nocookie.com/embed/${videoId}`,
originalUrl: url,
}
}
if (url.includes('youtu.be/')) {
const videoId = url.split('youtu.be/')[1].split('?')[0]
return {
platform: 'youtube',
videoId,
embedUrl: `https://www.youtube-nocookie.com/embed/${videoId}`,
originalUrl: url,
}
}
// Vimeo
if (url.includes('vimeo.com/')) {
const videoId = url.split('vimeo.com/')[1].split('?')[0]
return {
platform: 'vimeo',
videoId,
embedUrl: `https://player.vimeo.com/video/${videoId}`,
originalUrl: url,
}
}
// Instagram (Reel oder Post)
if (url.includes('instagram.com/reel/') || url.includes('instagram.com/p/')) {
const postId = url.match(/\/(reel|p)\/([^\/\?]+)/)[2]
return {
platform: 'instagram',
postId,
embedUrl: `https://www.instagram.com/p/${postId}/embed`,
originalUrl: url,
}
}
// TikTok
if (url.includes('tiktok.com/')) {
const videoId = url.match(/video\/(\d+)/)?.[1]
return {
platform: 'tiktok',
videoId,
embedUrl: `https://www.tiktok.com/embed/v2/${videoId}`,
originalUrl: url,
}
}
return null
}
const handleEmbedParse = async () => {
const parsed = parseEmbedUrl(embedUrl)
if (!parsed) {
setError('Ungültige URL. Unterstützt: YouTube, Vimeo, Instagram, TikTok')
return
}
// Optional: Metadata via oEmbed API holen
const metadata = await fetchOembedData(parsed)
setPreview({ ...parsed, ...metadata })
}
```
### 3.3 oEmbed Metadata (Optional)
**YouTube oEmbed:**
```javascript
const fetchYoutubeMetadata = async (videoId) => {
const response = await fetch(
`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`
)
const data = await response.json()
return {
title: data.title,
author: data.author_name,
thumbnail: data.thumbnail_url,
}
}
```
**Vimeo oEmbed:**
```javascript
const fetchVimeoMetadata = async (videoId) => {
const response = await fetch(
`https://vimeo.com/api/oembed.json?url=https://vimeo.com/${videoId}`
)
const data = await response.json()
return {
title: data.title,
author: data.author_name,
thumbnail: data.thumbnail_url,
}
}
```
### 3.4 Backend-Speicherung (Embed)
**Endpoint:** `POST /api/exercises/{exercise_id}/media` (gleicher Endpoint)
```python
@router.post("/exercises/{exercise_id}/media")
async def add_media(
exercise_id: int,
# Entweder file ODER embed_url (nicht beides)
file: UploadFile = File(default=None),
embed_url: str = Form(default=None),
media_type: str = Form(...),
title: str = Form(default=""),
description: str = Form(default=""),
context: str = Form(default="ablauf"),
session: dict = Depends(require_auth)
):
if file and embed_url:
raise HTTPException(400, "Entweder file oder embed_url, nicht beides")
if not file and not embed_url:
raise HTTPException(400, "file oder embed_url erforderlich")
if embed_url:
# Embed-URL validieren
platform = detect_platform(embed_url)
if not platform:
raise HTTPException(400, "Ungültige Embed-URL")
# DB-Eintrag (ohne file_path)
cur.execute("""
INSERT INTO exercise_media (
exercise_id, media_type, embed_url, embed_platform,
title, description, context, is_primary, sort_order
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s,
COALESCE((SELECT MAX(sort_order) + 1 FROM exercise_media WHERE exercise_id = %s), 1)
)
RETURNING id, sort_order, created_at
""", (
exercise_id, media_type, embed_url, platform,
title, description, context, False, exercise_id
))
# ... return result
# ... else: file upload (siehe 2.4)
def detect_platform(url):
if 'youtube.com' in url or 'youtu.be' in url:
return 'youtube'
if 'vimeo.com' in url:
return 'vimeo'
if 'instagram.com' in url:
return 'instagram'
if 'tiktok.com' in url:
return 'tiktok'
return None
```
---
## 4. Media-Galerie (Anzeige)
### 4.1 Komponente: MediaGallery
**Props:**
```typescript
interface MediaGalleryProps {
media: Media[]
primaryMediaId?: number
onMediaClick?: (media: Media) => void
layout?: 'grid' | 'list' | 'carousel'
showControls?: boolean
}
```
**Render-Logik:**
```jsx
<div className="media-gallery">
{/* Primary Media (groß oben) */}
{primaryMedia && (
<div className="primary-media">
{renderMedia(primaryMedia, 'large')}
</div>
)}
{/* Grid mit restlichen Medien */}
<div className="media-grid">
{secondaryMedia.map(media => (
<div key={media.id} className="media-item">
{renderMedia(media, 'thumbnail')}
<div className="media-overlay">
<span className="media-title">{media.title}</span>
<span className="media-context">{media.context}</span>
</div>
</div>
))}
</div>
</div>
const renderMedia = (media, size) => {
// Lokale Datei
if (media.file_path) {
if (media.media_type === 'image') {
return <img src={`/media/${media.file_path}`} alt={media.title} />
}
if (media.media_type === 'video') {
return <video src={`/media/${media.file_path}`} controls />
}
if (media.media_type === 'document') {
return <a href={`/media/${media.file_path}`} target="_blank">📄 {media.title}</a>
}
}
// Embed
if (media.embed_url) {
return (
<iframe
src={media.embed_url}
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
/>
)
}
}
```
### 4.2 Lightbox (Vollbild-Ansicht)
**Pattern:**
```jsx
const [lightboxMedia, setLightboxMedia] = useState(null)
<MediaGallery
media={exercise.media}
onMediaClick={(media) => setLightboxMedia(media)}
/>
{lightboxMedia && (
<Lightbox
media={lightboxMedia}
onClose={() => setLightboxMedia(null)}
onPrev={() => setLightboxMedia(getPrevMedia(lightboxMedia))}
onNext={() => setLightboxMedia(getNextMedia(lightboxMedia))}
/>
)}
```
---
## 5. Drag & Drop Reordering
### 5.1 Frontend-Komponente
**Nutzt DragDropList aus UI_COMPONENTS_SPEC.md:**
```jsx
<DragDropList
items={media}
onReorder={handleMediaReorder}
renderItem={(media) => (
<div className="media-reorder-item">
<DragHandle />
<img src={getThumbnail(media)} />
<span>{media.title || media.original_filename}</span>
{media.is_primary && <Badge>Hauptbild</Badge>}
</div>
)}
/>
const handleMediaReorder = async (reorderedMedia) => {
const mediaIds = reorderedMedia.map(m => m.id)
try {
await api.reorderExerciseMedia(exerciseId, mediaIds)
setMedia(reorderedMedia)
} catch (error) {
console.error('Reorder failed:', error)
}
}
```
### 5.2 Backend-Endpoint
**Endpoint:** `PUT /api/exercises/{exercise_id}/media/reorder`
```python
@router.put("/exercises/{exercise_id}/media/reorder")
def reorder_media(
exercise_id: int,
request: dict, # {"media_ids": [3, 1, 2]}
session: dict = Depends(require_auth)
):
profile_id = session['profile_id']
check_exercise_permission(exercise_id, profile_id)
media_ids = request.get('media_ids', [])
# Validierung: Alle IDs gehören zur Exercise
cur = get_db_cursor()
cur.execute("""
SELECT id FROM exercise_media WHERE exercise_id = %s
""", (exercise_id,))
existing_ids = {row['id'] for row in cur.fetchall()}
if set(media_ids) != existing_ids:
raise HTTPException(400, "media_ids inkonsistent")
# Reorder
for idx, media_id in enumerate(media_ids, start=1):
cur.execute("""
UPDATE exercise_media SET sort_order = %s WHERE id = %s
""", (idx, media_id))
return {"ok": True, "reordered": len(media_ids)}
```
---
## 6. Security & Performance
### 6.1 Security
**File Upload:**
- MIME-Type-Validierung mit `python-magic` (nicht nur Extension)
- Max. Dateigröße serverseitig prüfen
- Virus-Scan optional (ClamAV) bei Prod-System
- Keine Ausführungsrechte auf Upload-Ordner
**Embed:**
- Nur Whitelist-Domains (youtube.com, vimeo.com, instagram.com, tiktok.com)
- Keine User-Content-Domains (pastebin, file-sharing)
### 6.2 Performance
**Thumbnails generieren (Videos):**
```python
import ffmpeg
def generate_video_thumbnail(video_path, output_path):
(
ffmpeg
.input(video_path, ss='00:00:01') # 1 Sekunde ins Video
.filter('scale', 320, -1)
.output(output_path, vframes=1)
.run()
)
```
**Responsive Images (automatisch generieren):**
```python
from PIL import Image
def create_responsive_sizes(image_path):
img = Image.open(image_path)
sizes = {
'thumbnail': (320, 240),
'medium': (800, 600),
'large': (1920, 1080),
}
for size_name, (width, height) in sizes.items():
img_resized = img.copy()
img_resized.thumbnail((width, height), Image.LANCZOS)
output_path = image_path.replace('.jpg', f'_{size_name}.jpg')
img_resized.save(output_path, quality=85)
```
**Frontend nutzt `srcset`:**
```jsx
<img
src={`/media/${media.file_path}`}
srcSet={`
/media/${media.file_path.replace('.jpg', '_thumbnail.jpg')} 320w,
/media/${media.file_path.replace('.jpg', '_medium.jpg')} 800w,
/media/${media.file_path} 1920w
`}
sizes="(max-width: 600px) 320px, (max-width: 1200px) 800px, 1920px"
/>
```
---
## 7. Error-Handling
### 7.1 Upload-Fehler
**Frontend:**
```javascript
try {
await uploadFile(file, metadata)
} catch (error) {
if (error.response?.status === 413) {
setError('Datei zu groß (max. 50 MB)')
} else if (error.response?.status === 400) {
setError(error.response.data.detail)
} else {
setError('Upload fehlgeschlagen. Bitte erneut versuchen.')
}
}
```
**Backend:**
```python
# Detaillierte Fehlermeldungen
if len(file_content) > max_size:
raise HTTPException(413, f"Datei zu groß: {len(file_content) / (1024*1024):.1f} MB (max. 50 MB)")
if mime not in allowed_mimes:
raise HTTPException(400, f"Dateityp {mime} nicht erlaubt. Erlaubt: {', '.join(allowed_mimes)}")
```
### 7.2 Embed-Fehler
**Ungültige URL:**
```javascript
if (!parseEmbedUrl(url)) {
setError('URL nicht erkannt. Unterstützte Plattformen: YouTube, Vimeo, Instagram, TikTok')
}
```
**Embed lädt nicht:**
```javascript
<iframe
src={embedUrl}
onError={() => {
setEmbedError('Video konnte nicht geladen werden. Ist das Video öffentlich?')
}}
/>
```
---
## 8. Testing
### 8.1 Upload-Tests
```javascript
// upload.spec.js
test('Upload von JPEG-Datei funktioniert', async ({ page }) => {
await page.goto('/exercises/1/edit')
const fileInput = page.locator('input[type="file"]')
await fileInput.setInputFiles('test-files/image.jpg')
await page.click('button:has-text("Hochladen")')
await expect(page.locator('.media-gallery img')).toBeVisible()
})
test('Upload > 50 MB wird abgelehnt', async ({ page }) => {
await page.goto('/exercises/1/edit')
await page.setInputFiles('input[type="file"]', 'test-files/large-video.mp4')
await expect(page.locator('.error:has-text("zu groß")')).toBeVisible()
})
```
### 8.2 Embed-Tests
```javascript
test('YouTube URL wird korrekt geparst', async ({ page }) => {
await page.goto('/exercises/1/edit')
await page.fill('input[placeholder*="YouTube"]', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ')
await page.blur('input[placeholder*="YouTube"]')
await expect(page.locator('iframe[src*="youtube-nocookie.com"]')).toBeVisible()
})
```
---
**Version:** 1.0
**Letzte Änderung:** 2026-04-24
**Status:** DRAFT - Awaiting Review
@@ -0,0 +1,233 @@
# Multi-Tenancy, Vereins-Membership und Rollenmodell – Zielarchitektur & Umsetzungsplan
**Status:** verbindliche Zielrichtung (Architekturpapier)
**Stand:** 2026-05-06
**Bezug:** `functional/shinkan_anforderungsdokument_entwurf.md` §5, §17–18 · `functional/DOMAIN_MODEL.md` (Sichtbarkeit §5.5) · `functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR-004–008)
**Operative Reihenfolge & einheitliche Zugriffsschicht:** [`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`](./ACCESS_LAYER_AND_GOVERNANCE_PLAN.md) – dort sind Stufen A–F, Drift-Prävention und die Zurückstellung von Vereinsabo/Limits festgehalten; dieses Dokument bleibt das übergeordnete **Zielbild**.
---
## 1. Zweck
Dieses Dokument fasst den **Soll-Zustand** für Mandantenfähigkeit (Verein = Mandant), **rollenbasierte Zugriffskontrolle auf Vereinsebene** und ein **Membership-/Limitsystem** zusammen – und definiert einen **phasenweisen Umsetzungsplan**, der mit dem bestehenden Governance-Kern (`visibility`, `club_id`, `created_by`) konsistent bleibt.
---
## 2. Abgleich mit vorhandener Dokumentation
| Quelle | Inhalt relevant für Tenancy/Rollen | Konsistenz mit Zielbild |
|--------|-----------------------------------|-------------------------|
| `shinkan_anforderungsdokument_entwurf.md` §5.4 | Rollen: Superadmin, Vereinsadmin, Trainer, Co-Trainer, Redakteur | Deckt sich; „Superadmin“ entspricht fachlich **Systemadmin** |
| §17.1 | Erweiterung: Systemadmin, Spartenadmin | Entspricht den gewünschten **Spartenverantwortlichen** |
| §5.5 / §17 | Sichtbarkeit: privat, Verein, Sparte, global, offiziell | DOMAIN_MODEL listet ähnliche Stufen; Bibliothek **`private` \| `club` \| `official`** technisch über Zugriffsschicht durchgesetzt; **Sparte/community** folgt |
| §18.5 | MVP: Datenmodell mandantenfähig, Rechte zunächst einfach | Bestätigt schrittweise Verschärfung |
| `DOMAIN_MODEL.md` §5.5 | Freigabeebenen inkl. Sparte | Zielbild; DB/API nutzen derzeit überwiegend `private` \| `club` \| `official` |
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | CURR-004–008: Governance-Kern, spätere Policy | Datenfelder vorbereitet; **Policy/Erzwingung** folgt |
| `working/SHINKAN_PROJECT_SETUP.md` §6 | „Multi-Tenant-Administration“ ausgeschlossen (MVP-Liste) | Historisch; **technische Mandanten** sind dennoch Ziel – UI-Komplexität kontrolliert einführen |
**Fazit:** Die fachlichen Rollen und Sichtbarkeitsebenen sind **in den funktionalen Docs skizziert**. Für die **Kernteile Bibliothek und Vereinskontext** ist eine **technische Zugriffsschicht** (`TenantContext`, `club_members`, einheitliche Sichtbarkeits-SQL/-Prüfungen) umgesetzt — Details und Restarbeit (**Sparte**, Konsolidierung der Hilfen, Planungs-/Admin-Flows) siehe §3 und `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`.
---
## 3. Ist-Stand im Code (Gap-Analyse)
> **Hinweis:** Die Unterabschnitte **3.1–3.6** enthalten weiterhin **historische Problemstellungen** (Ausgangsbild). Ergänzend beschreibt **3.0** den **aktualisierten Umsetzungsstand** nach Mitgliedschafts-, Tenant- und Bibliotheksarbeit. Verbindliche **offene Arbeit und Reihenfolge:** [`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`](./ACCESS_LAYER_AND_GOVERNANCE_PLAN.md).
### 3.0 Aktualisierung des Umsetzungsstands (kurz)
- **Mitgliedschaft:** Tabellen `club_members` und `club_member_roles`; aktiver Verein über Profilfeld und Header `X-Active-Club-Id`; Auflösung in **`TenantContext`** (`tenant_context.py`).
- **Bibliothek** (Übungen, Trainingsplan-Vorlagen, Rahmenprogramme u. a.): gemeinsame Leselogik **`library_content_visibility_sql`** / **`library_content_visible_to_profile`** — Vereinsinhalte **`club`** nur bei passendem **`club_id`** und **aktiver Mitgliedschaft** im Objekt-Verein (normale Nutzer ohne gültigen Vereinskontext: kein „beliebiges club“).
- **`GET /api/clubs`:** Nicht-Admins sehen nur Vereine mit Mitgliedschaft; **`POST /api/clubs`:** nur **Plattform-Admin**, mit Pflicht **`primary_admin_profile_id`**.
- **Organisation** (Sparten/Gruppen): Schreibzugriff über **`can_manage_club_org`** / **`can_plan_in_club`** auf Basis von **`club_member_roles`** (nicht mehr nur globales `admin`).
- **Profil-API:** eingeschränktes **`GET /profiles/{id}`**, **`DELETE`**, **`POST /profiles`** (Plattform-Admin / Selbstzugriff) — Details `backend/routers/profiles.py`.
- **Tests:** pytest inkl. optionaler Mandanten-Integration (`ACCESS_LAYER_INTEGRATION`); CI-Anbindung siehe `.gitea/workflows/test.yml` (Ausführung im Backend-Container wie Schwesterprojekt).
### 3.1 Identität und Rollen
- `profiles.role` ist eine **globale** Kennzeichnung (`admin`, `superadmin`, `trainer`, `user`, …).
- *(Historisch)* Fehlende Abbildung von Vereinsrollen **ohne** eigene Tabellen.
- **Ist:** Zusätzlich **`club_member_roles`** pro Verein (z. B. `club_admin`, `trainer`, …); Sessions liefern weiter **`profile_id`** + globale **`role`** (`auth.py` → `get_session`), Vereinsrechte werden aus Mitgliedschaft abgeleitet.
**Konsequenz:** Globale Rolle und Vereinsrollen **koexistieren**; Produkt und Code sollten langfristig klar trennen, was nur global vs. nur über Mitgliedschaft gilt (vgl. Zielarchitektur §4).
### 3.2 Organisation & APIs
- *(Historisch)* Zu offene Vereinsliste und Club-Anlage für jeden Trainer/User.
- **Ist:** siehe **3.0** — gefilterte Liste, eingeschränktes Anlegen, kontextbezogene Organisationsrechte.
**Konsequenz:** Offene Punkte verlagern sich in **feine Produktregeln** und **Sparten-/Community-Stufen** (ACCESS_LAYER Stufe D bzw. spätere Epics).
### 3.3 Trainingsplanung
- Zugriff auf Einheiten weiterhin stark **gruppenbezogen** (`training_groups`, optional **`lead_trainer_profile_id`** auf Einheiten).
- Mitgliedschaft/`TenantContext` unterstützen andere Endpoints; **`GET /training-units`** hat **keinen** impliziten Filter nur auf **`effective_club_id`** (Multi-Verein-Kalender; bei Bedarf Query **`club_id`**).
**Konsequenz:** Vereinsweite oder „Administrations“-Planungsaufgaben können weiter ausgebaut werden (eigenes Produkt-Thema; nicht identisch mit Bibliotheks-Governance).
### 3.4 Governance / Sichtbarkeit (Bibliothek)
- *(Historisch)* Risiko: **`club`**-Objekte ohne Bindung an **`club_id`** / Mitgliedschaft → mögliche Cross-Tenant-Sicht.
- **Ist:** Listen und Detail für die genannten Bibliotheksmodule nutzen die **einheitliche** Logik in **`club_tenancy`** / **`tenant_context`** (siehe **3.0**).
**Konsequenz:** Die historische „Leak“-Diagnose für **Übungen und Rahmenprogramme** in dieser Form ist **überholt**. Verbleibend: **Konsolidierung auf wenige Hilfsfunktionen** (ACCESS_LAYER Stufe C), **Sparte** als eigene Stufe, ggf. **community**.
### 3.5 Frontend
- `GET /api/profiles/me` liefert u. a. **`clubs[]`**, **`active_club_id`**; Client setzt **`X-Active-Club-Id`**. Geschützte Backend-Routen nutzen **`Depends(get_tenant_context)`** wo im Audit festgehalten.
### 3.6 Membership (kommerziell/limits)
- Mitai-artige Tabellen (`tiers`, `subscriptions`, `tier_limits`, …) sind **nutzerbezogen**, nicht **vereinsbezogen**.
- Kein konzipiertes **`club_subscription` / `club_plan`** im Schema — bewusst nach ACCESS_LAYER-Plan zurückgestellt.
**Letzte Überarbeitung dieses Abschnitts (3.x):** 2026-05-06.
---
## 4. Zielarchitektur
### 4.1 Begriffe
| Begriff | Definition |
|---------|------------|
| **Mandant** | Immer ein **Verein** (`clubs.id`). |
| **Systemadmin** | Global (`profiles.role` oder dediziertes Flag); darf Plattform-weite Objekte und **Vereinslifecycle** (Anlegen, Zuweisen Hauptverwalter). |
| **Vereinskontext** | Pro Session gewählter aktiver Verein (`active_club_id`), wenn der User Mitglied ist. |
| **Vereinsmitgliedschaft** | Zeile in einer Junction: User ↔ Verein ↔ **eine oder mehrere Rollen**. |
| **Effektive Berechtigung** | Funktion aus: globale Rolle, Mitgliedschaft im aktiven Verein, optional Sparte/Gruppe, Sichtbarkeit des Objekts. |
### 4.2 Rollenmodell (Schichten)
**Schicht A – Plattform (global, kleine Menge)**
- `system_admin` / `superadmin` (bestehende Semantik konsolidieren und benennen).
**Schicht B – Verein (pro Mitgliedschaft, mehrere Rollen möglich)**
- `club_admin` – Hauptverwalter:in (ein Verein **genau eine** „primäre“ Admin-Zuweisung empfohlen, siehe 4.4).
- `division_lead` – Spartenverantwortliche:r (Scope: `division_id` optional an Mitgliedschaft gebunden).
- `trainer` – Trainer/Übungsleitung (Abgrenzung zu Co-Trainer siehe Gruppe).
- `content_editor` – Redakteur:in / Inhaltsverantwortliche:r (fachlich wie Anforderungsdoc).
**Schicht C – Abgeleitet aus Trainingsgruppe (bereits teilweise vorhanden)**
- Haupttrainer / Co-Trainer über `training_groups.trainer_id` und `co_trainer_ids` (und ggf. `lead_trainer_profile_id` auf Einheit).
**Mapping Alt → Neu:** Bestehendes `profiles.role` kann Übergangsweise als „Default-Rolle für Pilotverein“ dienen, soll aber mittelfristig **nicht** die einzige Quelle für Vereinsrechte sein.
### 4.3 Mitgliedschaft und aktiver Verein
- Neue Kernstruktur (konzeptionell):
**`club_members`** (`profile_id`, `club_id`, `status`, `created_at`, …)
**`club_member_roles`** (`club_member_id`, `role_code`, optional `division_id` für spartenbezogene Rollen).
- **Aktiver Verein:**
- Persistenz: Nutzereinstellung (`profiles.default_club_id` oder eigene Tabelle `profile_preferences`).
- Pro Request: Header **`X-Active-Club-Id`** oder Query (einheitlich dokumentieren); Server validiert Mitgliedschaft.
- **Tenant-Switch UI:** Bei Mitgliedschaft in >1 Verein Auswahl im Frontend; alle Listen/Aktionen verwenden aktiven Kontext.
### 4.4 Vereins-Lebenszyklus
- Neuer Verein: **nur Systemadmin**; Pflichtfelder: Name, initialer `club_admin` (bestehendes Profil zuweisen oder Einladungsflow später).
- Vereinsadmin verwaltet in „Mein Verein“: Sparten, Gruppen, Trainerzuordnungen, Einladungen (später), interne Sichtbarkeit – **ohne** andere Vereine zu sehen.
### 4.5 Daten- und Funktionssicht
| Datenklasse | Leseregel (Ziel) |
|-------------|------------------|
| Global offiziell | Alle authentifizierten (ggf. später thematisch eingeschränkt). |
| Verein (`visibility=club`, `club_id` gesetzt) | Nur Profile mit Mitgliedschaft in **diesem** `club_id`; optional zusätzlich Sparte, wenn `division_id` am Objekt gepflegt wird. |
| Privat | Nur `created_by` (und explizite Shares später). |
| Geplante Einheiten | Wie heute über Gruppe + Trainer/Co; zusätzlich Vereinskontext zur Navigation/Audit. |
**Einheitlicher Governance-Kern** bleibt wie in CURR-005; Ergänzung: **`division_id`** auf Bibliotheksobjekten, wenn „Sparte“ technisch durchgesetzt werden soll (DOMAIN_MODEL / §17).
### 4.6 Membership-System (Vereinsabo / Limits) – Konzept
Ziel: **vereinszentrierte** Vertrags- und Limitlogik, analog zur bestehenden Tier-Infrastuktur, aber an **`club_id`** gebunden.
**Empfohlene Bausteine:**
1. **`club_plans`** – Produktdefinition (Name, Features, implizite Limits).
2. **`club_subscriptions`** – (`club_id`, `plan_id`, Status, Laufzeit).
3. **`club_usage_counters`** oder Ableitung aus DB – z. B. aktive Nutzer, aktive Trainingsgruppen (periodisch oder on-write).
4. **Enforcement-Schicht** – zentrale Funktion `assert_club_limit(club_id, metric)` vor `/groups`-POST, Einladungen, etc.
**Offene Produktentscheidungen** (vor Implementierung festlegen):
- Zählen „Nutzer“ alle Mitglieder oder nur aktive Trainer?
- Soft-Limits vs. Hard-Stops; Übergang für Pilotverein.
---
## 5. Umsetzungsplan (Phasen)
### Phase 0 – Foundations (kurz, risikoarm)
- Begriffe und Enums in einem Ort dokumentieren (dieses Dokument + Eintrag in `DATABASE_SCHEMA.md` nach Migration).
- Audit-Liste aller Router mit `club_id` / `visibility` / Listen-Endpunkten.
### Phase 1 – Datenmodell Mitgliedschaft & Hauptverwalter
- Migration: `club_members`, `club_member_roles`; optional `clubs.primary_admin_profile_id` (oder Primär-Flag auf Mitgliedschaft).
- Backfill: bestehende Trainer aus `training_groups` → minimale Mitgliedschaft `trainer` im jeweiligen Verein (Skript/Migration mit dokumentierter Annahme CURR-008).
- **Breaking/API:** keine – nur erweiterte Datenbasis.
### Phase 2 – Aktiver Vereinskontext & API-Kontrakte
- Backend: Validierung `X-Active-Club-Id` gegen Mitgliedschaft; Hilfsfunktion `get_effective_club_context(session, header)`.
- `GET /api/clubs` für Nicht-Systemadmins: **nur Vereine mit Mitgliedschaft**.
- `POST /api/clubs`: nur Systemadmin; Vergabe `club_admin`-Mitgliedschaft.
- Frontend: Club-Switcher + Persistenz.
### Phase 3 – Effektive Berechtigungen (RBAC)
- **Mitgliederverwaltung per API (ohne UI):** `GET/POST /api/clubs/{club_id}/members`, `GET/PUT/DELETE /api/clubs/{club_id}/members/{profile_id}` — nur Plattform-Admin oder `club_admin` im Zielverein (Stand Code **0.8.16**).
- Zentrale Modulfunktion z. B. `authorization/club_permissions.py`:
`can(club_id, profile_id, permission, division_id=None)` — optional später; aktuell `club_tenancy.can_manage_club_org` / `has_club_role`.
- Router schrittweise umbinden: Sparten/Gruppen CRUD nach Rolle `club_admin` im Kontext; Systemadmin unverändert Vollzugriff.
### Phase 4 – Sichtbarkeit & Leaks schließen
- **Übungen:** `club`-Sichtbarkeit nur bei Übereinstimmung `exercise.club_id` mit Mitgliedschaft (und später `division`).
- **Trainingsplan-Vorlagen** (`training_plan_templates`) und **Rahmenprogramme** (`training_framework_programs`): gleiches Muster für Listen/GET (Stand **0.8.17**); Schreiben weiterhin nur Ersteller oder Plattform-Admin.
- Gleiches Muster für Progressionsgraphen, ggf. Medien (offen).
- Tests: zwei Vereine, zwei Nutzer, keine Kreuzzugriffe.
### Phase 5 – Mitgliedschaft / Limits
- Tabellen `club_plans`, `club_subscriptions`; Integration mit Enforcement vor relevanten Writes.
- UI „Mein Verein“: Kennzahlenteaser oder Hinweise bei Limit (minimal).
### Phase 6 – Verfeinerung
- Einladungsflow (E-Mail), Mehrfachrollen-UI, Audit-Log für Admin-Aktionen.
- Optionale thematische Sperren (Karate vs. Gewaltschutz) als eigene Policy-Schicht.
---
## 6. Abhängigkeiten und Risiken
- **Übergang:** Pilot mit einem Verein nutzt weiterhin einfache Defaults; Multi-Verein erfordert Pflicht **aktiver Kontext**.
- **Performance:** Mitgliedschaft und Rolle sollten **einmal pro Request** geladen und gecacht werden (Request-Scope).
- **Konsistenz mit Mitai:** Nutzer-Tiers können parallel bleiben; **vereinsbezogene** Limits sind die neue Quelle für Shinkan-spezifische Kaufmotive.
---
## 7. Nächste konkrete Artefakte
1. TenantContext-Spezifikation & Endpoint-Audit (siehe `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` §6).
2. Aktualisierung `DATABASE_SCHEMA.md` bei neuen Governance-/Scope-Feldern.
3. Sicherheits-Review der `list_*`-Endpunkte mit `club`-Visibility (fortlaufend bis Governance vereinheitlicht).
---
## 8. Verwandtes Dokument
- **`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`** – verbindliche Umsetzungsstufen A–F, einheitliche Zugriffsschicht, Scope-Erweiterung (`division`, später Community), Capability-Vorbereitung ohne Custom-Rollen-UI; Vereinsabo explizit zurückgestellt.
---
**Letzte Aktualisierung:** 2026-05-05
@@ -0,0 +1,771 @@
# Search & Filter Specification
**Version:** 1.1
**Datum:** 2026-04-27
**Status:** DRAFT - Awaiting Review
**Autor:** Claude Code
**Änderungen v1.1:** Abschnitt 1.2 – implementiertes Verhalten Übungsliste (Fokus, listFetching, Chips, datalist)
---
## 1. Suchstrategie
### 1.1 Multi-Layer Search
**Drei Suchebenen:**
1. **Keyword-Search:** Titel, Summary, Execution (PostgreSQL tsvector)
2. **Katalog-Filter:** Focus Area, Style, Target Group, Age Group, Skill
3. **Meta-Filter:** Visibility, Status, Creator, Club
**Kombination:** Alle Filter UND Keyword-Search kombinierbar
### 1.2 Übungsliste (Frontend, implementiert)
Auf **`ExercisesListPage`** gilt:
- Filter und Suche kombinieren sich; **Server-Request** bei geänderter Query (Debouncing möglich).
- **Kein Ersetzen der gesamten Seite** durch einen Ladezustand bei List-Refetch — nur die Liste zeigt einen **„Aktualisiere Treffer…“**-Zustand; Suchfelder bleiben montiert (**Fokus erhalten**).
- Erste Ladephase ohne Treffer: kompakter Spinner **unter** der Suchleiste.
- **`<datalist>`** (`list=` an Suchfeldern) mit Distinct-Titeln aus den aktuellen Treffern zur Auswahl.
- Zusätzliche Filter erscheinen als **Chips**; Zähler am Filter-Button = Anzahl aktiver Filter.
---
## 2. Volltext-Suche (PostgreSQL)
### 2.1 tsvector Implementation
**Migration:** Erweitert `exercises` Tabelle
```sql
-- Migration 014 (Teil)
ALTER TABLE exercises ADD COLUMN search_vector tsvector;
-- Index für Volltext-Suche
CREATE INDEX idx_exercises_search ON exercises USING gin(search_vector);
-- Trigger für automatische Updates
CREATE OR REPLACE FUNCTION update_exercises_search_vector()
RETURNS trigger AS $$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('german', COALESCE(NEW.title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(NEW.summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(NEW.trainer_notes, '')), 'D');
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER exercises_search_update
BEFORE INSERT OR UPDATE ON exercises
FOR EACH ROW EXECUTE FUNCTION update_exercises_search_vector();
```
**Gewichtung:**
- A (höchste): Titel
- B: Summary
- C: Execution
- D (niedrigste): Trainer Notes
### 2.2 Backend-Query
**Endpoint:** `GET /api/exercises?search=<keyword>`
```python
@router.get("/exercises")
def list_exercises(
search: str = None,
focus_area: int = None,
visibility: str = None,
status: str = None,
skill_id: int = None,
limit: int = 50,
offset: int = 0,
session: dict = Depends(require_auth)
):
profile_id = session['profile_id']
conditions = []
params = []
# Volltext-Suche
if search:
conditions.append("""
search_vector @@ plainto_tsquery('german', %s)
""")
params.append(search)
# Katalog-Filter
if focus_area:
conditions.append("""
EXISTS (
SELECT 1 FROM exercise_focus_areas
WHERE exercise_id = exercises.id AND focus_area_id = %s
)
""")
params.append(focus_area)
# Meta-Filter
if visibility:
conditions.append("visibility = %s")
params.append(visibility)
if status:
conditions.append("status = %s")
params.append(status)
# Skill-Filter
if skill_id:
conditions.append("""
EXISTS (
SELECT 1 FROM exercise_skills
WHERE exercise_id = exercises.id AND skill_id = %s
)
""")
params.append(skill_id)
# WHERE-Clause zusammenbauen
where_clause = " AND ".join(conditions) if conditions else "1=1"
# Query mit Ranking (bei Volltext-Suche)
if search:
query = f"""
SELECT exercises.*,
ts_rank(search_vector, plainto_tsquery('german', %s)) AS rank
FROM exercises
WHERE {where_clause}
ORDER BY rank DESC, created_at DESC
LIMIT %s OFFSET %s
"""
params = [search] + params + [limit, offset]
else:
query = f"""
SELECT exercises.* FROM exercises
WHERE {where_clause}
ORDER BY created_at DESC
LIMIT %s OFFSET %s
"""
params = params + [limit, offset]
cur = get_db_cursor()
cur.execute(query, params)
return [r2d(row) for row in cur.fetchall()]
```
### 2.3 Highlighting (Optional)
**Snippet mit Treffer-Markierung:**
```python
def get_search_snippet(exercise, search_term):
"""Generiert Snippet mit <mark>-Tags um Treffer"""
cur = get_db_cursor()
cur.execute("""
SELECT ts_headline('german', execution,
plainto_tsquery('german', %s),
'StartSel=<mark>, StopSel=</mark>, MaxWords=50, MinWords=30'
) AS snippet
FROM exercises WHERE id = %s
""", (search_term, exercise['id']))
result = cur.fetchone()
return result['snippet'] if result else exercise['summary']
```
**Response mit Snippet:**
```json
{
"id": 1,
"title": "Maai - Distanzübung",
"summary": "...",
"snippet": "...Partner hält <mark>Pratzen</mark>, Ausführung wie Haupt..."
}
```
---
## 3. Frontend-Filter-UI
### 3.1 Komponente: SearchFilterBar
**Layout:**
```
┌────────────────────────────────────────────────────────┐
│ 🔍 [Suche...] [Filter ▼] [×] │
├────────────────────────────────────────────────────────┤
│ Aktive Filter: │
│ [Karate ×] [Breitensport ×] [Freigegeben ×] │
└────────────────────────────────────────────────────────┘
```
**Code:**
```jsx
function SearchFilterBar({ onFiltersChange, initialFilters = {} }) {
const [search, setSearch] = useState(initialFilters.search || '')
const [showFilterPanel, setShowFilterPanel] = useState(false)
const [filters, setFilters] = useState(initialFilters)
const { focusAreas, trainingStyles, targetGroups } = useCatalog()
const handleSearchChange = debounce((value) => {
const newFilters = { ...filters, search: value }
setFilters(newFilters)
onFiltersChange(newFilters)
}, 300)
const handleFilterChange = (key, value) => {
const newFilters = { ...filters, [key]: value }
setFilters(newFilters)
onFiltersChange(newFilters)
}
const clearFilter = (key) => {
const newFilters = { ...filters }
delete newFilters[key]
setFilters(newFilters)
onFiltersChange(newFilters)
}
const clearAllFilters = () => {
setFilters({})
setSearch('')
onFiltersChange({})
}
return (
<div className="search-filter-bar">
{/* Suchfeld */}
<div className="search-input">
<SearchIcon />
<input
type="search"
placeholder="Übungen durchsuchen..."
value={search}
onChange={(e) => {
setSearch(e.target.value)
handleSearchChange(e.target.value)
}}
/>
</div>
{/* Filter-Toggle */}
<button
className="btn-filter"
onClick={() => setShowFilterPanel(!showFilterPanel)}
>
Filter {Object.keys(filters).length > 0 && `(${Object.keys(filters).length})`}
<ChevronIcon direction={showFilterPanel ? 'up' : 'down'} />
</button>
{/* Clear-Button */}
{Object.keys(filters).length > 0 && (
<button className="btn-clear" onClick={clearAllFilters}>
×
</button>
)}
{/* Aktive Filter (Chips) */}
{Object.keys(filters).length > 0 && (
<div className="active-filters">
<span>Aktive Filter:</span>
{filters.focus_area && (
<Chip
label={focusAreas.find(f => f.id === filters.focus_area)?.name}
onRemove={() => clearFilter('focus_area')}
/>
)}
{filters.visibility && (
<Chip
label={filters.visibility}
onRemove={() => clearFilter('visibility')}
/>
)}
{filters.status && (
<Chip
label={filters.status}
onRemove={() => clearFilter('status')}
/>
)}
</div>
)}
{/* Filter-Panel (aufklappbar) */}
{showFilterPanel && (
<div className="filter-panel">
<div className="filter-section">
<label>Fokusbereich</label>
<select
value={filters.focus_area || ''}
onChange={(e) => handleFilterChange('focus_area', parseInt(e.target.value) || null)}
>
<option value="">Alle</option>
{focusAreas.map(fa => (
<option key={fa.id} value={fa.id}>{fa.name}</option>
))}
</select>
</div>
<div className="filter-section">
<label>Stil</label>
<select
value={filters.training_style || ''}
onChange={(e) => handleFilterChange('training_style', parseInt(e.target.value) || null)}
>
<option value="">Alle</option>
{trainingStyles.map(ts => (
<option key={ts.id} value={ts.id}>{ts.name}</option>
))}
</select>
</div>
<div className="filter-section">
<label>Sichtbarkeit</label>
<select
value={filters.visibility || ''}
onChange={(e) => handleFilterChange('visibility', e.target.value || null)}
>
<option value="">Alle</option>
<option value="private">Privat</option>
<option value="club">Verein</option>
<option value="official">Offiziell</option>
</select>
</div>
<div className="filter-section">
<label>Status</label>
<select
value={filters.status || ''}
onChange={(e) => handleFilterChange('status', e.target.value || null)}
>
<option value="">Alle</option>
<option value="draft">Entwurf</option>
<option value="in_review">In Prüfung</option>
<option value="approved">Freigegeben</option>
<option value="archived">Archiviert</option>
</select>
</div>
</div>
)}
</div>
)
}
```
### 3.2 Debouncing (Performance)
**Verhindert API-Call bei jedem Tastendruck:**
```javascript
function debounce(func, wait) {
let timeout
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout)
func(...args)
}
clearTimeout(timeout)
timeout = setTimeout(later, wait)
}
}
```
**Nur nach 300ms Pause wird gesucht → weniger Server-Last**
---
## 4. Erweiterte Filter
### 4.1 Multi-Select-Filter
**Beispiel: Mehrere Zielgruppen gleichzeitig:**
```jsx
<MultiSelect
options={targetGroups}
selected={filters.target_groups || []}
onChange={(selected) => handleFilterChange('target_groups', selected)}
label="Zielgruppen"
placeholder="Wähle eine oder mehrere..."
/>
```
**Backend-Query:**
```python
if target_groups: # List von IDs
conditions.append("""
EXISTS (
SELECT 1 FROM exercise_target_groups
WHERE exercise_id = exercises.id
AND target_group_id = ANY(%s)
)
""")
params.append(target_groups)
```
### 4.2 Range-Filter (Dauer, Gruppengröße)
**UI:**
```jsx
<div className="filter-range">
<label>Dauer (Minuten)</label>
<input
type="number"
placeholder="Min"
value={filters.duration_min || ''}
onChange={(e) => handleFilterChange('duration_min', parseInt(e.target.value) || null)}
/>
<span>bis</span>
<input
type="number"
placeholder="Max"
value={filters.duration_max || ''}
onChange={(e) => handleFilterChange('duration_max', parseInt(e.target.value) || null)}
/>
</div>
```
**Backend-Query:**
```python
if duration_min:
conditions.append("duration_max >= %s")
params.append(duration_min)
if duration_max:
conditions.append("duration_min <= %s")
params.append(duration_max)
```
### 4.3 Equipment-Filter (JSONB)
**UI:**
```jsx
<div className="filter-equipment">
<label>
<input
type="checkbox"
checked={filters.no_equipment || false}
onChange={(e) => handleFilterChange('no_equipment', e.target.checked)}
/>
Ohne Hilfsmittel
</label>
</div>
```
**Backend-Query:**
```python
if no_equipment:
conditions.append("""
(equipment IS NULL OR equipment = '[]'::jsonb)
""")
```
---
## 5. Faceted Search (Treffer-Zählung pro Filter)
### 5.1 Backend-Aggregation
**Zeigt Anzahl Treffer pro Filter-Option:**
```python
@router.get("/exercises/facets")
def get_facets(search: str = None, session: dict = Depends(require_auth)):
base_condition = "1=1"
params = []
if search:
base_condition = "search_vector @@ plainto_tsquery('german', %s)"
params = [search]
cur = get_db_cursor()
# Focus Area Facets
cur.execute(f"""
SELECT fa.id, fa.name, COUNT(DISTINCT e.id) as count
FROM focus_areas fa
LEFT JOIN exercise_focus_areas efa ON fa.id = efa.focus_area_id
LEFT JOIN exercises e ON efa.exercise_id = e.id
WHERE {base_condition}
GROUP BY fa.id, fa.name
ORDER BY count DESC
""", params)
focus_areas = [r2d(r) for r in cur.fetchall()]
# Visibility Facets
cur.execute(f"""
SELECT visibility, COUNT(*) as count
FROM exercises
WHERE {base_condition}
GROUP BY visibility
""", params)
visibility = [r2d(r) for r in cur.fetchall()]
return {
"focus_areas": focus_areas,
"visibility": visibility,
# ... weitere Facets
}
```
### 5.2 Frontend-Anzeige
**Zeigt Treffer-Anzahl neben Filter:**
```jsx
<select>
<option value="">Alle</option>
{facets.focus_areas.map(fa => (
<option key={fa.id} value={fa.id}>
{fa.name} ({fa.count})
</option>
))}
</select>
```
---
## 6. Saved Searches / Presets
### 6.1 Favoriten-Filter speichern
**UI:**
```jsx
<button onClick={handleSaveFilter}>
⭐ Filter speichern
</button>
{savedFilters.map(sf => (
<button
key={sf.id}
onClick={() => loadFilter(sf)}
className="saved-filter"
>
{sf.name}
</button>
))}
```
**Backend-Tabelle:**
```sql
CREATE TABLE saved_exercise_searches (
id SERIAL PRIMARY KEY,
profile_id INT REFERENCES profiles(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
filters JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
```
**API:**
```python
@router.post("/exercises/saved-searches")
def save_search(
name: str,
filters: dict,
session: dict = Depends(require_auth)
):
profile_id = session['profile_id']
cur = get_db_cursor()
cur.execute("""
INSERT INTO saved_exercise_searches (profile_id, name, filters)
VALUES (%s, %s, %s)
RETURNING id, created_at
""", (profile_id, name, json.dumps(filters)))
result = cur.fetchone()
return {
"id": result['id'],
"name": name,
"filters": filters,
"created_at": result['created_at'].isoformat(),
}
```
---
## 7. Sortierung
### 7.1 Sortier-Optionen
**UI:**
```jsx
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
>
<option value="relevance">Relevanz</option>
<option value="newest">Neueste zuerst</option>
<option value="oldest">Älteste zuerst</option>
<option value="title_asc">Titel A-Z</option>
<option value="title_desc">Titel Z-A</option>
<option value="duration">Dauer (kurz → lang)</option>
</select>
```
### 7.2 Backend-Sortierung
**Query-Parameter:** `?sort=newest`
```python
SORT_OPTIONS = {
'relevance': 'rank DESC', # nur bei Volltext-Suche
'newest': 'created_at DESC',
'oldest': 'created_at ASC',
'title_asc': 'title ASC',
'title_desc': 'title DESC',
'duration': 'duration_min ASC',
}
@router.get("/exercises")
def list_exercises(sort: str = 'newest', ...):
order_by = SORT_OPTIONS.get(sort, 'created_at DESC')
# Bei Volltext-Suche IMMER nach Relevanz sortieren
if search and sort != 'relevance':
order_by = f"rank DESC, {order_by}"
query = f"""
SELECT ... FROM exercises
WHERE {where_clause}
ORDER BY {order_by}
LIMIT %s OFFSET %s
"""
```
---
## 8. Performance-Optimierung
### 8.1 Indizes
**Wichtige Indizes:**
```sql
-- Volltext-Suche
CREATE INDEX idx_exercises_search ON exercises USING gin(search_vector);
-- Häufige Filter
CREATE INDEX idx_exercises_visibility ON exercises(visibility);
CREATE INDEX idx_exercises_status ON exercises(status);
CREATE INDEX idx_exercises_created_at ON exercises(created_at DESC);
-- M:N Relations
CREATE INDEX idx_exercise_focus_areas_focus ON exercise_focus_areas(focus_area_id);
CREATE INDEX idx_exercise_skills_skill ON exercise_skills(skill_id);
```
### 8.2 Query-Caching (Backend)
**Cachen häufiger Abfragen:**
```python
from functools import lru_cache
import hashlib
@lru_cache(maxsize=100)
def get_exercises_cached(filters_hash: str):
# filters_hash = SHA256 von JSON(filters)
# Cached für 60 Sekunden
pass
def list_exercises(filters: dict):
filters_hash = hashlib.sha256(
json.dumps(filters, sort_keys=True).encode()
).hexdigest()
return get_exercises_cached(filters_hash)
```
### 8.3 Client-Side Caching (React Query)
**Nutzt React Query für intelligentes Caching:**
```jsx
const { data: exercises, isLoading } = useQuery(
['exercises', filters],
() => api.listExercises(filters),
{
staleTime: 5 * 60 * 1000, // 5 Minuten fresh
cacheTime: 10 * 60 * 1000, // 10 Minuten im Cache
}
)
```
---
## 9. Mobile-Optimierung
### 9.1 Filter-Drawer (Mobile)
**Statt Dropdown → Fullscreen-Drawer:**
```jsx
{/* Desktop: Inline-Panel */}
<div className="filter-panel desktop-only">
{/* Filter-Felder */}
</div>
{/* Mobile: Drawer */}
<Drawer
isOpen={showFilterDrawer}
onClose={() => setShowFilterDrawer(false)}
position="bottom"
>
<div className="filter-drawer">
<h3>Filter</h3>
{/* Filter-Felder */}
<button onClick={applyFilters}>
{resultsCount} Ergebnisse anzeigen
</button>
</div>
</Drawer>
```
### 9.2 Sticky Search-Bar
**Bleibt beim Scrollen oben:**
```css
.search-filter-bar {
position: sticky;
top: 0;
z-index: 10;
background: var(--bg);
border-bottom: 1px solid var(--border);
padding: 12px;
}
```
---
## 10. Testing
### 10.1 Volltext-Suche-Tests
```javascript
test('Volltext-Suche findet Übung im Titel', async ({ page }) => {
await page.goto('/exercises')
await page.fill('input[type="search"]', 'Maai')
await expect(page.locator('.exercise-card:has-text("Maai")')).toBeVisible()
})
test('Volltext-Suche findet Übung in Execution', async ({ page }) => {
await page.goto('/exercises')
await page.fill('input[type="search"]', 'Pratzen')
await expect(page.locator('.exercise-card')).toHaveCount(1)
})
```
### 10.2 Filter-Kombination-Tests
```javascript
test('Filter kombinierbar: Focus Area + Visibility', async ({ page }) => {
await page.goto('/exercises')
await page.selectOption('select[name="focus_area"]', '1') // Karate
await page.selectOption('select[name="visibility"]', 'club')
const cards = page.locator('.exercise-card')
await expect(cards).toHaveCount(3)
})
```
---
**Version:** 1.0
**Letzte Änderung:** 2026-04-24
**Status:** DRAFT - Awaiting Review
@@ -0,0 +1,454 @@
# Fähigkeitsmatrix / Reifegradmodell – Specification
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT
**Autor:** Claude Code
**Basis:** shinkan_anforderungsdokument_entwurf.md §8 + DOMAIN_MODEL.md
---
## 1. Konzept
### 1.1 Was ist die Fähigkeitsmatrix?
Die Fähigkeitsmatrix verbindet **globale Fähigkeiten** (Skills) mit **kontextspezifischen
Reifegradmodellen**. Sie beantwortet pro Kontext die Frage:
> „Was muss ein Schüler auf Stufe X dieser Fähigkeit können, und welche Übungen trainieren ihn von Stufe A auf Stufe B?"
**Drei Ebenen:**
```
1. Globale Fähigkeit (skill)
"Distanzgefühl" – gilt überall, für alle Stile und Zielgruppen
2. Reifegradmodell (maturity_model)
"Karate / Shotokan / Breitensport" – definiert WIE VIELE Stufen es gibt
und wie die Stufen heißen
3. Modell-Fähigkeitsstufe (model_skill_level)
"Stufe 3 von Distanzgefühl im Shotokan-Breitensport-Modell" –
beschreibt KONKRET was auf Stufe 3 erwartet wird
```
### 1.2 Warum kontextabhängig?
Dieselbe Fähigkeit (z.B. „Distanzgefühl") hat in verschiedenen Kontexten
unterschiedliche Bedeutungen:
| Kontext | Stufe 3 Bedeutung |
|---------|-------------------|
| Karate / Shotokan / Breitensport | Distanzkontrolle in einfachen Partnerübungen |
| Karate / Shotokan / Leistungssport | Stabile Distanz im freien Kumite |
| Selbstverteidigung / Erwachsene | Sicherheitsabstand in Alltagssituationen einschätzen |
Ein Modell hat **variable Stufenanzahl** (3-7, nicht fest 5):
```
Shotokan Breitensport → 5 Stufen (Einsteiger bis Experte)
Kinder-Karate → 4 Stufen (Kinder-gerecht vereinfacht)
Leistungssport → 7 Stufen (feiner granuliert)
```
### 1.3 Abgrenzung zu exercise_skills
```
exercise_skills: Übung trainiert Fähigkeit mit Intensität und
suggested required/target Stufe
→ kontextunabhängig (gilt für alle Modelle)
model_skill_levels: Für dieses Modell bedeutet "Stufe 3" von Fähigkeit X:
"[konkrete Beschreibung]"
→ kontextspezifisch
```
---
## 2. Datenmodell
### 2.1 Entity-Übersicht
```
focus_areas (global, existiert)
└─ style_directions (existiert, früher training_styles)
└─ target_groups (M:N, existiert)
maturity_models (NEU)
├─ focus_area_id FK (optional, NULL = gilt für alle Fokusbereiche)
├─ style_direction_id FK (optional)
├─ target_group_id FK (optional)
└─ level_count (INT) – wie viele Stufen hat das Modell?
model_levels (NEU) – Stufen-Definitionen
├─ maturity_model_id FK
├─ level_number (1 bis level_count)
├─ name (z.B. "Einsteiger", "Grundlagen", ...)
└─ description
model_skill_levels (NEU) – Was bedeutet Stufe X für Fähigkeit Y im Modell Z?
├─ maturity_model_id FK
├─ skill_id FK
├─ level_number (muss in maturity_model.level_count liegen)
├─ description (Pflicht-Text: was soll der Lernende können?)
├─ observable_criteria (Beobachtungskriterien für Trainer)
└─ example_exercises JSONB (Empfohlene Übungs-Typen, keine FK)
```
### 2.2 Vollständige Migration (019_maturity_models.sql)
```sql
-- Migration 019: Fähigkeitsmatrix / Reifegradmodelle
-- Autor: Claude Code
-- Datum: 2026-04-24
DO $$
BEGIN
-- ============================================================================
-- MATURITY MODELS (Reifegradmodelle)
-- ============================================================================
CREATE TABLE IF NOT EXISTS maturity_models (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
-- Kontext-Bindung (alle optional – NULL bedeutet "gilt allgemein")
-- Je mehr gesetzt, desto spezifischer das Modell
focus_area_id INT REFERENCES focus_areas(id) ON DELETE RESTRICT,
style_direction_id INT REFERENCES style_directions(id) ON DELETE RESTRICT,
target_group_id INT REFERENCES target_groups(id) ON DELETE RESTRICT,
-- Stufenanzahl (flexibel, nicht fest auf 5)
level_count INT NOT NULL DEFAULT 5 CHECK (level_count BETWEEN 3 AND 10),
-- Sichtbarkeit & Freigabe
-- 'draft': in Bearbeitung | 'active': in Nutzung | 'archived': nicht mehr aktiv
status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'active', 'archived')),
-- Versionierung
version VARCHAR(20) DEFAULT '1.0',
-- Ownership
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
-- Import-Tracking (für Semantic MediaWiki Import)
import_source VARCHAR(50),
import_id VARCHAR(200),
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Constraint: Name + Kontext eindeutig
UNIQUE(name, focus_area_id, style_direction_id, target_group_id)
);
-- ============================================================================
-- MODEL LEVELS (Stufendefinitionen pro Modell)
-- ============================================================================
CREATE TABLE IF NOT EXISTS model_levels (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
level_number INT NOT NULL CHECK (level_number >= 1),
name VARCHAR(100) NOT NULL, -- z.B. "Einsteiger", "Grundlagen", "Aufbau"
description TEXT, -- Was zeichnet diese Stufe generell aus?
sort_order INT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(maturity_model_id, level_number)
);
-- ============================================================================
-- MODEL SKILL LEVELS
-- Was bedeutet "Stufe X der Fähigkeit Y im Modell Z"?
-- ============================================================================
CREATE TABLE IF NOT EXISTS model_skill_levels (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE RESTRICT,
level_number INT NOT NULL CHECK (level_number >= 1),
-- Was wird auf dieser Stufe erwartet? (Pflichtfeld)
description TEXT NOT NULL,
-- Konkrete Beobachtungskriterien für Trainer
-- z.B. "Kann Distanz in ruhigen Partnerübungen halten (3/3 Versuchen)"
observable_criteria TEXT,
-- Empfohlene Übungs-Typen (keine FK, nur Hinweise)
-- z.B. {"types": ["Grundübung", "Partnerübung"], "max_duration_min": 15}
example_exercise_hints JSONB,
-- KI-generiert?
ai_generated BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE(maturity_model_id, skill_id, level_number),
-- level_number muss im Bereich des Modells liegen
-- (wird per Trigger oder Backend-Validierung geprüft)
CONSTRAINT ck_level_positive CHECK (level_number > 0)
);
-- ============================================================================
-- SKILL CATALOG: Felder für Matrix-Nutzung (falls noch nicht vorhanden)
-- ============================================================================
-- Fähigkeiten können einem bestimmten Fokusbereich "zugehören" (primär)
-- bleiben aber global nutzbar (secondary assignments über M:N)
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS primary_focus_area_id INT REFERENCES focus_areas(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS is_cross_domain BOOLEAN DEFAULT false; -- gilt für alle Fokusbereiche
-- ============================================================================
-- INDEXES
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_maturity_models_focus ON maturity_models(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_style ON maturity_models(style_direction_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_target ON maturity_models(target_group_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_status ON maturity_models(status);
CREATE INDEX IF NOT EXISTS idx_model_levels_model ON model_levels(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_model_skill_levels_model ON model_skill_levels(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_model_skill_levels_skill ON model_skill_levels(skill_id);
CREATE INDEX IF NOT EXISTS idx_model_skill_levels_combo ON model_skill_levels(maturity_model_id, skill_id);
-- ============================================================================
-- TRIGGERS
-- ============================================================================
DROP TRIGGER IF EXISTS maturity_models_update ON maturity_models;
CREATE TRIGGER maturity_models_update
BEFORE UPDATE ON maturity_models
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
DROP TRIGGER IF EXISTS model_skill_levels_update ON model_skill_levels;
CREATE TRIGGER model_skill_levels_update
BEFORE UPDATE ON model_skill_levels
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
RAISE NOTICE 'Migration 019 completed successfully (Maturity Models / Fähigkeitsmatrix)';
END $$;
```
---
## 3. Beispiel-Daten
### 3.1 Beispiel-Modell: Karate Shotokan Breitensport (5 Stufen)
```sql
INSERT INTO maturity_models (name, focus_area_id, style_direction_id, target_group_id, level_count, status)
VALUES ('Karate Shotokan Breitensport', 1, 1, 1, 5, 'active');
-- Stufennamen
INSERT INTO model_levels (maturity_model_id, level_number, name, description, sort_order) VALUES
(1, 1, 'Einsteiger', 'Erste Begegnung – keine Vorkenntnisse erforderlich', 1),
(1, 2, 'Grundlagen', 'Grundprinzipien bekannt, in ruhigen Situationen anwendbar', 2),
(1, 3, 'Aufbau', 'Semi-intuitiver Einsatz, mit gelegentlicher Korrektur', 3),
(1, 4, 'Fortgeschritten', 'Intuitiver Einsatz auch unter Druck', 4),
(1, 5, 'Experte', 'Vollständig automatisiert, stabile Leistung auf Spitzenniveau', 5);
-- Fähigkeitsstufen: Distanzgefühl im Shotokan-Breitensport-Modell
INSERT INTO model_skill_levels (maturity_model_id, skill_id, level_number, description, observable_criteria)
VALUES
(1, 10, 1, 'Versteht das Konzept "Distanz" und kann erklären warum es wichtig ist.',
'Kann auf Frage benennen, was Maai bedeutet.'),
(1, 10, 2, 'Hält in langsamen, geführten Partnerübungen die Angriffsdistanz.',
'In 3 von 3 langsamen Wiederholungen korrekte Distanz eingenommen.'),
(1, 10, 3, 'Kontrolliert Distanz in mittlerer Geschwindigkeit bei Standardtechniken.',
'Trainer bewertet Distanzkontrolle mit "gut" in Kihon-Ippon-Kumite.'),
(1, 10, 4, 'Stabiler Einsatz im Jiyu-Ippon-Kumite, selten vom Partner überrascht.',
'In freiem Jiyu-Kumite hält Schüler Linie in >70% der Aktionen.'),
(1, 10, 5, 'Feingefühl für minimale Distanzveränderungen, taktischer Einsatz im Shiai.',
'Wettkampferfolge durch bewusstes Distanzmanagement nachweisbar.');
```
---
## 4. API-Endpoints
### 4.1 Übersicht
| Method | Endpoint | Beschreibung |
|--------|----------|--------------|
| GET | `/maturity-models` | Liste aller Modelle (mit Filter) |
| GET | `/maturity-models/{id}` | Modell-Detail mit Stufen + Skills |
| POST | `/maturity-models` | Neues Modell erstellen (Admin) |
| PUT | `/maturity-models/{id}` | Modell bearbeiten (Admin) |
| DELETE | `/maturity-models/{id}` | Modell löschen (Admin) |
| GET | `/maturity-models/{id}/skills` | Alle Fähigkeiten + Stufen dieses Modells |
| PUT | `/maturity-models/{id}/skills/{skill_id}/levels` | Stufen-Beschreibungen setzen (Admin) |
| GET | `/maturity-models/resolve` | Bestes Modell für Kontext finden |
### 4.2 `GET /maturity-models/resolve`
Findet das spezifischste Modell für einen gegebenen Kontext.
Wird von der KI und vom Frontend verwendet.
**Query Parameters:**
- `focus_area_id` (int, optional)
- `style_direction_id` (int, optional)
- `target_group_id` (int, optional)
**Response:**
```json
{
"model": {
"id": 1,
"name": "Karate Shotokan Breitensport",
"level_count": 5,
"match_specificity": "full"
},
"fallback_used": false
}
```
**Auflösungslogik (Most Specific First):**
1. Alle drei passen (focus + style + target) → `match_specificity: "full"`
2. focus + style passen → `match_specificity: "style"`
3. Nur focus passt → `match_specificity: "focus"`
4. Allgemeines Modell (alle FK = NULL) → `match_specificity: "generic"`
5. Kein Modell vorhanden → `match_specificity: null`, 404
---
## 5. Verbindung zu Übungen
### 5.1 Wie exercise_skills das Modell referenziert
`exercise_skills` speichert `required_level` und `target_level` als **Stufen-Namen**
(einsteiger/grundlagen/aufbau/fortgeschritten/experte), die modellunabhängig sind.
Das Frontend kann bei Bedarf die konkrete Modell-Beschreibung nachladen:
```
exercise_skills.required_level = "grundlagen"
→ GET /maturity-models/resolve?focus_area_id=1
→ Model: Karate Shotokan Breitensport (level_count=5)
→ model_levels: level_number=2, name="Grundlagen"
→ model_skill_levels für skill_id=10: "Hält in ruhigen Partnerübungen Distanz"
```
### 5.2 Darstellung in der Übungsdetail-Ansicht
```
Fähigkeiten
─────────────────────────────────────────────
★ Distanzgefühl (primär)
Voraussetzung: Grundlagen → Ziel: Aufbau
Intensität: Hoch
────────────────────────────────
Grundlagen: "Hält in ruhigen Partnerübungen
Distanz"
Aufbau: "Kontrolle in mittlerer
Geschwindigkeit"
[Kontext: Shotokan Breitensport ▼]
─────────────────────────────────────────────
◦ Reaktionsschnelligkeit (sekundär)
Voraussetzung: Einsteiger → Ziel: Grundlagen
Intensität: Mittel
```
**Kontext-Dropdown:** Trainer kann Modell wechseln um kontextspezifische Beschreibungen zu sehen.
---
## 6. KI-Unterstützung für Modell-Pflege
Die KI kann `model_skill_levels`-Beschreibungen vorschlagen.
**Prompt-Placeholder:**
- `{{skill_name}}` – Name der Fähigkeit
- `{{model_name}}` – Name des Reifegradmodells
- `{{level_count}}` – Anzahl der Stufen
- `{{level_names}}` – Namen der Stufen (z.B. "Einsteiger, Grundlagen, Aufbau...")
- `{{focus_area}}` – Fokusbereich
- `{{target_group}}` – Zielgruppe
**Endpoint:** `POST /maturity-models/{id}/ai/suggest-skill-levels`
```json
// Request
{
"skill_id": 10,
"regenerate_existing": false
}
// Response
{
"skill": {"id": 10, "name": "Distanzgefühl"},
"suggestions": [
{
"level_number": 1,
"level_name": "Einsteiger",
"description": "...",
"observable_criteria": "...",
"ai_generated": true
},
...
]
}
```
---
## 7. Semantic MediaWiki Import
Die bestehende Fähigkeitsmatrix im SMW enthält bereits Stufen-Beschreibungen.
**Erweiterung der MEDIAWIKI_IMPORT_SPEC.md:**
| Wiki-Feld | Ziel-Tabelle | Transformation |
|-----------|-------------|----------------|
| SMW Property: `Stufe 1 Beschreibung` | `model_skill_levels.description` (level=1) | Direkt |
| SMW Property: `Stufe N Beschreibung` | `model_skill_levels.description` (level=N) | Direkt |
| SMW Property: `Modell` | `maturity_models.name` | Lookup/Create |
| SMW Property: `Fokusbereich` | `maturity_models.focus_area_id` | Name → ID |
**Import-Endpoint:** `POST /import/mediawiki/execute` mit `import_type: "maturity_model"`
---
## 8. Admin-Workflow
### 8.1 Modell anlegen (Admin)
```
1. Admin wählt: Fokusbereich + Stil + Zielgruppe
2. Admin legt Stufenanzahl + Stufennamen fest
3. Admin weist Fähigkeiten dem Modell zu (Pflicht-/Optional-Skills)
4. Für jede Fähigkeit × Stufe: Beschreibung eingeben
→ Optional: KI-Vorschlag generieren
5. Modell auf "active" stellen
```
### 8.2 SMW-Migration-Workflow
```
1. SMW-Import: Bestehende Modelle und Beschreibungen importieren
2. Review: Trainer prüft importierte Beschreibungen
3. KI-Ergänzung: Für fehlende Stufen KI-Vorschläge generieren
4. Freigabe: status → 'active'
```
---
**Version:** 1.0
**Datum:** 2026-04-24
**Status:** DRAFT
**Nächste Schritte:**
- SMW-Struktur analysieren (User legt Daten ins Repo)
- Migration 019 implementieren
- Admin-UI für Modellpflege spezifizieren (UI_COMPONENTS_SPEC.md ergänzen)
@@ -0,0 +1,193 @@
# Trainingsrahmenprogramm — Technische Spezifikation
**Status:** Rahmen‑Bibliothek + Slot‑Blueprint dokumentiert · **Stand:** 2026-05-05 (Migration **036–037**)
**Bindendes Fachkonzept / Entscheide:** `.claude/docs/functional/TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` (CURR‑001 bis CURR‑013)
**Relevant für nächsten Schritt:** CURR‑002 **(2)** Trainingsplanung / Rahmen über mehrere Einheiten — der hier dokumentierte **Progressionsgraph Stufe 1** ist bewusst **unterstützend**, keine Pflicht für Slot-Zuordnungen (**CURR‑013**).
---
## 1. Abgrenzung zu anderen Dokumenten
| Dokument | Rolle · warum **nicht** hier hineinmischen |
|----------|--------------------------------------------|
| `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_API_SPEC.md` | **Übungskatalog** inkl. Varianten-Progression **innerhalb einer Übung** (Migration 014). Kanten **zwischen** Übungen siehe **§3**. |
| `DATABASE_SCHEMA.md` | **Nachgeordnete** Übersicht: Migrationshistorie und Tabellenliste; Detail-DDL primär **hier §2–§3** + SQL unter `backend/migrations/`. |
| `functional/DOMAIN_MODEL.md` | Fachliche Begriffe; Kurzverweis auf Progressionsgraph ergänzt. |
| `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` | **Was** und **warum** (Bibliothek vs. Instanz, Governance, CURR‑Tabelle). |
**Konsequenz:** Diese Datei bleibt der **technische Arbeitspool** für Rahmenprogramm Stufe 1–2. Abschnitt **§4** beschreibt explizit den **aktuellen Produktfreigabe-Umfang** und **bekannte Lücken** (damit Trainingsplanung weiter gebaut werden kann ohne falscher Erwartung an „Alternative‑Pakete“ in der UI).
---
## 2. Rahmenprogramm (CURR‑002 Stufe 2) — Checkliste & technische Ausarbeitung
### 2.0 Technische Entscheidung: nur Bibliothek + Slot‑Blueprint = `training_units`
**Fachlich:** Das Rahmenprogramm ist eine **wiederverwendbare Bibliotheksvorlage** ohne Bindung an eine Trainingsgruppe oder einen Kalendertermin (**Migration 036** entfernte `plan_mode`, `group_id` am Kopf sowie die Nutzung von `training_framework_slots.training_unit_id` für „konkrete“ Kopplung).
**Slot‑Inhalt (Migration 037):** Pro `training_framework_slot` existiert genau eine **Blueprint‑Zeile** in `training_units` mit **`framework_slot_id`** (partieller **UNIQUE**-Index); der Ablauf entspricht **derselben** Struktur wie geplante Einheiten über **`training_unit_sections`** und **`training_unit_section_items`** (Übungen, Notizen, Varianten wie in der Planung). Die frühere Tabelle **`training_framework_slot_exercises`** wird nach Datenübernahme **`DROP`**pt.
**Geplante Einheit aus Rahmen:** **`POST /api/training-units/from-framework-slot`** kopiert diese Blueprint‑Unit (**tiefe Kopie**) mit **`group_id` + `planned_date`**; **`origin_framework_slot_id`** hält die Herkunft (Lineage‑Light). **`GET /api/training-units`** blendet Einheiten mit **`framework_slot_id IS NOT NULL`** aus (Kalender/API‑Liste ohne Rahmen‑Blueprints).
**CHECK‑Constraint auf `training_units`:** Zeile ist entweder **Blueprint** (`framework_slot_id` gesetzt, `group_id`/`planned_date` NULL, kein `origin_framework_slot_id`) oder **Kalender‑Einheit** (`framework_slot_id` NULL, `group_id` und `planned_date` gesetzt; `origin_framework_slot_id` optional).
**Konsequenz Konzept CURR‑012 („concrete/library“):** Persistiert wird **ein** Kopf ohne Modus-Spalte: Immer Bibliotheks‑Rolle; Konkretisierung nur über Planung/API‑Kopie. Historische DDL mit `plan_mode` siehe **`035`**/`036` in dieser Datei (**§5 Changelog**) und `backend/migrations/`.
### 2.1 Checkliste (Abhak-Stand)
- [x] **Entität(en):** `training_framework_programs` (**CURR‑009**); `training_plan_templates` unverändert **eine‑Einheit‑Mikrovorlage** (**C5**).
- [x] **Bibliothek only (036):** Kopf ohne `plan_mode`/`group_id`; Kontextfilter **`focus_area_id`**, **`style_direction_id`**; M:N **`training_framework_program_training_types`**, **`training_framework_program_target_groups`**.
- [x] **Zielliste:** `training_framework_goals`, API **≥ 1** Ziel (**CURR‑011**).
- [x] **Slots:** `training_framework_slots` mit **`sort_order`**, optional **Titel/Notizen**; **Ablauf** über zugehörige **Blueprint‑`training_units`** + Sektionen/Items (**037**), nicht mehr `training_framework_slot_exercises`.
- [x] **Progressionsgraph:** Stufe 1 (**§3–§4**); **kein Pflichtbezug** pro Slot (**CURR‑013**).
- [x] **Kein Live‑Write** von Kalendereinheiten zurück in die Vorlage (**CURR‑006**); Konkretisierung = **Kopie** (siehe **§2.4**).
- [x] **Instanziierung (MVP):** `POST /api/training-units/from-framework-slot` — weiterer Ausbau: Bulk, Kalender‑UI‑Flow, **`training_plan_template_id` pro Slot** weiterhin optional/deferred (**CURR‑010**).
- [x] **Governance:** `visibility`, `club_id`, **`training_plan_templates.visibility`** (**035**) — (**CURR‑005–008**).
- [x] **REST Rahmenprogramm:** `/api/training-framework-programs` (**§2.3**); Planung (**§2.4**).
### 2.2 DDL‑Überblick (Migrationen **035** → **036** → **037**)
Auszug aktueller Zustand nach **036/037** (Details: `backend/migrations/035_training_framework_programs.sql`, `036_framework_program_context_only_library.sql`, `037_training_framework_blueprint_units.sql`):
```sql
-- Kopf (ohne Modus-Spalten nach 036)
training_framework_programs (
id, title NOT NULL, description,
planned_period_start, planned_period_end NULL,
visibility NOT NULL, club_id, created_by,
focus_area_id, style_direction_id NULL REFERENCES …,
… timestamps
)
training_framework_goals (
id, framework_program_id FK CASCADE, sort_order UNIQUE per framework,
title, notes
)
training_framework_slots (
id, framework_program_id FK CASCADE, sort_order UNIQUE per framework,
title, notes,
training_unit_id FK … (Spalte technisch noch vorhanden; fachlich ungenutzt, per 036 geleert)
)
-- Blueprint: eigene Einheit wie in der Planung (031)
training_units.framework_slot_id -- UNIQUE (partial index), FK → slots ON DELETE CASCADE
training_units.origin_framework_slot_id -- optional auf Kopien aus dem Rahmen (SET NULL)
-- CHECK chk_training_units_blueprint_vs_scheduled (Blueprint vs. Kalender‑Zeile)
-- training_framework_slot_exercises → entfallen (037)
```
**Löschkaskaden:** Rahmen löschen ⇒ Ziele + Slots; **Slot löschen** ⇒ zugehörige Blueprint‑`training_unit` per **`ON DELETE CASCADE`** auf `framework_slot_id`.
### 2.3 REST‑Überblick (`router` `training_framework_programs`)
| Methode | Pfad | Zweck |
|---------|------|--------|
| GET | `/training-framework-programs` | Liste; Admin/Superadmin alle, sonst eigene (`created_by`); u. a. `goals_count`, `slots_count`, Kontext‑Counts |
| GET | `/training-framework-programs/{id}` | Detail inkl. `goals[]`, `slots[]` mit je **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`** (letzteres aus Sektionen geflacht, kompatibel zum Editor) |
| POST | `/training-framework-programs` | Neu; **Pflicht:** `title`, **`goals`** (≥ 1); optional `slots` (weiterhin **`exercises[]`** pro Slot möglich — Backend materialisiert Sektionen); Header: `focus_area_id`, `style_direction_id`, `training_type_ids`, `target_group_ids`, … |
| PUT | `/training-framework-programs/{id}` | Header; volles Ersetzen von **`goals`** und/oder **`slots`** (neue Slots ⇒ neue Blueprint‑Units) |
| DELETE | `/training-framework-programs/{id}` | Rahmen + Kinder |
**AuthZ:** wie zuvor — Planungsrolle zum Schreiben; Lesen/Schreiben/Löschen des Rahmens: Admin/Superadmin oder Ersteller.
**Payload‑Hinweise (JSON), Slots:**
- Weiterhin: `exercises: [{ exercise_id, exercise_variant_id?, order_index? }]` (wird intern in eine Sektion übernommen).
- Erweitert möglich: `sections` wie bei **`PUT /api/training-units/{id}`** (voller Ablauf mit Notizen/Items).
### 2.4 Planung / Kalender (`router` `training_planning.py`, Auszug)
| Methode | Pfad | Zweck |
|---------|------|--------|
| GET | `/training-units` | Nur **Kalender‑Einheiten** (`framework_slot_id IS NULL`) |
| GET/PUT | `/training-units/{id}` | Blueprint lesen/bearbeiten: möglich mit Rahmen‑Auth; spezielle Regeln im **PUT** (kein Template‑Reset, kein `plan_template_id` am Blueprint) |
| DELETE | `/training-units/{id}` | Blueprint **nicht** über diesen Pfad löschen (Fehlerhinweis); Slot entfernen über Rahmen‑**PUT** |
| POST | `/training-units/from-framework-slot` | Body: `framework_slot_id`, `group_id`, `planned_date` — tiefe Kopie + **`origin_framework_slot_id`** |
**Frontend:** `createTrainingUnitFromFrameworkSlot` in `frontend/src/utils/api.js`.
---
## 3. Progressionsgraph Übung → Übung (implementierter Stand)
### 3.1 Abgrenzung
- **Zwischen Übungen:** gerichtete Kanten auf Ebene **`exercises`** mit optionalen Endpunkten auf konkreten **`exercise_variants`** (Knoten = „Übung“ oder „Übung · Variante“). Migrationen **032–034**.
- **Innerhalb einer Übung:** Reihenfolge / Progressionsmetadaten der Varianten unverändert über **`exercise_variants`** (Migration **014**) — nicht duplizieren.
AuthZ analog **`training_plan_templates`**: Graph nur für **Admin/Superadmin** oder **Ersteller** (`created_by`); Anlegen neuer Graphen mit **`_has_planning_role`**.
### 3.2 Migrationen & Schema (Kurz)
| Mig. | Inhalt |
|------|--------|
| **032** | `exercise_progression_graphs` (Name, Beschreibung, **`visibility`**, **`club_id`**, **`created_by`**); `exercise_progression_edges` (`graph_id`, von/nach Übung, `edge_type` VARCHAR Default `next_exercise`). FK CASCADE zu Graph und Übungen. |
| **033** | `exercise_progression_edges.notes` (freier Text / „Entwicklungsziel“ pro Kante). |
| **034** | `from_exercise_variant_id`, `to_exercise_variant_id` (nullable, FK `exercise_variants`, CASCADE). CHECK: gleiche Übung nur mit **zwei verschiedenen Varianten**. UNIQUE-Index über Graph + Endpunkte inkl. `COALESCE(variant_id,0)` + `edge_type`. |
Kantentypen in Produktnutzung: **`next_exercise`** (Nachfolger), **`sibling`** (Schwester / gleiche „Entwicklungslage“, semantisch oft Paar — weiterhin eine gerichtete Kante in DB).
Listenqueries liefern Join‑Felder **`from_exercise_title`**, **`to_exercise_title`**, **`from_variant_name`**, **`to_variant_name`**.
### 3.3 REST (`/api`, Router `exercise_progression_graphs.py`)
| Methode | Pfad | Zweck |
|---------|------|--------|
| GET | `/exercise-progression-graphs` | Liste (+ `edges_count`); Admin sieht alle, sonst nur eigene. |
| GET | `/exercise-progression-graphs/{id}` | Detail; `?include_edges=true` |
| POST | `/exercise-progression-graphs` | Graph anlegen |
| PUT | `/exercise-progression-graphs/{id}` | Metadaten |
| DELETE | `/exercise-progression-graphs/{id}` | Graph + Kanten |
| GET | `/exercise-progression-graphs/{id}/edges` | Kanten; Query optional `from_exercise_id`, `to_exercise_id` |
| POST | `/exercise-progression-graphs/{id}/edges` | Einzelkante; Duplikat/Constraint → **409** |
| POST | `/exercise-progression-graphs/{id}/edges/sequence` | **Bulk:** `{ steps: [{ exercise_id, variant_id? }, …], segment_notes?: [...] }` — nur **`next_exercise`**, Transaktion alle oder keine Zeile |
| PUT | `/exercise-progression-graphs/{id}/edges/{edge_id}` | z. B. **`notes`** |
| DELETE | `/exercise-progression-graphs/{id}/edges/{edge_id}` | eine Kante |
| POST | `/exercise-progression-graphs/{id}/edges/delete-batch` | `{ edge_ids: [...] }` — z. B. gesamte sichtbare „Reihe“ löschen |
### 3.4 Frontend (Stand Code)
- **`ExercisesListPage`:** Tabs **Liste** · **Progressionsgraphen** → **`ExerciseProgressionGraphPanel`**.
- **`ExerciseFormPage`** (nur Edit): eingeklappter Block **Progressionsgraph** mit Kontext „diese Übung“ + Filter „nur betroffene Kanten“.
- Panel‑Funktionen: **Sequenz‑Editor** (mehrere Schritte → ein Bulk‑Speichern), zusammengefasste **Reihen‑Lesart** für `next_exercise`, eigene Liste für **Schwestern**, Einzelkantenbereich, Tab **Alle Kanten (Tabelle)**.
- API‑Client: `frontend/src/utils/api.js` (`createExerciseProgressionSequence`, `deleteExerciseProgressionEdgesBatch`, …).
---
## 4. Zwischenstand für Produkt / Trainingsplanung (bewusste Grenzen)
**Freigabe:** Der beschriebene Stand unterstützt **Rahmen‑Bibliothek mit vollem Ablauf pro Slot** (wie Planung) und **Kopie in die Gruppenplanung**; der **Progressionsgraph** bleibt **unterstützend** (**CURR‑013**). Offen: Kalender‑UI‑Flow, Bulk‑Instanziierung, erweiterte Lineage/Feedback (**Konzept Schritt E**).
**Was gut nutzbar ist**
- Lineare **Reihen** mehrerer Übungen (bzw. Varianten‑Knoten) über **Sequenz‑API** bzw. Sequenz‑UI.
- **Nachfolger‑Lesart** als zusammenhängende Kette in der Übersicht.
- **Schwester‑Kanten** als eigene Liste (Alternative gleicher „Stufe“ zwischen zwei Knoten).
- **Einzelkanten** für Sonderfälle und Verzweigungen.
**Was noch nicht „ein Knopf“ ist (bekannt)**
- **Parallele gleichwertige Alternativen** („Paket B bestehend aus mehreren Übungen als echte Alternative zu Paket A“) sind **nicht** als erste‑Klass‑UX modelliert: mehrere Nachfolger aus einem Knoten sind technisch möglich (mehrere `next_exercise`‑Kanten), aber **keine** dedizierte Gruppe „Alternativ‑Set“. Pflege kann mehrzeilig und koplastisch wirken.
- **Visualisierung echter Bäume** (Join‑Points, mehrere ausgehende Pfeile in einem Bild) ist nur eingeschränkt über Reihen‑Zusammenfassung + Tabelle abbildbar.
**Nächste sinnvolle Ausbaustufen** (Backlog Graph‑UX, nicht Blocker Planung)
- Semantik **`alternative_group_id`** oder **Hyperkanten** (ein UX‑Schritt legt mehrere Kanten mit gemeinsamer Gruppe an).
- Komfort beim Pflegen **symmetrischer Schwestern** (ein Klick für zwei Richtungen / Dedupe).
- Karten-/Baum‑Layout statt nur Zeilen.
Details weiterhin Diskussionsgrundlage in `TRAINING_CURRICULUM_AND_GOVERNANCE_CONCEPT.md` §6 (Kantentypen).
---
## 5. Changelog (Dokument)
| Datum | Änderung |
|-------|----------|
| 2026-05-05 | **037 / API:** Nur Bibliothek + **Blueprint** pro Slot über `training_units` + Sektionen/Items; `training_framework_slot_exercises` entfernt; `POST …/training-units/from-framework-slot`; Planungsliste ohne Blueprints. **036** dokumentiert am Kopf (Kontext, M:N, kein plan_mode/group_id). **§2** vollständig ersetzt. |
| 2026-05-05 | **CURR‑002 (2):** §2 Rahmenprogramm — Entscheid **eine Tabelle + `plan_mode`**, DDL‑Skizze, REST‑Überblick; Migration **035**; `training_plan_templates.visibility`. *(Historisch — Modus-Spalten durch **036** ersetzt.)* |
| 2026-04-30 | **Zwischen-Doku:** §3 auf Migrationen 032–034 + API **sequence/delete-batch** + Frontend erweitert; **§4** Produktfreigabe vs. Lücken (parallele Alternativen); Changelog §5. |
| 2026-04-30 | §3: erste Fassung Migration 032 + REST‑Basis (CURR‑002 (1)). |
| 2026-04-28 | Erstanlage Stub mit Checkliste. |
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
# Endpoint-Audit: Mandanten & Governance
Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| Router / Bereich | Beispiel-Endpunkt | tenant-relevant | `Depends(get_tenant_context)` / Kontext | Governance geprüft (Liste+Detail) | Notizen |
|------------------|-------------------|-----------------|----------------------------------------|-------------------------------------|---------|
| profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht |
| profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin |
| profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft |
| clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth |
| club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | |
| club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | |
| exercises | `PATCH /api/exercises/bulk-metadata` | ja | `get_tenant_context` | ja | Liste: UI-Mehrfachwahl; bis 500 IDs; nur Ersteller oder Plattform-Admin |
| exercises | `GET .../media/{mid}/file` | ja | `get_tenant_context_flexible` | ja (wie Übung lesen) | Datei oder `?ssetoken`; kein anonymes `/media/` ohne ALLOW_PUBLIC_MEDIA_STATIC |
| exercises | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | PUT Einzelübung: bei Sichtbarkeit `official` Medien-§4.2 (422: Lifecycle/Promotion/Copyright) |
| exercise_progression_graphs | `/api/exercise-progression-graphs*` | ja | `get_tenant_context` | Liste wie Bibliothek; Schreiben Ersteller/Plattform-Admin | Kanten: Lesen wenn Graph lesbar |
| training_planning | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Vorlagen-Liste wie Übungen; POST Vorlage Default club_id |
| training_framework_programs | alle geschützten Endpoints | ja | `get_tenant_context` | ja | Liste + POST Default club_id |
| admin_users | `GET /api/admin/users` | Plattform | `require_auth` | Admin-Rolle | EXEMPT `check_access_layer_hints.py` |
| platform_media_storage | `GET/PUT /api/admin/platform-media-storage` | Plattform | `require_auth` | GET: `is_platform_admin`; PUT: nur `superadmin` | Relativer Pfad unter `MEDIA_ROOT`; keine Secrets; EXEMPT wie admin_users |
| media_assets | `POST /api/media-assets/{id}/lifecycle` | ja | `get_tenant_context` | ja | u. a. `trash_soft` mit Trainer-nur-privat-Eigentum; `purge` nur **Superadmin**; Superadmin: `superadmin_force_lifecycle`, `superadmin_hard_delete` |
| media_assets | `GET /api/media-assets` | ja | `get_tenant_context` | ja | optional `lifecycle`; Standard `active`; Liste inkl. `copyright_notice`; Papierkorb-Ansicht nur sichtbare Mandanten-Assets |
| media_assets | `POST /api/media-assets/bulk-lifecycle` | ja | `get_tenant_context` | ja | Mehrfach-Lifecycle; gleiche Regeln wie Einzel-POST |
| media_assets | `POST /api/media-assets/bulk-patch` | ja | `get_tenant_context` | ja | Copyright / Bezeichner / Sichtbarkeit für viele IDs; gemischte Fehler in `failed[]` |
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
| maturity_models | Admin-Matrix | nein (global) | `require_auth` | Admin für Schreiben; `GET …/{id}` nur Portal-Admin | EXEMPT |
| matrix_stack_bundle | Export/Import Bundles | Plattform/Test | `require_auth` | Admin | EXEMPT |
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
**Legende:** Router auf der EXEMPT-Liste des Scripts sind globale oder Auth-only-Pfade; sobald ein Router Vereinsdaten oder Bibliotheks-Sichtbarkeit erhält, EXEMPT entfernen und `get_tenant_context` einführen.
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
Letzte Änderung: 2026-05-07 — Upload-Dedupe Papierkorb 409 + `reactivate`; DELETE …/media nur Verknüpfung.
---
### Changelog (Fortführung)
- **2026-05-07:** Legacy `GET/PUT /api/profile` auf Session-Profil gehärtet; OpenAPI/Health-Ready Produktionsdefaults; Security-Release-Tests + CI-Schritt `security_release_checks.py` — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
- **2026-05-07 (Phase 3):** CSP SPA (nginx); API `nosniff`-Middleware — siehe `PRODUCTION_READINESS_AUDIT_2026-05.md`.
---
### Hinweis `GET /training-units`
Kein impliziter Filter nach `effective_club_id` (Multi-Verein-Kalender); bei Bedarf `club_id` Query setzen.
+10 -344
View File
@@ -1,348 +1,14 @@
# Shinkan Jinkendo - Session Handover
# Session Handover (Verweis)
**Datum:** 2026-04-22
**Kontext:** App-Entwicklung nach Login-Setup - Kern-Features implementieren
**Aktuelle Handover-Basis (Stand Implementierung + Medien):**
👉 **`docs/HANDOVER.md`** (Projektroot)
Dort: **Medien-Archiv/Medienbibliothek (Ist)**, **geplante Inline-Medienverlinkung (§11 Spec)**, Reifegrad/Matrix, Rahmenprogramm, nächste sinnvolle Arbeitspakete für neue Sessions.
**Projektstatus-Kachel:** `.claude/docs/PROJECT_STATUS.md`
**Medien Single Source of Truth:** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
---
## 🎯 Projekt-Mission
**Shinkan Jinkendo** (真観) - Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung.
**NICHT:** Persönliches Athleten-Tracking (das ist Mitai)
**SONDERN:** Trainer verwalten Vereine, Gruppen, Übungen, Training
---
## 📚 Pflicht-Dokumentation (ZUERST LESEN!)
### Fachliches Design
```
c:\Dev\shinkan-jinkendo\.claude\docs\working\SHINKAN_PROJECT_SETUP.md
```
**Enthält:**
- Domain Model (Clubs, Groups, Skills, Methods, Exercises)
- MVP Features
- Datenbank-Schema
- User Stories
### Technisches Setup (bereits erstellt von vorheriger Session)
Siehe: `SHINKAN_PROJECT_SETUP.md` - Abschnitte:
- Tech Stack (React 18, FastAPI, PostgreSQL 16, Docker)
- Ports: Dev 3098/8098, Prod 3003/8003
- Deployment: Gitea Actions auf develop Branch
### Referenz-Codebase
```
c:\Dev\mitai-jinkendo\
```
**Nutzen für Standards:**
- Router-Struktur (`backend/routers/`)
- Frontend-Patterns (`frontend/src/pages/`)
- CSS-System (`frontend/src/app.css`)
**⚠️ WARNUNG:** Mitai-Code NICHT blind kopieren!
- Mitai hat AI-Features, Export, komplexes Membership
- Shinkan ist einfacher, andere DB-Spalten
- **Immer Schema prüfen** vor Copy/Paste!
---
## 🔧 Aktueller Stand
### ✅ Was funktioniert
- **Login/Auth:** lars@stommer.com / 12345678 (admin, premium)
- **Backend API:** http://192.168.2.49:8098
- **Frontend:** http://192.168.2.49:3098
- **Datenbank:**
- profiles, sessions (Auth)
- clubs, divisions, training_groups (Organisation)
- skills (12 Einträge), training_methods (8 Einträge) - bereits geseedet!
- exercises, exercise_skills (leer)
### ❌ Bekannte Probleme
**1. Navigation erscheint nicht im Browser**
- Code existiert: `frontend/src/components/Navigation.jsx`
- Routes hinzugefügt: ProfilePage, ExercisesPage, ClubsPage
- Deploy erfolgt (Commit c4b1b54)
- **Problem:** Nicht im Browser sichtbar - vermutlich Browser-Cache oder Build-Issue
**2. Sessions funktionieren nicht**
- User muss sich ständig neu einloggen
- Backend-Fix gepusht (Commit 08326bd) - Mitai-Spalten entfernt
- **Problem:** Unklar ob Fix deployed wurde
**Erste Aufgabe:** Diese beiden Issues fixen, DANN Features bauen!
### 📁 Code-Struktur
```
c:\Dev\shinkan-jinkendo\
├── backend/
│ ├── main.py (FastAPI setup, Router registration)
│ ├── auth.py (Session management, require_auth)
│ ├── db.py (PostgreSQL connection pool)
│ ├── models.py (Pydantic models)
│ ├── routers/
│ │ ├── auth.py (Login, Register, Logout)
│ │ └── profiles.py (User profile CRUD)
│ └── migrations/
│ ├── 001_auth_membership.sql
│ ├── 002_organization.sql
│ ├── 003_catalogs.sql (Skills + Methods seeded!)
│ └── 004_add_auth_columns.sql
│
├── frontend/src/
│ ├── App.jsx (Routing + ProtectedRoute)
│ ├── context/
│ │ └── AuthContext.jsx (User state, login/logout)
│ ├── components/
│ │ └── Navigation.jsx (Header-Menü - NICHT SICHTBAR)
│ ├── pages/
│ │ ├── LoginPage.jsx (✅ funktioniert)
│ │ ├── Dashboard.jsx (✅ zeigt Welcome)
│ │ ├── ProfilePage.jsx (NEU - Platzhalter)
│ │ ├── ExercisesPage.jsx (NEU - leer)
│ │ └── ClubsPage.jsx (NEU - leer)
│ └── utils/
│ └── api.js (Zentrale API-Client mit Token-Injektion)
│
└── .claude/docs/
└── working/
└── SHINKAN_PROJECT_SETUP.md (LESEN!)
```
---
## 🚀 Was JETZT gebaut werden muss (MVP Scope)
### Phase 1: Core CRUD (Priorität)
**1. Übungsverwaltung** (Kernobjekt) - 2-3h
- `backend/routers/exercises.py`
- GET /exercises (Liste mit Filter)
- POST /exercises (Create)
- GET /exercises/{id} (Detail)
- PUT /exercises/{id} (Update)
- DELETE /exercises/{id}
- `frontend/src/pages/ExercisesPage.jsx`
- Liste (Tabelle oder Cards)
- Create-Modal/Form
- Edit inline oder Modal
- Delete mit Confirm
**Schema:** Siehe `migrations/001_auth_membership.sql` - Tabelle `exercises`
**Felder:**
- title, summary, goal, execution, preparation, trainer_notes
- equipment (JSONB array), duration_min/max, group_size_min/max
- age_groups (JSONB), focus_area, secondary_areas (JSONB)
- training_character, visibility (private/club/public)
- primary_method_id, secondary_method_ids (JSONB)
**Referenz:** Mitai hat ähnliche CRUD-Pattern in `routers/weight.py`, `routers/activity.py`
---
**2. Vereinsverwaltung** - 1-2h
- `backend/routers/clubs.py`
- CRUD für clubs
- CRUD für divisions (optional)
- `frontend/src/pages/ClubsPage.jsx`
**Schema:** Siehe `migrations/002_organization.sql`
---
**3. Gruppenverwaltung** - 1-2h
- `backend/routers/groups.py`
- CRUD für training_groups
- Zuordnung zu Clubs
- Trainer-Zuordnung (trainer_id, co_trainer_ids)
- `frontend/src/pages/GroupsPage.jsx`
---
### Phase 2: Kataloge & Zuordnungen (Später)
**4. Skills & Methods anzeigen** - 0.5h
- `/skills` Route (Read-only, bereits geseedet)
- `/methods` Route (Read-only, bereits geseedet)
**5. Übungen ↔ Skills verknüpfen** - 1h
- M:N Relationship über `exercise_skills` Tabelle
- UI: Multi-Select für Skills beim Übung-Erstellen
---
## 🔍 Debugging-Checkliste (Vor neuen Features!)
### Problem: Navigation nicht sichtbar
```bash
# SSH zum Server
ssh lars@192.168.2.49
# Frontend Container prüfen
docker exec dev-shinkan-ui ls -la /usr/share/nginx/html/assets/
# Erwartung: Datei index-CYNK--85.js oder neuer
# Prüfen ob Navigation.jsx im Bundle
docker exec dev-shinkan-ui grep -o "Navigation\|Übungen" /usr/share/nginx/html/assets/index-*.js | head -5
# Falls nicht: Frontend neu bauen
cd /home/lars/docker/shinkan-dev
git pull
docker compose -f docker-compose.dev-env.yml build --no-cache frontend
docker compose -f docker-compose.dev-env.yml up -d
```
### Problem: Sessions funktionieren nicht
```bash
# Backend Logs prüfen
docker logs dev-shinkan-api --tail 50 | grep -E "error|Error|column.*does not exist"
# Erwartung: KEINE "column p.ai_enabled does not exist" Fehler mehr
# Session-Test
curl -X POST http://192.168.2.49:8098/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"lars@stommer.com","password":"12345678"}' | python3 -m json.tool
# Erwartung: {"token": "...", "role": "admin", ...}
```
---
## 🛠️ Entwicklungs-Workflow
### 1. Feature implementieren (Lokal)
```bash
# Backend
cd c:\Dev\shinkan-jinkendo
# Router erstellen: backend/routers/exercises.py
# Models ergänzen: backend/models.py
# Router registrieren: backend/main.py
# Frontend
# Seite erstellen: frontend/src/pages/ExercisesPage.jsx
# API-Funktionen: frontend/src/utils/api.js
# Route in App.jsx
```
### 2. Committen & Pushen
```bash
git add -A
git commit -m "feat: Exercise CRUD implementation"
git push origin develop
```
### 3. Gitea Action deployt automatisch
- Kein manuelles `docker compose` mehr!
- Warte 1-2 Min
- Prüfe: http://192.168.2.49:3098
### 4. Testen im Browser
- Login: lars@stommer.com / 12345678
- Feature testen
- Console prüfen (F12) bei Fehlern
---
## 📊 Datenbank-Zugriff
```bash
# SSH
ssh lars@192.168.2.49
# PostgreSQL CLI
docker exec -it dev-shinkan-postgres psql -U shinkan_dev -d shinkan_dev
# Hilfreiche Queries
\d profiles # Schema anzeigen
\d exercises # Exercise-Schema
SELECT * FROM skills; # Alle Skills (12 Einträge)
SELECT * FROM training_methods; # Alle Methods (8 Einträge)
```
---
## ⚠️ Lessons Learned (Vermeide diese Fehler!)
### 1. Mitai vs Shinkan Schema
**Problem:** Auth.py von Mitai kopiert, aber Spalten fehlen in Shinkan
**Fehler:**
- `ai_enabled`, `ai_limit_day`, `export_enabled` - existieren nur in Mitai
- `auth_type`, `verification_expires`, `trial_ends_at` - mussten hinzugefügt werden
- `created` vs `created_at` - unterschiedliche Spaltennamen
**Regel:** Vor Mitai-Code kopieren → **Schema prüfen**!
### 2. Frontend-Cache
**Problem:** Code deployed aber nicht sichtbar im Browser
**Lösung:**
- Browser-Cache leeren (Ctrl+Shift+R)
- Oder `docker compose build --no-cache frontend`
### 3. Gitea Actions nicht mit manuellen Deploys mischen
**Problem:** Container-Namens-Konflikte
**Regel:** Nur `git push` → Gitea macht den Rest
---
## 📞 Server-Info
| System | Wert |
|--------|------|
| **Pi IP** | 192.168.2.49 |
| **Gitea** | http://192.168.2.144:3000/Lars/shinkan-jinkendo |
| **Dev Frontend** | http://192.168.2.49:3098 |
| **Dev Backend** | http://192.168.2.49:8098 |
| **Deploy Path** | /home/lars/docker/shinkan-dev |
| **DB Name** | shinkan_dev |
| **DB User** | shinkan_dev |
| **DB Pass** | dev_password |
---
## 🎯 Erfolgs-Kriterien MVP
Nach MVP soll User können:
1. ✅ Login/Logout (erledigt)
2. ⏳ Übungen verwalten (CRUD)
3. ⏳ Vereine anlegen
4. ⏳ Trainingsgruppen anlegen
5. ⏳ Übungen Skills zuordnen
6. ⏳ Skills/Methods katalog ansehen
**Geschätzte Zeit:** 6-8h für Punkte 2-6
---
## 🚦 Start-Kommando für neue Session
```
Ich übernehme die Entwicklung von Shinkan Jinkendo.
Kontext gelesen: HANDOVER_NEXT_SESSION.md
Erste Schritte:
1. Navigation + Sessions debuggen
2. Dann: Exercise CRUD implementieren
Bitte bestätige dass du bereit bist und zeige mir den aktuellen Status (Container, letzte Commits, bekannte Probleme).
```
---
**Viel Erfolg!** 🥋
*Die historische „Übungen Lücke“-Fassung (2026-04) ist überholt; Medien-UI und Archiv sind seit 0.8.41+ weitgehend umgesetzt — Details `docs/HANDOVER.md` §4.*
@@ -0,0 +1,95 @@
# Produktionsreife: Audit-Ergebnis & Umsetzungsplan (Stand 2026-05-07, Phase-3-Update)
**Zweck:** Einheitliche Referenz gegen **Drift** zwischen Sicherheits-/Betriebsanforderungen und Code.
**Bezug:** Zugriffsschicht `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`, Cursor-Regel `.cursor/rules/access-layer.mdc`.
---
## Teil A — Audit-Ergebnis (Kurzfassung)
### A.1 Kritisch / Hoch (behoben oder geplant)
| ID | Befund | Status (2026-05-07) |
|----|--------|----------------------|
| SEC-01 | `GET /api/profile` (Legacy): ohne Header wurde das **erste Profil der DB** geliefert → IDOR / Datenleck | **Behoben:** Profil immer aus Session |
| SEC-02 | OpenAPI `/docs`, `/redoc`, `/openapi.json` in Produktion exponiert | **Behoben:** bei `ENVIRONMENT=production` aus; Override `PUBLIC_OPENAPI=1` |
| SEC-03 | `/api/health/ready` mit Tabellendetails / Migrationszähler öffentlich | **Behoben:** in Prod nur kompakte Antwort; Detail via `HEALTH_READY_PUBLIC_DETAIL=1` |
| SEC-04 | Statische Auslieferung `/media` ohne Auth (Link-Leak) | **Behoben:** `GET /api/exercises/.../media/.../file` mit Governance + `ssetoken`; `/media` nur mit `ALLOW_PUBLIC_MEDIA_STATIC=1` |
| OPS-01 | PostgreSQL-Hostport in `docker-compose.yml` | **Behoben:** Bind `127.0.0.1:5434` (nur Host-Local) |
### A.2 Mittel / Konsistenz
| ID | Befund | Status |
|----|--------|--------|
| CON-01 | Frontend: direktes `fetch('/api/profiles')` ohne zentralen Client | **Behoben** (AdminCatalogsPage → `api.listProfiles`) |
| CON-02 | `ProfileContext.jsx` (unused): falsches Token-Feld / `session` | **Behoben** (`user` + `getCurrentProfile` / `listProfiles`) |
| MEM-01 | Vereinsmitgliederverzeichnis zeigt E-Mail an alle Mitglieder | **Behoben:** E-Mail nur Plattform-Admin / `can_manage_club_org` |
| MAT-01 | `GET /maturity-models/{id}` für jeden Auth-Nutzer | **Behoben:** nur Portal-Admin (UI nutzt ohnehin nur Admin-Panel) |
### A.3 Niedrig / Offen
| ID | Befund | Status |
|----|--------|--------|
| CON-03 | Sparten (`division`) vs. Zielbild ACCESS_LAYER | **Roadmap** — siehe Phase 3 unten (Stufe D); nicht in diesem Schritt implementiert |
| OPS-02 | CSP / restliche Browser-Härtung | **Behoben (Basis):** CSP auf SPA-Dokumente (nginx `location /`); API `X-Content-Type-Options: nosniff` (FastAPI-Middleware) |
| MISC-01 | `auth.py` Debug-`print` beim Import | **Behoben** (entfernt) |
| MISC-02 | `delete_profile`: DELETE auf Mitai-Tabellen schlägt fehl, wenn Tabelle fehlt | **Behoben:** nur löschen, wenn Tabelle existiert |
---
## Teil B — Priorisierter Umsetzungsplan
### Phase 1 — Sofort (Beta-Blocker) ✅ umgesetzt in Repo-Stand
1. Legacy-Endpunkte `/api/profile` GET/PUT: **nur Session-`profile_id`**, kein „erstes Profil“-Fallback.
2. OpenAPI in Produktion deaktivieren; opt-in für Notfall-Debugging.
3. Readiness-Endpoint in Prod entschärfen; operatives Detail per Env.
4. Automatisierte **Security-Release-Tests** (`tests/test_security_release.py`) + Script `scripts/security_release_checks.py` in CI.
5. Profil-Löschung: optionale Tabellen nur bei Existenz.
6. Frontend: Admin-Kataloge Profilliste über `api.js`.
### Phase 2 — Kurzfristig (vor breitem Go-Live) ✅ Hauptpunkte umgesetzt (2026-05-07)
1. **Medien:** `GET /api/exercises/{id}/media/{mid}/file` — Auth (`X-Auth-Token` oder `?ssetoken=`), Zugriff wie GET Übung; statisches `/media` standardmäßig aus.
2. **Mitgliederverzeichnis:** E-Mail nur wenn Plattform-Admin oder `can_manage_club_org`.
3. **DB-Port:** Prod-Compose Postgres an `127.0.0.1` gebunden.
4. **`GET /api/maturity-models/{id}`:** nur Portal-Admin (Liste/resolve unverändert für Trainer).
### Phase 3 — Mittelfristig
1. **CSP & Header:** Content-Security-Policy für die SPA (nginx, `location /`); `X-Content-Type-Options: nosniff` auf allen FastAPI-Responses — ✅ umgesetzt.
2. **Audit-Pflege:** bei Tenant/Governance-Änderungen `ACCESS_LAYER_ENDPOINT_AUDIT.md` und dieses Dokument anpassen — fortlaufend (Hinweis im Endpoint-Audit).
3. **Division / Sparten (CON-03, Stufe D):** noch **nicht** code-seitig durchgesetzt. Nächste technische Schritte (für eigenes Epic):
- Ist-Zustand: `division_id` auf Objekten & `division_lead` in `can_plan_in_club` ohne strikte Objekt-Filter.
- Ziel: Lesen/Schreiben nur mit passender Sparten-Mitgliedschaft bzw. Rolle; einheitliche Filter in Listen (`training_groups`, Übungen, Planung).
- Tests: Zwei Nutzer, zwei Sparten, kein Cross-Lesen; Superadmin-Pfade getrennt.
- Spec: `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe D.
---
## Teil C — CI / Qualitätssicherung
- **ACCESS_LAYER_STRICT:** `scripts/check_access_layer_hints.py` (unverändert Pflicht).
- **Security-Release:** `python scripts/security_release_checks.py` (pytest-Modul `test_security_release`).
- **Regression Profil:** `tests/test_profiles_read_access.py` (Legacy-Route).
---
## Teil D — Umgebungsvariablen (Referenz)
| Variable | Bedeutung |
|----------|-----------|
| `ENVIRONMENT` | `production` / `prod` → OpenAPI aus, Health-Ready kompakt |
| `PUBLIC_OPENAPI` | `1` / `true` → OpenAPI trotz Prod einschalten (nur Debugging) |
| `HEALTH_READY_PUBLIC_DETAIL` | `1` / `true` → volle Ready-JSON inkl. Tabellenliste in Prod |
| `ALLOW_PUBLIC_MEDIA_STATIC` | `1` / `true` → öffentliches Mount von `/media/` (Notfall/Legacy; Standard: aus) |
| `CSP` (nginx) | Kein Env: Policy fest in `frontend/nginx.conf` (`location /`). API auf **anderer Host-URL** als SPA: `connect-src` in der Policy erweitern oder Build mit envsubst. |
---
**Pflege:** Nach jeder relevanten Änderung **Status-Spalte** und ggf. **Phase** aktualisieren; bei neuem Audit Datum im Titel anpassen oder Abschnitt „Changelog“ ergänzen.
### Changelog
- **2026-05-07:** Phase 2 Medien, Mitgliederverzeichnis E-Mail, maturity GET admin-only, Postgres localhost bind, Tests `test_exercise_media_download.py`.
- **Phase 3:** CSP (nginx SPA), API `X-Content-Type-Options` (FastAPI), Test `test_api_attachments_x_content_type_options_nosniff`; Division-Durchsetzung nur als Roadmap (CON-03).
@@ -0,0 +1,391 @@
# SMW-Importer Gap-Analyse & Umsetzungsplanung
**Datum:** 2026-04-24
**Status:** Requirement Analysis Complete
**Nächste Schritte:** User-Approval → Implementation
---
## 1. Executive Summary
**Ziel:** SMW-Importer fertigstellen inkl. Frontend, saubere Datenbank, Issue #53 Compliance
**Aktueller Status:**
- ✅ Backend komplett (smw_client.py, smw_mapper.py, import_wiki.py)
- ✅ Migration 018 (wiki_import_tracking) deployed
- ✅ Issue #53 konform (keine fachliche Interpretation im Import)
- ✅ Duplikats-Handling via wiki_import_references
- ❌ Migrations 014-017 fehlen (Blocker für saubere DB)
- ❌ exercises.py Router nutzt Legacy-Felder (Inkonsistenz)
- ❌ Frontend für Importer fehlt komplett
**Kritischer Pfad:**
1. Migrations 014-017 anlegen (DB-Konsistenz)
2. exercises.py auf M:N umstellen (Legacy-Cleanup)
3. Frontend für Importer (Admin-UI)
---
## 2. Issue #53 Compliance Check (Mitai → Shinkan)
### 2.1 Was ist Issue #53?
**Quelle:** `c:\Dev\mitai-jinkendo\docs\issues\issue-53-phase-0c-multi-layer-architecture.md`
**Kern-Prinzip:**
```
┌────────────────────────────────────────────────┐
│ Layer 1: DATA LAYER │
│ - Pure data retrieval + calculation logic │
│ - Returns: Structured data (dict/list/float) │
│ - No formatting, no strings │
└──────────────────┬─────────────────────────────┘
│
┌───────────┴──────────┐
│ │
▼ ▼
┌──────────────┐ ┌─────────────────────┐
│ Layer 2a: │ │ Layer 2b: │
│ KI LAYER │ │ VISUALIZATION LAYER │
└──────────────┘ └─────────────────────┘
```
**Import-Regeln (ARCHITECTURE.md §8):**
- ✅ **Erlaubt:** Typ-/Einheits-Konvertierung, Zuordnung CSV→Feld, Duplikat-Logik
- ❌ **Verboten:** Fachliche Interpretation, Aggregation von "Bedeutung", Metriken für Auswertung
### 2.2 Shinkan SMW-Importer Compliance
**✅ KONFORM:**
```python
# smw_mapper.py - Nur Feld-Zuordnung
EXERCISE_PROPERTY_MAP = {
"Übungsbezeichnung": "title_override",
"Ziel": "goal",
"Durchführung": "execution",
"Plandauer": "duration_raw", # String → Int Konvertierung
"Übungstyp": "focus_area_names", # Name → ID Lookup
}
# Typ-Konvertierung (erlaubt)
duration_min = safe_int(raw_value.get("Plandauer"))
# Keine fachliche Interpretation ✅
# Keine Metriken-Berechnung ✅
```
**✅ Duplikats-Handling:**
```python
# import_wiki.py - reimport-safe
if not reimport:
cur.execute(
"SELECT id FROM wiki_import_references WHERE wiki_page_title = %s",
(page_title, import_type)
)
if cur.fetchone():
stats["skipped"] += 1
continue
```
**✅ M:N Katalog-Zuordnung:**
```python
# _assign_exercise_catalogs() - lookup only, keine Berechnung
cur.execute("SELECT id FROM focus_areas WHERE name ILIKE %s", (name,))
if row:
cur.execute(
"INSERT INTO exercise_focus_areas (exercise_id, focus_area_id, is_primary) ..."
)
```
**Fazit:** SMW-Importer ist Issue #53 konform. KEIN Refactoring nötig.
---
## 3. Datenbank-Inkonsistenz: Legacy vs. M:N
### 3.1 Problem
**Migration 005** (deployed) definiert Legacy-Felder:
```sql
CREATE TABLE exercises (
...
age_groups JSONB, -- ["minis", "kinder", "erwachsene"]
focus_area VARCHAR(100), -- karate, selbstverteidigung, gewaltschutz
secondary_areas JSONB,
...
);
```
**Migration 008** (deployed) definiert M:N Tabellen:
```sql
CREATE TABLE exercise_focus_areas (...);
CREATE TABLE exercise_age_groups (...);
CREATE TABLE exercise_target_groups (...);
```
**exercises.py Router** (aktuell) nutzt BEIDE:
```python
# Legacy beim CREATE
data.get('age_groups'), # JSONB
data.get('focus_area'), # VARCHAR
# M:N beim GET
SELECT fa.name FROM exercise_focus_areas efa
JOIN focus_areas fa ON efa.focus_area_id = fa.id
```
**Migration 014** (geplant) würde Legacy-Felder droppen:
```sql
ALTER TABLE exercises DROP COLUMN IF EXISTS age_groups;
ALTER TABLE exercises DROP COLUMN IF EXISTS focus_area;
ALTER TABLE exercises DROP COLUMN IF EXISTS secondary_areas;
```
### 3.2 Auswirkung
**Wenn Migration 014 jetzt ausgeführt wird:**
- ✅ SMW-Importer funktioniert (nutzt nur M:N)
- ❌ exercises.py CREATE bricht (INSERT referenziert gedropte Spalten)
- ❌ exercises.py GET funktioniert (nutzt M:N)
**Lösung:** exercises.py auf M:N umstellen BEVOR Migration 014
---
## 4. Fehlende Migrations 014-017
### 4.1 Inhalt
**Migration 014: Variant Progression + Search + Legacy Cleanup**
- Variant Progression (progression_level, sequence_order, prerequisite_variant_id)
- Search Vector (tsvector für Volltext-Suche)
- Legacy DROP (age_groups, focus_area, secondary_areas)
**Migration 015: Semantic Matching (OPTIONAL - Phase 2)**
- exercise_embeddings Tabelle für Vector Search
**Migration 016: Saved Searches**
- saved_exercise_searches Tabelle
**Migration 017: Exercise Blocks**
- exercise_blocks + exercise_block_items
- Template Blocks (is_template, is_placeholder, placeholder_criteria)
### 4.2 SQL-Dateien
**Status:** Spec-Inhalt existiert in `EXERCISES_DATABASE_FINAL.md`, muss als .sql extrahiert werden
**Action Items:**
- [ ] 014_variant_progression_search_legacy.sql anlegen
- [ ] 015_semantic_matching.sql anlegen (OPTIONAL)
- [ ] 016_saved_searches.sql anlegen
- [ ] 017_exercise_blocks.sql anlegen
---
## 5. Frontend für SMW-Importer
### 5.1 Fehlende Komponenten
**Admin-Seite:**
- `frontend/src/pages/MediaWikiImportPage.jsx` (NEU)
**API-Funktionen:**
- `frontend/src/utils/api.js` - Wiki-Import Funktionen ergänzen
**Navigation:**
- Admin-Navigation erweitern (Link zu Import-Seite)
### 5.2 UI-Requirements
**3-Tab Layout:**
1. **Preview Tab**
- Kategorie-Auswahl (Übungen, Fähigkeiten, Methoden)
- Limit-Auswahl (10, 50, 100)
- Preview-Button → zeigt Tabelle mit:
- Wiki-Seitentitel
- Already Imported (Ja/Nein)
- Last Imported (Datum)
- Mapped Fields (Accordion)
- Warnings/Errors
2. **Execute Tab**
- Import-Typ (Exercise, Skill, Method)
- Kategorie-Input
- Reimport-Existing (Checkbox)
- Dry-Run (Checkbox)
- Limit (Optional)
- Execute-Button → startet Background-Task
- Status-Display (Running, Completed, Failed)
- Progress (Imported/Skipped/Failed Counts)
3. **History Tab**
- Liste aller Import-Logs (neueste zuerst)
- Spalten: Type, Category, Status, Items (Total/Imported/Skipped/Failed), Date
- Expandable Row für Error-Details
**API-Endpoints (bereits vorhanden):**
- `GET /api/import/mediawiki/preview?category=Übungen&import_type=exercise&limit=10`
- `POST /api/import/mediawiki/execute` (Body: category, import_type, reimport, dry_run, limit)
- `GET /api/import/mediawiki/status/{log_id}`
- `GET /api/import/mediawiki/logs`
- `DELETE /api/import/mediawiki/references/{ref_id}` (Force Reimport)
---
## 6. Umsetzungsplan (priorisiert)
### Phase 1: Datenbank-Konsistenz (BLOCKER)
**1.1 Migrations anlegen**
- [ ] Migration 014 als .sql (Variant + Search + **Legacy DROP**)
- [ ] Migration 015 als .sql (Semantic Matching) - OPTIONAL, kann warten
- [ ] Migration 016 als .sql (Saved Searches)
- [ ] Migration 017 als .sql (Exercise Blocks)
**Aufwand:** 2-3h (SQL aus Spec extrahieren, testen)
**1.2 exercises.py Router überarbeiten**
- [ ] CREATE: Legacy-Felder entfernen, nur M:N nutzen
- [ ] UPDATE: Legacy-Felder entfernen
- [ ] Query-Filter: focus_area String-Filter durch M:N-Join ersetzen
**Aufwand:** 1-2h
**1.3 Deployment**
- [ ] Migrations 014-017 deployen (dev → prod)
- [ ] exercises.py deployen
- [ ] Testen: SMW-Import funktioniert
**Aufwand:** 1h
**Total Phase 1:** 4-6h
---
### Phase 2: SMW-Importer Frontend
**2.1 API-Funktionen**
- [ ] `api.js` erweitern:
- `previewMediaWikiImport(category, importType, limit)`
- `executeMediaWikiImport(category, importType, reimport, dryRun, limit)`
- `getMediaWikiImportStatus(logId)`
- `listMediaWikiImportLogs()`
- `deleteMediaWikiImportReference(refId)`
**Aufwand:** 0.5h
**2.2 MediaWikiImportPage.jsx**
- [ ] 3-Tab Layout (Preview, Execute, History)
- [ ] Preview: Kategorie-Auswahl, Preview-Tabelle mit Accordions
- [ ] Execute: Form mit Status-Polling
- [ ] History: Tabelle mit Expandable Rows
**Aufwand:** 3-4h
**2.3 Navigation**
- [ ] Admin-Navigation erweitern (Link zu Import-Seite)
**Aufwand:** 0.5h
**Total Phase 2:** 4-5h
---
### Phase 3: Testing & Refinement
**3.1 Integration Testing**
- [ ] Dev-System: Import von BINGO + Speed Jab Drills
- [ ] Prüfen: Alle M:N Tabellen korrekt befüllt
- [ ] Prüfen: Reimport überschreibt korrekt
- [ ] Prüfen: Duplikats-Handling funktioniert
**Aufwand:** 1-2h
**3.2 Prod Deployment**
- [ ] SMW-Importer deployen (dev → prod)
- [ ] Erste echte Imports durchführen
**Aufwand:** 1h
**Total Phase 3:** 2-3h
---
## 7. Gesamt-Aufwand
| Phase | Tasks | Aufwand |
|-------|-------|---------|
| Phase 1: DB-Konsistenz | Migrations + Router | 4-6h |
| Phase 2: Frontend | UI + API | 4-5h |
| Phase 3: Testing | Integration + Deploy | 2-3h |
| **TOTAL** | | **10-14h** |
**Empfehlung:** Phase 1 zuerst (kritisch für DB-Konsistenz), dann Phase 2+3
---
## 8. Offene Fragen
**Q1:** Sollen wir Migration 015 (Semantic Matching) jetzt anlegen oder später?
- **Pro:** Komplett-System
- **Con:** OPTIONAL, braucht Vector-Embeddings (nicht kritisch)
- **Empfehlung:** SKIPPEN, erst bei Bedarf
**Q2:** Soll exercises.py komplett refactored werden oder nur Legacy-Felder entfernen?
- **Empfehlung:** Nur Legacy-Felder entfernen (minimal invasiv)
**Q3:** Data Layer in Shinkan anlegen (wie Mitai)?
- **Status:** Shinkan hat KEIN `data_layer/` Verzeichnis
- **Empfehlung:** SPÄTER, nicht Blocker für Importer
---
## 9. Issue #53 Learnings für Shinkan
**Aus Mitai übernehmen:**
1. ✅ Import darf nur Feld-Zuordnung + Typ-Konvertierung (bereits konform)
2. ✅ Keine fachliche Interpretation im Import (bereits konform)
3. ⏸️ Data Layer für Metriken-Berechnung (SPÄTER, separate Task)
**NICHT übernehmen:**
- ❌ Komplett-Refactoring jetzt (zu großer Scope)
- ❌ Chart-Endpoints jetzt (kein Bedarf)
**Fazit:** Shinkan Import ist bereits Issue #53 konform. Kein Action-Item.
---
## 10. Nächste Schritte (User-Approval erforderlich)
**Option A: Komplett-Durchlauf (empfohlen)**
1. Migrations 014-017 anlegen
2. exercises.py auf M:N umstellen
3. Frontend für Importer bauen
4. Testen + Deployen
**Aufwand:** 10-14h
**Option B: Minimaler Pfad (schnell, aber unvollständig)**
1. Nur Migration 014 anlegen (Legacy DROP)
2. exercises.py minimal fixen
3. Frontend SPÄTER
**Aufwand:** 4-6h, aber Frontend fehlt
**Option C: User entscheidet Priorität**
- Welche Phase zuerst?
- Migration 015 (Semantic Matching) jetzt oder später?
- exercises.py komplett refactorn oder minimal?
**Empfehlung:** Option A (Komplett-Durchlauf), weil:
- Saubere Datenbank (keine Legacy-Felder)
- Vollständiger Importer (Backend + Frontend)
- Issue #53 konform
- Basis für zukünftige Features
---
**Autor:** Claude Code
**Version:** 1.0
**Status:** Pending User-Approval
+17
View File
@@ -55,6 +55,23 @@ return {"error": "not found"}
return {"message": "Fehler", "success": False}
```
### 1.4 Mandanten & Zugriffsschicht (Shinkan / ACCESS_LAYER)
**Verbindlicher Rahmen:** `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`
**Medien-Assets (Archiv, Papierkorb, Promotion, Copyright, externer Speicher, geplante Inline-Verlinkung §11):** `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`
**Session-Handover (Ist + nächste Schritte):** `docs/HANDOVER.md`
**Fortlaufendes Inventar:** `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`
**Definition of Done für neue oder geänderte geschützte APIs**, sobald Daten **Verein**, **Sichtbarkeit** oder **mandantenbezogene Listen** betreffen:
1. Request-Kontext: `Depends(get_tenant_context)` (oder dokumentierte Ausnahme mit Kommentar `# ACCESS_LAYER exempt:` + Audit).
2. Lesen: gleiche Sichtbarkeitslogik wie vergleichbare Bibliotheks-/Planungsartefakte (`library_content_visibility_sql`, `exercise_visible_to_profile` / zentrale Helfer — nicht ad-hoc „alles aus der Tabelle“).
3. Schreiben: `assert_valid_governance_visibility` wo `visibility` / `club_id` gesetzt oder geändert wird.
4. Audit-Tabelle und bei Bedarf die EXEMPT-Liste im Script `backend/scripts/check_access_layer_hints.py` aktualisieren.
5. Optional vor Commit: `python backend/scripts/check_access_layer_hints.py` (mit `ACCESS_LAYER_STRICT=1` schlägt bei neuen Verstößen fehl).
Router ohne Vereinsbezug (z. B. globale Kataloge, Auth-Login) bleiben bewusst ohne `get_tenant_context`; sie stehen im Script auf der **EXEMPT**-Liste.
---
## 2. Versionskontrollsystem
+22 -7
View File
@@ -4,17 +4,32 @@ Diese Regeln IMMER befolgen. Sie basieren auf Erfahrungen aus der Entwicklung.
## Backend
### 1. Auth auf jeden Endpoint
### 1. Auth und Mandantenkontext (Shinkan)
**Jeder geschützte Endpoint braucht Auth.** Sofern der Endpoint **Vereinsdaten**, **visibility/club_id** oder **mandanten-gefilterte Listen** betrifft, zusätzlich **`TenantContext`** — nicht nur `require_auth` allein.
```python
# Jeder neue Endpoint braucht Auth:
@router.get("/neuer-endpoint")
def neuer_endpoint(session: dict = Depends(require_auth)):
pid = session['profile_id']
from tenant_context import TenantContext, get_tenant_context
@router.get("/beispiel")
def beispiel(tenant: TenantContext = Depends(get_tenant_context)):
pid = tenant.profile_id
role = tenant.global_role
club_ctx = tenant.effective_club_id # kann None sein (z. B. Plattform-Admin)
```
### 2. Profile-ID aus Session – nie aus Header
- **Bibliotheks-/Planungslisten:** Filter wie bestehende Module (`library_content_visibility_sql` oder gleiche Leseprüfung); keine vollständige Tabelle für normale Nutzer.
- **Schreiben:** `assert_valid_governance_visibility` aus `club_tenancy`, wenn `visibility` / `club_id` gesetzt werden.
- **Dokumentation:** Änderungen in `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` festhalten.
- **Ausnahmen** (z. B. reiner Login, globale Kataloge): Kommentar `# ACCESS_LAYER exempt: …` und ggf. Eintrag in `backend/scripts/check_access_layer_hints.py`.
Reine Plattform-Admin-Router (ohne Vereinskontext) können bei Bedarf weiter `Depends(require_auth)` nutzen — dann im Audit als „Plattform“ kennzeichnen.
### 2. Profile-ID aus TenantContext oder Session — nie aus freiem Header
```python
pid = session['profile_id'] # ✅
pid = tenant.profile_id # ✅ bei Depends(get_tenant_context)
# oder session['profile_id'] nur wenn Endpoint ausdrücklich ohne TenantContext (Ausnahme dokumentieren)
# Nicht: request.headers.get('X-Profile-Id') ❌
```
+2 -1
View File
@@ -10,7 +10,8 @@
1. Repo-Root: `CLAUDE.md` (Kontext, Links, Pflicht-Dokus)
2. Agent-Übersicht: **`.claude/README.md`** (Baum, wo was liegt)
3. Spez-Index: **`.claude/docs/README.md`**
4. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
4. **Session-Handover (aktuelle Prioritäten, Medien-Ist):** **`docs/HANDOVER.md`**
5. Aufgaben-Tracking: **Gitea** – Übersicht lokal: **`.claude/docs/GITEA_ISSUES_INDEX.md`** (regelmäßig refreshen nach Bedarf)
---
+36
View File
@@ -0,0 +1,36 @@
---
description: Mandanten & Governance — TenantContext, Sichtbarkeit, keine Schnellpfade
globs: backend/routers/*.py
alwaysApply: false
---
# Zugriffsschicht (Shinkan)
Vor neuen oder geänderten Endpoints in `backend/routers/` kurz prüfen:
1. **Pflichtlektüre** (bei inhaltsbezogenen APIs): `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` und `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md`.
2. **Auth**: kein geschützter Endpoint ohne `Depends(require_auth)` bzw. eingebettet in `Depends(get_tenant_context)` (der holt die Session bereits).
3. **Verein / Sichtbarkeit** (`visibility`, `club_id`, Mitglieder-Inhalte):
`tenant: TenantContext = Depends(get_tenant_context)` verwenden; Profile-ID aus `tenant.profile_id`, Rolle aus `tenant.global_role`.
4. **Bibliothekslisten** (Übungen, Vorlagen, Rahmenprogramme, Progressionsgraphen, gleiche Semantik): Filter über `library_content_visibility_sql(...)` bzw. gleiche Leseregel wie bestehende Module — nicht „alle Zeilen aus SELECT“.
5. **Schreiben mit Governance**: bei `visibility`/`club_id`-Änderungen `assert_valid_governance_visibility`; bei `club` ohne `club_id` im Body → `tenant.effective_club_id` oder klare 400-Hinweise (wie bei Übungen).
6. **Ausnahmen** nur mit kurzem Kommentar im Code: `# ACCESS_LAYER exempt: …` und Eintrag im Audit oder in `backend/scripts/check_access_layer_hints.py` (EXEMPT-Liste).
7. **Nach Merge**: eine Zeile `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` anpassen, wenn sich Tenant oder Governance ändert.
```python
# ❌ Schnellpfad: nur Session, obwohl Vereinsdaten betroffen
@router.get("/foo")
def foo(session=Depends(require_auth)):
...
# ✅ Konsistent zu clubs/exercises/planning
@router.get("/foo")
def foo(tenant: TenantContext = Depends(get_tenant_context)):
...
```
+47 -6
View File
@@ -1,25 +1,66 @@
# Database
# === .env neben der Jeweiligen docker-compose.*.yml kopieren ====================
# Docker Compose ersetzt ${VARIABLE} beim Start.
#
# Pro Umgebung eigene Datei (z. B. ~/docker/shinkan/.env für Prod,
# ~/docker/shinkan-dev/.env für Dev) — dieselben SCHLÜSSEL, unterschiedliche Werte.
# Kein separates DEV_APP_URL vs APP_URL: immer APP_URL, ALLOWED_ORIGINS, DB_*, …
# ─── Typische Werte PROD (docker-compose.yml) ─────────────────────────────────
# DB_NAME=shinkan
# DB_USER=shinkan_user
# DB_PASSWORD=…
# APP_URL=https://shinkan.jinkendo.de
# ALLOWED_ORIGINS=https://shinkan.jinkendo.de
# ENVIRONMENT=production
# SHINKAN_MEDIA_HOST=/shinkan-media
# MEDIA_ROOT=/app/media
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
# DB_NAME=shinkan_dev
# DB_USER=shinkan_dev
# DB_PASSWORD=dev_password
# APP_URL=https://dev.shinkan.jinkendo.de
# ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098
# ENVIRONMENT=development
# SHINKAN_MEDIA_HOST=/shinkan-media/dev
# MEDIA_ROOT=/app/media
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
DB_HOST=postgres
DB_PORT=5432
DB_NAME=shinkan
DB_USER=shinkan_user
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
# OpenRouter (KI - optional)
OPENROUTER_API_KEY=your_api_key_here
OPENROUTER_MODEL=anthropic/claude-sonnet-4
# SMTP (E-Mail)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=noreply@jinkendo.de
SMTP_PASS=your_smtp_password
SMTP_FROM=noreply@jinkendo.de
SMTP_SSL=
SMTP_STARTTLS=
AUTO_ADMIN_FIRST_USER=true
ADMIN_BOOTSTRAP_EMAILS=
# App
APP_URL=https://shinkan.jinkendo.de
ALLOWED_ORIGINS=https://shinkan.jinkendo.de
ENVIRONMENT=production
# Media Storage
MEDIA_DIR=/app/media
# Medien (Docker Compose): SHINKAN_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
# MEDIA_ROOT = gleicher Pfad im Container (muss mit dem Mount-Ziel übereinstimmen — FastAPI).
# Prod: Verzeichnis VOR erstem "docker compose up" anlegen (z. B. sudo mkdir -p …/prod).
# Wenn Docker meldet "chown … operation not permitted": oft NAS/NFS oder Rechte — lokalen Pfad nutzen.
SHINKAN_MEDIA_HOST=/shinkan-media
MEDIA_ROOT=/app/media
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
MEDIAWIKI_USER=Jinkendo
MEDIAWIKI_PASSWORD=CHANGE_ME
MEDIAWIKI_CATEGORY_EXERCISES=Übungen
MEDIAWIKI_CATEGORY_SKILLS=Fähigkeitsbeschreibung
MEDIAWIKI_CATEGORY_METHODS=Methodenbeschreibung
MEDIAWIKI_CATEGORY_MODELS=Reifegradmodelle
+1
View File
@@ -19,4 +19,5 @@ jobs:
docker compose -f docker-compose.dev-env.yml up -d
sleep 5
curl -sf http://localhost:8098/api/version && echo "✓ DEV API healthy"
curl -sf http://localhost:3098/api/version && echo "✓ DEV über Frontend-Nginx (wie Browser) healthy"
echo "=== Shinkan DEV Deploy complete ==="
+2 -1
View File
@@ -18,5 +18,6 @@ jobs:
docker compose build --no-cache
docker compose up -d
sleep 5
curl -sf http://localhost:8003/api/version && echo "✓ PROD API healthy"
curl -sf http://localhost:8003/api/version && echo "✓ PROD API (direkt) healthy"
curl -sf http://localhost:3003/api/version && echo "✓ PROD API über Frontend-Nginx (wie Browser) healthy"
echo "=== Shinkan PROD Deploy complete ==="
+130 -5
View File
@@ -3,11 +3,45 @@ name: Test Suite
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
workflow_run:
workflows: ["Deploy Development", "Deploy Production"]
types: [completed]
jobs:
# Wie Mitai-Jinkendo: pytest im laufenden backend-Container (Python aus Image, gleiche DB wie Deploy).
pytest-backend:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Backend pytest im deployten Container
run: |
EVENT_NAME="${{ github.event_name }}"
REF_NAME="${{ github.ref_name }}"
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
APP_DIR="/home/lars/docker/shinkan"
COMPOSE_FILE="docker-compose.yml"
if [ "$EVENT_NAME" = "workflow_run" ]; then
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
APP_DIR="/home/lars/docker/shinkan-dev"
COMPOSE_FILE="docker-compose.dev-env.yml"
fi
elif [ "$REF_NAME" = "develop" ]; then
APP_DIR="/home/lars/docker/shinkan-dev"
COMPOSE_FILE="docker-compose.dev-env.yml"
fi
cd "$APP_DIR"
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
pip install -r /app/requirements-dev.txt &&
cd /app &&
ACCESS_LAYER_STRICT=1 python scripts/check_access_layer_hints.py &&
python scripts/security_release_checks.py &&
ACCESS_LAYER_INTEGRATION=1 SKIP_DB_MIGRATE=1 python -m pytest tests -m 'not slow' -ra -vv --tb=short
"
lint-backend:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
@@ -57,7 +91,11 @@ jobs:
playwright-tests:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
needs: [lint-backend, build-frontend]
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
# Dev: Tests gegen bereits deployte URL (HTTPS, Reverse-Proxy). Prod: gleicher Ablauf.
env:
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -67,22 +105,109 @@ jobs:
with:
node-version: '20'
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
id: e2e
run: |
EVENT="${{ github.event_name }}"
WF_NAME="${{ github.event.workflow_run.name }}"
DEV_BASE="${{ env.E2E_TARGET_URL }}"
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
echo "mode=prod" >> $GITHUB_OUTPUT
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
else
echo "mode=dev" >> $GITHUB_OUTPUT
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
fi
- name: Dev /health abwarten
if: ${{ steps.e2e.outputs.mode == 'dev' }}
run: |
BASE="${{ steps.e2e.outputs.base_url }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 90); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
echo "Health OK (Versuch $i)"
exit 0
fi
sleep 2
done
echo "Timeout: Dev /health nicht erreichbar — Deploy / DNS / Firewall prüfen."
curl -v "$BASE/health" || true
exit 1
- name: Prod /health abwarten
if: ${{ steps.e2e.outputs.mode == 'prod' }}
run: |
BASE="${{ steps.e2e.outputs.base_url }}"
echo "Warte auf $BASE/health …"
for i in $(seq 1 60); do
if curl -sf "$BASE/health" >/dev/null 2>&1; then
echo "Health OK (Versuch $i)"
exit 0
fi
sleep 5
done
echo "Timeout: Prod /health nicht erreichbar"
curl -v "$BASE/health" || true
exit 1
- name: Testnutzer registrieren (Dev, nur wenn möglich)
if: ${{ steps.e2e.outputs.mode == 'dev' }}
env:
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
run: |
BASE="${{ steps.e2e.outputs.base_url }}"
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
exit 0
fi
curl -sf -X POST "$BASE/api/auth/register" \
-H "Content-Type: application/json" \
-d "{\"email\":\"${E2E_DEV_TEST_EMAIL}\",\"password\":\"${E2E_DEV_TEST_PASSWORD}\",\"name\":\"Playwright CI\"}" \
|| echo "(Register evtl. schon erfolgt oder Limits — Login-Test gilt trotzdem.)"
- name: Install Playwright
run: |
npm install -D @playwright/test
npm ci || npm install
npx playwright install --with-deps chromium
- name: Run Playwright tests
env:
TEST_EMAIL: lars@stommer.com
TEST_PASSWORD: 12345678
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
run: |
set -e
MODE="${{ steps.e2e.outputs.mode }}"
BASE_URL="${{ steps.e2e.outputs.base_url }}"
export PLAYWRIGHT_BASE_URL="$BASE_URL"
if [ "$MODE" = "prod" ]; then
export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
exit 1
fi
else
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
exit 1
fi
fi
mkdir -p screenshots
npx playwright test
echo "✓ Playwright tests passed"
- name: Upload test screenshots
if: failure()
uses: actions/upload-artifact@v4
# v4 ist auf Gitea (GHES-kompatibles Actions-Backend) oft nicht verfügbar
uses: actions/upload-artifact@v3
with:
name: playwright-screenshots
path: screenshots/
+25 -18
View File
@@ -5,9 +5,14 @@
> VOR jeder Implementierung lesen:
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` |
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
> | Zugriffsschicht (Multi-Tenancy, Governance) | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
> | Endpoint-Audit (Tenant/Governance) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
> | Cursor-Regel Zugriffsschicht | `.cursor/rules/access-layer.mdc` |
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
> | Setup-Dokument | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
> | Anforderungen | `.claude/docs/functional/SHINKAN_REQUIREMENTS.md` |
> | Medien-Archiv, Lifecycle, Inline (Plan §11) | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
> | Handover / nächste Session | **`docs/HANDOVER.md`** |
## Projekt-Übersicht
@@ -52,8 +57,8 @@ backend/
├── migrations/ # SQL-Migrationen (XXX_*.sql Pattern)
└── routers/ # Router-Module
auth · profiles · clubs · groups · skills · methods
exercises · training_units · training_programs
planning · import_wiki · admin · membership
exercises · exercise_progression_graphs · training_units · training_programs
planning · import_wiki · admin · membership · media_assets
frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation
@@ -74,18 +79,17 @@ frontend/src/
└── library/ # Auto-generierte Docs
```
## Aktuelle Version: v0.1.0 (Initial Setup)
## Aktuelle Version
**Status:** Initial Setup in Arbeit
**Branch:** develop
**Nächster Schritt:** Basis-Migrationen + Core-Router
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
### Updates (21.04.2026 - Initial Setup)
Kurz (Stand 2026-05-08): App **0.8.64**, DB‑Schema‑Version siehe **`backend/version.py`**; Kern: Übungen, Varianten, **Medien-Archiv & Bibliothek (`/media`)**, **Inline-Medien im Rich-Text** (Modal-Picker, Größenwahl, Drag&Drop + Auto-Scroll), Mandanten-Sync aktiver Verein, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md`, `docs/HANDOVER.md`, `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (§11 umgesetzt).
- **Repository:** Erstellt auf Gitea
- **Basis-Struktur:** Verzeichnisse angelegt
- **Von Mitai übernommen:** auth.py, db.py, db_init.py
- **Eigene Dateien:** version.py, CLAUDE.md
### Log (Auszug)
- 2026-05-07: **Medien** — zentrales Archiv (`media_assets`), Bibliothek-UI, Lifecycle/Papierkorb, `from-asset`, Speicherpfade `library/…`, Governance `official`/Copyright; **0.8.59** aktiver Verein UI/API-Sync — siehe `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12, `docs/HANDOVER.md`.
- 2026-05-05: Rahmen nur Bibliothek (**036**), Slot‑Ablauf = `training_units` + Sektionen (**037**), `POST /api/training-units/from-framework-slot`, keine `training_framework_slot_exercises` mehr — siehe `DATABASE_SCHEMA.md` / `FEATURES_DELIVERED_2026-Q2.md`.
- 2026-04-27: Übungsvarianten API/UI, Migration 030, Listen-UX-Suche, Admin-Upload-Limits — siehe `PROJECT_STATUS.md` und `docs/library/FEATURES_DELIVERED_2026-Q2.md`.
## Domänenmodell (MVP Core)
@@ -104,14 +108,13 @@ frontend/src/
- `exercises` - Übungen (Kernobjekt)
- `exercise_variants` - Übungsvarianten
- `exercise_skills` - M:N Übung ↔ Fähigkeit
- `exercise_media` - Medien (Bilder, Videos)
- `exercise_media` - Medien (Bilder, Videos); Zielbild Archiv & Lifecycle: **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**. **Inline im Fließtext** (Übungstexte) ist implementiert (Spec §11): Anker `exercise_media.id`, einheitlicher Render-Pfad.
**Trainingsplanung:**
- `training_templates` - Vorlagen / Standards
- `training_sections` - Trainingsabschnitte
- `section_exercises` - Übungen in Abschnitten
- `training_units` - Konkrete Trainingseinheiten
- `training_programs` - Trainingsprogramme
**Trainingsplanung / Rahmen:**
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
- `training_units` — Kalender‑Instanzen **und** Rahmen‑Slot‑Blueprints (`framework_slot_id` ab **037**)
- `training_framework_programs` + Ziele + Slots (Migration **035–036**) — Bibliotheks‑Rahmen
- Legacy: `training_templates` / `section_exercises` o. ä. — in älteren Skizzen; produktiver Pfad siehe Migrationen **006**/**031**
**Governance:**
- `content_change_requests` - Änderungsanfragen
@@ -200,6 +203,10 @@ ALLOWED_ORIGINS=https://shinkan.jinkendo.de
MEDIA_DIR=/app/media
```
## Produktions-/Sicherheitsaudit (Drift vermeiden)
Aktuelle Befunde und Umsetzungsstände: `.claude/docs/working/PRODUCTION_READINESS_AUDIT_2026-05.md` (Fortlaufend pflegen.)
## Kritische Regeln für Claude Code
### Must-Do:
+1
View File
@@ -13,6 +13,7 @@ Shinkan ist eine moderne Web- und Mobile-App für Kampfsport-Trainer und Vereine
- **Kataloge:** Fähigkeiten und Trainingsmethoden strukturiert verwalten
- **Standardisierung:** Vereinsstandards und wiederverwendbare Vorlagen
- **Freigabe:** Gesteuerte Veröffentlichung von Inhalten
- **Medien:** Zentrale **Medienbibliothek** (`/media`), Archiv mit Lifecycle/Papierkorb, Verknüpfung in Übungen — Norm: `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` · Einstieg: `docs/HANDOVER.md`
## Nicht in Shinkan
+1 -3
View File
@@ -13,8 +13,6 @@ import bcrypt
from db import get_db, get_cursor
print("[AUTH.PY] Module loaded - require_auth_flexible will be defined")
def hash_pin(pin: str) -> str:
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
@@ -117,7 +115,7 @@ def require_admin(x_auth_token: Optional[str] = Header(default=None)):
session = get_session(x_auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
if session['role'] != 'admin':
if session.get("role") not in ("admin", "superadmin"):
raise HTTPException(403, "Nur für Admins")
return session
+247
View File
@@ -0,0 +1,247 @@
"""
Vereins-Mandanten: Mitgliedschaften, aktiver Vereinskontext, einfache Berechtigungen.
Siehe .claude/docs/technical/MULTI_TENANCY_RBAC_ARCHITECTURE.md
"""
from typing import Any, Dict, List, Optional, Set
from fastapi import HTTPException
def is_platform_admin(role: Optional[str]) -> bool:
return (role or "").lower() in ("admin", "superadmin")
def is_superadmin(role: Optional[str]) -> bool:
return (role or "").lower() == "superadmin"
def club_ids_for_profile(cur, profile_id: int) -> Set[int]:
cur.execute(
"""
SELECT club_id FROM club_members
WHERE profile_id = %s AND status = 'active'
""",
(profile_id,),
)
return {r["club_id"] for r in cur.fetchall()}
def assert_club_member(cur, profile_id: int, club_id: int) -> None:
cur.execute(
"""
SELECT 1 FROM club_members
WHERE profile_id = %s AND club_id = %s AND status = 'active'
LIMIT 1
""",
(profile_id, club_id),
)
if not cur.fetchone():
raise HTTPException(status_code=403, detail="Keine Mitgliedschaft in diesem Verein")
def has_club_role(cur, profile_id: int, club_id: int, *role_codes: str) -> bool:
if not role_codes:
return False
cur.execute(
"""
SELECT 1
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.club_id = %s AND cm.status = 'active'
AND r.role_code IN ({ph})
LIMIT 1
""".format(ph=",".join(["%s"] * len(role_codes))),
(profile_id, club_id, *role_codes),
)
return cur.fetchone() is not None
def club_admin_shares_club_with_creator(
cur, club_admin_profile_id: int, creator_profile_id: int
) -> bool:
"""
True, wenn club_admin_profile_id in mindestens einem Verein die Rolle club_admin hat und
creator_profile_id dort ebenfalls aktives Mitglied ist (z. B. Löschen fremder privater Übungen).
"""
if club_admin_profile_id == creator_profile_id:
return False
cur.execute(
"""
SELECT 1
FROM club_members cm_admin
INNER JOIN club_member_roles r
ON r.club_member_id = cm_admin.id AND r.role_code = 'club_admin'
INNER JOIN club_members cm_creator
ON cm_creator.club_id = cm_admin.club_id
AND cm_creator.profile_id = %s
AND cm_creator.status = 'active'
WHERE cm_admin.profile_id = %s AND cm_admin.status = 'active'
LIMIT 1
""",
(creator_profile_id, club_admin_profile_id),
)
return cur.fetchone() is not None
def can_manage_club_org(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
"""Sparten/Gruppen/Struktur: Vereinsadmin oder Plattform-Admin."""
if is_platform_admin(global_role):
return True
return has_club_role(cur, profile_id, club_id, "club_admin")
def can_plan_in_club(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
"""Trainingsgruppe anlegen u.Ä.; Vereins-rollentrainer, Content-Editor, Spartenleitung …
Hinweis: ``content_editor`` ist derzeit zusammen mit ``trainer``/``division_lead`` in diesem
gemeinsamen Strang gebündelt — u.a. Vereinsübungen bearbeiten (s. exercises) und
Trainingsgruppen unter ``clubs``. Es gibt noch keine eigene Nur-Content-Guard pro Endpunkt.
"""
if is_platform_admin(global_role):
return True
return has_club_role(
cur, profile_id, club_id, "club_admin", "trainer", "content_editor", "division_lead"
)
def memberships_with_roles(cur, profile_id: int, active_only: bool = True) -> List[Dict[str, Any]]:
status_filter = "AND cm.status = 'active'" if active_only else ""
cur.execute(
f"""
SELECT c.id, c.name, c.abbreviation, c.status,
cm.status AS membership_status,
COALESCE(
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
ARRAY[]::varchar[]
) AS roles
FROM club_members cm
INNER JOIN clubs c ON c.id = cm.club_id
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s {status_filter}
GROUP BY c.id, c.name, c.abbreviation, c.status, cm.status
ORDER BY c.name
""",
(profile_id,),
)
out: List[Dict[str, Any]] = []
for row in cur.fetchall():
d = dict(row)
roles = d.get("roles") or []
if hasattr(roles, "tolist"):
roles = roles.tolist()
d["roles"] = list(roles)
out.append(d)
return out
def club_ids_for_profile_with_roles(cur, profile_id: int, *role_codes: str) -> Set[int]:
"""Vereins-IDs, in denen das Profil mindestens eine der Rollen hat."""
if not role_codes:
return set()
ph = ",".join(["%s"] * len(role_codes))
cur.execute(
f"""
SELECT DISTINCT cm.club_id
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.profile_id = %s AND cm.status = 'active'
AND r.role_code IN ({ph})
""",
(profile_id, *role_codes),
)
return {int(r["club_id"]) for r in cur.fetchall() if r.get("club_id") is not None}
_GOVERNANCE_VISIBILITY = frozenset({"private", "club", "official"})
def assert_valid_governance_visibility(
cur,
profile_id: int,
role: Optional[str],
visibility: str,
club_id: Optional[int],
) -> None:
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Superadmin."""
if visibility not in _GOVERNANCE_VISIBILITY:
raise HTTPException(status_code=400, detail="Ungültige visibility")
if visibility == "official" and not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Nur Superadmins dürfen offizielle Inhalte setzen",
)
if visibility == "club":
if club_id is None:
raise HTTPException(status_code=400, detail="club_id ist bei visibility=club erforderlich")
if is_platform_admin(role):
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Verein nicht gefunden")
else:
assert_club_member(cur, profile_id, club_id)
def library_content_visible_to_profile(
cur,
profile_id: int,
visibility: str,
content_club_id: Optional[int],
created_by: Optional[int],
global_role: Optional[str],
) -> bool:
"""Leserechte wie Übungen für alle Objekte mit visibility/club_id/created_by (Bibliothek & Co.)."""
return exercise_visible_to_profile(
cur, profile_id, visibility, content_club_id, created_by, global_role
)
def exercise_visible_to_profile(
cur,
profile_id: int,
visibility: str,
exercise_club_id: Optional[int],
created_by: Optional[int],
global_role: Optional[str],
) -> bool:
"""
Leserechte einer Übung (und analoger Bibliotheksobjekte).
Vereinsbezogene Inhalte (visibility club): aktiv nur mit **aktiver** Mitgliedschaft in diesem Verein.
Mitgliedschaft mit status **inactive** sperrt — auch für Plattform-/Super-Admins — solange eine
Mitgliedschaft existiert.
Ist man kein Mitglied dieses Vereins, behalten Plattform-Admins den bisherigen „Audit“-Zugang
zum Vereinskontext ohne eigene Mitgliedschaft.
"""
vis = (visibility or "").strip().lower()
plat = is_platform_admin(global_role)
pid = int(profile_id)
if vis == "official":
return True
if created_by is not None and int(created_by) == pid:
return True
if vis == "private":
return plat
if vis != "club":
return False
if exercise_club_id is None:
return False
try:
ecid = int(exercise_club_id)
except (TypeError, ValueError):
return False
cur.execute(
"""
SELECT cm.status
FROM club_members cm
WHERE cm.profile_id = %s AND cm.club_id = %s
LIMIT 1
""",
(pid, ecid),
)
row = cur.fetchone()
if row is None:
return plat
st_raw = row["status"] if isinstance(row, dict) else row[0]
return str(st_raw or "active").strip().lower() == "active"
+16 -16
View File
@@ -32,13 +32,13 @@ def wait_for_postgres(max_retries=30):
try:
conn = get_connection()
conn.close()
print("✓ PostgreSQL ready")
print("[OK] PostgreSQL ready")
return True
except OperationalError:
print(f" Waiting for PostgreSQL... (attempt {i}/{max_retries})")
time.sleep(2)
print(f"✗ PostgreSQL not ready after {max_retries} attempts")
print(f"[FAIL] PostgreSQL not ready after {max_retries} attempts")
return False
def check_table_exists(table_name="profiles"):
@@ -71,10 +71,10 @@ def load_schema(schema_file="/app/schema.sql"):
conn.commit()
cur.close()
conn.close()
print("✓ Schema loaded from schema.sql")
print("[OK] Schema loaded from schema.sql")
return True
except Exception as e:
print(f"✗ Error loading schema: {e}")
print(f"[FAIL] Error loading schema: {e}")
return False
def get_profile_count():
@@ -146,10 +146,10 @@ def apply_migration(filepath, filename):
conn.commit()
cur.close()
conn.close()
print(f" ✓ Applied: {filename}")
print(f" [OK] Applied: {filename}")
return True
except Exception as e:
print(f" ✗ Failed to apply {filename}: {e}")
print(f" [FAIL] Failed to apply {filename}: {e}")
return False
def run_migrations(migrations_dir="/app/migrations"):
@@ -158,7 +158,7 @@ def run_migrations(migrations_dir="/app/migrations"):
import re
if not os.path.exists(migrations_dir):
print("✓ No migrations directory found")
print("[OK] No migrations directory found")
return True
# Ensure migration tracking table exists
@@ -174,7 +174,7 @@ def run_migrations(migrations_dir="/app/migrations"):
migration_files = [f for f in all_files if migration_pattern.match(os.path.basename(f))]
if not migration_files:
print("✓ No migration files found")
print("[OK] No migration files found")
return True
# Apply pending migrations
@@ -185,7 +185,7 @@ def run_migrations(migrations_dir="/app/migrations"):
pending.append((filepath, filename))
if not pending:
print(f"✓ All {len(applied)} migrations already applied")
print(f"[OK] All {len(applied)} migrations already applied")
return True
print(f" Found {len(pending)} pending migration(s)...")
@@ -211,12 +211,12 @@ if __name__ == "__main__":
if not load_schema():
sys.exit(1)
else:
print("✓ Schema already exists")
print("[OK] Schema already exists")
# Run migrations
print("\nRunning database migrations...")
if not run_migrations():
print("✗ Migration failed")
print("[FAIL] Migration failed")
sys.exit(1)
# Check for migration
@@ -232,14 +232,14 @@ if __name__ == "__main__":
from migrate_to_postgres import main as migrate
migrate()
except Exception as e:
print(f"✗ Migration failed: {e}")
print(f"[FAIL] Migration failed: {e}")
sys.exit(1)
elif os.path.exists(sqlite_db) and profile_count > 0:
print(f"⚠ SQLite DB exists but PostgreSQL already has {profile_count} profiles")
print(f"[WARN] SQLite DB exists but PostgreSQL already has {profile_count} profiles")
print(" Skipping migration (already migrated)")
elif not os.path.exists(sqlite_db):
print("✓ No SQLite database found (fresh install or already migrated)")
print("[OK] No SQLite database found (fresh install or already migrated)")
else:
print("✓ No migration needed")
print("[OK] No migration needed")
print("\n✓ Database initialization complete")
print("\n[OK] Database initialization complete")
+101
View File
@@ -0,0 +1,101 @@
"""
Übungs-Fließtext: Inline-Verweise auf exercise_media.id (MEDIA_ASSETS_AND_ARCHIVE_SPEC §11).
- Kurzsyntax beim Speichern → kanonisches <span data-shinkan-exercise-media="…">.
- Verweise müssen für die betreffende Übung gültige exercise_media-Zeilen sein.
"""
from __future__ import annotations
import re
from typing import FrozenSet, Optional, Set
from fastapi import HTTPException
# {{exerciseMedia:123}} (Whitespace tolerant, case-insensitive Schlüssel)
_BRACE_PATTERN = re.compile(r"\{\{\s*exerciseMedia\s*:\s*(\d+)\s*\}\}", re.IGNORECASE)
# bereits gespeichertes Markup (einfache Anführungszeichen-varianten durch Regex abgedeckt)
_DATA_ATTR_PATTERN = re.compile(r'data-shinkan-exercise-media\s*=\s*["\']?(\d+)["\']?', re.IGNORECASE)
RICH_HTML_EXERCISE_FIELDS: FrozenSet[str] = frozenset(
{"summary", "goal", "execution", "preparation", "trainer_notes"}
)
def normalize_inline_exercise_media_markup(html: Optional[str]) -> Optional[str]:
"""Wandelt {{exerciseMedia:id}} in kanonisches span mit data-shinkan-exercise-media."""
if html is None:
return None
if not isinstance(html, str):
html = str(html)
stripped = html.strip()
if not stripped:
return html
def _repl(match: re.Match) -> str:
mid = int(match.group(1))
return (
f'<span data-shinkan-exercise-media="{mid}" data-shinkan-exercise-media-size="medium" '
f'class="shinkan-inline-media"></span>'
)
return _BRACE_PATTERN.sub(_repl, html)
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
"""Sammelt alle referenzierten exercise_media.ids aus Kurzsyntax und kanonischem Span."""
if html is None or not isinstance(html, str):
return set()
if not html.strip():
return set()
ids: Set[int] = set()
ids.update(int(m) for m in _BRACE_PATTERN.findall(html))
ids.update(int(m) for m in _DATA_ATTR_PATTERN.findall(html))
return ids
def assert_no_inline_media_references_on_create(ids: Set[int]) -> None:
"""Neue Übung hat noch keine exercise_media-Zeilen — Platzhalter verboten."""
if not ids:
return
raise HTTPException(
status_code=400,
detail={
"code": "INLINE_EXERCISE_MEDIA_ON_CREATE",
"message": (
"Medienverweise im Fließtext sind beim ersten Anlegen der Übung nicht möglich. "
"Bitte Übung ohne Platzhalter speichern, Medien hochladen oder verknüpfen "
"und die Verweise dann bearbeiten ({{exerciseMedia:id}} oder „Medium einfügen“)."
),
"invalid_exercise_media_ids": sorted(ids),
},
)
def validate_inline_exercise_media_ids_for_exercise(cur, exercise_id: int, ids: Set[int]) -> None:
"""Prüft, dass jede genannte exercise_media.id zu dieser Übung gehört."""
if not ids:
return
sid = sorted(ids)
ph = ",".join(["%s"] * len(sid))
cur.execute(
f"SELECT id FROM exercise_media WHERE exercise_id = %s AND id IN ({ph})",
(exercise_id, *sid),
)
found = set()
for row in cur.fetchall():
rid = row["id"] if isinstance(row, dict) else row[0]
found.add(int(rid))
missing = ids - found
if missing:
raise HTTPException(
status_code=400,
detail={
"code": "INLINE_EXERCISE_MEDIA_INVALID",
"message": "Ein oder mehrere eingebettete Medien-Verweise gehören nicht zu dieser Übung.",
"invalid_exercise_media_ids": sorted(missing),
},
)
+159 -17
View File
@@ -3,31 +3,80 @@ Shinkan Jinkendo - Main Application Entry Point
Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
"""
from fastapi import FastAPI
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
import os
import sys
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
# Run database migrations on startup
try:
import run_migrations
run_migrations.main()
print("✓ Database migrations completed")
except Exception as e:
print(f"⚠ Warning: Migration error: {e}")
print(" Continuing startup - migrations may need manual intervention")
def _is_production_environment() -> bool:
return os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod")
def _public_openapi_enabled() -> bool:
return os.getenv("PUBLIC_OPENAPI", "").strip().lower() in ("1", "true", "yes")
def _health_ready_public_detail_enabled() -> bool:
"""In Prod standardmäßig keine Tabellen-/Migrations-Details (Information Disclosure)."""
return os.getenv("HEALTH_READY_PUBLIC_DETAIL", "").strip().lower() in ("1", "true", "yes")
# Run database migrations before API start — halbes Schema ist schlimmer als kein Start
# (run_migrations: pending *.sql in einer Transaktion pro Datei, Buchführung schema_migrations)
# Lokal ohne DB / nur Tests: SKIP_DB_MIGRATE=1
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
print("[SKIP_DB_MIGRATE] Migrationen uebersprungen (nur fuer Entwicklung ohne DB)")
else:
try:
import run_migrations
rc = run_migrations.main()
if rc != 0:
print(f"[FAIL] Datenbank-Migration fehlgeschlagen (Exit-Code {rc}). Start abgebrochen.")
sys.exit(1)
print("[OK] Database migrations completed")
except SystemExit:
raise
except Exception as e:
print(f"[FAIL] Migration-Laufzeitfehler: {e}")
sys.exit(1)
from routers.auth import limiter as auth_rate_limiter
# OpenAPI: in Produktion standardmäßig aus (Schema nicht öffentlich). Notfall: PUBLIC_OPENAPI=1
_expose_docs = (not _is_production_environment()) or _public_openapi_enabled()
_openapi_url = "/openapi.json" if _expose_docs else None
_docs_url = "/docs" if _expose_docs else None
_redoc_url = "/redoc" if _expose_docs else None
# Initialize FastAPI app
app = FastAPI(
title="Shinkan Jinkendo API",
description="Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung",
version=APP_VERSION
version=APP_VERSION,
openapi_url=_openapi_url,
docs_url=_docs_url,
redoc_url=_redoc_url,
)
# CORS Configuration
ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS", "http://localhost:3098").split(",")
# SlowAPI: Rate Limits auf /api/auth/* (Decorator in routers/auth.py)
app.state.limiter = auth_rate_limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# CORS — kommaseparierte Liste (z. B. https://dev.shinkan… und http://192.168.x.x:3098)
_cors_raw = os.getenv("ALLOWED_ORIGINS", "http://localhost:3098")
ALLOWED_ORIGINS = [o.strip() for o in _cors_raw.split(",") if o.strip()]
app.add_middleware(
CORSMiddleware,
@@ -37,7 +86,13 @@ app.add_middleware(
allow_headers=["*"],
)
# TODO: Initialize Database with migrations
@app.middleware("http")
async def add_api_security_headers(request: Request, call_next):
"""Konsistente Basis-Header auch für rein JSON-Responses (MIME-Sniffing)."""
response = await call_next(request)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
return response
# Version Endpoint (public, no auth)
@app.get("/api/version")
@@ -58,27 +113,114 @@ def health_check():
"""Health check endpoint"""
return {"status": "healthy", "version": APP_VERSION}
@app.get("/api/health/ready")
def health_ready():
"""
Verbindung + Kern-Tabellen prüfen (ohne Login).
Nutzen bei Prod-Debugging: wenn schema_complete=false, Migrationen nicht vollständig.
"""
from db import get_db, get_cursor
REQUIRED = (
"schema_migrations",
"skills",
"skill_main_categories",
"skill_categories",
"maturity_models",
"sessions",
"club_members",
"club_member_roles",
)
tables: dict = {}
err: Optional[str] = None
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT 1")
for tbl in REQUIRED:
cur.execute(
"""
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = %s
)
""",
(tbl,),
)
row = cur.fetchone()
tables[tbl] = bool(next(iter(row.values()))) if row else False
migration_count = 0
if tables.get("schema_migrations"):
cur.execute("SELECT COUNT(*)::int FROM schema_migrations")
mig_row = cur.fetchone()
migration_count = (
int(list(mig_row.values())[0]) if mig_row is not None else 0
)
except Exception as e:
err = str(e)
migration_count = 0
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
body = {
"status": "ready" if complete else "degraded",
"database": err is None,
"detail": err,
"schema_complete": complete,
"tables": tables,
"schema_migrations_count": migration_count,
}
if _is_production_environment() and not _health_ready_public_detail_enabled():
return {
"status": body["status"],
"database": body["database"],
"schema_complete": body["schema_complete"],
}
return body
# Root Endpoint
@app.get("/")
def read_root():
"""Root endpoint - API info"""
return {
out = {
"app": "Shinkan Jinkendo API",
"version": APP_VERSION,
"docs": "/docs",
"health": "/health"
"health": "/health",
}
if _expose_docs:
out["docs"] = "/docs"
return out
# Register routers
from routers import auth, profiles, exercises, clubs, skills, training_planning, catalogs
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
app.include_router(auth.router)
app.include_router(profiles.router)
app.include_router(exercises.router)
app.include_router(exercise_progression_graphs.router)
app.include_router(clubs.router)
app.include_router(club_memberships.router)
app.include_router(club_join_requests.router)
app.include_router(admin_users.router)
app.include_router(platform_media_storage.router)
app.include_router(media_assets.router)
app.include_router(skills.router)
app.include_router(training_planning.router)
app.include_router(training_framework_programs.router)
app.include_router(catalogs.router)
app.include_router(maturity_models.router)
app.include_router(matrix_stack_bundle.router)
app.include_router(import_wiki.router)
app.include_router(import_wiki_admin.router)
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
# Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
Path(_media_dir).mkdir(parents=True, exist_ok=True)
if os.getenv("ALLOW_PUBLIC_MEDIA_STATIC", "").strip().lower() in ("1", "true", "yes"):
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
if __name__ == "__main__":
import uvicorn
+305
View File
@@ -0,0 +1,305 @@
"""
Medien-Lebenszyklus (Papierkorb) — siehe MEDIA_ASSETS_AND_ARCHIVE_SPEC.md §5.
"""
from __future__ import annotations
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from fastapi import HTTPException
from club_tenancy import can_manage_club_org, is_platform_admin, is_superadmin
from db import r2d
from media_storage import get_effective_media_root, path_under_media_root
logger = logging.getLogger(__name__)
LC_ACTIVE = "active"
LC_TRASH_SOFT = "trash_soft"
LC_TRASH_HIDDEN = "trash_hidden"
SOFT_TO_HIDDEN_DAYS = max(1, int(os.getenv("MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS", "30")))
HIDDEN_TO_PURGE_DAYS = max(1, int(os.getenv("MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS", "90")))
def assert_can_manage_media_asset_lifecycle(cur: Any, tenant: Any, asset: dict) -> None:
"""
Papierkorb Stufe 2 / Recovery / Reaktivierung — nicht für trash_soft (siehe assert_can_trash_soft).
§5.2: official nur Superadmin; club Vereinsorga; privat nur Uploader (Plattform-Admin sonst wie bisher).
"""
profile_id = tenant.profile_id
role = (tenant.global_role or "").strip().lower()
vis = (asset.get("visibility") or "private").strip().lower()
if vis == "official":
if not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Offizielle Medien dürfen nur von Superadmins geändert oder gelöscht werden",
)
return
if is_platform_admin(role):
return
uid = asset.get("uploaded_by_profile_id")
if vis == "private":
if uid is not None and int(uid) == int(profile_id):
return
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
if vis == "club":
cid = asset.get("club_id")
if cid is None:
raise HTTPException(status_code=403, detail="Ungültiges Vereins-Medium")
if can_manage_club_org(cur, profile_id, int(cid), role):
return
raise HTTPException(status_code=403, detail="Nur Vereinsorganisation/Plattform-Admin")
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
def assert_can_trash_soft(cur: Any, tenant: Any, asset: dict) -> None:
"""
Aktiv → Papierkorb (Stufe 1). Trainer: nur eigene private Uploads.
Vereinsmedien: Vereinsorga; official: nur Superadmin; Plattform-Admin: sonst wie Verein/privat.
"""
role_raw = tenant.global_role
role = (role_raw or "").strip().lower()
if is_superadmin(role):
return
vis = (asset.get("visibility") or "private").strip().lower()
if vis == "official":
raise HTTPException(
status_code=403,
detail="Offizielle Medien dürfen nur von Superadmins in den Papierkorb gelegt werden",
)
if is_platform_admin(role):
return
uid = asset.get("uploaded_by_profile_id")
cid = asset.get("club_id")
pid = int(tenant.profile_id)
if vis == "private":
if uid is not None and int(uid) == pid:
return
raise HTTPException(
status_code=403,
detail="Nur eigene private Medien dürfen in den Papierkorb",
)
if vis == "club":
if cid is not None and can_manage_club_org(cur, pid, int(cid), role_raw):
return
raise HTTPException(
status_code=403,
detail="Nur Vereinsorganisation darf Vereinsmedien in den Papierkorb legen",
)
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Medium")
def assert_can_edit_media_asset_metadata(cur: Any, tenant: Any, asset: dict) -> None:
"""PATCH Metadaten / Sichtbarkeit — gleiche Stufen wie Lifecycle (ohne Papierkorb)."""
assert_can_manage_media_asset_lifecycle(cur, tenant, asset)
def superadmin_force_lifecycle_state(cur: Any, conn: Any, asset_id: int, target: str) -> dict:
"""Nur Superadmin: Zustand direkt setzen."""
if target not in (LC_ACTIVE, LC_TRASH_SOFT, LC_TRASH_HIDDEN):
raise HTTPException(status_code=400, detail="Ungültiger Ziel-Lifecycle")
if target == LC_ACTIVE:
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, updated_at = NOW(),
trash_soft_at = NULL, trash_hidden_at = NULL, purge_after_at = NULL
WHERE id = %s
RETURNING id, lifecycle_state""",
(LC_ACTIVE, asset_id),
)
elif target == LC_TRASH_SOFT:
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, trash_soft_at = COALESCE(trash_soft_at, NOW()),
trash_hidden_at = NULL, purge_after_at = NULL, updated_at = NOW()
WHERE id = %s
RETURNING id, lifecycle_state, trash_soft_at""",
(LC_TRASH_SOFT, asset_id),
)
else:
pa = datetime.now(timezone.utc) + timedelta(days=HIDDEN_TO_PURGE_DAYS)
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, trash_hidden_at = NOW(),
purge_after_at = %s, updated_at = NOW(),
trash_soft_at = COALESCE(trash_soft_at, NOW())
WHERE id = %s
RETURNING id, lifecycle_state, trash_hidden_at, purge_after_at""",
(LC_TRASH_HIDDEN, pa, asset_id),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
conn.commit()
return r2d(row)
def superadmin_hard_delete_media_asset(cur: Any, conn: Any, asset_id: int) -> bool:
"""Nur Superadmin: Zeile + Datei unabhängig vom Lifecycle entfernen."""
cur.execute(
"SELECT id, storage_key FROM media_assets WHERE id = %s",
(asset_id,),
)
row = cur.fetchone()
if not row:
return False
asset = r2d(row)
cur.execute("DELETE FROM exercise_media WHERE media_asset_id = %s", (asset_id,))
purge_asset_filesystem(cur, asset)
cur.execute("DELETE FROM media_assets WHERE id = %s", (asset_id,))
conn.commit()
return True
def fetch_media_asset_row(cur: Any, asset_id: int) -> Optional[dict]:
cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
storage_key, storage_backend, trash_soft_at, trash_hidden_at, purge_after_at
FROM media_assets WHERE id = %s""",
(asset_id,),
)
row = cur.fetchone()
return r2d(row) if row else None
def purge_asset_filesystem(cur: Any, asset: dict) -> None:
sk = asset.get("storage_key")
if not sk:
return
root = get_effective_media_root(cur)
p = path_under_media_root(root, str(sk))
if p and p.is_file():
try:
p.unlink()
except OSError as e:
logger.warning("Physische Medien-Löschung fehlgeschlagen: %s", e)
def purge_media_asset(cur: Any, conn: Any, asset_id: int) -> bool:
"""Löscht Verknüpfungen, Datei und DB-Zeile. Returns True wenn ausgeführt."""
cur.execute(
"""SELECT id, storage_key FROM media_assets
WHERE id = %s AND lifecycle_state = %s""",
(asset_id, LC_TRASH_HIDDEN),
)
row = cur.fetchone()
if not row:
return False
asset = r2d(row)
cur.execute("DELETE FROM exercise_media WHERE media_asset_id = %s", (asset_id,))
purge_asset_filesystem(cur, asset)
cur.execute("DELETE FROM media_assets WHERE id = %s", (asset_id,))
conn.commit()
return True
def transition_to_trash_soft(cur: Any, conn: Any, asset_id: int) -> dict:
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, trash_soft_at = NOW(), updated_at = NOW(),
trash_hidden_at = NULL, purge_after_at = NULL
WHERE id = %s AND lifecycle_state = %s
RETURNING id, lifecycle_state, trash_soft_at""",
(LC_TRASH_SOFT, asset_id, LC_ACTIVE),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=400, detail="Nur aktive Medien können in den Papierkorb")
conn.commit()
return r2d(row)
def reactivate_media_asset_from_trash(cur: Any, conn: Any, asset_id: int) -> dict:
"""
Stufe 1 oder 2 → wieder aktiv (z. B. erneuter Upload derselben Datei / explizite Wiederherstellung).
"""
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, updated_at = NOW(),
trash_soft_at = NULL, trash_hidden_at = NULL, purge_after_at = NULL
WHERE id = %s AND lifecycle_state IN (%s, %s)
RETURNING id, lifecycle_state""",
(LC_ACTIVE, asset_id, LC_TRASH_SOFT, LC_TRASH_HIDDEN),
)
row = cur.fetchone()
if not row:
raise HTTPException(
status_code=400,
detail="Nur Medien aus dem Papierkorb (Stufe 1 oder 2) können reaktiviert werden",
)
conn.commit()
return r2d(row)
def transition_to_trash_hidden(cur: Any, conn: Any, asset_id: int, *, set_purge_after: Optional[datetime] = None) -> dict:
now = datetime.now(timezone.utc)
if set_purge_after is None:
set_purge_after = now + timedelta(days=HIDDEN_TO_PURGE_DAYS)
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, trash_hidden_at = NOW(), updated_at = NOW(),
purge_after_at = %s
WHERE id = %s AND lifecycle_state IN (%s, %s)
RETURNING id, lifecycle_state, trash_hidden_at, purge_after_at""",
(LC_TRASH_HIDDEN, set_purge_after, asset_id, LC_ACTIVE, LC_TRASH_SOFT),
)
row = cur.fetchone()
if not row:
raise HTTPException(
status_code=400,
detail="Nur aktive oder Papierkorb-Stufe-1 Medien können ausgeblendet werden",
)
conn.commit()
return r2d(row)
def transition_recover_from_hidden(cur: Any, conn: Any, asset_id: int) -> dict:
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, updated_at = NOW(),
trash_hidden_at = NULL, purge_after_at = NULL
WHERE id = %s AND lifecycle_state = %s
RETURNING id, lifecycle_state, trash_soft_at""",
(LC_TRASH_SOFT, asset_id, LC_TRASH_HIDDEN),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=400, detail="Nur ausgeblendete Medien können zurückgestuft werden")
conn.commit()
return r2d(row)
def run_retention_pass(cur: Any, conn: Any) -> dict:
"""
Automatik: trash_soft älter als SOFT_TO_HIDDEN_DAYS → trash_hidden;
trash_hidden mit purge_after_at in der Vergangenheit → purge.
"""
cutoff_soft = datetime.now(timezone.utc) - timedelta(days=SOFT_TO_HIDDEN_DAYS)
cur.execute(
"""UPDATE media_assets
SET lifecycle_state = %s, trash_hidden_at = NOW(), updated_at = NOW(),
purge_after_at = NOW() + (%s * INTERVAL '1 day')
WHERE lifecycle_state = %s AND trash_soft_at IS NOT NULL AND trash_soft_at <= %s
RETURNING id""",
(LC_TRASH_HIDDEN, HIDDEN_TO_PURGE_DAYS, LC_TRASH_SOFT, cutoff_soft),
)
n_hidden = len(cur.fetchall())
conn.commit()
cur.execute(
"""SELECT id FROM media_assets
WHERE lifecycle_state = %s AND purge_after_at IS NOT NULL AND purge_after_at <= NOW()""",
(LC_TRASH_HIDDEN,),
)
purge_ids = [r2d(r)["id"] for r in cur.fetchall()]
purged = 0
for aid in purge_ids:
if purge_media_asset(cur, conn, int(aid)):
purged += 1
return {"moved_to_hidden": n_hidden, "purged": purged}
+229
View File
@@ -0,0 +1,229 @@
"""Effektives Medien-Wurzelverzeichnis (MEDIA_ROOT + Superadmin-relativer Pfad). Siehe MEDIA_ASSETS_AND_ARCHIVE_SPEC.md §7.1."""
from __future__ import annotations
import os
import re
import shutil
import unicodedata
from pathlib import Path
from typing import Any, Optional
_CLUB_SLUG_TRANS = str.maketrans(
{
"ä": "ae",
"ö": "oe",
"ü": "ue",
"ß": "ss",
"Ä": "ae",
"Ö": "oe",
"Ü": "ue",
}
)
def _default_media_root() -> Path:
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
def normalize_local_relative_root(raw: str) -> str:
s = (raw or "").strip().replace("\\", "/")
s = s.strip("/")
if not s:
return ""
if ".." in s.split("/"):
raise ValueError("Pfad darf nicht '..' enthalten")
if s.startswith("/"):
raise ValueError("Nur relativer Pfad erlaubt")
return s
def get_effective_media_root(cur: Any) -> Path:
"""
MEDIA_ROOT aus ENV mit optionalem local_relative_root aus platform_media_storage (id=1).
"""
base = _default_media_root().resolve()
rel = ""
try:
cur.execute(
"SELECT local_relative_root FROM platform_media_storage WHERE id = 1",
)
row = cur.fetchone()
if row is not None:
v = row["local_relative_root"] if isinstance(row, dict) else row[0]
rel = normalize_local_relative_root(str(v or ""))
except Exception:
rel = ""
if not rel:
return base
return (base / rel).resolve()
def library_media_kind_dir(mime_type: Optional[str], ext: str) -> str:
"""
Unterordner unter library/* — an API-Filter media_kind angelehnt (image/video/pdf/other).
Bei fehlendem MIME wird anhand der Dateiendung geraten (letzte Instanz: other).
"""
m = (mime_type or "").strip().lower()
x = (ext or "").strip().lower()
if x and not x.startswith("."):
x = "." + x
if m.startswith("image/"):
return "image"
if m.startswith("video/"):
return "video"
if m == "application/pdf" or (m and "pdf" in m):
return "pdf"
if x in (
".jpg",
".jpeg",
".png",
".gif",
".webp",
".heic",
".heif",
".bmp",
".svg",
".avif",
):
return "image"
if x in (".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"):
return "video"
if x == ".pdf":
return "pdf"
return "other"
def library_club_path_segment(club_id: int, club_name: Optional[str]) -> str:
"""
Ein Verzeichnissegment pro Verein: aus Anzeigenamen abgeleitet + „-c{id}“ für Eindeutigkeit
(Umbenennung, Kollisionen nach Slugify). Nur [a-z0-9-], keine Pfad-Sonderzeichen.
Fehlt der Name / Slug leer → „verein-c{id}“.
"""
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
raw = unicodedata.normalize("NFKC", (club_name or "").strip()).translate(_CLUB_SLUG_TRANS).lower()
raw = re.sub(r"[^a-z0-9]+", "-", raw)
raw = raw.strip("-")
if len(raw) > 48:
raw = raw[:48].rstrip("-")
if not raw:
base = f"verein-c{cid}"
else:
base = f"{raw}-c{cid}"
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", base):
raise ValueError("Ungültiger abgeleiteter Vereins-Ordnername")
return base
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
if not key or ".." in key.split("/"):
return None
p = (media_root / key).resolve()
try:
p.relative_to(media_root.resolve())
except ValueError:
return None
return p
def library_storage_key(
visibility: str,
club_id: Optional[int],
sha256_hex: str,
ext: str,
*,
uploader_profile_id: Optional[int] = None,
mime_type: Optional[str] = None,
club_name: Optional[str] = None,
) -> str:
"""
Relativer Speicherpfad unter MEDIA_ROOT für lokale media_assets.
- official → library/official/{kind}/{sha256}{ext}
- club (vereinsgeteilt) → library/{vereins-segment}/{kind}/{sha256}{ext}
- private → dieselbe Ordnerlogik wie Verein: library/{vereins-segment}/{kind}/{sha}.u{profile}{ext}
Dateiname bei private: „{sha}.u{profile_id}{ext}“ (nicht Unterordner u{…}), damit Ordnerstruktur wie bei „Verein“.
Vereins-Segment: aus club_name abgeleitet + „-c{club_id}“ — siehe library_club_path_segment.
kind ∈ {image, video, pdf, other} — siehe library_media_kind_dir.
Kein Ordnername „private“ auf der Platte. Private Dateien unterscheiden sich nur im Dateinamen (.u{Profil} vor Endung).
"""
vis = (visibility or "private").strip().lower()
if vis not in ("private", "club", "official"):
raise ValueError(f"Ungültige Sichtbarkeit für Speicherpfad: {visibility!r}")
sha = (sha256_hex or "").strip().lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
raise ValueError("sha256_hex muss 64 Hex-Zeichen sein")
e = (ext or "").strip()
if not e:
e = ".bin"
if not e.startswith("."):
e = "." + e
if ".." in e or "/" in e or "\\" in e or "\x00" in e:
raise ValueError("Ungültige Dateiendung")
kind = library_media_kind_dir(mime_type, e)
e = e[:16]
club_blob = f"{kind}/{sha}{e}"
if vis == "official":
return f"library/official/{club_blob}"
if club_id is None:
raise ValueError("Verein (club_id) ist für diese Sichtbarkeit auf der Platte erforderlich")
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
club_seg = library_club_path_segment(cid, club_name)
if vis == "club":
return f"library/{club_seg}/{club_blob}"
if uploader_profile_id is None:
raise ValueError("uploader_profile_id ist für private Archiv-Medien erforderlich")
up = int(uploader_profile_id)
if up < 1:
raise ValueError("uploader_profile_id muss positiv sein")
priv_name = f"{sha}.u{up}{e}"
return f"library/{club_seg}/{kind}/{priv_name}"
def relocate_local_media_file(media_root: Path, old_storage_key: str, new_storage_key: str) -> None:
"""
Physisches Verschieben bei geändertem library_*-Pfad (z. B. nach PATCH visibility/club_id).
- Kein Op, wenn Quelle fehlt aber Ziel bereits existiert (idempotent).
- Erwartet storage_backend=local; Aufrufer prüft das.
"""
if (old_storage_key or "").replace("\\", "/").lstrip("/") == (new_storage_key or "").replace(
"\\", "/"
).lstrip("/"):
return
old_p = path_under_media_root(media_root, old_storage_key)
new_p = path_under_media_root(media_root, new_storage_key)
if old_p is None or new_p is None:
raise ValueError("Ungültiger Speicherpfad (Path-Traversal)")
if new_p.is_file():
if not old_p.is_file():
return
if old_p.resolve() == new_p.resolve():
return
raise FileExistsError(f"Zieldatei existiert bereits: {new_storage_key}")
if not old_p.is_file():
raise FileNotFoundError(f"Medien-Quelldatei nicht gefunden: {old_storage_key}")
new_p.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(old_p), str(new_p))
@@ -0,0 +1,112 @@
-- Migration 012: Exercise Training Characters (M:N) + Trainer Contexts
-- Author: Claude Code
-- Date: 2026-04-23
-- Purpose: Add M:N relationship for training characters and trainer profile system
DO $$
BEGIN
-- ============================================================================
-- EXERCISE TRAINING CHARACTERS (M:N)
-- ============================================================================
-- Create junction table for exercise ↔ training_characters
IF NOT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'exercise_training_characters'
) THEN
CREATE TABLE exercise_training_characters (
id SERIAL PRIMARY KEY,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
training_character_id INT NOT NULL REFERENCES training_characters(id) ON DELETE RESTRICT,
is_primary BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(exercise_id, training_character_id)
);
CREATE INDEX idx_exercise_training_characters_exercise
ON exercise_training_characters(exercise_id);
CREATE INDEX idx_exercise_training_characters_character
ON exercise_training_characters(training_character_id);
RAISE NOTICE 'Created table: exercise_training_characters';
END IF;
-- ============================================================================
-- TRAINER CONTEXTS (Fokussierte Trainer-Ansichten)
-- ============================================================================
-- Create trainer_contexts table
IF NOT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'trainer_contexts'
) THEN
CREATE TABLE trainer_contexts (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Context definition
name VARCHAR(100) NOT NULL, -- "Karate Goju-Ryu Breitensport", "Gewaltschutz"
-- Hierarchical filters (all optional)
focus_area_id INT REFERENCES focus_areas(id) ON DELETE CASCADE,
style_direction_id INT REFERENCES style_directions(id) ON DELETE CASCADE,
training_type_id INT REFERENCES training_types(id) ON DELETE SET NULL,
-- Flags
is_style_independent BOOLEAN DEFAULT false, -- true = "Leistungssport stilunabhängig"
is_active BOOLEAN DEFAULT true,
-- Metadata
description TEXT,
sort_order INT DEFAULT 99,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Prevent duplicates
UNIQUE(profile_id, focus_area_id, style_direction_id, training_type_id)
);
CREATE INDEX idx_trainer_contexts_profile ON trainer_contexts(profile_id);
CREATE INDEX idx_trainer_contexts_focus ON trainer_contexts(focus_area_id);
CREATE INDEX idx_trainer_contexts_style ON trainer_contexts(style_direction_id);
CREATE INDEX idx_trainer_contexts_type ON trainer_contexts(training_type_id);
RAISE NOTICE 'Created table: trainer_contexts';
END IF;
-- ============================================================================
-- SEED DATA: Example Trainer Contexts
-- ============================================================================
-- Insert example contexts for profile_id = 1 (if exists)
DO $seed$
BEGIN
IF EXISTS (SELECT 1 FROM profiles WHERE id = 1) THEN
-- Only insert if not already present
IF NOT EXISTS (SELECT 1 FROM trainer_contexts WHERE profile_id = 1) THEN
INSERT INTO trainer_contexts (profile_id, name, focus_area_id, style_direction_id, training_type_id, is_style_independent, description, sort_order)
VALUES
-- Karate Breitensport (if focus_area and style exist)
(1, 'Karate Breitensport',
(SELECT id FROM focus_areas WHERE name = 'Karate' LIMIT 1),
NULL, -- all styles
(SELECT id FROM training_types WHERE name = 'Breitensport' LIMIT 1),
false,
'Breitensport für alle Karate-Stilrichtungen',
1
);
RAISE NOTICE 'Inserted example trainer contexts for profile_id = 1';
END IF;
END IF;
END $seed$;
RAISE NOTICE 'Migration 012 completed successfully';
END $$;
@@ -0,0 +1,133 @@
-- Migration 013: Training Types → Focus Area Hierarchie
-- Author: Claude Code
-- Date: 2026-04-23
-- Purpose: Training Types sind kontextabhängig vom Fokusbereich
DO $$
BEGIN
-- ============================================================================
-- ADD focus_area_id TO training_types
-- ============================================================================
-- Add focus_area_id column if not exists
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'training_types'
AND column_name = 'focus_area_id'
) THEN
ALTER TABLE training_types
ADD COLUMN focus_area_id INT REFERENCES focus_areas(id) ON DELETE CASCADE;
CREATE INDEX idx_training_types_focus_area ON training_types(focus_area_id);
RAISE NOTICE 'Added focus_area_id to training_types';
END IF;
-- ============================================================================
-- MIGRATE EXISTING DATA (assign to Karate if exists)
-- ============================================================================
-- Assign existing training types to Karate (if Karate focus area exists)
DO $migrate$
DECLARE
karate_id INT;
BEGIN
-- Get Karate focus area ID
SELECT id INTO karate_id FROM focus_areas WHERE name = 'Karate' LIMIT 1;
IF karate_id IS NOT NULL THEN
-- Assign existing training types to Karate
UPDATE training_types
SET focus_area_id = karate_id
WHERE focus_area_id IS NULL;
RAISE NOTICE 'Assigned existing training types to Karate (focus_area_id: %)', karate_id;
ELSE
RAISE NOTICE 'No Karate focus area found - skipping migration';
END IF;
END $migrate$;
-- ============================================================================
-- SEED EXAMPLE DATA (focus-area-specific training types)
-- ============================================================================
DO $seed$
DECLARE
karate_id INT;
gewaltschutz_id INT;
fitness_id INT;
BEGIN
-- Get focus area IDs
SELECT id INTO karate_id FROM focus_areas WHERE name = 'Karate' LIMIT 1;
SELECT id INTO gewaltschutz_id FROM focus_areas WHERE name = 'Gewaltschutz' LIMIT 1;
SELECT id INTO fitness_id FROM focus_areas WHERE name = 'Fitness' LIMIT 1;
-- Karate-specific training types (if Karate exists)
IF karate_id IS NOT NULL THEN
INSERT INTO training_types (name, abbreviation, description, focus_area_id, sort_order, status)
VALUES
('Dan-Vorbereitung', 'DAN', 'Vorbereitung auf Dan-Prüfungen', karate_id, 4, 'active')
ON CONFLICT (name) DO NOTHING;
END IF;
-- Gewaltschutz-specific training types (if exists)
IF gewaltschutz_id IS NOT NULL THEN
INSERT INTO training_types (name, abbreviation, description, focus_area_id, sort_order, status)
VALUES
('Präventivkurse', 'PREV', 'Präventive Selbstverteidigung und Deeskalation', gewaltschutz_id, 1, 'active'),
('Intensivtraining', 'INT', 'Intensives Selbstverteidigungs-Training', gewaltschutz_id, 2, 'active'),
('Spezialkurse', 'SPEC', 'Spezielle Kurse (Frauen, Sicherheitspersonal, etc.)', gewaltschutz_id, 3, 'active')
ON CONFLICT (name) DO NOTHING;
END IF;
-- Fitness-specific training types (if exists)
IF fitness_id IS NOT NULL THEN
INSERT INTO training_types (name, abbreviation, description, focus_area_id, sort_order, status)
VALUES
('Gesundheitssport', 'GES', 'Gesundheitsorientiertes Training', fitness_id, 1, 'active'),
('Funktionelles Training', 'FUNKT', 'Funktionelle Fitness und Beweglichkeit', fitness_id, 2, 'active')
ON CONFLICT (name) DO NOTHING;
END IF;
RAISE NOTICE 'Seeded focus-area-specific training types';
END $seed$;
-- ============================================================================
-- UPDATE UNIQUE CONSTRAINT (if needed)
-- ============================================================================
-- Drop old unique constraint if exists
DO $constraint$
BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'training_types_name_key'
) THEN
ALTER TABLE training_types DROP CONSTRAINT training_types_name_key;
RAISE NOTICE 'Dropped old unique constraint on name';
END IF;
END $constraint$;
-- Add new unique constraint (name per focus_area)
DO $constraint$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'training_types_name_focus_area_key'
) THEN
ALTER TABLE training_types
ADD CONSTRAINT training_types_name_focus_area_key
UNIQUE (name, focus_area_id);
RAISE NOTICE 'Added unique constraint: name per focus_area';
END IF;
END $constraint$;
RAISE NOTICE 'Migration 013 completed successfully';
END $$;
@@ -0,0 +1,115 @@
-- Migration 014: Variant Progression System + Search Vector + Legacy Cleanup
-- Autor: Claude Code
-- Datum: 2026-04-24
-- Zweck: Varianten-Progression, Volltext-Suche, Legacy-Spalten entfernen
DO $$
BEGIN
-- ============================================================================
-- HELPER FUNCTION: update_timestamp (für Triggers)
-- ============================================================================
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS trigger AS $func$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
-- ============================================================================
-- VARIANT PROGRESSION
-- ============================================================================
-- Erweitere exercise_variants Tabelle
ALTER TABLE exercise_variants
ADD COLUMN IF NOT EXISTS progression_level INT DEFAULT 1 CHECK (progression_level BETWEEN 1 AND 10),
ADD COLUMN IF NOT EXISTS sequence_order INT,
ADD COLUMN IF NOT EXISTS prerequisite_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL;
-- Index für Prerequisites
CREATE INDEX IF NOT EXISTS idx_exercise_variants_prerequisite
ON exercise_variants(prerequisite_variant_id);
-- ============================================================================
-- SEARCH VECTOR (Volltext-Suche)
-- ============================================================================
-- Füge search_vector zu exercises hinzu
ALTER TABLE exercises
ADD COLUMN IF NOT EXISTS search_vector tsvector;
-- Index für Volltext-Suche
CREATE INDEX IF NOT EXISTS idx_exercises_search
ON exercises USING gin(search_vector);
-- Funktion für automatisches Update
CREATE OR REPLACE FUNCTION update_exercises_search_vector()
RETURNS trigger AS $func$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('german', COALESCE(NEW.title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(NEW.summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(NEW.trainer_notes, '')), 'D');
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
-- Trigger
DROP TRIGGER IF EXISTS exercises_search_update ON exercises;
CREATE TRIGGER exercises_search_update
BEFORE INSERT OR UPDATE ON exercises
FOR EACH ROW EXECUTE FUNCTION update_exercises_search_vector();
-- Initiales Befüllen (für existierende Zeilen)
UPDATE exercises SET search_vector = (
setweight(to_tsvector('german', COALESCE(title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(trainer_notes, '')), 'D')
) WHERE search_vector IS NULL;
-- ============================================================================
-- LEGACY COLUMN CLEANUP
-- Deprecated Felder aus exercises (ersetzt durch M:N Tabellen in Migration 008+)
-- ============================================================================
-- age_groups JSONB → ersetzt durch exercise_age_groups M:N (seit Migration 008)
ALTER TABLE exercises DROP COLUMN IF EXISTS age_groups;
-- focus_area VARCHAR → ersetzt durch exercise_focus_areas M:N (seit Migration 008)
ALTER TABLE exercises DROP COLUMN IF EXISTS focus_area;
-- secondary_areas JSONB → ersetzt durch exercise_focus_areas M:N
ALTER TABLE exercises DROP COLUMN IF EXISTS secondary_areas;
-- training_character VARCHAR → ersetzt durch exercise_training_characters M:N (seit Migration 012)
ALTER TABLE exercises DROP COLUMN IF EXISTS training_character;
-- ============================================================================
-- ADDITIONAL INDEXES (Performance)
-- ============================================================================
-- Häufige Filter
CREATE INDEX IF NOT EXISTS idx_exercises_visibility ON exercises(visibility);
CREATE INDEX IF NOT EXISTS idx_exercises_status ON exercises(status);
CREATE INDEX IF NOT EXISTS idx_exercises_created_at ON exercises(created_at DESC);
-- M:N Relations (falls noch nicht vorhanden)
CREATE INDEX IF NOT EXISTS idx_exercise_focus_areas_focus
ON exercise_focus_areas(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_exercise_styles_style
ON exercise_style_directions(style_direction_id);
CREATE INDEX IF NOT EXISTS idx_exercise_target_groups_group
ON exercise_target_groups(target_group_id);
CREATE INDEX IF NOT EXISTS idx_exercise_skills_skill
ON exercise_skills(skill_id);
RAISE NOTICE 'Migration 014 completed successfully';
END $$;
+34
View File
@@ -0,0 +1,34 @@
-- Migration 016: Saved Exercise Searches
-- Autor: Claude Code
-- Datum: 2026-04-24
-- Zweck: Nutzer können häufige Suchfilter speichern
DO $$
BEGIN
-- ============================================================================
-- SAVED SEARCHES
-- ============================================================================
CREATE TABLE IF NOT EXISTS saved_exercise_searches (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
filters JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Index für User-Zugriff
CREATE INDEX IF NOT EXISTS idx_saved_searches_profile
ON saved_exercise_searches(profile_id);
-- Trigger für updated_at
DROP TRIGGER IF EXISTS saved_searches_update ON saved_exercise_searches;
CREATE TRIGGER saved_searches_update
BEFORE UPDATE ON saved_exercise_searches
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
RAISE NOTICE 'Migration 016 completed successfully';
END $$;
+103
View File
@@ -0,0 +1,103 @@
-- Migration 017: Exercise Blocks + Template Blocks
-- Autor: Claude Code
-- Datum: 2026-04-24
-- Zweck: Gruppierung verschiedener Übungen in Blöcken
-- Series = Varianten-Progression (via exercise_variants, KEINE eigene Tabelle)
-- Blocks = Verschiedene Übungen in Reihenfolge (DIESE Migration)
DO $$
BEGIN
-- ============================================================================
-- EXERCISE BLOCKS
-- Eine Sammlung verschiedener Übungen in definierter Reihenfolge
-- ============================================================================
CREATE TABLE IF NOT EXISTS exercise_blocks (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
goal TEXT,
-- Template-Modus: Block mit Platzhaltern für flexible Planung
is_template BOOLEAN DEFAULT false,
-- Ownership & Sichtbarkeit
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
visibility VARCHAR(20) DEFAULT 'private' CHECK (visibility IN ('private', 'club', 'official')),
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- ============================================================================
-- EXERCISE BLOCK ITEMS
-- Einzelne Positionen innerhalb eines Blocks
-- ============================================================================
CREATE TABLE IF NOT EXISTS exercise_block_items (
id SERIAL PRIMARY KEY,
block_id INT NOT NULL REFERENCES exercise_blocks(id) ON DELETE CASCADE,
-- Konkrete Übung (NULL wenn is_placeholder = true)
exercise_id INT REFERENCES exercises(id) ON DELETE RESTRICT,
-- Optionale Variante (kann NULL sein → Haupt-Übung wird genutzt)
variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
-- Reihenfolge innerhalb des Blocks
sequence_order INT NOT NULL,
-- Template-Modus: Platzhalter statt konkreter Übung
is_placeholder BOOLEAN DEFAULT false,
-- Kriterien für Platzhalter-Auflösung (nur relevant wenn is_placeholder = true)
-- Schema: {"focus_area_id": 1, "max_duration": 10, "skill_ids": [3, 7], "difficulty": "easier"}
-- Alle Felder optional, werden als AND-Filter bei der Übungssuche genutzt
placeholder_criteria JSONB,
-- Platzhalter-Beschriftung (für UX im Template-Modus)
placeholder_label VARCHAR(100), -- z.B. "Aufwärmübung Schlag", "Hauptübung Kumite"
-- Zusätzliche Notizen für diese Position
notes TEXT,
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
-- Constraints
UNIQUE(block_id, sequence_order),
-- Entweder exercise_id ODER is_placeholder=true
CHECK (
(is_placeholder = false AND exercise_id IS NOT NULL) OR
(is_placeholder = true AND exercise_id IS NULL)
)
);
-- ============================================================================
-- INDEXES
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_club ON exercise_blocks(club_id);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_creator ON exercise_blocks(created_by);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_visibility ON exercise_blocks(visibility);
CREATE INDEX IF NOT EXISTS idx_exercise_blocks_template ON exercise_blocks(is_template) WHERE is_template = true;
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_block ON exercise_block_items(block_id);
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_exercise ON exercise_block_items(exercise_id);
CREATE INDEX IF NOT EXISTS idx_exercise_block_items_placeholder ON exercise_block_items(is_placeholder) WHERE is_placeholder = true;
-- ============================================================================
-- UPDATED_AT TRIGGER
-- ============================================================================
DROP TRIGGER IF EXISTS exercise_blocks_update ON exercise_blocks;
CREATE TRIGGER exercise_blocks_update
BEFORE UPDATE ON exercise_blocks
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
RAISE NOTICE 'Migration 017 completed successfully (Exercise Blocks)';
END $$;
@@ -0,0 +1,40 @@
-- Migration 018: MediaWiki Import Tracking Tables
-- Tracks import runs and cross-references between Wiki pages and local DB entries
CREATE TABLE IF NOT EXISTS wiki_import_log (
id SERIAL PRIMARY KEY,
import_type VARCHAR(50) NOT NULL
CHECK (import_type IN ('exercise', 'skill', 'method', 'maturity_model')),
import_status VARCHAR(20) NOT NULL DEFAULT 'running'
CHECK (import_status IN ('running', 'completed', 'failed')),
category VARCHAR(200), -- Wiki category name used
dry_run BOOLEAN DEFAULT false,
reimport BOOLEAN DEFAULT false,
items_total INT DEFAULT 0,
items_imported INT DEFAULT 0,
items_skipped INT DEFAULT 0,
items_failed INT DEFAULT 0,
error_log JSONB DEFAULT '[]'::jsonb, -- [{item, error}, ...]
imported_by INT REFERENCES profiles(id),
started_at TIMESTAMP DEFAULT NOW(),
finished_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS wiki_import_references (
id SERIAL PRIMARY KEY,
wiki_page_title VARCHAR(500) NOT NULL,
wiki_page_id INT, -- MediaWiki internal page ID
content_type VARCHAR(50) NOT NULL
CHECK (content_type IN ('exercise', 'skill', 'method', 'maturity_model')),
local_id INT NOT NULL, -- ID in the local DB table
last_imported TIMESTAMP DEFAULT NOW(),
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(wiki_page_title, content_type)
);
CREATE INDEX IF NOT EXISTS idx_wiki_refs_title ON wiki_import_references(wiki_page_title);
CREATE INDEX IF NOT EXISTS idx_wiki_refs_type ON wiki_import_references(content_type);
CREATE INDEX IF NOT EXISTS idx_wiki_log_status ON wiki_import_log(import_status);
CREATE INDEX IF NOT EXISTS idx_wiki_log_type ON wiki_import_log(import_type);
@@ -0,0 +1,11 @@
-- Migration 019: Make exercise goal and execution optional
-- Many wiki exercises have only goal OR execution, not both
ALTER TABLE exercises
ALTER COLUMN goal DROP NOT NULL,
ALTER COLUMN execution DROP NOT NULL;
-- Add CHECK constraint: at least one of goal/execution must be present
ALTER TABLE exercises
ADD CONSTRAINT exercises_goal_or_execution_required
CHECK (goal IS NOT NULL OR execution IS NOT NULL);
@@ -0,0 +1,7 @@
-- Migration 020: Add UNIQUE constraint to exercise_skills
-- Fixes: "no unique or exclusion constraint matching the ON CONFLICT specification"
-- Required for ON CONFLICT (exercise_id, skill_id) in import_wiki.py
ALTER TABLE exercise_skills
ADD CONSTRAINT exercise_skills_exercise_skill_unique
UNIQUE (exercise_id, skill_id);
@@ -0,0 +1,58 @@
-- Migration 021: Import Skills from Fähigkeitsmatrix
-- One-time import of skills with categories from karatetrainer.net
-- Source: https://karatetrainer.net/index.php?title=Fähigkeitsmatrix
-- ON CONFLICT (name) erfordert einen UNIQUE-Constraint auf skills.name (003/007 legten keinen an)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint c
JOIN pg_class t ON c.conrelid = t.oid
WHERE t.relname = 'skills' AND c.contype = 'u' AND c.conname = 'skills_name_unique'
) THEN
ALTER TABLE skills ADD CONSTRAINT skills_name_unique UNIQUE (name);
END IF;
END $$;
-- Create skill categories first
INSERT INTO skill_categories (name, description, sort_order) VALUES
('Kihon', 'Grundtechniken', 1),
('Kumite', 'Kampf', 2),
('Kata', 'Formen', 3),
('Selbstverteidigung', 'Selbstschutz und Gefahrenabwehr', 4),
('Koordination', 'Koordinative Fähigkeiten', 5),
('Kondition', 'Konditionelle Fähigkeiten', 6),
('Kognition', 'Kognitive Fähigkeiten', 7),
('Soziale Fähigkeiten', 'Sozialkompetenzen', 8),
('Psychische Fähigkeiten', 'Mentale Stärke', 9)
ON CONFLICT (name) DO NOTHING;
-- Import skills (name unique, category by name lookup)
INSERT INTO skills (name, description, category_id)
SELECT
skill_name,
skill_description,
(SELECT id FROM skill_categories WHERE name = category_name LIMIT 1)
FROM (VALUES
('Dachi Waza', 'Standtechniken - stabiler Stand mit korrekter Gewichtsverteilung', 'Kihon'),
('Uke Waza', 'Blocktechniken - Abwehr von Angriffen', 'Kihon'),
('Zuki Waza', 'Stoßtechniken - gerade und kreisförmige Stöße', 'Kihon'),
('Geri Waza', 'Tritttechniken - verschiedene Kicks', 'Kihon'),
('Beinarbeit', 'Grundlegende Bewegungen im Kumite', 'Kumite'),
('Distanzkontrolle', 'Kontrolle der Kampfdistanz', 'Kumite'),
('Flexibilität', 'Beweglichkeit und Dehnfähigkeit', 'Kondition'),
('Präzision', 'Treffergenauigkeit', 'Kumite'),
('Bewegungsschnelligkeit', 'Schnelligkeit der Bewegungsausführung', 'Kondition'),
('Anaerobe Ausdauer', 'Ausdauer bei hoher Intensität', 'Kondition'),
('Schnelligkeitsausdauer', 'Ausdauer bei schnellen Bewegungen', 'Kondition'),
('Antizipation', 'Vorhersage gegnerischer Aktionen', 'Kognition'),
('Reaktionsschnelligkeit', 'Reaktion auf Reize', 'Koordination'),
('Timing', 'Zeitliche Abstimmung von Aktionen', 'Kumite'),
('Fokus', 'Konzentration auf das Wesentliche', 'Psychische Fähigkeiten'),
('Mentale Stärke', 'Psychische Belastbarkeit', 'Psychische Fähigkeiten'),
('Kata Ablauf', 'Korrekte Ausführung der Kata-Sequenz', 'Kata'),
('Bunkai', 'Anwendung der Kata-Techniken', 'Kata')
) AS skills(skill_name, skill_description, category_name)
ON CONFLICT (name) DO UPDATE SET
description = EXCLUDED.description,
category_id = EXCLUDED.category_id;
@@ -0,0 +1,90 @@
-- Migration 022: Skills Schema Complete - Hauptkategorien + Fokusbereich + Level-Definitionen
-- Purpose: Erweitert Skills-Schema um vollständige Kategorisierung für Prod-Import
-- Date: 2026-04-27
-- ======================================================================
-- 1. Haupt-Kategorien (KARATE Fähigkeiten / ALLGEMEINE sportliche Fähigkeiten)
-- ======================================================================
CREATE TABLE IF NOT EXISTS skill_main_categories (
id SERIAL PRIMARY KEY,
name VARCHAR(200) UNIQUE NOT NULL,
slug VARCHAR(50) UNIQUE NOT NULL,
description TEXT,
sort_order INT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- ======================================================================
-- 2. Unterkategorien erweitern (Beziehung zu Hauptkategorie)
-- ======================================================================
-- Slug für URL-friendly Namen
ALTER TABLE skill_categories
ADD COLUMN IF NOT EXISTS slug VARCHAR(50);
-- Beziehung zu Hauptkategorie
ALTER TABLE skill_categories
ADD COLUMN IF NOT EXISTS main_category_id INT REFERENCES skill_main_categories(id);
-- Unique constraint für slug
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'skill_categories_slug_unique'
) THEN
ALTER TABLE skill_categories ADD CONSTRAINT skill_categories_slug_unique UNIQUE (slug);
END IF;
END $$;
-- ======================================================================
-- 3. Skills erweitern (Hauptkategorie + Fokusbereich)
-- ======================================================================
-- Beziehung zu Hauptkategorie (für direkte Queries)
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS main_category_id INT REFERENCES skill_main_categories(id);
-- Fokusbereich als JSONB Array (z.B. ['karate'], ['universal'], ['karate', 'selbstverteidigung'])
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS focus_areas JSONB DEFAULT '[]'::jsonb;
-- ======================================================================
-- 4. Level-Definitionen (1-5 Beschreibungen aus Matrix)
-- ======================================================================
CREATE TABLE IF NOT EXISTS skill_level_definitions (
id SERIAL PRIMARY KEY,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
level INT NOT NULL CHECK (level BETWEEN 1 AND 5),
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE (skill_id, level)
);
-- Index für schnelle Abfragen
CREATE INDEX IF NOT EXISTS idx_skill_level_definitions_skill_id
ON skill_level_definitions(skill_id);
-- ======================================================================
-- 5. Indizes für Performance
-- ======================================================================
CREATE INDEX IF NOT EXISTS idx_skills_main_category_id
ON skills(main_category_id);
CREATE INDEX IF NOT EXISTS idx_skills_category_id
ON skills(category_id);
CREATE INDEX IF NOT EXISTS idx_skill_categories_main_category_id
ON skill_categories(main_category_id);
-- ======================================================================
-- 6. Kommentare für Dokumentation
-- ======================================================================
COMMENT ON TABLE skill_main_categories IS 'Hauptkategorien: KARATE Fähigkeiten / ALLGEMEINE sportliche Fähigkeiten';
COMMENT ON COLUMN skills.focus_areas IS 'JSONB Array: [''karate''] = nur Karate, [''universal''] = alle Fokussbereiche';
COMMENT ON TABLE skill_level_definitions IS 'Level 1-5 Beschreibungen aus Fähigkeitsmatrix für jede Fähigkeit';
@@ -0,0 +1,147 @@
-- Total: 69 Skills
-- Migration 023: Vollständiger Skills-Import
-- Purpose: Produktionsreifer Import aller 69 Skills mit vollständiger Kategorisierung
-- Source: Fähigkeitsmatrix https://karatetrainer.net/index.php?title=Fähigkeitsmatrix
-- Date: 2026-04-27
-- ======================================================================
-- CLEANUP: Alte Daten löschen
-- ======================================================================
-- Erst M:N-Beziehungen löschen
DELETE FROM exercise_skills;
-- Skills löschen (Cascades zu skill_level_definitions)
DELETE FROM skills;
-- Kategorien löschen
DELETE FROM skill_categories;
DELETE FROM skill_main_categories WHERE id > 0; -- Falls Tabelle existiert
-- ======================================================================
-- 1. HAUPT-KATEGORIEN
-- ======================================================================
INSERT INTO skill_main_categories (name, slug, description, sort_order) VALUES
('KARATE Fähigkeiten', 'karate', 'Karate-spezifische Techniken und Fähigkeiten', 1),
('ALLGEMEINE sportliche Fähigkeiten', 'allgemeine', 'Universelle sportliche und mentale Fähigkeiten', 2);
-- ======================================================================
-- 2. UNTERKATEGORIEN
-- ======================================================================
INSERT INTO skill_categories (name, slug, main_category_id, description, sort_order) VALUES
('Kata', 'kata', (SELECT id FROM skill_main_categories WHERE slug='karate'), '', 1),
('Kihon', 'kihon', (SELECT id FROM skill_main_categories WHERE slug='karate'), '', 2),
('Kumite', 'kumite', (SELECT id FROM skill_main_categories WHERE slug='karate'), '', 3),
('Selbstverteidigung', 'selbstverteidigung', (SELECT id FROM skill_main_categories WHERE slug='karate'), '', 4),
('Kognition', 'kognition', (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '', 5),
('Kondition', 'kondition', (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '', 6),
('Koordination', 'koordination', (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '', 7),
('Psychische Fähigkeiten', 'psychische_faehigkeiten', (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '', 8),
('Soziale Fähigkeiten', 'soziale_faehigkeiten', (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '', 9);
-- ======================================================================
-- 3. SKILLS
-- ======================================================================
INSERT INTO skills (name, description, category_id, main_category_id, focus_areas) VALUES
('Technik Kombination', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Kata Ablauf', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Bunkai', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Oyo', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Henka', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Kakushi', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Kata Atmung', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Kata Rhythmus', '', (SELECT id FROM skill_categories WHERE slug='kata'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Dachi Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Uke Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Zuki Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Uchi Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Geri Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Nage Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Nukite Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Ken Waza', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Hüfteinsatz', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Kime', '', (SELECT id FROM skill_categories WHERE slug='kihon'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Beinarbeit', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Distanzkontrolle', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Angriff', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Abwehr Konter', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Präzision', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Antizipation', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Timing', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Taktik', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Fokus', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Mentale Stärke', '', (SELECT id FROM skill_categories WHERE slug='kumite'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Gefahrenbewustsein', '', (SELECT id FROM skill_categories WHERE slug='selbstverteidigung'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Selbstbehauptung', '', (SELECT id FROM skill_categories WHERE slug='selbstverteidigung'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Selbstschutz', '', (SELECT id FROM skill_categories WHERE slug='selbstverteidigung'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Gefahrenabwehr', '', (SELECT id FROM skill_categories WHERE slug='selbstverteidigung'), (SELECT id FROM skill_main_categories WHERE slug='karate'), '["karate"]'::jsonb),
('Aufmerksamkeit', '', (SELECT id FROM skill_categories WHERE slug='kognition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Wahrnehmung', '', (SELECT id FROM skill_categories WHERE slug='kognition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Urteilsvermögen', '', (SELECT id FROM skill_categories WHERE slug='kognition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Merkfähigkeit', '', (SELECT id FROM skill_categories WHERE slug='kognition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Lernfähigkeit', '', (SELECT id FROM skill_categories WHERE slug='kognition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Maximalkraft', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Schnellkraft', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Reaktivkraft', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Kraftausdauer', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Muskelaufbau', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Reaktionsschnelligkeit', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Bewegungsschnelligkeit', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Handlungsschnelligkeit', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Schnelligkeitsausdauer', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Grundlagenausdauer', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Aerobe Ausdauer', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Anaerobe Ausdauer', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Regenerationsfähigkeit', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Ermüdungswiderstandsfähigkeit', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Flexibilität', '', (SELECT id FROM skill_categories WHERE slug='kondition'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Orientierung', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Differenzierung', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Kopplung', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Gleichgewicht', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Rhythmisierung', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Reaktion', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Umstellung', '', (SELECT id FROM skill_categories WHERE slug='koordination'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Selbstvertrauen', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Konzentration', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Emotionale Kontrolle', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Motivation', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Stressresistenz', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Stressregulation', '', (SELECT id FROM skill_categories WHERE slug='psychische_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Deeskalation', '', (SELECT id FROM skill_categories WHERE slug='soziale_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Selbstdisziplin', '', (SELECT id FROM skill_categories WHERE slug='soziale_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Toleranz', '', (SELECT id FROM skill_categories WHERE slug='soziale_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb),
('Fairness', '', (SELECT id FROM skill_categories WHERE slug='soziale_faehigkeiten'), (SELECT id FROM skill_main_categories WHERE slug='allgemeine'), '["universal"]'::jsonb);
-- ======================================================================
-- 4. VERIFIKATION
-- ======================================================================
-- Sollte 69 Skills ergeben
DO $$
DECLARE
skill_count INT;
BEGIN
SELECT COUNT(*) INTO skill_count FROM skills;
IF skill_count != 69 THEN
RAISE WARNING 'FEHLER: % Skills gefunden, erwartet 69', skill_count;
ELSE
RAISE NOTICE 'OK: 69 Skills importiert';
END IF;
END $$;
-- Zeige Verteilung
SELECT
mc.name AS hauptkategorie,
sc.name AS unterkategorie,
COUNT(s.id) AS anzahl_skills
FROM skills s
JOIN skill_categories sc ON s.category_id = sc.id
JOIN skill_main_categories mc ON s.main_category_id = mc.id
GROUP BY mc.name, sc.name, mc.sort_order, sc.sort_order
ORDER BY mc.sort_order, sc.sort_order;
+132
View File
@@ -0,0 +1,132 @@
-- Migration 024: Reifegradmodelle / Fähigkeitsmatrix (kontextbezogen)
-- Datum: 2026-04-27
-- ============================================================================
-- MATURITY MODELS
-- ============================================================================
CREATE TABLE IF NOT EXISTS maturity_models (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
focus_area_id INT REFERENCES focus_areas(id) ON DELETE RESTRICT,
style_direction_id INT REFERENCES style_directions(id) ON DELETE RESTRICT,
target_group_id INT REFERENCES target_groups(id) ON DELETE RESTRICT,
level_count INT NOT NULL DEFAULT 5 CHECK (level_count BETWEEN 3 AND 10),
status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'active', 'archived')),
version VARCHAR(20) DEFAULT '1.0',
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
import_source VARCHAR(50),
import_id VARCHAR(200),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT maturity_models_context_name_unique
UNIQUE (name, focus_area_id, style_direction_id, target_group_id)
);
-- ============================================================================
-- MODEL LEVELS (Stufen-Labels pro Modell)
-- ============================================================================
CREATE TABLE IF NOT EXISTS model_levels (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
level_number INT NOT NULL CHECK (level_number >= 1),
name VARCHAR(100) NOT NULL,
description TEXT,
sort_order INT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(maturity_model_id, level_number)
);
-- ============================================================================
-- MODEL SKILLS: Welche Fähigkeiten sind im Modell geführt (Matrix-Zeilen)
-- ============================================================================
CREATE TABLE IF NOT EXISTS model_skills (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
sort_order INT NOT NULL DEFAULT 0,
relevance VARCHAR(50),
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(maturity_model_id, skill_id)
);
CREATE INDEX IF NOT EXISTS idx_model_skills_model ON model_skills(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_model_skills_skill ON model_skills(skill_id);
-- ============================================================================
-- MODEL SKILL LEVELS (Zelltexte der Matrix)
-- ============================================================================
CREATE TABLE IF NOT EXISTS model_skill_levels (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
skill_id INT NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
level_number INT NOT NULL CHECK (level_number >= 1),
description TEXT NOT NULL,
observable_criteria TEXT,
example_exercise_hints JSONB,
ai_generated BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE(maturity_model_id, skill_id, level_number)
);
-- ============================================================================
-- SKILLS: optionale Matrix-Felder (Spec)
-- ============================================================================
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS primary_focus_area_id INT REFERENCES focus_areas(id) ON DELETE SET NULL;
ALTER TABLE skills
ADD COLUMN IF NOT EXISTS is_cross_domain BOOLEAN DEFAULT false;
-- ============================================================================
-- INDEXES
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_maturity_models_focus ON maturity_models(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_style ON maturity_models(style_direction_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_target ON maturity_models(target_group_id);
CREATE INDEX IF NOT EXISTS idx_maturity_models_status ON maturity_models(status);
CREATE INDEX IF NOT EXISTS idx_model_levels_model ON model_levels(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_model_skill_levels_model ON model_skill_levels(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_model_skill_levels_skill ON model_skill_levels(skill_id);
CREATE INDEX IF NOT EXISTS idx_skills_primary_focus ON skills(primary_focus_area_id);
-- ============================================================================
-- TRIGGERS updated_at
-- ============================================================================
DROP TRIGGER IF EXISTS maturity_models_update ON maturity_models;
CREATE TRIGGER maturity_models_update
BEFORE UPDATE ON maturity_models
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
DROP TRIGGER IF EXISTS model_skill_levels_update ON model_skill_levels;
CREATE TRIGGER model_skill_levels_update
BEFORE UPDATE ON model_skill_levels
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
@@ -0,0 +1,160 @@
-- Migration 025: Reifegradmodell-Kontext als M:N (Fokusbereich, Stilrichtung, Zielgruppe)
-- + Bootstrap: ein Modell aus allen importierten Skills (Wiki / Migration 023)
-- Datum: 2026-04-27
-- ============================================================================
-- JUNCTION TABLES
-- ============================================================================
CREATE TABLE IF NOT EXISTS maturity_model_focus_areas (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
is_primary BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (maturity_model_id, focus_area_id)
);
CREATE INDEX IF NOT EXISTS idx_mmfa_model ON maturity_model_focus_areas(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_mmfa_focus ON maturity_model_focus_areas(focus_area_id);
CREATE TABLE IF NOT EXISTS maturity_model_style_directions (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
style_direction_id INT NOT NULL REFERENCES style_directions(id) ON DELETE CASCADE,
is_primary BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (maturity_model_id, style_direction_id)
);
CREATE INDEX IF NOT EXISTS idx_mmsd_model ON maturity_model_style_directions(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_mmsd_style ON maturity_model_style_directions(style_direction_id);
CREATE TABLE IF NOT EXISTS maturity_model_target_groups (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
target_group_id INT NOT NULL REFERENCES target_groups(id) ON DELETE CASCADE,
is_primary BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (maturity_model_id, target_group_id)
);
CREATE INDEX IF NOT EXISTS idx_mmtg_model ON maturity_model_target_groups(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_mmtg_tg ON maturity_model_target_groups(target_group_id);
-- ============================================================================
-- Daten aus 1:1-FKs übernehmen (falls Spalten noch existieren), dann FK-Spalten entfernen
-- ============================================================================
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'maturity_models' AND column_name = 'focus_area_id'
) THEN
INSERT INTO maturity_model_focus_areas (maturity_model_id, focus_area_id, is_primary)
SELECT id, focus_area_id, true
FROM maturity_models
WHERE focus_area_id IS NOT NULL
ON CONFLICT (maturity_model_id, focus_area_id) DO NOTHING;
END IF;
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'maturity_models' AND column_name = 'style_direction_id'
) THEN
INSERT INTO maturity_model_style_directions (maturity_model_id, style_direction_id, is_primary)
SELECT id, style_direction_id, true
FROM maturity_models
WHERE style_direction_id IS NOT NULL
ON CONFLICT (maturity_model_id, style_direction_id) DO NOTHING;
END IF;
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'maturity_models' AND column_name = 'target_group_id'
) THEN
INSERT INTO maturity_model_target_groups (maturity_model_id, target_group_id, is_primary)
SELECT id, target_group_id, true
FROM maturity_models
WHERE target_group_id IS NOT NULL
ON CONFLICT (maturity_model_id, target_group_id) DO NOTHING;
END IF;
END $$;
ALTER TABLE maturity_models DROP CONSTRAINT IF EXISTS maturity_models_context_name_unique;
ALTER TABLE maturity_models DROP COLUMN IF EXISTS focus_area_id;
ALTER TABLE maturity_models DROP COLUMN IF EXISTS style_direction_id;
ALTER TABLE maturity_models DROP COLUMN IF EXISTS target_group_id;
CREATE UNIQUE INDEX IF NOT EXISTS idx_maturity_models_wiki_import
ON maturity_models(import_source, import_id)
WHERE import_id IS NOT NULL;
-- ============================================================================
-- Bootstrap: Standard-Modell für alle Skills aus der Wiki-Matrix (Migration 023)
-- ============================================================================
DO $$
DECLARE
mid INT;
n_skills INT;
BEGIN
SELECT COUNT(*) INTO n_skills FROM skills;
IF n_skills = 0 THEN
RAISE NOTICE 'Bootstrap: keine Skills – übersprungen';
RETURN;
END IF;
SELECT id INTO mid FROM maturity_models WHERE import_id = 'faehigkeitsmatrix_karatetrainer' LIMIT 1;
IF mid IS NOT NULL THEN
RAISE NOTICE 'Bootstrap: Modell bereits vorhanden (id=%)', mid;
RETURN;
END IF;
INSERT INTO maturity_models (name, description, level_count, status, import_source, import_id, version)
VALUES (
'Fähigkeitsmatrix (Wiki Import)',
'Alle Fähigkeiten aus der Wiki-Matrix (Karatetrainer). Haupt- und Untergruppen kommen aus skill_main_categories / skill_categories.',
5,
'active',
'wiki_matrix',
'faehigkeitsmatrix_karatetrainer',
'1.0'
)
RETURNING id INTO mid;
INSERT INTO maturity_model_focus_areas (maturity_model_id, focus_area_id, is_primary)
SELECT mid, fa.id, (fa.name = 'Karate')
FROM focus_areas fa
WHERE fa.name IN ('Karate', 'Selbstverteidigung', 'Gewaltschutz')
ON CONFLICT (maturity_model_id, focus_area_id) DO NOTHING;
INSERT INTO model_levels (maturity_model_id, level_number, name, description, sort_order)
VALUES
(mid, 1, 'Einsteiger', NULL, 1),
(mid, 2, 'Grundlagen', NULL, 2),
(mid, 3, 'Aufbau', NULL, 3),
(mid, 4, 'Fortgeschritten', NULL, 4),
(mid, 5, 'Experte', NULL, 5);
INSERT INTO model_skills (maturity_model_id, skill_id, sort_order, relevance)
SELECT
mid,
s.id,
ROW_NUMBER() OVER (
ORDER BY mc.sort_order NULLS LAST, sc.sort_order NULLS LAST, s.name
),
NULL
FROM skills s
LEFT JOIN skill_categories sc ON s.category_id = sc.id
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id;
INSERT INTO model_skill_levels (maturity_model_id, skill_id, level_number, description, observable_criteria)
SELECT mid, sld.skill_id, sld.level, sld.description, NULL
FROM skill_level_definitions sld
ON CONFLICT (maturity_model_id, skill_id, level_number) DO NOTHING;
RAISE NOTICE 'Bootstrap: Reifegradmodell id=% angelegt (% Skills)', mid, n_skills;
END $$;
@@ -0,0 +1,35 @@
-- Migration 026: Hierarchische Kontext-Zuordnung Reifegradmodell → Fokus / Stilrichtung / Trainingsstil
-- Vererbung: Modell auf Fokus-Ebene gilt als Basis; spezifischere Zeilen überschreiben Zelltexte
-- für dieselbe Fähigkeit (skill_id) beim Zusammenführen (resolve).
-- Datum: 2026-04-27
CREATE TABLE IF NOT EXISTS maturity_model_context_bindings (
id SERIAL PRIMARY KEY,
maturity_model_id INT NOT NULL REFERENCES maturity_models(id) ON DELETE CASCADE,
focus_area_id INT NOT NULL REFERENCES focus_areas(id) ON DELETE CASCADE,
style_direction_id INT REFERENCES style_directions(id) ON DELETE CASCADE,
training_type_id INT REFERENCES training_types(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT chk_mcb_tier CHECK (
(style_direction_id IS NULL AND training_type_id IS NULL)
OR (style_direction_id IS NOT NULL AND training_type_id IS NULL)
OR (style_direction_id IS NOT NULL AND training_type_id IS NOT NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_mmcb_model ON maturity_model_context_bindings(maturity_model_id);
CREATE INDEX IF NOT EXISTS idx_mmcb_focus ON maturity_model_context_bindings(focus_area_id);
-- Pro Ebene höchstens eine Zuordnung je Kontext
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_only
ON maturity_model_context_bindings (focus_area_id)
WHERE style_direction_id IS NULL AND training_type_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_style
ON maturity_model_context_bindings (focus_area_id, style_direction_id)
WHERE style_direction_id IS NOT NULL AND training_type_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_style_ttype
ON maturity_model_context_bindings (focus_area_id, style_direction_id, training_type_id)
WHERE training_type_id IS NOT NULL;
@@ -0,0 +1,17 @@
-- Migration 027: Kontext-Bindings – Fokus + Trainingsstil ohne Stilrichtung (z. B. Karate + Breitensport)
-- Ersetzt die alte CHECK-Constraint-Kette; partielle Unique-Indizes für alle vier Kombinationen.
-- Datum: 2026-04-27
ALTER TABLE maturity_model_context_bindings DROP CONSTRAINT IF EXISTS chk_mcb_tier;
DROP INDEX IF EXISTS uq_mmcb_focus_style_ttype;
-- Fokus + Stilrichtung + Trainingsstil (alle drei gesetzt)
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_style_training
ON maturity_model_context_bindings (focus_area_id, style_direction_id, training_type_id)
WHERE style_direction_id IS NOT NULL AND training_type_id IS NOT NULL;
-- Fokus + Trainingsstil (ohne Stilrichtung)
CREATE UNIQUE INDEX IF NOT EXISTS uq_mmcb_focus_training
ON maturity_model_context_bindings (focus_area_id, training_type_id)
WHERE style_direction_id IS NULL AND training_type_id IS NOT NULL;
@@ -0,0 +1,72 @@
-- Migration 028: exercise_media (Upload/Embed laut Spec) + exercise_skills Typen für API v2
-- Datum: 2026-04-27
-- exercise_media: Metadaten + Embed
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS file_size INT;
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS mime_type VARCHAR(100);
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS original_filename VARCHAR(300);
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS embed_url TEXT;
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS embed_platform VARCHAR(50);
ALTER TABLE exercise_media ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT NOW();
CREATE INDEX IF NOT EXISTS idx_exercise_media_exercise_sort ON exercise_media(exercise_id, sort_order);
-- exercise_skills: KI-Flag + benannte Stufen / Intensität (EXERCISES_API_SPEC)
ALTER TABLE exercise_skills ADD COLUMN IF NOT EXISTS ai_suggested BOOLEAN DEFAULT FALSE;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns c
WHERE c.table_schema = 'public' AND c.table_name = 'exercise_skills'
AND c.column_name = 'intensity' AND c.data_type IN ('integer', 'bigint', 'smallint')
) THEN
ALTER TABLE exercise_skills DROP CONSTRAINT IF EXISTS exercise_skills_intensity_check;
ALTER TABLE exercise_skills ALTER COLUMN intensity DROP DEFAULT;
ALTER TABLE exercise_skills ALTER COLUMN intensity TYPE VARCHAR(10) USING
CASE
WHEN intensity IS NULL THEN NULL
WHEN intensity::integer <= 2 THEN 'niedrig'
WHEN intensity::integer = 3 THEN 'mittel'
ELSE 'hoch'
END;
END IF;
END $$;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns c
WHERE c.table_schema = 'public' AND c.table_name = 'exercise_skills'
AND c.column_name = 'required_level' AND c.data_type IN ('integer', 'bigint', 'smallint')
) THEN
ALTER TABLE exercise_skills ALTER COLUMN required_level TYPE VARCHAR(20) USING
CASE WHEN required_level IS NULL THEN NULL ELSE required_level::text END;
END IF;
END $$;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns c
WHERE c.table_schema = 'public' AND c.table_name = 'exercise_skills'
AND c.column_name = 'target_level' AND c.data_type IN ('integer', 'bigint', 'smallint')
) THEN
ALTER TABLE exercise_skills ALTER COLUMN target_level TYPE VARCHAR(20) USING
CASE WHEN target_level IS NULL THEN NULL ELSE target_level::text END;
END IF;
END $$;
-- Volltext: Ziel einbeziehen (Wiki-Import nutzt oft nur goal)
CREATE OR REPLACE FUNCTION update_exercises_search_vector()
RETURNS trigger AS $func$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('german', COALESCE(NEW.title, '')), 'A') ||
setweight(to_tsvector('german', COALESCE(NEW.summary, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.goal, '')), 'B') ||
setweight(to_tsvector('german', COALESCE(NEW.execution, '')), 'C') ||
setweight(to_tsvector('german', COALESCE(NEW.trainer_notes, '')), 'D');
RETURN NEW;
END;
$func$ LANGUAGE plpgsql;
@@ -0,0 +1,27 @@
-- Migration 029: Einheitliche Fähigkeitsstufen 1–5 (Basis … Optimierung)
-- Datum: 2026-04-27
-- exercise_skills: Legacy- und Zahl-Strings → kanonische Slugs
UPDATE exercise_skills SET required_level = 'basis' WHERE required_level IN ('einsteiger', '1');
UPDATE exercise_skills SET required_level = 'optimierung' WHERE required_level IN ('experte', '5');
UPDATE exercise_skills SET required_level = 'grundlagen' WHERE required_level = '2';
UPDATE exercise_skills SET required_level = 'aufbau' WHERE required_level = '3';
UPDATE exercise_skills SET required_level = 'fortgeschritten' WHERE required_level = '4';
UPDATE exercise_skills SET target_level = 'basis' WHERE target_level IN ('einsteiger', '1');
UPDATE exercise_skills SET target_level = 'optimierung' WHERE target_level IN ('experte', '5');
UPDATE exercise_skills SET target_level = 'grundlagen' WHERE target_level = '2';
UPDATE exercise_skills SET target_level = 'aufbau' WHERE target_level = '3';
UPDATE exercise_skills SET target_level = 'fortgeschritten' WHERE target_level = '4';
-- Reifegradmodell-Stufen (einheitliche Bezeichnungen für Stufe 1–5)
UPDATE model_levels SET
name = CASE level_number
WHEN 1 THEN 'Basis'
WHEN 2 THEN 'Grundlagen'
WHEN 3 THEN 'Aufbau'
WHEN 4 THEN 'Fortgeschritten'
WHEN 5 THEN 'Optimierung'
ELSE name
END
WHERE level_number BETWEEN 1 AND 5;
@@ -0,0 +1,9 @@
-- Migration 030: Übungsvariante in geplanten Trainingseinheiten
-- Nullable FK: keine Variante = Stammübung; bei Löschen der Variante bleibt die Zuordnung zur Übung erhalten
ALTER TABLE training_unit_exercises
ADD COLUMN IF NOT EXISTS exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_training_unit_exercises_variant
ON training_unit_exercises(exercise_variant_id)
WHERE exercise_variant_id IS NOT NULL;
@@ -0,0 +1,113 @@
-- Migration 031: Trainingsvorlagen (Sektionen) und strukturierter Ablauf pro Einheit
-- Freie Anmerkungszeilen (note) zwischen Übungen (exercise) mit optionaler Variante/Dauer.
-- ── Vorlagen (wiederverwendbare Gliederung für Gruppen/Trainer) ─────────────
CREATE TABLE IF NOT EXISTS training_plan_templates (
id SERIAL PRIMARY KEY,
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
name VARCHAR(200) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS training_plan_template_sections (
id SERIAL PRIMARY KEY,
template_id INT NOT NULL REFERENCES training_plan_templates(id) ON DELETE CASCADE,
order_index INT NOT NULL,
title VARCHAR(200) NOT NULL,
guidance_text TEXT,
UNIQUE (template_id, order_index)
);
CREATE INDEX IF NOT EXISTS idx_training_plan_templates_club ON training_plan_templates(club_id);
CREATE INDEX IF NOT EXISTS idx_training_plan_templates_creator ON training_plan_templates(created_by);
CREATE INDEX IF NOT EXISTS idx_training_plan_template_sections_template ON training_plan_template_sections(template_id);
DROP TRIGGER IF EXISTS training_plan_templates_update ON training_plan_templates;
CREATE TRIGGER training_plan_templates_update
BEFORE UPDATE ON training_plan_templates
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
-- ── Verknüpfung Einheit ↔ genutzte Vorlage (nur Metadaten) ──────────────────
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS plan_template_id INT REFERENCES training_plan_templates(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_training_units_plan_template ON training_units(plan_template_id);
-- ── Konkrete Sektionen je Trainingseinheit ────────────────────────────────
CREATE TABLE IF NOT EXISTS training_unit_sections (
id SERIAL PRIMARY KEY,
training_unit_id INT NOT NULL REFERENCES training_units(id) ON DELETE CASCADE,
order_index INT NOT NULL,
title VARCHAR(200) NOT NULL DEFAULT 'Abschnitt',
guidance_notes TEXT,
source_template_section_id INT REFERENCES training_plan_template_sections(id) ON DELETE SET NULL,
UNIQUE (training_unit_id, order_index)
);
CREATE INDEX IF NOT EXISTS idx_training_unit_sections_unit ON training_unit_sections(training_unit_id);
-- ── Positionen: Übung oder freie Anmerkung ────────────────────────────────
CREATE TABLE IF NOT EXISTS training_unit_section_items (
id SERIAL PRIMARY KEY,
section_id INT NOT NULL REFERENCES training_unit_sections(id) ON DELETE CASCADE,
order_index INT NOT NULL,
item_type VARCHAR(20) NOT NULL CHECK (item_type IN ('exercise', 'note')),
exercise_id INT REFERENCES exercises(id) ON DELETE SET NULL,
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
planned_duration_min INT,
actual_duration_min INT,
notes TEXT,
modifications TEXT,
note_body TEXT,
UNIQUE (section_id, order_index),
CHECK (
(item_type = 'exercise' AND exercise_id IS NOT NULL AND note_body IS NULL)
OR
(item_type = 'note' AND exercise_id IS NULL)
)
);
CREATE INDEX IF NOT EXISTS idx_training_unit_section_items_section ON training_unit_section_items(section_id);
CREATE INDEX IF NOT EXISTS idx_training_unit_section_items_exercise ON training_unit_section_items(exercise_id)
WHERE exercise_id IS NOT NULL;
-- ── Bestehende Zeilen migrieren: eine Sektion „Übungen“ pro Einheit ─────────
INSERT INTO training_unit_sections (training_unit_id, order_index, title)
SELECT id, 0, 'Übungen'
FROM training_units tu
WHERE NOT EXISTS (
SELECT 1 FROM training_unit_sections tus WHERE tus.training_unit_id = tu.id
);
INSERT INTO training_unit_section_items (
section_id,
order_index,
item_type,
exercise_id,
exercise_variant_id,
planned_duration_min,
actual_duration_min,
notes,
modifications,
note_body
)
SELECT
tus.id,
tue.order_index,
'exercise',
tue.exercise_id,
tue.exercise_variant_id,
tue.planned_duration_min,
tue.actual_duration_min,
tue.notes,
tue.modifications,
NULL
FROM training_unit_exercises tue
INNER JOIN training_unit_sections tus
ON tus.training_unit_id = tue.training_unit_id
AND tus.order_index = 0;
DROP TABLE IF EXISTS training_unit_exercises;
@@ -0,0 +1,38 @@
-- Migration 032: Progressionsgraph zwischen Übungen (Übung → Übung), getrennt von Varianten-Progression (014).
-- CURR-002 (1): gerichtete Kanten mit optionalem Graph-Kontainer; FK auf exercises; MVP edge_type erweiterbar.
CREATE TABLE IF NOT EXISTS exercise_progression_graphs (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
description TEXT,
visibility VARCHAR(50) NOT NULL DEFAULT 'private'
CHECK (visibility IN ('private', 'club', 'official')),
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_club ON exercise_progression_graphs(club_id);
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_creator ON exercise_progression_graphs(created_by);
CREATE INDEX IF NOT EXISTS idx_exercise_progression_graphs_visibility ON exercise_progression_graphs(visibility);
DROP TRIGGER IF EXISTS exercise_progression_graphs_update ON exercise_progression_graphs;
CREATE TRIGGER exercise_progression_graphs_update
BEFORE UPDATE ON exercise_progression_graphs
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
CREATE TABLE IF NOT EXISTS exercise_progression_edges (
id SERIAL PRIMARY KEY,
graph_id INT NOT NULL REFERENCES exercise_progression_graphs(id) ON DELETE CASCADE,
from_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
to_exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
edge_type VARCHAR(50) NOT NULL DEFAULT 'next_exercise',
created_at TIMESTAMP DEFAULT NOW(),
CHECK (from_exercise_id <> to_exercise_id),
UNIQUE (graph_id, from_exercise_id, to_exercise_id, edge_type)
);
CREATE INDEX IF NOT EXISTS idx_progression_edges_graph ON exercise_progression_edges(graph_id);
CREATE INDEX IF NOT EXISTS idx_progression_edges_from ON exercise_progression_edges(from_exercise_id);
CREATE INDEX IF NOT EXISTS idx_progression_edges_to ON exercise_progression_edges(to_exercise_id);
@@ -0,0 +1,4 @@
-- Migration 033: Optionale Notiz / Entwicklungsziel pro Progressions-Kante (Übung→Übung).
ALTER TABLE exercise_progression_edges
ADD COLUMN IF NOT EXISTS notes TEXT;
@@ -0,0 +1,45 @@
-- Migration 034: Progressionskanten optional mit Übungsvarianten (Knoten = Übung oder konkrete Variante).
-- UNIQUE und CHECK angepasst; Kanten innerhalb derselben Übung nur zwischen verschiedenen Varianten.
ALTER TABLE exercise_progression_edges
ADD COLUMN IF NOT EXISTS from_exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS to_exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE CASCADE;
CREATE INDEX IF NOT EXISTS idx_progression_edges_from_variant ON exercise_progression_edges(from_exercise_variant_id)
WHERE from_exercise_variant_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_progression_edges_to_variant ON exercise_progression_edges(to_exercise_variant_id)
WHERE to_exercise_variant_id IS NOT NULL;
DO $$
BEGIN
ALTER TABLE exercise_progression_edges
DROP CONSTRAINT exercise_progression_edges_graph_id_from_exercise_id_to_exercise_id_edge_type_key;
EXCEPTION
WHEN undefined_object THEN NULL;
END $$;
DO $$
BEGIN
ALTER TABLE exercise_progression_edges DROP CONSTRAINT exercise_progression_edges_check;
EXCEPTION
WHEN undefined_object THEN NULL;
END $$;
ALTER TABLE exercise_progression_edges ADD CONSTRAINT exercise_progression_edges_endpoints_distinct CHECK (
(from_exercise_id <> to_exercise_id)
OR (
from_exercise_variant_id IS NOT NULL
AND to_exercise_variant_id IS NOT NULL
AND from_exercise_variant_id <> to_exercise_variant_id
)
);
CREATE UNIQUE INDEX IF NOT EXISTS exercise_progression_edges_unique_endpoints
ON exercise_progression_edges (
graph_id,
from_exercise_id,
COALESCE(from_exercise_variant_id, 0),
to_exercise_id,
COALESCE(to_exercise_variant_id, 0),
edge_type
);
@@ -0,0 +1,92 @@
-- Migration 035: Trainingsrahmenprogramm (Rahmen‑Vorlage, CURR‑002 Stufe 2 / CURR‑009–013)
-- + CURR‑007/008: training_plan_templates.visibility (Backfill club, dann NOT NULL + Default)
-- ── Trainings‑Mikrovorlagen: gemeinsamer Governance‑Kern (visibility) ─────
ALTER TABLE training_plan_templates
ADD COLUMN IF NOT EXISTS visibility VARCHAR(50)
CHECK (visibility IN ('private', 'club', 'official'));
UPDATE training_plan_templates
SET visibility = 'club'
WHERE visibility IS NULL;
ALTER TABLE training_plan_templates
ALTER COLUMN visibility SET DEFAULT 'club';
ALTER TABLE training_plan_templates
ALTER COLUMN visibility SET NOT NULL;
CREATE INDEX IF NOT EXISTS idx_training_plan_templates_visibility ON training_plan_templates(visibility);
-- ── Rahmen‑Header ────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_programs (
id SERIAL PRIMARY KEY,
title VARCHAR(200) NOT NULL,
description TEXT,
plan_mode VARCHAR(20) NOT NULL
CHECK (plan_mode IN ('concrete', 'library')),
-- Modus B (library): immer NULL · Modus A (concrete): optional gebunden an eine Trainingsgruppe
group_id INT REFERENCES training_groups(id) ON DELETE SET NULL,
planned_period_start DATE,
planned_period_end DATE,
visibility VARCHAR(50) NOT NULL DEFAULT 'private'
CHECK (visibility IN ('private', 'club', 'official')),
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
created_by INT REFERENCES profiles(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CHECK (
(plan_mode = 'library' AND group_id IS NULL)
OR plan_mode = 'concrete'
)
);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_creator ON training_framework_programs(created_by);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_club ON training_framework_programs(club_id);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_visibility ON training_framework_programs(visibility);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_mode ON training_framework_programs(plan_mode);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_group ON training_framework_programs(group_id);
DROP TRIGGER IF EXISTS training_framework_programs_update ON training_framework_programs;
CREATE TRIGGER training_framework_programs_update
BEFORE UPDATE ON training_framework_programs
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
-- ── Zielliste (CURR‑011: ≥ 1 durch API beim Speichern) ─────────────────────
CREATE TABLE IF NOT EXISTS training_framework_goals (
id SERIAL PRIMARY KEY,
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
sort_order INT NOT NULL,
title VARCHAR(500) NOT NULL,
notes TEXT,
UNIQUE (framework_program_id, sort_order)
);
CREATE INDEX IF NOT EXISTS idx_training_framework_goals_framework ON training_framework_goals(framework_program_id);
-- ── Slots (Sessions im Rahmen) ──────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_slots (
id SERIAL PRIMARY KEY,
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
sort_order INT NOT NULL,
title VARCHAR(200),
notes TEXT,
training_unit_id INT REFERENCES training_units(id) ON DELETE SET NULL,
UNIQUE (framework_program_id, sort_order)
);
CREATE INDEX IF NOT EXISTS idx_training_framework_slots_framework ON training_framework_slots(framework_program_id);
CREATE INDEX IF NOT EXISTS idx_training_framework_slots_unit ON training_framework_slots(training_unit_id);
-- ── Übungen pro Slot (tragende „Stückliste“, CURR‑010) ────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_slot_exercises (
id SERIAL PRIMARY KEY,
slot_id INT NOT NULL REFERENCES training_framework_slots(id) ON DELETE CASCADE,
exercise_id INT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
exercise_variant_id INT REFERENCES exercise_variants(id) ON DELETE SET NULL,
order_index INT NOT NULL,
UNIQUE (slot_id, order_index)
);
CREATE INDEX IF NOT EXISTS idx_training_framework_slot_exercises_slot ON training_framework_slot_exercises(slot_id);
CREATE INDEX IF NOT EXISTS idx_training_framework_slot_exercises_exercise ON training_framework_slot_exercises(exercise_id);
@@ -0,0 +1,64 @@
-- Migration 036: Rahmenprogramm — nur Bibliothek + Kontext-Stammdaten (Fokus, Stil, Typen, Zielgruppen)
-- Grund: Zuordnung zu Gruppen/Kalender nur aus der Planung (Kopie + Lineage), nicht am Rahmenkopf.
-- ── Kontext am Rahmenkopf (Zuordenbarkeit / Filter) ─────────────────────────
ALTER TABLE training_framework_programs
ADD COLUMN IF NOT EXISTS focus_area_id INT REFERENCES focus_areas(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS style_direction_id INT REFERENCES style_directions(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_focus ON training_framework_programs(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_training_framework_programs_style ON training_framework_programs(style_direction_id);
-- ── M:N Trainingsstile (training_types Katalog) ─────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_program_training_types (
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
training_type_id INT NOT NULL REFERENCES training_types(id) ON DELETE CASCADE,
PRIMARY KEY (framework_program_id, training_type_id)
);
CREATE INDEX IF NOT EXISTS idx_tfptt_type ON training_framework_program_training_types(training_type_id);
-- ── M:N Zielgruppen ─────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS training_framework_program_target_groups (
framework_program_id INT NOT NULL REFERENCES training_framework_programs(id) ON DELETE CASCADE,
target_group_id INT NOT NULL REFERENCES target_groups(id) ON DELETE CASCADE,
PRIMARY KEY (framework_program_id, target_group_id)
);
CREATE INDEX IF NOT EXISTS idx_tfptg_tg ON training_framework_program_target_groups(target_group_id);
-- ── Kein „Konkret“ mehr: Slots nicht an Kalender-Einheiten hängen ───────────
UPDATE training_framework_slots SET training_unit_id = NULL WHERE training_unit_id IS NOT NULL;
-- Gruppe/Modus vom Rahmen lösen (Historie: evtl. noch concrete + group_id gesetzt)
UPDATE training_framework_programs SET group_id = NULL;
DROP INDEX IF EXISTS idx_training_framework_programs_group;
ALTER TABLE training_framework_programs DROP CONSTRAINT IF EXISTS training_framework_programs_group_id_fkey;
ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS group_id;
-- Inline-CHECK(s) aus Migration 035 (plan_mode + group-Kombination) entfernen
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN (
SELECT c.conname AS cn
FROM pg_constraint c
WHERE c.conrelid = 'public.training_framework_programs'::regclass
AND c.contype = 'c'
AND (
pg_get_constraintdef(c.oid) ILIKE '%plan_mode%'
OR pg_get_constraintdef(c.oid) ILIKE '%group_id%'
)
)
LOOP
EXECUTE format('ALTER TABLE training_framework_programs DROP CONSTRAINT %I', r.cn);
END LOOP;
END $$;
ALTER TABLE training_framework_programs DROP COLUMN IF EXISTS plan_mode;
DROP INDEX IF EXISTS idx_training_framework_programs_mode;
@@ -0,0 +1,130 @@
-- Migration 037: Rahmen-Slot-„Blueprint“ = eine training_units-Zeile (Ablauf wie echte Einheit)
-- training_framework_slot_exercises migriert nach training_unit_sections / training_unit_section_items,
-- dann entfernt.
-- ── Neue Spalten ───────────────────────────────────────────────────────────────
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS framework_slot_id INT REFERENCES training_framework_slots(id)
ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS origin_framework_slot_id INT REFERENCES training_framework_slots(id)
ON DELETE SET NULL;
-- Genau eine Blueprint-Einheit pro Slot (PostgreSQL UNIQUE erlaubt mehrere NULLs — hier Partial Index)
DROP INDEX IF EXISTS uq_training_units_blueprint_slot;
CREATE UNIQUE INDEX uq_training_units_blueprint_slot
ON training_units(framework_slot_id)
WHERE framework_slot_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_training_units_framework_blueprint_calendar
ON training_units(planned_date, group_id)
WHERE framework_slot_id IS NULL;
CREATE INDEX IF NOT EXISTS idx_training_units_origin_slot
ON training_units(origin_framework_slot_id)
WHERE origin_framework_slot_id IS NOT NULL;
-- ── Nullable für Blueprint-Zeilen ────────────────────────────────────────────
ALTER TABLE training_units ALTER COLUMN planned_date DROP NOT NULL;
ALTER TABLE training_units ALTER COLUMN group_id DROP NOT NULL;
-- ── Für jeden Slot eine Blueprint-Einheit; vorhandene Übungen in erste Sektion ─
DO $$
DECLARE
rec RECORD;
new_uid INTEGER;
new_sec INTEGER;
BEGIN
FOR rec IN
SELECT s.id AS sid, fp.created_by AS fp_created_by
FROM training_framework_slots s
JOIN training_framework_programs fp ON fp.id = s.framework_program_id
LOOP
IF EXISTS (SELECT 1 FROM training_units tu WHERE tu.framework_slot_id = rec.sid) THEN
CONTINUE;
END IF;
INSERT INTO training_units (
group_id,
planned_date,
planned_time_start,
planned_time_end,
planned_focus,
status,
notes,
trainer_notes,
created_by,
plan_template_id,
framework_slot_id
)
VALUES (
NULL,
NULL,
NULL,
NULL,
NULL,
'planned',
NULL,
NULL,
rec.fp_created_by,
NULL,
rec.sid
)
RETURNING id INTO new_uid;
INSERT INTO training_unit_sections (
training_unit_id,
order_index,
title,
guidance_notes
)
VALUES (new_uid, 0, 'Ablauf', NULL)
RETURNING id INTO new_sec;
INSERT INTO training_unit_section_items (
section_id,
order_index,
item_type,
exercise_id,
exercise_variant_id,
planned_duration_min,
actual_duration_min,
notes,
modifications,
note_body
)
SELECT
new_sec,
sf.order_index,
'exercise'::character varying(20),
sf.exercise_id,
sf.exercise_variant_id,
NULL::integer,
NULL::integer,
NULL::text,
NULL::text,
NULL::text
FROM training_framework_slot_exercises sf
WHERE sf.slot_id = rec.sid
ORDER BY sf.order_index;
END LOOP;
END $$;
DROP TABLE IF EXISTS training_framework_slot_exercises;
ALTER TABLE training_units DROP CONSTRAINT IF EXISTS chk_training_units_blueprint_vs_scheduled;
ALTER TABLE training_units
ADD CONSTRAINT chk_training_units_blueprint_vs_scheduled CHECK (
(
framework_slot_id IS NOT NULL
AND group_id IS NULL
AND planned_date IS NULL
AND origin_framework_slot_id IS NULL
)
OR (
framework_slot_id IS NULL
AND group_id IS NOT NULL
AND planned_date IS NOT NULL
)
);
@@ -0,0 +1,11 @@
-- Migration 038: Optionale verantwortliche Person pro Trainingstermin (Vertretung)
-- Für Vereins-/Trainerübersicht: COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) = wirksamer Leitungstrainer.
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS lead_trainer_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL;
COMMENT ON COLUMN training_units.lead_trainer_profile_id IS 'Vertretung / expliziter Leiter dieses Terms; NULL = Standard (Haupttrainer der Gruppe)';
CREATE INDEX IF NOT EXISTS idx_training_units_lead_trainer
ON training_units(lead_trainer_profile_id)
WHERE lead_trainer_profile_id IS NOT NULL;
@@ -0,0 +1,119 @@
-- Migration 039: Vereins-Mitgliedschaft, Rollen pro Verein, aktiver Vereinskontext (Multi-Tenancy Phase 1)
-- Erstellt: 2026-05-05
-- Mitgliedschaft Profil ↔ Verein
CREATE TABLE club_members (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
club_id INT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
status VARCHAR(20) NOT NULL DEFAULT 'active',
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE(profile_id, club_id)
);
CREATE INDEX idx_club_members_profile ON club_members(profile_id);
CREATE INDEX idx_club_members_club ON club_members(club_id);
CREATE INDEX idx_club_members_status ON club_members(status);
-- Rollen pro Mitgliedschaft (role_code: club_admin, trainer, division_lead, content_editor)
CREATE TABLE club_member_roles (
id SERIAL PRIMARY KEY,
club_member_id INT NOT NULL REFERENCES club_members(id) ON DELETE CASCADE,
role_code VARCHAR(50) NOT NULL,
division_id INT REFERENCES divisions(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE (club_member_id, role_code)
);
CREATE INDEX idx_club_member_roles_member ON club_member_roles(club_member_id);
CREATE INDEX idx_club_member_roles_code ON club_member_roles(role_code);
-- Hauptverwalter:in (fachliche Referenz; Rechte über club_member_roles.club_admin)
ALTER TABLE clubs ADD COLUMN IF NOT EXISTS primary_admin_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL;
CREATE INDEX idx_clubs_primary_admin ON clubs(primary_admin_profile_id);
-- Persistenz gewählter aktiver Verein (UI); Request-Header kann überschreiben
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS active_club_id INT REFERENCES clubs(id) ON DELETE SET NULL;
CREATE INDEX idx_profiles_active_club ON profiles(active_club_id);
-- ── Backfill: Trainer/Co-Trainer aus Trainingsgruppen → Mitgliedschaft + Rolle trainer
INSERT INTO club_members (profile_id, club_id, status)
SELECT DISTINCT t.trainer_id, t.club_id, 'active'
FROM training_groups t
WHERE t.trainer_id IS NOT NULL
ON CONFLICT (profile_id, club_id) DO NOTHING;
INSERT INTO club_members (profile_id, club_id, status)
SELECT DISTINCT elem::int, x.club_id, 'active'
FROM (
SELECT club_id, co_trainer_ids
FROM training_groups
WHERE CASE WHEN jsonb_typeof(co_trainer_ids) = 'array'
THEN jsonb_array_length(co_trainer_ids)
ELSE 0 END > 0
) x,
LATERAL jsonb_array_elements_text(x.co_trainer_ids) AS elem
ON CONFLICT (profile_id, club_id) DO NOTHING;
INSERT INTO club_member_roles (club_member_id, role_code)
SELECT cm.id, 'trainer'
FROM club_members cm
WHERE NOT EXISTS (
SELECT 1 FROM club_member_roles r
WHERE r.club_member_id = cm.id AND r.role_code = 'trainer'
);
-- Pro Verein: kleinste trainer_id einer Gruppe als primärer Admin (Pilot / CURR-008-Analog)
UPDATE clubs c
SET primary_admin_profile_id = sub.pid
FROM (
SELECT DISTINCT ON (club_id)
club_id,
trainer_id AS pid
FROM training_groups
WHERE trainer_id IS NOT NULL
ORDER BY club_id, id ASC
) sub
WHERE c.id = sub.club_id
AND c.primary_admin_profile_id IS NULL;
INSERT INTO club_member_roles (club_member_id, role_code)
SELECT cm.id, 'club_admin'
FROM club_members cm
INNER JOIN clubs cl ON cl.id = cm.club_id AND cl.primary_admin_profile_id = cm.profile_id
WHERE NOT EXISTS (
SELECT 1 FROM club_member_roles r
WHERE r.club_member_id = cm.id AND r.role_code = 'club_admin'
);
-- Globale Admins: in jedem bestehenden Verein als club_admin spiegeln (volle Plattform-Sicht)
INSERT INTO club_members (profile_id, club_id, status)
SELECT p.id, c.id, 'active'
FROM profiles p
CROSS JOIN clubs c
WHERE p.role IN ('admin', 'superadmin')
ON CONFLICT (profile_id, club_id) DO NOTHING;
INSERT INTO club_member_roles (club_member_id, role_code)
SELECT cm.id, 'club_admin'
FROM club_members cm
INNER JOIN profiles p ON p.id = cm.profile_id AND p.role IN ('admin', 'superadmin')
WHERE NOT EXISTS (
SELECT 1 FROM club_member_roles r
WHERE r.club_member_id = cm.id AND r.role_code = 'club_admin'
);
-- Default aktiver Verein: einziger Verein des Nutzers
UPDATE profiles p
SET active_club_id = sub.only_club
FROM (
SELECT profile_id, MIN(club_id) AS only_club
FROM club_members
WHERE status = 'active'
GROUP BY profile_id
HAVING COUNT(DISTINCT club_id) = 1
) sub
WHERE p.id = sub.profile_id AND (p.active_club_id IS NULL);
@@ -0,0 +1,29 @@
-- Migration 040: Antrag auf Vereinsbeitritt (pending → accept/reject durch Vereins-/Plattform-Admin)
CREATE TABLE IF NOT EXISTS club_membership_requests (
id SERIAL PRIMARY KEY,
profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
club_id INT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
status VARCHAR(20) NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'accepted', 'rejected', 'withdrawn')),
message TEXT,
decided_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
decided_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_club_membership_requests_pending
ON club_membership_requests (profile_id, club_id)
WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_club_membership_requests_club_status
ON club_membership_requests (club_id, status);
CREATE INDEX IF NOT EXISTS idx_club_membership_requests_profile
ON club_membership_requests (profile_id);
DROP TRIGGER IF EXISTS club_membership_requests_update ON club_membership_requests;
CREATE TRIGGER club_membership_requests_update
BEFORE UPDATE ON club_membership_requests
FOR EACH ROW EXECUTE FUNCTION update_timestamp();
@@ -0,0 +1,20 @@
-- Migration 041: Super-Admin für bestehende Installationen
-- Bisheriger Bootstrap (registration_role) setzte nur 'admin'. Viele Endpunkte
-- (z. B. Verein löschen, Super-Rolle vergeben) verlangen 'superadmin'.
-- Wenn noch kein Super-Admin existiert: den ältesten Nutzer mit role = admin hochstufen.
UPDATE profiles p
SET role = 'superadmin', updated_at = NOW()
FROM (
SELECT id
FROM profiles
WHERE lower(trim(COALESCE(role, ''))) = 'admin'
ORDER BY id ASC
LIMIT 1
) sub
WHERE p.id = sub.id
AND NOT EXISTS (
SELECT 1
FROM profiles
WHERE lower(trim(COALESCE(role, ''))) = 'superadmin'
);
@@ -0,0 +1,9 @@
-- Session-spezifische Co-Trainer: NULL = wie training_groups.co_trainer_ids; [] = explizit keine Co-Trainer
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS assistant_trainer_profile_ids JSONB;
COMMENT ON COLUMN training_units.assistant_trainer_profile_ids IS
'Co-Trainer nur für diese Einheit; NULL vererbt training_groups.co_trainer_ids; leeres Array = keine Co-Trainer';
CREATE INDEX IF NOT EXISTS idx_training_units_assistant_trainers
ON training_units USING GIN (assistant_trainer_profile_ids);
@@ -0,0 +1,3 @@
-- Gespeicherte Standard-Filter für die Übungsliste (pro Nutzer)
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS exercise_list_prefs JSONB NOT NULL DEFAULT '{}'::jsonb;
@@ -0,0 +1,10 @@
-- Rückschau / Nachbereitung: explizit abschließbar (Dashboard & Filter)
ALTER TABLE training_units
ADD COLUMN IF NOT EXISTS debrief_completed_at TIMESTAMPTZ NULL;
COMMENT ON COLUMN training_units.debrief_completed_at IS
'Zeitpunkt, zu dem die Trainer-Rückschau (Nachbereitung) bewusst abgeschlossen wurde; NULL = offen';
CREATE INDEX IF NOT EXISTS idx_training_units_debrief_open
ON training_units (status, debrief_completed_at)
WHERE status = 'completed' AND debrief_completed_at IS NULL;
@@ -0,0 +1,106 @@
-- Migration 045: Zentrale media_assets, exercise_media.media_asset_id, platform_media_storage (Superadmin-Pfad).
-- Siehe .claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE platform_media_storage (
id SMALLINT PRIMARY KEY DEFAULT 1,
CONSTRAINT platform_media_storage_singleton CHECK (id = 1),
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
local_relative_root VARCHAR(512) NOT NULL DEFAULT '',
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
);
INSERT INTO platform_media_storage (id, storage_backend, local_relative_root)
VALUES (1, 'local', '')
ON CONFLICT (id) DO NOTHING;
CREATE TABLE media_assets (
id SERIAL PRIMARY KEY,
mime_type VARCHAR(100),
byte_size INT,
sha256 CHAR(64) NOT NULL,
original_filename VARCHAR(300),
visibility VARCHAR(32) NOT NULL DEFAULT 'private',
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
uploaded_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
copyright_notice TEXT,
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
storage_key TEXT NOT NULL,
lifecycle_state VARCHAR(32) NOT NULL DEFAULT 'active',
trash_soft_at TIMESTAMP WITH TIME ZONE,
trash_hidden_at TIMESTAMP WITH TIME ZONE,
purge_after_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_media_assets_club ON media_assets(club_id);
CREATE INDEX idx_media_assets_sha256 ON media_assets(sha256);
CREATE INDEX idx_media_assets_lifecycle ON media_assets(lifecycle_state);
CREATE UNIQUE INDEX ux_media_assets_storage_key ON media_assets(storage_key);
ALTER TABLE exercise_media
ADD COLUMN IF NOT EXISTS media_asset_id INT REFERENCES media_assets(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_exercise_media_asset ON exercise_media(media_asset_id);
-- Bestand: je distinct storage_key ein Asset; sha256 aus DB-Pfad (Migrations-Platzhalter, nicht Content-Hash)
INSERT INTO media_assets (
mime_type,
byte_size,
sha256,
original_filename,
visibility,
club_id,
uploaded_by_profile_id,
storage_backend,
storage_key,
copyright_notice,
lifecycle_state,
created_at,
updated_at
)
SELECT
s.mime_type,
s.byte_size,
s.sha256,
s.original_filename,
s.visibility,
s.club_id,
s.uploaded_by_profile_id,
'local',
s.storage_key,
NULL,
'active',
s.created_at,
NOW()
FROM (
SELECT DISTINCT ON (storage_key)
em.mime_type,
em.file_size AS byte_size,
encode(digest(trim(em.file_path), 'sha256'), 'hex') AS sha256,
em.original_filename,
lower(trim(e.visibility)) AS visibility,
e.club_id,
e.created_by AS uploaded_by_profile_id,
regexp_replace(trim(em.file_path), '^/+media/+', '') AS storage_key,
em.created_at
FROM exercise_media em
JOIN exercises e ON e.id = em.exercise_id
WHERE em.file_path IS NOT NULL
AND trim(em.file_path) <> ''
AND em.embed_url IS NULL
ORDER BY regexp_replace(trim(em.file_path), '^/+media/+', ''), em.id
) s
WHERE NOT EXISTS (SELECT 1 FROM media_assets ma WHERE ma.storage_key = s.storage_key);
UPDATE exercise_media em
SET media_asset_id = ma.id
FROM media_assets ma
WHERE em.media_asset_id IS NULL
AND em.file_path IS NOT NULL
AND trim(em.file_path) <> ''
AND em.embed_url IS NULL
AND ma.storage_key = regexp_replace(trim(em.file_path), '^/+media/+', '');
@@ -0,0 +1,9 @@
-- Migration 046: Schlagwörter (tags) für media_assets — Suche & Filter in der Medienbibliothek.
--
-- Einordnung: läuft nach 045 (media_assets existiert). Idempotent:
-- • wird pro Umgebung höchstens einmal über schema_migrations ausgeführt;
-- • dieselben Statements sind bei Wiederholung harmlos (IF NOT EXISTS).
ALTER TABLE media_assets
ADD COLUMN IF NOT EXISTS tags TEXT[] NOT NULL DEFAULT '{}';
CREATE INDEX IF NOT EXISTS idx_media_assets_tags_gin ON media_assets USING GIN (tags);
+16 -3
View File
@@ -4,7 +4,7 @@ Pydantic Models for Shinkan Jinkendo API
Request/Response schemas for all endpoints
"""
from pydantic import BaseModel, EmailStr, Field
from typing import Optional, List
from typing import Optional, List, Dict, Any
from datetime import date, time, datetime
# ============================================================================
@@ -19,6 +19,7 @@ class RegisterRequest(BaseModel):
email: EmailStr
password: str
name: Optional[str] = None
requested_club_id: Optional[int] = Field(default=None, ge=1)
class PasswordResetRequest(BaseModel):
email: str
@@ -28,12 +29,24 @@ class PasswordResetConfirm(BaseModel):
new_password: str
class ProfileCreate(BaseModel):
name: str
email: Optional[str] = None
"""Nur für POST /api/profiles (Plattform-Admin): neues Nutzerprofil ohne Self-Registration."""
name: str = Field(min_length=2, max_length=200)
email: EmailStr
class ProfileUpdate(BaseModel):
name: Optional[str] = None
email: Optional[str] = None
active_club_id: Optional[int] = None
role: Optional[str] = Field(
default=None,
description="Portal-Rolle: user, trainer, admin, superadmin (nur Plattform-Admin)",
)
tier: Optional[str] = Field(default=None, max_length=50)
exercise_list_prefs: Optional[Dict[str, Any]] = Field(
default=None,
description="JSON: gespeicherte Standardfilter für die Übungsliste",
)
class ProfileResponse(BaseModel):
id: int
+68
View File
@@ -0,0 +1,68 @@
"""Gemeinsame Passwort-Link-Erzeugung (Sessions) + Mailtext — wie /auth/forgot-password."""
from __future__ import annotations
import os
import secrets
from datetime import datetime, timedelta
from typing import Any
RESET_TOKEN_PREFIX = "reset_"
def public_reset_link(token: str) -> str:
base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
return f"{base}/reset-password?token={token}"
def revoke_pending_password_resets_for_profile(cur: Any, profile_id: int) -> None:
"""Entfernt alte Reset-Sessions eines Profils, damit nur der neueste Link aktiv ist."""
cur.execute(
"""
DELETE FROM sessions
WHERE profile_id = %s AND token LIKE %s
""",
(profile_id, f"{RESET_TOKEN_PREFIX}%"),
)
def insert_password_reset_session(cur: Any, profile_id: int, *, hours_valid: int = 1) -> str:
"""
Legt reset_<token>-Session an. Gibt den Klartext-Token zurück (wie bei forgot-password).
"""
raw = secrets.token_urlsafe(32)
expires = datetime.now() + timedelta(hours=hours_valid)
cur.execute(
"""
INSERT INTO sessions (token, profile_id, expires_at, created_at)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
""",
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
)
return raw
def password_reset_email_body(*, recipient_name: str | None, token: str, intro: str) -> str:
name = (recipient_name or "").strip() or "Kollege/Kollegin"
link = public_reset_link(token)
return f"""Hallo {name},
{intro}
Neues Passwort setzen:
{link}
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
Dein Shinkan Jinkendo Team
"""
def issue_password_reset_via_email(cur: Any, send_email_fn, *, profile_id: int, email: str, name: str | None, intro: str) -> bool:
"""Session anlegen und Mail schicken (send_email_fn wie routers.auth.send_email)."""
revoke_pending_password_resets_for_profile(cur, profile_id)
raw_token = insert_password_reset_session(cur, profile_id)
body = password_reset_email_body(recipient_name=name, token=raw_token, intro=intro)
return send_email_fn(email, "Passwort-Link – Shinkan Jinkendo", body)
+10
View File
@@ -0,0 +1,10 @@
[pytest]
testpaths = tests
pythonpath = .
python_files = test_*.py
python_functions = test_*
addopts = -q --tb=short
markers =
smoke: Schnelle Kern-Regression.
integration: PostgreSQL-Mandanten-Integration (ACCESS_LAYER_INTEGRATION=1).
slow: Lange/schwere Tests; in CI wie Mitai-Jinkendo ausgeschlossen (Auswahl: not slow).
+3
View File
@@ -0,0 +1,3 @@
# Entwicklung / CI — zusätzlich zu backend/requirements.txt installieren:
# pip install -r backend/requirements.txt -r backend/requirements-dev.txt
pytest>=8.0,<9
+1
View File
@@ -10,3 +10,4 @@ slowapi==0.1.9
psycopg2-binary==2.9.9
python-dateutil==2.9.0
tzdata>=2024.1 # ZoneInfo (Europe/Berlin) auch unter Windows
sqlparse>=0.5.0 # Migrationen: Statements splitten (Fallback ohne psql)
+41
View File
@@ -0,0 +1,41 @@
"""
Plattform-Admin: Übersicht aller Nutzer inkl. Vereinsmitgliedschaften (ohne Passwort-Hashes).
"""
from typing import Any, Dict, List
from fastapi import APIRouter, Depends, HTTPException
from auth import require_auth
from club_tenancy import is_platform_admin, memberships_with_roles
from db import get_db, get_cursor, r2d
router = APIRouter(prefix="/api/admin", tags=["admin_users"])
_SAFE_PROFILE_COLS = """
id, name, email, role, tier, email_verified, active_club_id,
created_at, updated_at, auth_type
"""
@router.get("/users")
def list_platform_users(session: dict = Depends(require_auth)):
"""Alle Profile mit Vereinen/Rollen — nur Portal-Admin (admin oder superadmin)."""
role = (session.get("role") or "").lower()
if not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Nur Portal-Administratoren")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"""
SELECT {_SAFE_PROFILE_COLS.strip()}
FROM profiles
ORDER BY COALESCE(lower(trim(email)), ''), id
"""
)
rows: List[Dict[str, Any]] = []
for r in cur.fetchall():
d = r2d(r)
d["clubs"] = memberships_with_roles(cur, int(d["id"]), active_only=False)
rows.append(d)
return rows
+152 -91
View File
@@ -6,6 +6,8 @@ Handles login, logout, password reset, and profile authentication.
import os
import secrets
import smtplib
import ssl
from urllib.parse import quote
from typing import Optional
from datetime import datetime, timedelta, timezone
from email.mime.text import MIMEText
@@ -18,13 +20,18 @@ from slowapi.util import get_remote_address
from db import get_db, get_cursor
from auth import hash_pin, verify_pin, make_token, require_auth
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
from password_reset_mail import (
insert_password_reset_session,
password_reset_email_body,
revoke_pending_password_resets_for_profile,
)
router = APIRouter(prefix="/api/auth", tags=["auth"])
limiter = Limiter(key_func=get_remote_address)
@router.post("/login")
@limiter.limit("5/minute")
@limiter.limit("30/minute")
async def login(req: LoginRequest, request: Request):
"""Login with email + password."""
with get_db() as conn:
@@ -53,9 +60,11 @@ async def login(req: LoginRequest, request: Request):
return {
"token": token,
"profile_id": prof['id'],
"name": prof['name'],
"role": prof['role'],
"expires_at": expires.isoformat()
"email": prof.get("email"),
"name": prof.get("name"),
"role": prof.get("role"),
"tier": prof.get("tier"),
"expires_at": expires.isoformat(),
}
@@ -74,8 +83,8 @@ def get_me(session: dict=Depends(require_auth)):
"""Get current user info."""
pid = session['profile_id']
# Import here to avoid circular dependency
from routers.profiles import get_profile
return get_profile(pid, session)
from routers.profiles import profile_document
return profile_document(pid)
@router.get("/status")
@@ -112,47 +121,16 @@ async def password_reset_request(req: PasswordResetRequest, request: Request):
if not prof:
# Don't reveal if email exists
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
revoke_pending_password_resets_for_profile(cur, prof["id"])
raw_token = insert_password_reset_session(cur, prof["id"])
# Generate reset token
token = secrets.token_urlsafe(32)
expires = datetime.now() + timedelta(hours=1)
# Store in sessions table (reuse mechanism)
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
(f"reset_{token}", prof['id'], expires.isoformat()))
# Send email
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM")
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
if smtp_host and smtp_user and smtp_pass:
msg = MIMEText(f"""Hallo {prof['name']},
Du hast einen Passwort-Reset angefordert.
Reset-Link: {app_url}/reset-password?token={token}
Der Link ist 1 Stunde gültig.
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
Dein Mitai Jinkendo Team
""")
msg['Subject'] = "Passwort zurücksetzen – Mitai Jinkendo"
msg['From'] = smtp_from
msg['To'] = email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
except Exception as e:
print(f"Email error: {e}")
reset_body = password_reset_email_body(
recipient_name=prof.get("name"),
token=raw_token,
intro="Du hast einen Passwort-Reset angefordert.",
)
if not send_email(email, "Passwort zurücksetzen – Shinkan Jinkendo", reset_body):
print("[SMTP] Passwort-Reset konnte nicht gesendet werden (SMTP prüfen).")
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
@@ -175,34 +153,102 @@ def password_reset_confirm(req: PasswordResetConfirm):
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
# ── Helpers (Registrierung / E-Mail-Links) ─────────────────────────────────────
def _public_app_base() -> str:
return (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
def _verification_link_expired(expires_at) -> bool:
"""
True, wenn Ablaufzeit in der Vergangenheit liegt.
PG liefert TIMESTAMP oft als naive datetime — Vergleich mit timezone-aware UTC
würde sonst TypeError → 500.
"""
if expires_at is None:
return False
deadline = expires_at.replace(tzinfo=timezone.utc) if expires_at.tzinfo is None else expires_at.astimezone(timezone.utc)
return datetime.now(timezone.utc) > deadline
def verification_link(token: str) -> str:
"""Link zur Web-App (`/verify?token=`); die SPA ruft wie bei Mitai die API auf."""
return f"{_public_app_base()}/verify?token={quote(token, safe='')}"
def registration_role(cur, email_lower: str) -> str:
"""
bootstrap: erste Registrierung in leerer DB → superadmin,
oder E-Mail ∈ ADMIN_BOOTSTRAP_EMAILS (kommasepariert, Groß/Klein egal).
superadmin deckt alle Portal-Rechte ab (inkl. löschen / andere Super-Admins).
Um alle Self-Regs als Trainer zu haben: AUTO_ADMIN_FIRST_USER=false und keine ADMIN_BOOTSTRAP_EMAILS.
"""
bootstrap = {
x.strip().lower()
for x in os.getenv("ADMIN_BOOTSTRAP_EMAILS", "").split(",")
if x.strip()
}
if email_lower in bootstrap:
return "superadmin"
if os.getenv("AUTO_ADMIN_FIRST_USER", "true").strip().lower() not in ("1", "true", "yes"):
return "trainer"
cur.execute("SELECT COUNT(*) AS n FROM profiles")
row = cur.fetchone()
try:
n = int(row["n"]) if row is not None else 0
except (KeyError, TypeError, ValueError):
n = 0
return "superadmin" if n == 0 else "trainer"
# ── Helper: Send Email ────────────────────────────────────────────────────────
def send_email(to_email: str, subject: str, body: str):
"""Send email via SMTP (reusable helper)."""
"""Send mail via SMTP. Port 465 → SSL; sonst SMTP + optional STARTTLS (587)."""
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_host = (os.getenv("SMTP_HOST") or "").strip()
smtp_port_raw = os.getenv("SMTP_PORT") or "587"
try:
smtp_port = int(str(smtp_port_raw).strip())
except ValueError:
smtp_port = 587
smtp_user = (os.getenv("SMTP_USER") or "").strip()
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
if not smtp_host or not smtp_user or not smtp_pass:
print("SMTP not configured, skipping email")
if not smtp_host or not smtp_user or smtp_pass is None or smtp_pass == "":
print("[SMTP] Nicht konfiguriert — setze SMTP_HOST, SMTP_USER, SMTP_PASS (und ggf. SMTP_PORT)")
return False
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to_email
msg["Subject"] = subject
msg["From"] = smtp_from
msg["To"] = to_email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
use_tls_env = (os.getenv("SMTP_STARTTLS", "true").strip().lower() not in ("0", "false", "no"))
force_ssl = (os.getenv("SMTP_SSL", "").strip().lower() in ("1", "true", "yes")) or smtp_port == 465
ctx = ssl.create_default_context()
if force_ssl:
print(f"[SMTP] Versand (SSL) an …@{to_email.split('@')[-1]} über {smtp_host}:{smtp_port}")
with smtplib.SMTP_SSL(smtp_host, smtp_port, context=ctx, timeout=30) as server:
server.login(smtp_user, smtp_pass)
server.send_message(msg)
else:
print(f"[SMTP] Versand (STARTTLS={use_tls_env}) an …@{to_email.split('@')[-1]} über {smtp_host}:{smtp_port}")
with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as server:
server.ehlo()
if use_tls_env:
server.starttls(context=ctx)
server.ehlo()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
print("[SMTP] Nachricht erfolgreich akzeptiert (Server-Queue)")
return True
except Exception as e:
print(f"Email error: {e}")
print(f"[SMTP] Fehler: {e}")
return False
@@ -235,37 +281,64 @@ async def register(req: RegisterRequest, request: Request):
verification_token = secrets.token_urlsafe(32)
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
# Create profile (inactive until verified)
profile_id = str(secrets.token_hex(16))
# Rolle: erster Nutzer oder ADMIN_BOOTSTRAP_EMAILS → superadmin
role = registration_role(cur, email)
# Create profile (inactive until verified) — profiles.id ist SERIAL (INT), keine String-IDs einfügen.
pin_hash = hash_pin(password)
trial_ends = datetime.now(timezone.utc) + timedelta(days=14) # 14-day trial
cur.execute("""
INSERT INTO profiles (
id, name, email, pin_hash, auth_type, role, tier,
name, email, pin_hash, auth_type, role, tier,
email_verified, verification_token, verification_expires,
trial_ends_at, created
) VALUES (%s, %s, %s, %s, 'email', 'user', 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
""", (profile_id, name, email, pin_hash, verification_token, verification_expires, trial_ends))
trial_ends_at, created_at
) VALUES (%s, %s, %s, 'email', %s, 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
RETURNING id
""", (name, email, pin_hash, role, verification_token, verification_expires, trial_ends))
new_profile_id = cur.fetchone()["id"]
# Send verification email
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
verify_url = f"{app_url}/verify?token={verification_token}"
req_club = req.requested_club_id
if req_club is not None:
cur.execute(
"SELECT id FROM clubs WHERE id = %s AND status = 'active'",
(int(req_club),),
)
if cur.fetchone():
cur.execute(
"""
SELECT id FROM club_membership_requests
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
LIMIT 1
""",
(new_profile_id, int(req_club)),
)
if not cur.fetchone():
cur.execute(
"""
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
VALUES (%s, %s, 'pending', NULL)
""",
(new_profile_id, int(req_club)),
)
verify_url = verification_link(verification_token)
email_body = f"""Hallo {name},
willkommen bei Mitai Jinkendo!
willkommen bei Shinkan Jinkendo!
Bitte bestätige deine E-Mail-Adresse um die Registrierung abzuschließen:
Bitte bestätige deine E-Mail-Adresse, um die Registrierung abzuschließen:
{verify_url}
Der Link ist 24 Stunden gültig.
Dein Mitai Jinkendo Team
Dein Shinkan Jinkendo Team
"""
send_email(email, "Willkommen bei Mitai Jinkendo – E-Mail bestätigen", email_body)
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.")
return {
"ok": True,
@@ -297,7 +370,7 @@ async def verify_email(token: str):
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
# Check if token expired
if prof['verification_expires'] and datetime.now(timezone.utc) > prof['verification_expires']:
if _verification_link_expired(prof["verification_expires"]):
raise HTTPException(400, "Verifikations-Link abgelaufen. Bitte registriere dich erneut.")
# Mark as verified and clear token
@@ -365,34 +438,22 @@ async def resend_verification(req: dict, request: Request):
WHERE id=%s
""", (verification_token, verification_expires, prof['id']))
# Send verification email
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
verify_url = f"{app_url}/verify?token={verification_token}"
verify_url = verification_link(verification_token)
email_body = f"""Hallo {prof['name']},
du hast eine neue Bestätigungs-E-Mail angefordert.
Bitte bestätige deine E-Mail-Adresse, indem du auf folgenden Link klickst:
Bitte bestätige deine E-Mail-Adresse mit diesem Link:
{verify_url}
Dieser Link ist 24 Stunden gültig.
Falls du diese E-Mail nicht angefordert hast, kannst du sie einfach ignorieren.
Viele Grüße
Dein Mitai Jinkendo Team
Dein Shinkan Jinkendo Team
"""
try:
send_email(
to=email,
subject="Neue Bestätigungs-E-Mail - Mitai Jinkendo",
body=email_body
)
except Exception as e:
print(f"Failed to send verification email: {e}")
raise HTTPException(500, "E-Mail konnte nicht versendet werden")
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
raise HTTPException(502, "E-Mail konnte nicht versendet werden. SMTP-Einstellungen und Container-Logs prüfen.")
return {"ok": True, "message": "Bestätigungs-E-Mail wurde erneut versendet."}
File diff suppressed because it is too large. Load diff
+347
View File
@@ -0,0 +1,347 @@
"""
Anträge auf Vereinsbeitritt: Nutzer stellt Antrag, Vereins-/Plattform-Admin nimmt an oder lehnt ab.
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from club_tenancy import can_manage_club_org, is_platform_admin
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context
router = APIRouter(prefix="/api", tags=["club_join_requests"])
_ALLOWED_MEMBER_ROLES = frozenset({"club_admin", "trainer", "division_lead", "content_editor"})
def _normalize_roles(raw: List[str]) -> List[str]:
out: List[str] = []
seen = set()
for r in raw:
if not isinstance(r, str):
raise HTTPException(status_code=400, detail="Rollen müssen Strings sein")
code = r.strip().lower()
if not code or code not in _ALLOWED_MEMBER_ROLES:
raise HTTPException(status_code=400, detail=f"Unbekannte Rolle: {code}")
if code not in seen:
seen.add(code)
out.append(code)
return out
def _club_active(cur, club_id: int) -> bool:
cur.execute("SELECT 1 FROM clubs WHERE id = %s AND status = 'active'", (club_id,))
return cur.fetchone() is not None
def _assert_manage_club(cur, tenant: TenantContext, club_id: int) -> None:
pid = tenant.profile_id
role = tenant.global_role
if not can_manage_club_org(cur, pid, club_id, role):
raise HTTPException(status_code=403, detail="Keine Berechtigung für Mitglieder-Verwaltung in diesem Verein")
def _is_active_member(cur, profile_id: int, club_id: int) -> bool:
cur.execute(
"""
SELECT 1 FROM club_members
WHERE profile_id = %s AND club_id = %s AND status = 'active'
LIMIT 1
""",
(profile_id, club_id),
)
return cur.fetchone() is not None
def _upsert_active_member_with_roles(cur, club_id: int, profile_id: int, roles: List[str]) -> None:
roles_n = _normalize_roles(roles)
if not roles_n:
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
cur.execute(
"""
INSERT INTO club_members (profile_id, club_id, status)
VALUES (%s, %s, 'active')
ON CONFLICT (profile_id, club_id)
DO UPDATE SET status = 'active', updated_at = NOW()
RETURNING id
""",
(profile_id, club_id),
)
cm_id = cur.fetchone()["id"]
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
for rc in roles_n:
cur.execute(
"""
INSERT INTO club_member_roles (club_member_id, role_code)
VALUES (%s, %s)
ON CONFLICT (club_member_id, role_code) DO NOTHING
""",
(cm_id, rc),
)
class JoinRequestCreate(BaseModel):
club_id: int = Field(..., ge=1)
message: Optional[str] = Field(None, max_length=2000)
class JoinRequestAccept(BaseModel):
roles: List[str] = Field(default_factory=lambda: ["trainer"])
def _response_one(cur, req_id: int, viewer_profile_id: int) -> Dict[str, Any]:
cur.execute(
"""
SELECT r.*, c.name AS club_name, c.abbreviation AS club_abbreviation
FROM club_membership_requests r
INNER JOIN clubs c ON c.id = r.club_id
WHERE r.id = %s AND r.profile_id = %s
""",
(req_id, viewer_profile_id),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Antrag nicht gefunden")
return r2d(row)
def _can_access_org_inbox(cur, profile_id: int, global_role: Optional[str]) -> bool:
"""Posteingang (Beitrittsanträge bearbeiten): Plattform-Admin oder Vereinsadmin in mind. einem Verein."""
if is_platform_admin(global_role):
return True
cur.execute(
"""
SELECT 1
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
WHERE cm.profile_id = %s AND cm.status = 'active'
LIMIT 1
""",
(profile_id,),
)
return cur.fetchone() is not None
def _club_ids_manageable_by_user(cur, profile_id: int, global_role: Optional[str]) -> List[int]:
"""Club-IDs, für die der Nutzer Beitrittsanträge sehen darf."""
if is_platform_admin(global_role):
cur.execute("SELECT id FROM clubs WHERE status = 'active' ORDER BY name")
return [int(r["id"]) for r in cur.fetchall()]
cur.execute(
"""
SELECT DISTINCT cm.club_id
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
WHERE cm.profile_id = %s AND cm.status = 'active'
""",
(profile_id,),
)
return [int(r["club_id"]) for r in cur.fetchall()]
@router.get("/me/inbox/join-requests")
def list_inbox_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
"""
Alle offenen Beitrittsanträge, die der Nutzer bearbeiten darf:
Plattform-Admin: alle Vereine; sonst nur Vereine mit Rolle club_admin.
"""
pid = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
if not _can_access_org_inbox(cur, pid, role):
raise HTTPException(status_code=403, detail="Kein Zugriff auf den Organisations-Posteingang")
club_ids = _club_ids_manageable_by_user(cur, pid, role)
if not club_ids:
return []
cur.execute(
"""
SELECT r.id, r.profile_id, r.club_id, r.status, r.message, r.created_at,
c.name AS club_name, c.abbreviation AS club_abbreviation,
p.name AS applicant_name, p.email AS applicant_email
FROM club_membership_requests r
INNER JOIN clubs c ON c.id = r.club_id
INNER JOIN profiles p ON p.id = r.profile_id
WHERE r.status = 'pending'
AND r.club_id = ANY(%s)
ORDER BY r.created_at ASC
""",
(club_ids,),
)
return [r2d(row) for row in cur.fetchall()]
@router.get("/me/club-join-requests")
def get_my_join_requests(tenant: TenantContext = Depends(get_tenant_context)):
pid = tenant.profile_id
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT r.*, c.name AS club_name, c.abbreviation AS club_abbreviation
FROM club_membership_requests r
INNER JOIN clubs c ON c.id = r.club_id
WHERE r.profile_id = %s
ORDER BY r.created_at DESC
LIMIT 100
""",
(pid,),
)
return [r2d(r) for r in cur.fetchall()]
@router.post("/me/club-join-requests", status_code=201)
def create_my_join_request(body: JoinRequestCreate, tenant: TenantContext = Depends(get_tenant_context)):
"""Antrag stellen (nicht möglich wenn bereits aktives Mitglied)."""
pid = tenant.profile_id
msg = (body.message or "").strip() or None
cid = body.club_id
with get_db() as conn:
cur = get_cursor(conn)
if not _club_active(cur, cid):
raise HTTPException(status_code=404, detail="Verein nicht gefunden oder nicht aktiv")
if _is_active_member(cur, pid, cid):
raise HTTPException(status_code=400, detail="Du bist bereits Mitglied in diesem Verein")
cur.execute(
"""
SELECT id FROM club_membership_requests
WHERE profile_id = %s AND club_id = %s AND status = 'pending'
LIMIT 1
""",
(pid, cid),
)
if cur.fetchone():
raise HTTPException(status_code=409, detail="Für diesen Verein liegt bereits ein offener Antrag vor")
cur.execute(
"""
INSERT INTO club_membership_requests (profile_id, club_id, status, message)
VALUES (%s, %s, 'pending', %s)
RETURNING id
""",
(pid, cid, msg),
)
rid = cur.fetchone()["id"]
conn.commit()
with get_db() as conn:
cur = get_cursor(conn)
return _response_one(cur, rid, pid)
@router.delete("/me/club-join-requests/{request_id}")
def withdraw_my_join_request(request_id: int, tenant: TenantContext = Depends(get_tenant_context)):
pid = tenant.profile_id
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
UPDATE club_membership_requests
SET status = 'withdrawn', updated_at = NOW()
WHERE id = %s AND profile_id = %s AND status = 'pending'
RETURNING id
""",
(request_id, pid),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Offener Antrag nicht gefunden")
conn.commit()
return {"ok": True}
@router.get("/clubs/{club_id}/join-requests")
def list_club_join_requests(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Offene Anträge für einen Verein (Vereins-/Plattform-Admin)."""
with get_db() as conn:
cur = get_cursor(conn)
_assert_manage_club(cur, tenant, club_id)
cur.execute(
"""
SELECT r.*, p.email AS applicant_email, p.name AS applicant_name
FROM club_membership_requests r
INNER JOIN profiles p ON p.id = r.profile_id
WHERE r.club_id = %s AND r.status = 'pending'
ORDER BY r.created_at ASC
""",
(club_id,),
)
return [r2d(r) for r in cur.fetchall()]
@router.post("/clubs/{club_id}/join-requests/{request_id}/accept")
def accept_club_join_request(
club_id: int,
request_id: int,
body: JoinRequestAccept,
tenant: TenantContext = Depends(get_tenant_context),
):
admin_pid = tenant.profile_id
roles = _normalize_roles(body.roles)
with get_db() as conn:
cur = get_cursor(conn)
_assert_manage_club(cur, tenant, club_id)
cur.execute(
"""
SELECT id, profile_id, status FROM club_membership_requests
WHERE id = %s AND club_id = %s
""",
(request_id, club_id),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Antrag nicht gefunden")
if row["status"] != "pending":
raise HTTPException(status_code=400, detail="Antrag ist nicht mehr offen")
applicant_id = row["profile_id"]
cur.execute(
"""
UPDATE club_membership_requests
SET status = 'accepted',
decided_by_profile_id = %s,
decided_at = NOW(),
updated_at = NOW()
WHERE id = %s AND club_id = %s AND status = 'pending'
RETURNING id
""",
(admin_pid, request_id, club_id),
)
if not cur.fetchone():
raise HTTPException(status_code=409, detail="Antrag konnte nicht angenommen werden")
_upsert_active_member_with_roles(cur, club_id, applicant_id, roles)
conn.commit()
return {"ok": True, "profile_id": applicant_id, "club_id": club_id}
@router.post("/clubs/{club_id}/join-requests/{request_id}/reject")
def reject_club_join_request(club_id: int, request_id: int, tenant: TenantContext = Depends(get_tenant_context)):
admin_pid = tenant.profile_id
with get_db() as conn:
cur = get_cursor(conn)
_assert_manage_club(cur, tenant, club_id)
cur.execute(
"""
UPDATE club_membership_requests
SET status = 'rejected',
decided_by_profile_id = %s,
decided_at = NOW(),
updated_at = NOW()
WHERE id = %s AND club_id = %s AND status = 'pending'
RETURNING id
""",
(admin_pid, request_id, club_id),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Offener Antrag nicht gefunden")
conn.commit()
return {"ok": True}
+341
View File
@@ -0,0 +1,341 @@
"""
Vereins-Mitgliedschaften und Rollen (ohne UI nutzbar für Admin/Automatisierung).
Berechtigung: Plattform-Admin (admin/superadmin) oder Vereinsadmin (club_admin) im Zielverein.
"""
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from club_tenancy import can_manage_club_org
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context
router = APIRouter(prefix="/api", tags=["club_memberships"])
_ALLOWED_ROLES = frozenset({"club_admin", "trainer", "division_lead", "content_editor"})
_ALLOWED_STATUS = frozenset({"active", "inactive"})
def _normalize_roles(raw: List[str]) -> List[str]:
out: List[str] = []
seen = set()
for r in raw:
if not isinstance(r, str):
raise HTTPException(status_code=400, detail="Rollen müssen Strings sein")
code = r.strip().lower()
if not code:
continue
if code not in _ALLOWED_ROLES:
raise HTTPException(
status_code=400,
detail=f"Unbekannte Rolle: {code}. Erlaubt: {', '.join(sorted(_ALLOWED_ROLES))}",
)
if code not in seen:
seen.add(code)
out.append(code)
return out
def _assert_manage(cur, tenant: TenantContext, club_id: int) -> None:
pid = tenant.profile_id
role = tenant.global_role
if not can_manage_club_org(cur, pid, club_id, role):
raise HTTPException(status_code=403, detail="Keine Berechtigung zur Mitglieder-Verwaltung in diesem Verein")
def _club_exists(cur, club_id: int) -> bool:
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
return cur.fetchone() is not None
def _count_other_active_club_admins(cur, club_id: int, exclude_profile_id: int) -> int:
"""Aktive Vereinsadmins im Verein, außer exclude_profile_id."""
cur.execute(
"""
SELECT COUNT(DISTINCT cm.profile_id)::int AS n
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
WHERE cm.club_id = %s AND cm.status = 'active' AND cm.profile_id <> %s
""",
(club_id, exclude_profile_id),
)
row = cur.fetchone()
try:
return int(row["n"]) if row is not None else 0
except (KeyError, TypeError, ValueError):
return 0
def _member_is_active_club_admin(cur, club_id: int, profile_id: int) -> bool:
cur.execute(
"""
SELECT 1
FROM club_members cm
INNER JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = 'club_admin'
WHERE cm.club_id = %s AND cm.profile_id = %s AND cm.status = 'active'
LIMIT 1
""",
(club_id, profile_id),
)
return cur.fetchone() is not None
_LAST_CLUB_ADMIN_MSG = (
"Mindestens ein aktiver Vereinsadmin muss im Verein verbleiben. "
"Weise die Rolle zuerst einem anderen Mitglied zu oder aktiviere einen anderen Vereinsadmin."
)
class ClubMemberUpsert(BaseModel):
profile_id: int = Field(..., ge=1)
roles: List[str] = Field(default_factory=list, description="Mindestens eine Vereinsrolle")
class ClubMemberPatch(BaseModel):
roles: Optional[List[str]] = None
status: Optional[str] = Field(None, description="active oder inactive")
@router.get("/clubs/{club_id}/members")
def list_club_members(
club_id: int,
include_inactive: bool = Query(False),
tenant: TenantContext = Depends(get_tenant_context),
):
"""Alle Mitglieder eines Vereins mit Rollen (nur Vereins-/Plattform-Admin)."""
with get_db() as conn:
cur = get_cursor(conn)
if not _club_exists(cur, club_id):
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
_assert_manage(cur, tenant, club_id)
status_clause = "" if include_inactive else "AND cm.status = 'active'"
cur.execute(
f"""
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
COALESCE(
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
ARRAY[]::varchar[]
) AS roles
FROM club_members cm
INNER JOIN profiles p ON p.id = cm.profile_id
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.club_id = %s {status_clause}
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
ORDER BY p.name NULLS LAST, p.email
""",
(club_id,),
)
rows = []
for row in cur.fetchall():
d = r2d(row)
roles = d.get("roles") or []
if hasattr(roles, "tolist"):
roles = roles.tolist()
d["roles"] = list(roles)
rows.append(d)
return rows
@router.post("/clubs/{club_id}/members", status_code=201)
def upsert_club_member(
club_id: int,
body: ClubMemberUpsert,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Mitglied anlegen oder aktivieren; Rollen werden vollständig ersetzt."""
roles = _normalize_roles(body.roles)
if not roles:
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
with get_db() as conn:
cur = get_cursor(conn)
if not _club_exists(cur, club_id):
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
_assert_manage(cur, tenant, club_id)
cur.execute("SELECT id FROM profiles WHERE id = %s", (body.profile_id,))
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
cur.execute(
"""
INSERT INTO club_members (profile_id, club_id, status)
VALUES (%s, %s, 'active')
ON CONFLICT (profile_id, club_id)
DO UPDATE SET status = 'active', updated_at = NOW()
RETURNING id
""",
(body.profile_id, club_id),
)
cm_id = cur.fetchone()["id"]
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
for rc in roles:
cur.execute(
"""
INSERT INTO club_member_roles (club_member_id, role_code)
VALUES (%s, %s)
ON CONFLICT (club_member_id, role_code) DO NOTHING
""",
(cm_id, rc),
)
conn.commit()
return _one_member(cur, club_id, body.profile_id)
def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
cur.execute(
"""
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
p.email, p.name, COALESCE(p.email_verified, false) AS email_verified,
lower(trim(COALESCE(p.role, 'user'))) AS portal_role,
COALESCE(
ARRAY_AGG(DISTINCT r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
ARRAY[]::varchar[]
) AS roles
FROM club_members cm
INNER JOIN profiles p ON p.id = cm.profile_id
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.club_id = %s AND cm.profile_id = %s
GROUP BY cm.id, cm.profile_id, cm.status, cm.created_at, cm.updated_at, p.email, p.name, p.email_verified, p.role
""",
(club_id, profile_id),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
d = r2d(row)
roles = d.get("roles") or []
if hasattr(roles, "tolist"):
roles = roles.tolist()
d["roles"] = list(roles)
return d
@router.get("/clubs/{club_id}/members/{profile_id}")
def get_club_member(
club_id: int,
profile_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
with get_db() as conn:
cur = get_cursor(conn)
if not _club_exists(cur, club_id):
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
_assert_manage(cur, tenant, club_id)
return _one_member(cur, club_id, profile_id)
@router.put("/clubs/{club_id}/members/{profile_id}")
def update_club_member(
club_id: int,
profile_id: int,
body: ClubMemberPatch,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Rollen ersetzen und/oder Status setzen."""
with get_db() as conn:
cur = get_cursor(conn)
if not _club_exists(cur, club_id):
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
_assert_manage(cur, tenant, club_id)
cur.execute(
"SELECT id FROM club_members WHERE club_id = %s AND profile_id = %s",
(club_id, profile_id),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
cm_id = row["id"]
if body.roles is None and body.status is None:
return _one_member(cur, club_id, profile_id)
cur.execute(
"""
SELECT cm.status,
COALESCE(
ARRAY_AGG(r.role_code) FILTER (WHERE r.role_code IS NOT NULL),
ARRAY[]::varchar[]
) AS roles
FROM club_members cm
LEFT JOIN club_member_roles r ON r.club_member_id = cm.id
WHERE cm.id = %s
GROUP BY cm.status
""",
(cm_id,),
)
cur_row = cur.fetchone()
current_status = (cur_row["status"] or "active").strip().lower() if cur_row else "active"
cr = cur_row.get("roles") if cur_row else []
if hasattr(cr, "tolist"):
cr = cr.tolist()
current_roles = list(cr)
new_status = body.status.strip().lower() if body.status is not None else current_status
if body.status is not None and new_status not in _ALLOWED_STATUS:
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
new_roles = _normalize_roles(body.roles) if body.roles is not None else current_roles
if not new_roles:
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
effective_admin = new_status == "active" and "club_admin" in set(new_roles)
if not effective_admin:
others = _count_other_active_club_admins(cur, club_id, profile_id)
if others < 1:
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
if body.status is not None:
cur.execute(
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
(new_status, cm_id),
)
if body.roles is not None:
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
for rc in new_roles:
cur.execute(
"""
INSERT INTO club_member_roles (club_member_id, role_code)
VALUES (%s, %s)
ON CONFLICT (club_member_id, role_code) DO NOTHING
""",
(cm_id, rc),
)
conn.commit()
return _one_member(cur, club_id, profile_id)
@router.delete("/clubs/{club_id}/members/{profile_id}")
def delete_club_member(
club_id: int,
profile_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Mitgliedschaft löschen (Rollen per CASCADE)."""
with get_db() as conn:
cur = get_cursor(conn)
if not _club_exists(cur, club_id):
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
_assert_manage(cur, tenant, club_id)
if _member_is_active_club_admin(cur, club_id, profile_id):
if _count_other_active_club_admins(cur, club_id, profile_id) < 1:
raise HTTPException(status_code=400, detail=_LAST_CLUB_ADMIN_MSG)
cur.execute(
"DELETE FROM club_members WHERE club_id = %s AND profile_id = %s RETURNING id",
(club_id, profile_id),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Mitgliedschaft nicht gefunden")
conn.commit()
return {"ok": True}
+433 -179
View File
@@ -3,37 +3,101 @@ Club & Organization Management Endpoints for Shinkan Jinkendo
Handles CRUD operations for clubs, divisions, and training groups.
"""
from typing import Optional
from typing import Any, List, Optional
from fastapi import APIRouter, HTTPException, Depends, Query
from psycopg2.extras import Json
from db import get_db, get_cursor, r2d
from auth import require_auth
from tenant_context import TenantContext, get_tenant_context
from club_tenancy import (
assert_club_member,
can_manage_club_org,
can_plan_in_club,
club_ids_for_profile,
is_platform_admin,
)
router = APIRouter(prefix="/api", tags=["clubs"])
def _blank_to_none(value: Any) -> Any:
"""Frontend sendet häufig '' für optionale Felder — ungültig für PostgreSQL TIME/INTEGER."""
if value is None:
return None
if isinstance(value, str) and value.strip() == "":
return None
return value
def _optional_int(value: Any) -> Optional[int]:
v = _blank_to_none(value)
if v is None:
return None
try:
i = int(v)
except (TypeError, ValueError):
return None
return i if i > 0 else None
def _normalize_co_trainer_ids(val: Any) -> List[int]:
"""Listen von Profil-IDs für JSONB; ungültige Einträge werden verworfen."""
if val is None:
raw: List[Any] = []
elif isinstance(val, list):
raw = val
else:
raw = []
out: List[int] = []
seen = set()
for x in raw:
try:
i = int(x)
except (TypeError, ValueError):
continue
if i <= 0 or i in seen:
continue
seen.add(i)
out.append(i)
return out
def _co_trainer_ids_jsonb(val: Any) -> Json:
"""psycopg2: reine list/dict für JSONB → ProgrammingError ohne Json()."""
return Json(_normalize_co_trainer_ids(val))
# ── List Clubs ────────────────────────────────────────────────────────
@router.get("/clubs")
def list_clubs(
status: Optional[str] = Query(default=None),
session=Depends(require_auth)
tenant: TenantContext = Depends(get_tenant_context),
):
"""
List all clubs (public for authenticated users).
Filters:
- status: active, inactive
Vereine: für normale Nutzer nur Mitgliedschaft-Vereine; Plattform-Admins sehen alle.
"""
role = tenant.global_role
profile_id = tenant.profile_id
with get_db() as conn:
cur = get_cursor(conn)
query = "SELECT * FROM clubs"
params = []
params: List[Any] = []
conds = []
if not is_platform_admin(role):
cids = club_ids_for_profile(cur, profile_id)
if not cids:
return []
conds.append("id IN (" + ",".join(["%s"] * len(cids)) + ")")
params.extend(sorted(cids))
if status:
query += " WHERE status = %s"
conds.append("status = %s")
params.append(status)
if conds:
query += " WHERE " + " AND ".join(conds)
query += " ORDER BY name"
cur.execute(query, params)
@@ -41,12 +105,64 @@ def list_clubs(
return [r2d(r) for r in rows]
# ── Get Club ──────────────────────────────────────────────────────────
@router.get("/clubs/{club_id}")
def get_club(club_id: int, session=Depends(require_auth)):
"""Get club by ID with divisions and groups."""
# ── Öffentliches Vereinsverzeichnis (Registrierung / Antrag ohne Mitgliedschaft) ──
@router.get("/clubs/public-directory")
def public_club_directory():
"""Aktive Vereine zur Auswahl bei Registrierung oder Beitrittsantrag (nur id, name, Kürzel)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, name, abbreviation
FROM clubs
WHERE status = 'active'
ORDER BY name
"""
)
return [r2d(r) for r in cur.fetchall()]
# ── Aktive Mitglieder für Trainer-/Co-Trainer-Auswahl (Vereinsmitglied) ──
@router.get("/clubs/{club_id}/members/directory")
def club_members_directory(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""id + name für alle aktiven Mitglieder; E-Mail nur für Plattform-Admin oder Vereinsadmin (Org-Verwaltung)."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
if not is_platform_admin(role):
assert_club_member(cur, profile_id, club_id)
cur.execute("SELECT 1 FROM clubs WHERE id = %s", (club_id,))
if not cur.fetchone():
raise HTTPException(404, "Verein nicht gefunden")
cur.execute(
"""
SELECT p.id, p.name, p.email
FROM club_members cm
INNER JOIN profiles p ON p.id = cm.profile_id
WHERE cm.club_id = %s AND cm.status = 'active'
ORDER BY COALESCE(p.name, ''), p.email
""",
(club_id,),
)
rows = [r2d(r) for r in cur.fetchall()]
show_email = is_platform_admin(role) or can_manage_club_org(cur, profile_id, club_id, role)
if not show_email:
for d in rows:
d["email"] = None
return rows
# ── Get Club ──────────────────────────────────────────────────────────
@router.get("/clubs/{club_id}")
def get_club(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Get club by ID with divisions and groups – nur Mitglied oder Plattform-Admin."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
if not is_platform_admin(role):
assert_club_member(cur, profile_id, club_id)
# Get club
cur.execute("SELECT * FROM clubs WHERE id = %s", (club_id,))
@@ -58,66 +174,108 @@ def get_club(club_id: int, session=Depends(require_auth)):
club = r2d(club)
# Get divisions
cur.execute("""
cur.execute(
"""
SELECT * FROM divisions
WHERE club_id = %s
ORDER BY name
""", (club_id,))
club['divisions'] = [r2d(r) for r in cur.fetchall()]
""",
(club_id,),
)
club["divisions"] = [r2d(r) for r in cur.fetchall()]
# Get training groups
cur.execute("""
cur.execute(
"""
SELECT g.*,
p.name as trainer_name
FROM training_groups g
LEFT JOIN profiles p ON g.trainer_id = p.id
WHERE g.club_id = %s
ORDER BY g.weekday, g.time_start
""", (club_id,))
club['training_groups'] = [r2d(r) for r in cur.fetchall()]
""",
(club_id,),
)
club["training_groups"] = [r2d(r) for r in cur.fetchall()]
return club
# ── Create Club ───────────────────────────────────────────────────────
@router.post("/clubs")
def create_club(data: dict, session=Depends(require_auth)):
"""Create new club (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Vereine erstellen")
def create_club(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Neuen Verein anlegen – nur Plattform-Admin; Pflicht: primary_admin_profile_id (Hauptverwalter:in)."""
role = tenant.global_role
if not is_platform_admin(role):
raise HTTPException(403, "Nur Plattform-Administratoren dürfen neue Vereine anlegen")
name = data.get('name')
name = data.get("name")
primary_admin_profile_id = data.get("primary_admin_profile_id")
if not name:
raise HTTPException(400, "Name ist Pflichtfeld")
if not primary_admin_profile_id:
raise HTTPException(400, "primary_admin_profile_id ist Pflichtfeld (Hauptverwalter:in)")
try:
aid = int(primary_admin_profile_id)
except (TypeError, ValueError):
raise HTTPException(400, "primary_admin_profile_id ungültig")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM profiles WHERE id = %s", (aid,))
if not cur.fetchone():
raise HTTPException(404, "Profil für Hauptverwalter nicht gefunden")
cur.execute("""
INSERT INTO clubs (name, abbreviation, description, status)
VALUES (%s, %s, %s, %s)
cur.execute(
"""
INSERT INTO clubs (name, abbreviation, description, status, primary_admin_profile_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""", (
name,
data.get('abbreviation'),
data.get('description'),
data.get('status', 'active')
))
""",
(
name,
data.get("abbreviation"),
data.get("description"),
data.get("status", "active"),
aid,
),
)
club_id = cur.fetchone()["id"]
cur.execute(
"""
INSERT INTO club_members (profile_id, club_id, status)
VALUES (%s, %s, 'active')
ON CONFLICT (profile_id, club_id)
DO UPDATE SET status = 'active', updated_at = NOW()
RETURNING id
""",
(aid, club_id),
)
cm_id = cur.fetchone()["id"]
for rc in ("club_admin", "trainer"):
cur.execute(
"""
INSERT INTO club_member_roles (club_member_id, role_code)
VALUES (%s, %s)
ON CONFLICT (club_member_id, role_code) DO NOTHING
""",
(cm_id, rc),
)
club_id = cur.fetchone()['id']
conn.commit()
return get_club(club_id, session)
return get_club(club_id, tenant)
# ── Update Club ───────────────────────────────────────────────────────
@router.put("/clubs/{club_id}")
def update_club(club_id: int, data: dict, session=Depends(require_auth)):
"""Update club (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Vereine bearbeiten")
def update_club(club_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Verein bearbeiten – Plattform-Admin oder Vereinsadmin."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
@@ -127,33 +285,46 @@ def update_club(club_id: int, data: dict, session=Depends(require_auth)):
if not cur.fetchone():
raise HTTPException(404, "Verein nicht gefunden")
if not can_manage_club_org(cur, profile_id, club_id, role):
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
# Nur Plattform-Admin darf primary_admin_profile_id ändern
if "primary_admin_profile_id" in data and data["primary_admin_profile_id"] is not None:
if not is_platform_admin(role):
raise HTTPException(403, "Nur Plattform-Admins dürfen den Hauptverwalter ändern")
# Update
cur.execute("""
cur.execute(
"""
UPDATE clubs SET
name = %s,
abbreviation = %s,
description = %s,
status = %s,
name = COALESCE(%s, name),
abbreviation = COALESCE(%s, abbreviation),
description = COALESCE(%s, description),
status = COALESCE(%s, status),
primary_admin_profile_id = COALESCE(%s, primary_admin_profile_id),
updated_at = NOW()
WHERE id = %s
""", (
data.get('name'),
data.get('abbreviation'),
data.get('description'),
data.get('status'),
club_id
))
""",
(
data.get("name"),
data.get("abbreviation"),
data.get("description"),
data.get("status"),
data.get("primary_admin_profile_id"),
club_id,
),
)
conn.commit()
return get_club(club_id, session)
return get_club(club_id, tenant)
# ── Delete Club ───────────────────────────────────────────────────────
@router.delete("/clubs/{club_id}")
def delete_club(club_id: int, session=Depends(require_auth)):
def delete_club(club_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Delete club (superadmin only)."""
role = session.get('role')
role = tenant.global_role
if role != 'superadmin':
raise HTTPException(403, "Nur Superadmins dürfen Vereine löschen")
@@ -176,22 +347,41 @@ def delete_club(club_id: int, session=Depends(require_auth)):
@router.get("/divisions")
def list_divisions(
club_id: Optional[int] = Query(default=None),
session=Depends(require_auth)
tenant: TenantContext = Depends(get_tenant_context),
):
"""List divisions (optional filter by club)."""
"""Sparten – ohne Admin-Rechte nur in eigenen Vereinen sichtbar."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
mine = club_ids_for_profile(cur, profile_id)
if not is_platform_admin(role) and not mine:
return []
query = """
SELECT d.*, c.name as club_name
FROM divisions d
LEFT JOIN clubs c ON d.club_id = c.id
"""
where = []
params = []
if club_id:
query += " WHERE d.club_id = %s"
if club_id is not None:
where.append("d.club_id = %s")
params.append(club_id)
if not is_platform_admin(role) and club_id not in mine:
return []
if not is_platform_admin(role):
where.append(
"d.club_id IN (" + ",".join(["%s"] * len(mine)) + ")"
)
params.extend(sorted(mine))
if where:
query += " WHERE " + " AND ".join(where)
query += " ORDER BY d.name"
@@ -202,14 +392,13 @@ def list_divisions(
# ── Create Division ───────────────────────────────────────────────────
@router.post("/divisions")
def create_division(data: dict, session=Depends(require_auth)):
"""Create new division (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Sparten erstellen")
def create_division(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Create new division – Vereinsadmin / Plattform-Admin."""
profile_id = tenant.profile_id
role = tenant.global_role
club_id = data.get('club_id')
name = data.get('name')
club_id = data.get("club_id")
name = data.get("name")
if not club_id or not name:
raise HTTPException(400, "club_id und name sind Pflichtfelder")
@@ -217,93 +406,109 @@ def create_division(data: dict, session=Depends(require_auth)):
with get_db() as conn:
cur = get_cursor(conn)
if not can_manage_club_org(cur, profile_id, int(club_id), role):
raise HTTPException(403, "Keine Berechtigung, Sparten in diesem Verein anzulegen")
# Check club exists
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
if not cur.fetchone():
raise HTTPException(404, "Verein nicht gefunden")
# Insert
cur.execute("""
cur.execute(
"""
INSERT INTO divisions (club_id, name, focus_area)
VALUES (%s, %s, %s)
RETURNING id
""", (
club_id,
name,
data.get('focus_area')
))
""",
(
club_id,
name,
data.get("focus_area"),
),
)
division_id = cur.fetchone()['id']
division_id = cur.fetchone()["id"]
conn.commit()
# Return created division
cur.execute("""
cur.execute(
"""
SELECT d.*, c.name as club_name
FROM divisions d
LEFT JOIN clubs c ON d.club_id = c.id
WHERE d.id = %s
""", (division_id,))
""",
(division_id,),
)
return r2d(cur.fetchone())
# ── Update Division ───────────────────────────────────────────────────
@router.put("/divisions/{division_id}")
def update_division(division_id: int, data: dict, session=Depends(require_auth)):
"""Update division (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Sparten bearbeiten")
def update_division(division_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Update division – Vereinsadmin / Plattform-Admin."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
# Check existence
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
if not cur.fetchone():
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
div = cur.fetchone()
if not div:
raise HTTPException(404, "Sparte nicht gefunden")
# Update
cur.execute("""
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
raise HTTPException(403, "Keine Berechtigung")
cur.execute(
"""
UPDATE divisions SET
name = %s,
focus_area = %s,
updated_at = NOW()
WHERE id = %s
""", (
data.get('name'),
data.get('focus_area'),
division_id
))
""",
(
data.get("name"),
data.get("focus_area"),
division_id,
),
)
conn.commit()
# Return updated division
cur.execute("""
cur.execute(
"""
SELECT d.*, c.name as club_name
FROM divisions d
LEFT JOIN clubs c ON d.club_id = c.id
WHERE d.id = %s
""", (division_id,))
""",
(division_id,),
)
return r2d(cur.fetchone())
# ── Delete Division ───────────────────────────────────────────────────
@router.delete("/divisions/{division_id}")
def delete_division(division_id: int, session=Depends(require_auth)):
"""Delete division (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Sparten löschen")
def delete_division(division_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Delete division – Vereinsadmin / Plattform-Admin."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
# Check existence
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
if not cur.fetchone():
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
div = cur.fetchone()
if not div:
raise HTTPException(404, "Sparte nicht gefunden")
# Delete
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
raise HTTPException(403, "Keine Berechtigung")
cur.execute("DELETE FROM divisions WHERE id = %s", (division_id,))
conn.commit()
@@ -316,19 +521,21 @@ def list_training_groups(
club_id: Optional[int] = Query(default=None),
division_id: Optional[int] = Query(default=None),
status: Optional[str] = Query(default=None),
session=Depends(require_auth)
tenant: TenantContext = Depends(get_tenant_context),
):
"""
List training groups with optional filters.
Filters:
- club_id: Filter by club
- division_id: Filter by division
- status: active, inactive
Trainingsgruppen – ohne Plattform-Admin nur in eigenen Vereinen.
"""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
mine = club_ids_for_profile(cur, profile_id)
if not is_platform_admin(role) and not mine:
return []
query = """
SELECT g.*,
c.name as club_name,
@@ -343,11 +550,13 @@ def list_training_groups(
where = []
params = []
if club_id:
if club_id is not None:
where.append("g.club_id = %s")
params.append(club_id)
if not is_platform_admin(role) and club_id not in mine:
return []
if division_id:
if division_id is not None:
where.append("g.division_id = %s")
params.append(division_id)
@@ -355,6 +564,10 @@ def list_training_groups(
where.append("g.status = %s")
params.append(status)
if not is_platform_admin(role):
where.append("g.club_id IN (" + ",".join(["%s"] * len(mine)) + ")")
params.extend(sorted(mine))
if where:
query += " WHERE " + " AND ".join(where)
@@ -367,12 +580,15 @@ def list_training_groups(
# ── Get Training Group ────────────────────────────────────────────────
@router.get("/groups/{group_id}")
def get_training_group(group_id: int, session=Depends(require_auth)):
"""Get training group by ID."""
def get_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Trainingsgruppe – nur mit Vereinszugriff."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
cur.execute(
"""
SELECT g.*,
c.name as club_name,
d.name as division_name,
@@ -382,40 +598,61 @@ def get_training_group(group_id: int, session=Depends(require_auth)):
LEFT JOIN divisions d ON g.division_id = d.id
LEFT JOIN profiles p ON g.trainer_id = p.id
WHERE g.id = %s
""", (group_id,))
""",
(group_id,),
)
group = cur.fetchone()
if not group:
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
cid = group["club_id"]
if not is_platform_admin(role):
assert_club_member(cur, profile_id, cid)
return r2d(group)
# ── Create Training Group ─────────────────────────────────────────────
@router.post("/groups")
def create_training_group(data: dict, session=Depends(require_auth)):
"""Create new training group (admin or trainer)."""
role = session.get('role')
if role not in ['admin', 'superadmin', 'trainer']:
raise HTTPException(403, "Nur Admins und Trainer dürfen Gruppen erstellen")
def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Trainingsgruppe anlegen – Mitglied mit Planungs-/Admin-Rolle im Verein."""
profile_id = tenant.profile_id
role = tenant.global_role
if role not in ("admin", "superadmin", "trainer", "user"):
raise HTTPException(403, "Keine Berechtigung, Trainingsgruppen anzulegen")
club_id = data.get('club_id')
name = data.get('name')
club_id = data.get("club_id")
name = data.get("name")
if not club_id or not name:
raise HTTPException(400, "club_id und name sind Pflichtfelder")
raw_tid = data.get("trainer_id")
if role in ("trainer", "user"):
parsed_tid = _optional_int(raw_tid)
trainer_id = parsed_tid if parsed_tid is not None else profile_id
else:
trainer_id = _optional_int(raw_tid)
division_id = _optional_int(data.get("division_id"))
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
with get_db() as conn:
cur = get_cursor(conn)
if not can_plan_in_club(cur, profile_id, int(club_id), role):
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
# Check club exists
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
if not cur.fetchone():
raise HTTPException(404, "Verein nicht gefunden")
# Insert
cur.execute("""
cur.execute(
"""
INSERT INTO training_groups (
club_id, division_id, name, focus, level, age_group,
weekday, time_start, time_end, location,
@@ -423,52 +660,66 @@ def create_training_group(data: dict, session=Depends(require_auth)):
) VALUES (
%s, %s, %s, %s, %s, %s,
%s, %s, %s, %s,
%s, %s, %s
%s, %s::jsonb, %s
) RETURNING id
""", (
club_id,
data.get('division_id'),
name,
data.get('focus'),
data.get('level'),
data.get('age_group'),
data.get('weekday'),
data.get('time_start'),
data.get('time_end'),
data.get('location'),
data.get('trainer_id'),
data.get('co_trainer_ids'),
data.get('status', 'active')
))
""",
(
int(club_id),
division_id,
name,
_blank_to_none(data.get("focus")),
_blank_to_none(data.get("level")),
_blank_to_none(data.get("age_group")),
_blank_to_none(data.get("weekday")),
_blank_to_none(data.get("time_start")),
_blank_to_none(data.get("time_end")),
_blank_to_none(data.get("location")),
trainer_id,
co_json,
data.get("status") or "active",
),
)
group_id = cur.fetchone()['id']
group_id = cur.fetchone()["id"]
conn.commit()
return get_training_group(group_id, session)
return get_training_group(group_id, tenant)
# ── Update Training Group ─────────────────────────────────────────────
@router.put("/groups/{group_id}")
def update_training_group(group_id: int, data: dict, session=Depends(require_auth)):
"""Update training group (admin or assigned trainer)."""
profile_id = session['profile_id']
role = session.get('role')
def update_training_group(group_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)):
"""Update training group – Vereinsadmin, Plattform-Admin oder zugewiesene Trainer."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
# Check existence and ownership
cur.execute("SELECT trainer_id FROM training_groups WHERE id = %s", (group_id,))
cur.execute(
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
(group_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
# Only admin or assigned trainer can update
if role not in ['admin', 'superadmin'] and row['trainer_id'] != profile_id:
co_trainers = row["co_trainer_ids"] or []
club_id = row["club_id"]
allowed = role in ("admin", "superadmin")
if not allowed:
allowed = can_manage_club_org(cur, profile_id, club_id, role)
if not allowed:
allowed = row["trainer_id"] == profile_id or profile_id in co_trainers
if not allowed:
raise HTTPException(403, "Keine Berechtigung")
# Update
cur.execute("""
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
cur.execute(
"""
UPDATE training_groups SET
name = %s,
division_id = %s,
@@ -480,48 +731,51 @@ def update_training_group(group_id: int, data: dict, session=Depends(require_aut
time_end = %s,
location = %s,
trainer_id = %s,
co_trainer_ids = %s,
co_trainer_ids = %s::jsonb,
status = %s,
updated_at = NOW()
WHERE id = %s
""", (
data.get('name'),
data.get('division_id'),
data.get('focus'),
data.get('level'),
data.get('age_group'),
data.get('weekday'),
data.get('time_start'),
data.get('time_end'),
data.get('location'),
data.get('trainer_id'),
data.get('co_trainer_ids'),
data.get('status'),
group_id
))
""",
(
data.get("name"),
_optional_int(data.get("division_id")),
_blank_to_none(data.get("focus")),
_blank_to_none(data.get("level")),
_blank_to_none(data.get("age_group")),
_blank_to_none(data.get("weekday")),
_blank_to_none(data.get("time_start")),
_blank_to_none(data.get("time_end")),
_blank_to_none(data.get("location")),
_optional_int(data.get("trainer_id")),
co_json,
data.get("status") or "active",
group_id,
),
)
conn.commit()
return get_training_group(group_id, session)
return get_training_group(group_id, tenant)
# ── Delete Training Group ─────────────────────────────────────────────
@router.delete("/groups/{group_id}")
def delete_training_group(group_id: int, session=Depends(require_auth)):
"""Delete training group (admin only)."""
role = session.get('role')
if role not in ['admin', 'superadmin']:
raise HTTPException(403, "Nur Admins dürfen Gruppen löschen")
def delete_training_group(group_id: int, tenant: TenantContext = Depends(get_tenant_context)):
"""Delete training group – Vereinsadmin oder Plattform-Admin."""
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
# Check existence
cur.execute("SELECT id FROM training_groups WHERE id = %s", (group_id,))
if not cur.fetchone():
cur.execute("SELECT id, club_id FROM training_groups WHERE id = %s", (group_id,))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
# Delete
if not can_manage_club_org(cur, profile_id, row["club_id"], role):
raise HTTPException(403, "Keine Berechtigung")
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
conn.commit()
@@ -0,0 +1,587 @@
"""
Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
AuthZ analog training_plan_templates (_template_access / _has_planning_role).
"""
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field, model_validator
from psycopg2 import IntegrityError
from db import get_db, get_cursor, r2d
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
from club_tenancy import (
assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile,
)
from routers.training_planning import _has_planning_role
router = APIRouter(prefix="/api", tags=["exercises"])
class ProgressionGraphCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=200)
description: Optional[str] = None
visibility: str = Field(default="private", pattern="^(private|club|official)$")
club_id: Optional[int] = None
class ProgressionGraphUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=200)
description: Optional[str] = None
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
club_id: Optional[int] = None
class ProgressionEdgeCreate(BaseModel):
from_exercise_id: int = Field(..., gt=0)
to_exercise_id: int = Field(..., gt=0)
from_exercise_variant_id: Optional[int] = Field(default=None)
to_exercise_variant_id: Optional[int] = Field(default=None)
edge_type: str = Field(default="next_exercise", min_length=1, max_length=50)
notes: Optional[str] = Field(None, max_length=4000)
class ProgressionEdgeUpdate(BaseModel):
notes: Optional[str] = Field(None, max_length=4000)
class SequenceStep(BaseModel):
exercise_id: int = Field(..., gt=0)
variant_id: Optional[int] = Field(default=None)
class ProgressionSequenceCreate(BaseModel):
steps: List[SequenceStep] = Field(..., min_length=2)
segment_notes: Optional[List[Optional[str]]] = None
"""Länge muss len(steps)-1 sein, wenn gesetzt; Notiz pro Kante Zwischen je zwei Schritten."""
@model_validator(mode="after")
def check_segment_notes_len(self):
if self.segment_notes is not None and len(self.segment_notes) != len(self.steps) - 1:
raise ValueError(
f"segment_notes muss genau {len(self.steps) - 1} Einträge haben (len(steps)-1)"
)
return self
class EdgeIdsBatch(BaseModel):
edge_ids: List[int] = Field(..., min_length=1)
_EDGE_SELECT = """
SELECT e.id, e.graph_id,
e.from_exercise_id, e.from_exercise_variant_id,
e.to_exercise_id, e.to_exercise_variant_id,
e.edge_type, e.notes, e.created_at,
ef.title AS from_exercise_title, et.title AS to_exercise_title,
vf.variant_name AS from_variant_name, vt.variant_name AS to_variant_name
FROM exercise_progression_edges e
JOIN exercises ef ON ef.id = e.from_exercise_id
JOIN exercises et ON et.id = e.to_exercise_id
LEFT JOIN exercise_variants vf ON vf.id = e.from_exercise_variant_id
LEFT JOIN exercise_variants vt ON vt.id = e.to_exercise_variant_id
"""
def _graph_row(cur, graph_id: int) -> dict:
cur.execute(
"SELECT * FROM exercise_progression_graphs WHERE id = %s",
(graph_id,),
)
r = cur.fetchone()
if not r:
raise HTTPException(status_code=404, detail="Progressionsgraph nicht gefunden")
return r2d(r)
def _assert_graph_readable(cur, row: dict, profile_id: int, role: str) -> None:
vis = (row.get("visibility") or "private").strip().lower()
cid = row.get("club_id")
if cid is not None:
cid = int(cid)
cr = row.get("created_by")
if cr is not None:
cr = int(cr)
if not library_content_visible_to_profile(cur, profile_id, vis, cid, cr, role):
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
if is_platform_admin(role):
return
created_by = row.get("created_by")
if created_by is not None:
created_by = int(created_by)
if created_by != profile_id:
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Progressionsgraph")
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
row = _graph_row(cur, graph_id)
_assert_graph_readable(cur, row, profile_id, role)
return row
def _require_graph_write(cur, graph_id: int, profile_id: int, role: str) -> dict:
row = _graph_row(cur, graph_id)
_assert_graph_writable(cur, row, profile_id, role)
return row
def _assert_exercises_exist(cur, *exercise_ids: int) -> None:
unique_ids = list(dict.fromkeys(exercise_ids))
if not unique_ids:
return
cur.execute(
f"SELECT id FROM exercises WHERE id IN ({','.join(['%s'] * len(unique_ids))})",
tuple(unique_ids),
)
found = {r["id"] if isinstance(r, dict) else r[0] for r in cur.fetchall()}
missing = set(unique_ids) - found
if missing:
raise HTTPException(
status_code=400,
detail=f"Unbekannte Übung(en): {sorted(missing)}",
)
def _assert_variant_for_exercise(cur, exercise_id: int, variant_id: Optional[int]) -> None:
if variant_id is None:
return
cur.execute(
"SELECT exercise_id FROM exercise_variants WHERE id = %s",
(variant_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(status_code=400, detail=f"Unbekannte Variante: {variant_id}")
ev_ex = row["exercise_id"] if isinstance(row, dict) else row[0]
if ev_ex != exercise_id:
raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung")
def _insert_edge_row(
cur,
graph_id: int,
from_exercise_id: int,
from_variant_id: Optional[int],
to_exercise_id: int,
to_variant_id: Optional[int],
edge_type: str,
notes: Optional[str],
) -> dict:
cur.execute(
"""
INSERT INTO exercise_progression_edges (
graph_id,
from_exercise_id, from_exercise_variant_id,
to_exercise_id, to_exercise_variant_id,
edge_type, notes
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
graph_id,
from_exercise_id,
from_variant_id,
to_exercise_id,
to_variant_id,
edge_type,
notes,
),
)
new_id = cur.fetchone()["id"]
cur.execute(_EDGE_SELECT + " WHERE e.id = %s", (new_id,))
return r2d(cur.fetchone())
@router.get("/exercise-progression-graphs")
def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
vis_sql, vis_params = library_content_visibility_sql(
alias="g",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
SELECT g.*,
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
FROM exercise_progression_graphs g
WHERE ({vis_sql})
ORDER BY g.updated_at DESC NULLS LAST, g.name
""",
vis_params,
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/exercise-progression-graphs/{graph_id}")
def get_progression_graph(
graph_id: int,
include_edges: bool = Query(default=False),
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
row = _require_graph_read(cur, graph_id, profile_id, role)
if include_edges:
cur.execute(
_EDGE_SELECT + " WHERE e.graph_id = %s ORDER BY e.id",
(graph_id,),
)
row["edges"] = [r2d(r) for r in cur.fetchall()]
return row
@router.post("/exercise-progression-graphs", status_code=201)
def create_progression_graph(
body: ProgressionGraphCreate,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung zum Anlegen von Progressionsgraphen")
name = body.name.strip()
if not name:
raise HTTPException(status_code=400, detail="name ist Pflicht")
vis = (body.visibility or "private").strip().lower()
cid = body.club_id
if vis == "club":
if cid is None:
cid = tenant.effective_club_id
if cid is None:
raise HTTPException(
status_code=400,
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
)
gov_club = cid if vis == "club" else None
with get_db() as conn:
cur = get_cursor(conn)
assert_valid_governance_visibility(cur, profile_id, role, vis, gov_club)
cur.execute(
"""
INSERT INTO exercise_progression_graphs (name, description, visibility, club_id, created_by)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(name, body.description, vis, cid if vis == "club" else None, profile_id),
)
gid = cur.fetchone()["id"]
conn.commit()
return get_progression_graph(gid, include_edges=False, tenant=tenant)
@router.put("/exercise-progression-graphs/{graph_id}")
def update_progression_graph(
graph_id: int,
body: ProgressionGraphUpdate,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
original = body.model_dump(exclude_unset=True)
if not original:
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
with get_db() as conn:
cur = get_cursor(conn)
row = _require_graph_write(cur, graph_id, profile_id, role)
ex_vis = (row.get("visibility") or "private").strip().lower()
ex_cid_raw = row.get("club_id")
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
next_vis = ex_vis
if "visibility" in original and original["visibility"] is not None:
v_raw = str(original["visibility"]).strip().lower()
if v_raw:
next_vis = v_raw
next_club = ex_cid
if "club_id" in original:
raw_c = original["club_id"]
if raw_c in (None, "", []):
next_club = None
else:
next_club = int(raw_c)
if next_vis == "club":
if next_club is None:
next_club = tenant.effective_club_id
if next_club is None:
raise HTTPException(
status_code=400,
detail="Vereins-Graph: club_id angeben oder aktiven Verein wählen (X-Active-Club-Id).",
)
gov_club = next_club if next_vis == "club" else None
assert_valid_governance_visibility(cur, profile_id, role, next_vis, gov_club)
fields: List[str] = []
params: List[Any] = []
if "name" in original:
n = (original["name"] or "").strip()
if not n:
raise HTTPException(status_code=400, detail="name ist Pflicht")
fields.append("name = %s")
params.append(n)
if "description" in original:
fields.append("description = %s")
params.append(original["description"])
vis_changed = next_vis != ex_vis
if "visibility" in original or vis_changed:
fields.append("visibility = %s")
params.append(next_vis)
if "club_id" in original or vis_changed:
fields.append("club_id = %s")
params.append(next_club if next_vis == "club" else None)
if not fields:
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
fields.append("updated_at = NOW()")
params.append(graph_id)
cur.execute(
f"UPDATE exercise_progression_graphs SET {', '.join(fields)} WHERE id = %s",
tuple(params),
)
conn.commit()
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
@router.delete("/exercise-progression-graphs/{graph_id}")
def delete_progression_graph(graph_id: int, tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
cur.execute("DELETE FROM exercise_progression_graphs WHERE id = %s", (graph_id,))
conn.commit()
return {"ok": True}
@router.get("/exercise-progression-graphs/{graph_id}/edges")
def list_progression_edges(
graph_id: int,
from_exercise_id: Optional[int] = Query(default=None),
to_exercise_id: Optional[int] = Query(default=None),
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_read(cur, graph_id, profile_id, role)
q = _EDGE_SELECT + " WHERE e.graph_id = %s"
params: List[Any] = [graph_id]
if from_exercise_id is not None:
q += " AND e.from_exercise_id = %s"
params.append(from_exercise_id)
if to_exercise_id is not None:
q += " AND e.to_exercise_id = %s"
params.append(to_exercise_id)
q += " ORDER BY e.id"
cur.execute(q, tuple(params))
return [r2d(r) for r in cur.fetchall()]
@router.post("/exercise-progression-graphs/{graph_id}/edges", status_code=201)
def create_progression_edge(
graph_id: int,
body: ProgressionEdgeCreate,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
fv = body.from_exercise_variant_id
tv = body.to_exercise_variant_id
_assert_variant_for_exercise(cur, body.from_exercise_id, fv)
_assert_variant_for_exercise(cur, body.to_exercise_id, tv)
et = (body.edge_type or "next_exercise").strip() or "next_exercise"
notes = (body.notes or "").strip() or None
try:
row = _insert_edge_row(
cur,
graph_id,
body.from_exercise_id,
fv,
body.to_exercise_id,
tv,
et,
notes,
)
conn.commit()
except IntegrityError as e:
conn.rollback()
raise HTTPException(
status_code=409,
detail="Kante existiert bereits oder Endpunkte unzulässig (gleiche Übung ohne zwei Varianten)",
) from e
return row
@router.post("/exercise-progression-graphs/{graph_id}/edges/sequence", status_code=201)
def create_progression_sequence(
graph_id: int,
body: ProgressionSequenceCreate,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Legt n−1 Nachfolger-Kanten (next_exercise) für eine geordnete Schrittliste an."""
profile_id = tenant.profile_id
role = tenant.global_role
steps = body.steps
n_seg = len(steps) - 1
seg_notes = body.segment_notes
created: List[dict] = []
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
ex_ids = [s.exercise_id for s in steps]
_assert_exercises_exist(cur, *ex_ids)
try:
for i in range(n_seg):
a, b = steps[i], steps[i + 1]
_assert_variant_for_exercise(cur, a.exercise_id, a.variant_id)
_assert_variant_for_exercise(cur, b.exercise_id, b.variant_id)
note = None
if seg_notes is not None:
raw = seg_notes[i]
note = (raw or "").strip() or None if raw is not None else None
row = _insert_edge_row(
cur,
graph_id,
a.exercise_id,
a.variant_id,
b.exercise_id,
b.variant_id,
"next_exercise",
note,
)
created.append(row)
conn.commit()
except IntegrityError as e:
conn.rollback()
raise HTTPException(
status_code=409,
detail="Sequenz konnte nicht vollständig angelegt werden (Duplikat oder ungültige Endpunkte). Keine Teilmenge gespeichert.",
) from e
return {"created": created, "count": len(created)}
@router.put("/exercise-progression-graphs/{graph_id}/edges/{edge_id}")
def update_progression_edge(
graph_id: int,
edge_id: int,
body: ProgressionEdgeUpdate,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
data = body.model_dump(exclude_unset=True)
if not data:
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
cur.execute(
"SELECT id FROM exercise_progression_edges WHERE id = %s AND graph_id = %s",
(edge_id, graph_id),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Kante nicht gefunden")
if "notes" in data:
n = data["notes"]
notes_val = (n or "").strip() or None if n is not None else None
cur.execute(
"UPDATE exercise_progression_edges SET notes = %s WHERE id = %s AND graph_id = %s",
(notes_val, edge_id, graph_id),
)
conn.commit()
cur.execute(_EDGE_SELECT + " WHERE e.id = %s AND e.graph_id = %s", (edge_id, graph_id))
return r2d(cur.fetchone())
@router.delete("/exercise-progression-graphs/{graph_id}/edges/{edge_id}")
def delete_progression_edge(
graph_id: int,
edge_id: int,
tenant: TenantContext = Depends(get_tenant_context),
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
cur.execute(
"""
DELETE FROM exercise_progression_edges
WHERE id = %s AND graph_id = %s
RETURNING id
""",
(edge_id, graph_id),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Kante nicht gefunden")
conn.commit()
return {"ok": True}
@router.post("/exercise-progression-graphs/{graph_id}/edges/delete-batch")
def delete_progression_edges_batch(
graph_id: int,
body: EdgeIdsBatch,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Löscht mehrere Kanten (z. B. eine zusammenhängende Kette in einem Schritt)."""
profile_id = tenant.profile_id
role = tenant.global_role
ids = body.edge_ids
clean_ids = list(dict.fromkeys(ids))
with get_db() as conn:
cur = get_cursor(conn)
_require_graph_write(cur, graph_id, profile_id, role)
cur.execute(
f"""
DELETE FROM exercise_progression_edges
WHERE graph_id = %s AND id IN ({",".join(["%s"] * len(clean_ids))})
""",
(graph_id, *clean_ids),
)
deleted = cur.rowcount
conn.commit()
return {"ok": True, "deleted": deleted}
+2965 -376
View File
File diff suppressed because it is too large. Load diff
+694
View File
@@ -0,0 +1,694 @@
"""
MediaWiki Import Router
Importiert Übungen, Fähigkeiten und Methoden aus Semantic MediaWiki
direkt via API (kein XML-Export). Nur Super-Admin darf importieren.
Wiki-URL: https://karatetrainer.net/api.php
"""
import asyncio
import logging
import os
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, Query
from pydantic import BaseModel
from db import get_db, get_cursor, r2d
from auth import require_auth
from smw_client import SmwClient, SmwClientError
from smw_mapper import map_wiki_to_exercise, map_wiki_to_skill, map_wiki_to_method, build_skill_assignments
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["import"])
# Kategorie-Namen aus .env (echte Namen von karatetrainer.net)
CATEGORY_EXERCISES = os.getenv("MEDIAWIKI_CATEGORY_EXERCISES", "Übungen")
CATEGORY_SKILLS = os.getenv("MEDIAWIKI_CATEGORY_SKILLS", "Fähigkeitsbeschreibung")
CATEGORY_METHODS = os.getenv("MEDIAWIKI_CATEGORY_METHODS", "Methodenbeschreibung")
CATEGORY_MODELS = os.getenv("MEDIAWIKI_CATEGORY_MODELS", "Reifegradmodelle")
# ------------------------------------------------------------------ #
# Pydantic Models #
# ------------------------------------------------------------------ #
class ImportExecuteRequest(BaseModel):
category: str
import_type: str = "exercise" # exercise | skill | method
reimport_existing: bool = False
dry_run: bool = False
limit: Optional[int] = None
# ------------------------------------------------------------------ #
# Auth-Hilfsfunktion #
# ------------------------------------------------------------------ #
def require_admin(session: dict = Depends(require_auth)) -> dict:
"""Nur Super-Admins dürfen importieren."""
if session.get("role") not in ("admin", "superadmin"):
raise HTTPException(status_code=403, detail="Nur Admins dürfen den Import ausführen")
return session
# ------------------------------------------------------------------ #
# Preview Endpoint #
# ------------------------------------------------------------------ #
@router.get("/import/mediawiki/preview")
async def preview_import(
category: str = Query(default=CATEGORY_EXERCISES),
import_type: str = Query(default="exercise"),
limit: int = Query(default=10, ge=1, le=500),
session: dict = Depends(require_admin),
):
"""
Zeigt Vorschau: Welche Seiten würden importiert werden?
Überprüft Duplikate und mapped Felder ohne zu speichern.
"""
client = SmwClient()
try:
members = await client.get_category_members(category, limit=limit)
except SmwClientError as e:
raise HTTPException(status_code=502, detail=f"Wiki-API nicht erreichbar: {e}")
preview = []
with get_db() as conn:
cur = get_cursor(conn)
for member in members[:limit]:
page_title = member["title"]
page_id = member.get("pageid")
# Duplikat-Check
cur.execute(
"SELECT id, last_imported FROM wiki_import_references WHERE wiki_page_title = %s AND content_type = %s",
(page_title, import_type)
)
existing_ref = r2d(cur.fetchone())
# SMW Properties abrufen
mapped_fields = {}
warnings = []
errors = []
try:
smw_props = await client.browse_subject(page_title)
if import_type == "exercise":
mapped = map_wiki_to_exercise(page_title, page_id, smw_props)
elif import_type == "skill":
mapped = map_wiki_to_skill(page_title, page_id, smw_props)
else:
mapped = map_wiki_to_method(page_title, page_id, smw_props)
warnings = mapped.pop("warnings", [])
# Entferne interne Felder aus der Vorschau
for k in ("wiki_page_id", "import_source", "import_id"):
mapped.pop(k, None)
mapped_fields = mapped
# Warnung wenn Pflichtfelder fehlen (nur bei Übungen)
if import_type == "exercise":
if not mapped.get("goal") and not mapped.get("execution"):
errors.append("Pflichtfelder 'Ziel' und 'Durchführung' fehlen")
except SmwClientError as e:
errors.append(f"Seite nicht abrufbar: {e}")
preview.append({
"wiki_page_title": page_title,
"wiki_page_id": page_id,
"already_imported": existing_ref is not None,
"last_imported_at": existing_ref["last_imported"].isoformat()
if existing_ref and existing_ref.get("last_imported") is not None
else None,
"mapped_fields": mapped_fields,
"warnings": warnings,
"errors": errors,
})
return {
"category": category,
"import_type": import_type,
"total_found": len(members),
"preview": preview,
}
# ------------------------------------------------------------------ #
# Execute Import (async Background Task) #
# ------------------------------------------------------------------ #
@router.post("/import/mediawiki/execute", status_code=202)
async def execute_import(
body: ImportExecuteRequest,
background_tasks: BackgroundTasks,
session: dict = Depends(require_admin),
):
"""
Startet einen MediaWiki-Import als Background-Task.
Gibt sofort log_id zurück – Status via GET /import/mediawiki/status/{log_id}.
"""
profile_id = session["profile_id"]
# Log-Eintrag anlegen
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""INSERT INTO wiki_import_log
(import_type, import_status, category, dry_run, reimport, imported_by)
VALUES (%s, 'running', %s, %s, %s, %s)
RETURNING id""",
(body.import_type, body.category, body.dry_run, body.reimport_existing, profile_id)
)
log_id = cur.fetchone()['id']
conn.commit()
# Import asynchron starten
background_tasks.add_task(
_run_import,
log_id=log_id,
category=body.category,
import_type=body.import_type,
reimport=body.reimport_existing,
dry_run=body.dry_run,
limit=body.limit,
imported_by=profile_id,
)
return {
"log_id": log_id,
"status": "running",
"message": f"Import gestartet. Status: GET /api/import/mediawiki/status/{log_id}",
}
# ------------------------------------------------------------------ #
# Status & Logs #
# ------------------------------------------------------------------ #
@router.get("/import/mediawiki/status/{log_id}")
def get_import_status(
log_id: int,
session: dict = Depends(require_admin),
):
"""Status eines laufenden oder abgeschlossenen Imports."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM wiki_import_log WHERE id = %s", (log_id,))
row = r2d(cur.fetchone())
if not row:
raise HTTPException(status_code=404, detail="Import-Log nicht gefunden")
return row
@router.get("/import/mediawiki/logs")
def list_import_logs(
session: dict = Depends(require_admin),
):
"""Alle Import-Logs (neueste zuerst, ohne error_log Details)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT id, import_type, import_status, category, dry_run, reimport,
items_total, items_imported, items_skipped, items_failed,
imported_by, started_at, finished_at
FROM wiki_import_log
ORDER BY started_at DESC
LIMIT 50"""
)
rows = cur.fetchall()
return [r2d(r) for r in rows]
@router.delete("/import/mediawiki/references/{ref_id}", status_code=204)
def delete_import_reference(
ref_id: int,
session: dict = Depends(require_admin),
):
"""
Löscht eine Import-Referenz, damit das Item bei nächstem Import
als neu behandelt wird (Re-Import ermöglichen).
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM wiki_import_references WHERE id = %s RETURNING id", (ref_id,))
deleted = cur.fetchone()
conn.commit()
if not deleted:
raise HTTPException(status_code=404, detail="Referenz nicht gefunden")
# ------------------------------------------------------------------ #
# Schema-Discovery (Debug-Hilfsmittel für Admins) #
# ------------------------------------------------------------------ #
@router.get("/import/mediawiki/discover/{page_title:path}")
async def discover_properties(
page_title: str,
session: dict = Depends(require_admin),
):
"""
Gibt alle SMW-Properties einer Wiki-Seite zurück.
Nützlich um Property-Namen zu ermitteln und smw_mapper.py anzupassen.
"""
client = SmwClient()
try:
props = await client.discover_properties(page_title)
except SmwClientError as e:
raise HTTPException(status_code=502, detail=f"Wiki-API Fehler: {e}")
return {"page_title": page_title, "properties": props}
# ------------------------------------------------------------------ #
# Background Import Worker #
# ------------------------------------------------------------------ #
async def _run_import(
log_id: int,
category: str,
import_type: str,
reimport: bool,
dry_run: bool,
limit: Optional[int],
imported_by: int,
):
"""Hintergrund-Task: Importiert alle Seiten einer Kategorie."""
client = SmwClient()
stats = {"total": 0, "imported": 0, "skipped": 0, "failed": 0}
errors = []
try:
members = await client.get_category_members(category, limit=limit or 500)
stats["total"] = len(members)
_update_log(log_id, import_status="running", items_total=stats["total"])
for member in members:
page_title = member["title"]
page_id = member.get("pageid")
# Duplikat-Check: Prüfe ob bereits importiert UND ob tatsächlich existiert
if not reimport:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT local_id FROM wiki_import_references WHERE wiki_page_title = %s AND content_type = %s",
(page_title, import_type)
)
ref = cur.fetchone()
if ref:
# Prüfe ob die Übung tatsächlich existiert
if import_type == "exercise":
cur.execute("SELECT id FROM exercises WHERE id = %s", (ref['local_id'],))
elif import_type == "skill":
cur.execute("SELECT id FROM skills WHERE id = %s", (ref['local_id'],))
else:
cur.execute("SELECT id FROM training_methods WHERE id = %s", (ref['local_id'],))
if cur.fetchone():
# Referenz UND Übung existieren → Skip
stats["skipped"] += 1
_update_log(log_id, **stats)
continue
else:
# Referenz existiert, aber Übung fehlt → Lösche fehlerhafte Referenz
logger.warning("Orphaned reference found for '%s', re-importing", page_title)
cur.execute(
"DELETE FROM wiki_import_references WHERE wiki_page_title = %s AND content_type = %s",
(page_title, import_type)
)
conn.commit()
# SMW Properties abrufen (mit Retry)
try:
smw_props = await _fetch_with_retry(client, page_title)
except SmwClientError as e:
errors.append({"item": page_title, "error": str(e)})
stats["failed"] += 1
_update_log(log_id, **stats, error_log=errors)
continue
# Field-Mapping
if import_type == "exercise":
mapped = map_wiki_to_exercise(page_title, page_id, smw_props)
required_ok = bool(mapped.get("goal") or mapped.get("execution"))
elif import_type == "skill":
mapped = map_wiki_to_skill(page_title, page_id, smw_props)
required_ok = True
else:
mapped = map_wiki_to_method(page_title, page_id, smw_props)
required_ok = True
if not required_ok:
errors.append({"item": page_title, "error": "Pflichtfelder fehlen (Ziel + Durchführung)"})
stats["failed"] += 1
_update_log(log_id, **stats, error_log=errors)
continue
if dry_run:
stats["imported"] += 1
_update_log(log_id, **stats)
continue
# Speichern
try:
if import_type == "exercise":
local_id = _upsert_exercise(mapped, reimport, imported_by)
elif import_type == "skill":
local_id = _upsert_skill(mapped, reimport)
else:
local_id = _upsert_method(mapped, reimport)
if local_id:
_upsert_wiki_ref(page_title, page_id, import_type, local_id)
stats["imported"] += 1
else:
stats["skipped"] += 1
except Exception as e:
logger.exception("Fehler beim Speichern von '%s'", page_title)
errors.append({"item": page_title, "error": str(e)})
stats["failed"] += 1
_update_log(log_id, **stats, error_log=errors)
# Abschluss
_update_log(
log_id,
import_status="completed",
error_log=errors,
finished=True,
**stats,
)
except Exception as e:
logger.exception("Import-Prozess fehlgeschlagen (log_id=%s)", log_id)
_update_log(log_id, import_status="failed", error_log=[{"item": "global", "error": str(e)}], finished=True, **stats)
async def _fetch_with_retry(client: SmwClient, page_title: str, retries: int = 3) -> dict:
"""Ruft SMW-Properties mit bis zu 3 Versuchen ab."""
for attempt in range(retries):
try:
return await client.browse_subject(page_title)
except SmwClientError:
if attempt == retries - 1:
raise
await asyncio.sleep(2 ** attempt)
# ------------------------------------------------------------------ #
# DB-Helper #
# ------------------------------------------------------------------ #
def _update_log(
log_id: int,
import_status: Optional[str] = None,
items_total: int = 0,
total: int = 0,
imported: int = 0,
skipped: int = 0,
failed: int = 0,
error_log: Optional[list] = None,
finished: bool = False,
):
import json as _json
with get_db() as conn:
cur = get_cursor(conn)
fields = []
params = []
if import_status:
fields.append("import_status = %s")
params.append(import_status)
total_val = items_total or total
fields += [
"items_total = %s",
"items_imported = %s",
"items_skipped = %s",
"items_failed = %s",
]
params += [total_val, imported, skipped, failed]
if error_log is not None:
fields.append("error_log = %s")
params.append(_json.dumps(error_log))
if finished:
fields.append("finished_at = NOW()")
fields.append("updated_at = NOW()")
params.append(log_id)
cur.execute(
f"UPDATE wiki_import_log SET {', '.join(fields)} WHERE id = %s",
params
)
conn.commit()
def _upsert_exercise(mapped: dict, reimport: bool, created_by: int) -> Optional[int]:
"""Legt Übung an oder aktualisiert sie (wenn reimport=True)."""
import json as _json
with get_db() as conn:
cur = get_cursor(conn)
# Existiert die Übung bereits (über import_id)?
cur.execute(
"SELECT id FROM exercises WHERE import_id = %s AND import_source = 'mediawiki'",
(mapped["import_id"],)
)
existing = cur.fetchone()
equipment = _json.dumps(mapped.get("equipment", [])) if mapped.get("equipment") else None
if existing and reimport:
ex_id = existing['id']
cur.execute(
"""UPDATE exercises SET
title = %s, summary = %s, goal = %s, execution = %s,
preparation = %s, trainer_notes = %s,
duration_min = %s, duration_max = %s,
group_size_min = %s, group_size_max = %s,
equipment = %s, updated_at = NOW()
WHERE id = %s""",
(
mapped.get("title"), mapped.get("summary"), mapped.get("goal"),
mapped.get("execution"), mapped.get("preparation"), mapped.get("trainer_notes"),
mapped.get("duration_min"), mapped.get("duration_max"),
mapped.get("group_size_min"), mapped.get("group_size_max"),
equipment, ex_id
)
)
elif existing and not reimport:
return None # Übersprungen
else:
cur.execute(
"""INSERT INTO exercises
(title, summary, goal, execution, preparation, trainer_notes,
duration_min, duration_max, group_size_min, group_size_max,
equipment, visibility, status, import_source, import_id, created_by)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
RETURNING id""",
(
mapped.get("title"), mapped.get("summary"), mapped.get("goal"),
mapped.get("execution"), mapped.get("preparation"), mapped.get("trainer_notes"),
mapped.get("duration_min"), mapped.get("duration_max"),
mapped.get("group_size_min"), mapped.get("group_size_max"),
equipment,
mapped.get("visibility", "private"),
mapped.get("status", "draft"),
"mediawiki",
mapped.get("import_id"),
created_by,
)
)
ex_id = cur.fetchone()['id']
conn.commit()
# Katalog-Zuordnungen (Focus Areas, Skills, etc.)
_assign_exercise_catalogs(cur, conn, ex_id, mapped)
# Skill-Zuordnungen mit Levels
skill_assignments = build_skill_assignments(mapped)
_assign_exercise_skills(cur, conn, ex_id, skill_assignments)
return ex_id
def _find_skill_id_by_label(cur, label: str) -> Optional[int]:
"""Katalog-Skill anhand Wiki-Label; exakt, ohne Leerzeichen, zuletzt Teilstring."""
if not label or not str(label).strip():
return None
raw = str(label).strip()
cur.execute("SELECT id FROM skills WHERE TRIM(name) ILIKE %s", (raw,))
row = cur.fetchone()
if row:
return row["id"]
comp = "".join(raw.split())
if len(comp) >= 3:
cur.execute(
"SELECT id FROM skills WHERE regexp_replace(TRIM(name), E'\\s+', '', 'g') ILIKE %s",
(comp,),
)
row = cur.fetchone()
if row:
return row["id"]
cur.execute("SELECT id FROM skills WHERE name ILIKE %s LIMIT 1", (f"%{raw}%",))
row = cur.fetchone()
return row["id"] if row else None
def _assign_exercise_catalogs(cur, conn, exercise_id: int, mapped: dict):
"""Weist M:N Katalog-Zuordnungen für eine importierte Übung zu."""
# Focus Areas
for idx, name in enumerate(mapped.get("focus_area_names", [])):
cur.execute("SELECT id FROM focus_areas WHERE name ILIKE %s", (name,))
row = cur.fetchone()
if row:
cur.execute(
"""INSERT INTO exercise_focus_areas (exercise_id, focus_area_id, is_primary)
VALUES (%s, %s, %s)
ON CONFLICT (exercise_id, focus_area_id) DO NOTHING""",
(exercise_id, row['id'], idx == 0)
)
else:
logger.warning("Focus Area '%s' nicht im Katalog gefunden", name)
# Stilrichtungen
for idx, name in enumerate(mapped.get("style_names", [])):
cur.execute("SELECT id FROM style_directions WHERE name ILIKE %s", (name.strip(),))
row = cur.fetchone()
if row:
cur.execute(
"""INSERT INTO exercise_style_directions (exercise_id, style_direction_id, is_primary)
VALUES (%s, %s, %s) ON CONFLICT (exercise_id, style_direction_id) DO NOTHING""",
(exercise_id, row["id"], idx == 0),
)
else:
logger.warning("Stilrichtung '%s' nicht im Katalog gefunden", name)
# Target Groups
for name in mapped.get("target_group_names", []):
cur.execute("SELECT id FROM target_groups WHERE name ILIKE %s", (name,))
row = cur.fetchone()
if row:
cur.execute(
"""INSERT INTO exercise_target_groups (exercise_id, target_group_id)
VALUES (%s, %s) ON CONFLICT DO NOTHING""",
(exercise_id, row['id'])
)
# Fähigkeiten: nur über _assign_exercise_skills (Levels + is_primary), nicht doppelt hier
conn.commit()
def _assign_exercise_skills(cur, conn, exercise_id: int, skill_assignments: list):
"""Weist Skill-Zuordnungen mit Levels einer Übung zu."""
for assignment in skill_assignments:
sid = _find_skill_id_by_label(cur, assignment.get("skill_name") or "")
if not sid:
logger.warning("Skill '%s' nicht im Katalog gefunden", assignment.get("skill_name"))
continue
cur.execute(
"""INSERT INTO exercise_skills
(exercise_id, skill_id, target_level, required_level, intensity, is_primary)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (exercise_id, skill_id) DO UPDATE SET
target_level = EXCLUDED.target_level,
is_primary = EXCLUDED.is_primary""",
(
exercise_id,
sid,
assignment.get("target_level"),
assignment.get("required_level"),
assignment.get("intensity"),
assignment.get("is_primary", False),
)
)
conn.commit()
def _upsert_skill(mapped: dict, reimport: bool) -> Optional[int]:
"""Legt Skill an oder überspringt bei Duplikat."""
with get_db() as conn:
cur = get_cursor(conn)
# Kategorie auflösen (optional)
category_id = None
if mapped.get("category_name"):
cur.execute("SELECT id FROM skill_categories WHERE name ILIKE %s", (mapped["category_name"],))
row = cur.fetchone()
if row:
category_id = row['id']
cur.execute(
"""INSERT INTO skills (name, description, category_id)
VALUES (%s, %s, %s)
ON CONFLICT (name) DO UPDATE SET
description = EXCLUDED.description
RETURNING id""",
(mapped["name"], mapped.get("description"), category_id)
)
skill_id = cur.fetchone()['id']
conn.commit()
return skill_id
def _upsert_method(mapped: dict, _reimport: bool) -> Optional[int]:
"""Legt Trainingsmethode an oder aktualisiert Beschreibung nach Namen.
training_methods.name hat keinen UNIQUE-Constraint — daher kein ON CONFLICT (name).
"""
name = (mapped.get("name") or "").strip()
desc = mapped.get("description")
if not name:
return None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id FROM training_methods WHERE TRIM(name) ILIKE TRIM(%s)",
(name,),
)
row = cur.fetchone()
if row:
mid = row["id"]
cur.execute(
"UPDATE training_methods SET description = %s, updated_at = NOW() WHERE id = %s",
(desc, mid),
)
conn.commit()
return mid
cur.execute(
"INSERT INTO training_methods (name, description) VALUES (%s, %s) RETURNING id",
(name, desc),
)
mid = cur.fetchone()["id"]
conn.commit()
return mid
def _upsert_wiki_ref(
page_title: str, page_id: Optional[int], content_type: str, local_id: int
):
"""Legt Import-Referenz an oder aktualisiert last_imported."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""INSERT INTO wiki_import_references
(wiki_page_title, wiki_page_id, content_type, local_id, last_imported)
VALUES (%s, %s, %s, %s, NOW())
ON CONFLICT (wiki_page_title, content_type) DO UPDATE SET
wiki_page_id = EXCLUDED.wiki_page_id,
local_id = EXCLUDED.local_id,
last_imported = NOW()""",
(page_title, page_id, content_type, local_id)
)
conn.commit()
+95
View File
@@ -0,0 +1,95 @@
"""
Admin-Hilfsfunktionen für MediaWiki-Import
"""
from fastapi import APIRouter, Depends, HTTPException
from db import get_db, get_cursor
from routers.import_wiki import require_admin
router = APIRouter(prefix="/api/import/mediawiki/admin", tags=["import-admin"])
@router.delete("/cleanup-orphaned-references")
def cleanup_orphaned_references(session: dict = Depends(require_admin)):
"""
Löscht verwaiste Import-Referenzen (Referenz existiert, aber Übung fehlt).
Nützlich nach fehlgeschlagenen Imports.
"""
deleted = {"exercises": 0, "skills": 0, "methods": 0}
with get_db() as conn:
cur = get_cursor(conn)
# Exercises
cur.execute("""
DELETE FROM wiki_import_references
WHERE content_type = 'exercise'
AND local_id NOT IN (SELECT id FROM exercises)
""")
deleted["exercises"] = cur.rowcount
# Skills
cur.execute("""
DELETE FROM wiki_import_references
WHERE content_type = 'skill'
AND local_id NOT IN (SELECT id FROM skills)
""")
deleted["skills"] = cur.rowcount
# Methods
cur.execute("""
DELETE FROM wiki_import_references
WHERE content_type = 'method'
AND local_id NOT IN (SELECT id FROM training_methods)
""")
deleted["methods"] = cur.rowcount
conn.commit()
return {
"ok": True,
"deleted": deleted,
"message": f"Deleted {sum(deleted.values())} orphaned references"
}
@router.get("/stats")
def get_import_stats(session: dict = Depends(require_admin)):
"""Statistik über Import-Referenzen vs. tatsächliche Einträge."""
with get_db() as conn:
cur = get_cursor(conn)
# Exercises
cur.execute("SELECT COUNT(*) as count FROM wiki_import_references WHERE content_type = 'exercise'")
refs_exercises = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM exercises WHERE import_source = 'mediawiki'")
actual_exercises = cur.fetchone()['count']
# Skills
cur.execute("SELECT COUNT(*) as count FROM wiki_import_references WHERE content_type = 'skill'")
refs_skills = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM skills")
actual_skills = cur.fetchone()['count']
# Methods
cur.execute("SELECT COUNT(*) as count FROM wiki_import_references WHERE content_type = 'method'")
refs_methods = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM training_methods")
actual_methods = cur.fetchone()['count']
return {
"exercises": {
"references": refs_exercises,
"actual": actual_exercises,
"orphaned": refs_exercises - actual_exercises
},
"skills": {
"references": refs_skills,
"actual": actual_skills,
"orphaned": refs_skills - actual_skills
},
"methods": {
"references": refs_methods,
"actual": actual_methods,
"orphaned": refs_methods - actual_methods
}
}
+773
View File
@@ -0,0 +1,773 @@
"""
Vollständiger Export/Import: Fähigkeitskatalog (Haupt-/Unterkategorien, Skills, Level-Definitionen),
Reifegradmodelle inkl. Kontext-M:N und Kontext-Bindings.
Ziel: Test → Prod; IDs werden über Slugs/Namen aufgelöst, nicht 1:1 übernommen.
"""
from __future__ import annotations
import json
import re
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from auth import require_auth
from db import get_db, get_cursor, r2d
router = APIRouter(prefix="/api/admin/matrix-stack", tags=["admin_matrix_stack"])
KIND_V1 = "shinkan.matrix_stack.v1"
def _require_admin(session: dict) -> None:
role = session.get("role")
if role not in ("admin", "superadmin"):
raise HTTPException(403, "Nur Administratoren")
def _keywords_param(raw: Any) -> Any:
if raw is None:
return None
if isinstance(raw, str):
return raw
return json.dumps(raw)
def _slugify_label(text: str) -> str:
t = (text or "").strip().lower()
t = re.sub(r"[^a-z0-9äöüß]+", "_", t, flags=re.IGNORECASE)
t = re.sub(r"_+", "_", t).strip("_")
return (t[:48] or "gruppe")
def _jsonable(val: Any) -> Any:
if val is None:
return None
if hasattr(val, "isoformat"):
try:
return val.isoformat()
except Exception:
return str(val)
return val
def _sort_categories_topo(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
by_id = {int(r["id"]): r for r in rows}
children: Dict[Optional[int], List[int]] = {}
for r in rows:
pid = r.get("parent_category_id")
pk = int(pid) if pid is not None else None
children.setdefault(pk, []).append(int(r["id"]))
out: List[Dict[str, Any]] = []
seen = set()
def visit(cid: int) -> None:
if cid in seen:
return
seen.add(cid)
out.append(by_id[cid])
for ch in sorted(children.get(cid, [])):
visit(ch)
roots = sorted(children.get(None, []))
for root_id in roots:
visit(root_id)
# Zyklen / verwaiste Knoten
for r in rows:
rid = int(r["id"])
if rid not in seen:
visit(rid)
return out
def _catalog_name_maps(cur) -> Tuple[Dict[str, int], Dict[str, int], Dict[str, int], Dict[str, int]]:
cur.execute("SELECT id, name FROM focus_areas")
fa = {r["name"].strip(): int(r["id"]) for r in cur.fetchall() if r.get("name")}
cur.execute("SELECT id, name FROM style_directions")
sd = {r["name"].strip(): int(r["id"]) for r in cur.fetchall() if r.get("name")}
cur.execute("SELECT id, name FROM training_types")
tt = {r["name"].strip(): int(r["id"]) for r in cur.fetchall() if r.get("name")}
cur.execute("SELECT id, name FROM target_groups")
tg = {r["name"].strip(): int(r["id"]) for r in cur.fetchall() if r.get("name")}
return fa, sd, tt, tg
def export_matrix_stack_v1(session: dict = Depends(require_auth)) -> JSONResponse:
_require_admin(session)
export_uid = str(uuid.uuid4())
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT * FROM skill_main_categories
ORDER BY sort_order NULLS LAST, name
"""
)
main_cats = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM skill_categories ORDER BY sort_order NULLS LAST, name")
raw_cats = [r2d(r) for r in cur.fetchall()]
skill_categories = _sort_categories_topo(raw_cats)
cur.execute(
"""
SELECT s.*,
mc.slug AS _export_main_category_slug,
sc.slug AS _export_category_slug,
pfa.name AS _export_primary_focus_area_name
FROM skills s
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
LEFT JOIN skill_categories sc ON s.category_id = sc.id
LEFT JOIN focus_areas pfa ON s.primary_focus_area_id = pfa.id
ORDER BY mc.sort_order NULLS LAST, sc.sort_order NULLS LAST, s.sort_order NULLS LAST, s.name
"""
)
skills = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT sld.* FROM skill_level_definitions sld
JOIN skills s ON s.id = sld.skill_id
ORDER BY s.name, sld.level
"""
)
skill_level_definitions = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM maturity_models ORDER BY id")
maturity_models_raw = [r2d(r) for r in cur.fetchall()]
maturity_blocks: List[Dict[str, Any]] = []
for m in maturity_models_raw:
mid = int(m["id"])
cur.execute(
"""
SELECT fa.name, mfa.is_primary
FROM maturity_model_focus_areas mfa
JOIN focus_areas fa ON fa.id = mfa.focus_area_id
WHERE mfa.maturity_model_id = %s
ORDER BY mfa.is_primary DESC NULLS LAST, fa.sort_order, fa.name
""",
(mid,),
)
fa_rows = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT sd.name, msd.is_primary
FROM maturity_model_style_directions msd
JOIN style_directions sd ON sd.id = msd.style_direction_id
WHERE msd.maturity_model_id = %s
ORDER BY msd.is_primary DESC NULLS LAST, sd.name
""",
(mid,),
)
sd_rows = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT tg.name, mtg.is_primary
FROM maturity_model_target_groups mtg
JOIN target_groups tg ON tg.id = mtg.target_group_id
WHERE mtg.maturity_model_id = %s
ORDER BY mtg.is_primary DESC NULLS LAST, tg.name
""",
(mid,),
)
tg_rows = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT * FROM model_levels
WHERE maturity_model_id = %s
ORDER BY sort_order ASC, level_number ASC
""",
(mid,),
)
levels = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT ms.skill_id, ms.sort_order, ms.relevance
FROM model_skills ms
WHERE ms.maturity_model_id = %s
ORDER BY ms.sort_order ASC, ms.id ASC
""",
(mid,),
)
model_skills = [r2d(r) for r in cur.fetchall()]
cur.execute(
"""
SELECT msl.skill_id, msl.level_number, msl.description, msl.observable_criteria,
msl.example_exercise_hints, msl.ai_generated
FROM model_skill_levels msl
WHERE msl.maturity_model_id = %s
ORDER BY msl.skill_id, msl.level_number
""",
(mid,),
)
skill_levels = [r2d(r) for r in cur.fetchall()]
row = {k: _jsonable(v) for k, v in m.items()}
for drop in ("created_at", "updated_at"):
row.pop(drop, None)
maturity_blocks.append(
{
"source_id": mid,
"model": row,
"legacy_focus_areas": fa_rows,
"legacy_style_directions": sd_rows,
"legacy_target_groups": tg_rows,
"levels": levels,
"model_skills": model_skills,
"skill_levels": skill_levels,
}
)
cur.execute(
"""
SELECT b.maturity_model_id AS maturity_model_source_id,
fa.name AS focus_area_name,
sd.name AS style_direction_name,
tt.name AS training_type_name
FROM maturity_model_context_bindings b
JOIN focus_areas fa ON fa.id = b.focus_area_id
LEFT JOIN style_directions sd ON sd.id = b.style_direction_id
LEFT JOIN training_types tt ON tt.id = b.training_type_id
ORDER BY fa.sort_order, fa.name, sd.name NULLS LAST, tt.name NULLS LAST
"""
)
context_bindings = [r2d(r) for r in cur.fetchall()]
bundle = {
"kind": KIND_V1,
"export_version": 1,
"bundle_export_id": export_uid,
"exported_at": datetime.now(timezone.utc).isoformat(),
"skill_main_categories": main_cats,
"skill_categories": skill_categories,
"skills": skills,
"skill_level_definitions": skill_level_definitions,
"maturity_models": maturity_blocks,
"context_bindings": context_bindings,
}
return JSONResponse(
content=jsonable_encoder(bundle),
headers={
"Content-Disposition": f'attachment; filename="matrix-stack-{export_uid[:8]}.json"'
},
)
def _upsert_main_category(cur, row: Dict[str, Any]) -> int:
name = (row.get("name") or "").strip()
slug = (row.get("slug") or "").strip() or _slugify_label(name)
if not name:
raise HTTPException(400, "skill_main_categories: name fehlt")
cur.execute(
"""
INSERT INTO skill_main_categories (name, slug, description, sort_order)
VALUES (%s, %s, %s, %s)
ON CONFLICT (slug) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
sort_order = EXCLUDED.sort_order,
updated_at = NOW()
RETURNING id
""",
(name, slug, row.get("description"), row.get("sort_order")),
)
return int(cur.fetchone()["id"])
def _upsert_skill_category(
cur,
row: Dict[str, Any],
main_id_map: Dict[int, int],
cat_id_map: Dict[int, int],
) -> Tuple[int, int]:
"""Returns (old_id, new_id)."""
old_id = int(row["id"])
name = (row.get("name") or "").strip()
slug = (row.get("slug") or "").strip() or _slugify_label(name)
if not name:
raise HTTPException(400, f"skill_categories id={old_id}: name fehlt")
old_main = row.get("main_category_id")
new_main = main_id_map.get(int(old_main)) if old_main is not None else None
old_parent = row.get("parent_category_id")
new_parent = cat_id_map.get(int(old_parent)) if old_parent is not None else None
cur.execute(
"""
INSERT INTO skill_categories (
name, slug, description, parent_category_id, main_category_id, sort_order, status
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (slug) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
parent_category_id = EXCLUDED.parent_category_id,
main_category_id = EXCLUDED.main_category_id,
sort_order = EXCLUDED.sort_order,
status = EXCLUDED.status,
updated_at = NOW()
RETURNING id
""",
(
name,
slug,
row.get("description"),
new_parent,
new_main,
row.get("sort_order"),
row.get("status") or "active",
),
)
new_id = int(cur.fetchone()["id"])
return old_id, new_id
def import_matrix_stack_v1(
data: Dict[str, Any] = Body(...),
session: dict = Depends(require_auth),
) -> Dict[str, Any]:
_require_admin(session)
if data.get("kind") != KIND_V1:
raise HTTPException(400, f"kind muss {KIND_V1} sein")
replace_all = bool(data.get("replace_all_maturity_models"))
confirm = (data.get("confirm_replace_all") or "").strip()
if replace_all and confirm != "DELETE_MATURITY_STACK":
raise HTTPException(
400,
'replace_all_maturity_models erfordert confirm_replace_all: "DELETE_MATURITY_STACK"',
)
if replace_all and session.get("role") != "superadmin":
raise HTTPException(403, "replace_all_maturity_models nur für Superadmins")
profile_id = session.get("profile_id")
warnings: List[str] = []
main_rows = data.get("skill_main_categories") or []
cat_rows = _sort_categories_topo(list(data.get("skill_categories") or []))
skill_rows = data.get("skills") or []
sld_rows = data.get("skill_level_definitions") or []
model_blocks = data.get("maturity_models") or []
bind_rows = data.get("context_bindings") or []
skill_id_map: Dict[int, int] = {}
model_id_map: Dict[int, int] = {}
with get_db() as conn:
cur = get_cursor(conn)
fa_by_name, sd_by_name, tt_by_name, tg_by_name = _catalog_name_maps(cur)
# ── Katalog: Hauptkategorien ──
main_id_map: Dict[int, int] = {}
for mc in main_rows:
old = int(mc["id"])
main_id_map[old] = _upsert_main_category(cur, mc)
# ── Katalog: Unterkategorien (mehrere Durchläufe für Parent-Kette) ──
cat_id_map: Dict[int, int] = {}
remaining = list(cat_rows)
guard = 0
while remaining and guard < len(cat_rows) + 5:
guard += 1
next_pass: List[Dict[str, Any]] = []
for row in remaining:
old_parent = row.get("parent_category_id")
if old_parent is not None and int(old_parent) not in cat_id_map:
next_pass.append(row)
continue
old_id, new_id = _upsert_skill_category(cur, row, main_id_map, cat_id_map)
cat_id_map[old_id] = new_id
remaining = next_pass
if remaining:
raise HTTPException(400, "skill_categories: Parent-Auflösung fehlgeschlagen (Zyklus?)")
# ── Skills ──
slug_to_cat_id = {}
cur.execute("SELECT id, slug FROM skill_categories WHERE slug IS NOT NULL")
for r in cur.fetchall():
slug_to_cat_id[r["slug"]] = int(r["id"])
main_slug_to_id = {}
cur.execute("SELECT id, slug FROM skill_main_categories")
for r in cur.fetchall():
main_slug_to_id[r["slug"]] = int(r["id"])
for s in skill_rows:
old_sid = int(s["id"])
name = (s.get("name") or "").strip()
if not name:
raise HTTPException(400, f"Skill id={old_sid}: name fehlt")
cat_slug = s.get("_export_category_slug")
main_slug = s.get("_export_main_category_slug")
cat_id = None
main_id = None
if cat_slug:
cat_id = slug_to_cat_id.get(cat_slug)
if cat_id is None and s.get("category_id") is not None:
cat_id = cat_id_map.get(int(s["category_id"]))
if main_slug:
main_id = main_slug_to_id.get(main_slug)
if main_id is None and s.get("main_category_id") is not None:
main_id = main_id_map.get(int(s["main_category_id"]))
pfa_name = s.get("_export_primary_focus_area_name")
pfa_id = None
if pfa_name:
pfa_id = fa_by_name.get(str(pfa_name).strip())
if pfa_id is None:
warnings.append(f"primary_focus_area „{pfa_name}“ für Skill „{name}“ nicht gefunden")
focus_json = s.get("focus_areas")
if isinstance(focus_json, (dict, list)):
focus_json = json.dumps(focus_json)
elif focus_json is None:
focus_json = "[]"
cur.execute(
"""
SELECT id FROM skills
WHERE category_id IS NOT DISTINCT FROM %s AND name = %s
LIMIT 1
""",
(cat_id, name),
)
ex = cur.fetchone()
if ex:
new_sid = int(ex["id"])
cur.execute(
"""
UPDATE skills SET
category = %s,
description = %s,
importance = %s,
keywords = %s,
status = COALESCE(%s, status),
main_category_id = COALESCE(%s, main_category_id),
category_id = COALESCE(%s, category_id),
focus_areas = %s::jsonb,
sort_order = COALESCE(%s, sort_order),
primary_focus_area_id = COALESCE(%s, primary_focus_area_id),
is_cross_domain = COALESCE(%s, is_cross_domain),
level = COALESCE(%s, level),
parent_skill_id = COALESCE(%s, parent_skill_id),
updated_at = NOW()
WHERE id = %s
""",
(
s.get("category"),
s.get("description"),
s.get("importance"),
_keywords_param(s.get("keywords")),
s.get("status"),
main_id,
cat_id,
focus_json,
s.get("sort_order"),
pfa_id,
s.get("is_cross_domain"),
s.get("level"),
None,
new_sid,
),
)
else:
cur.execute(
"""
INSERT INTO skills (
name, category, description, importance, keywords, status,
category_id, main_category_id, focus_areas, sort_order,
primary_focus_area_id, is_cross_domain, level
)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s::jsonb,%s,%s,%s,%s)
RETURNING id
""",
(
name,
s.get("category"),
s.get("description"),
s.get("importance"),
_keywords_param(s.get("keywords")),
s.get("status") or "active",
cat_id,
main_id,
focus_json,
s.get("sort_order"),
pfa_id,
s.get("is_cross_domain"),
s.get("level"),
),
)
new_sid = int(cur.fetchone()["id"])
skill_id_map[old_sid] = new_sid
# parent_skill_id zweite Runde
for s in skill_rows:
old_sid = int(s["id"])
ps = s.get("parent_skill_id")
if ps is None:
continue
new_sid = skill_id_map.get(old_sid)
new_parent = skill_id_map.get(int(ps))
if new_sid and new_parent:
cur.execute(
"UPDATE skills SET parent_skill_id = %s WHERE id = %s",
(new_parent, new_sid),
)
# skill_level_definitions
for sld in sld_rows:
old_sk = int(sld["skill_id"])
new_sk = skill_id_map.get(old_sk)
if not new_sk:
warnings.append(f"skill_level_definitions: Skill {old_sk} nicht gemappt, übersprungen")
continue
lvl = int(sld["level"])
cur.execute(
"""
INSERT INTO skill_level_definitions (skill_id, level, description)
VALUES (%s, %s, %s)
ON CONFLICT (skill_id, level) DO UPDATE SET
description = EXCLUDED.description,
updated_at = NOW()
""",
(new_sk, lvl, sld.get("description") or ""),
)
if replace_all:
cur.execute("DELETE FROM maturity_models")
for block in model_blocks:
src_mid = int(block["source_id"])
mrow = dict(block.get("model") or {})
for drop in ("id", "created_at", "updated_at"):
mrow.pop(drop, None)
lc = int(mrow.get("level_count") or 5)
if lc < 3 or lc > 10:
raise HTTPException(400, "level_count ungültig")
cur.execute(
"""
INSERT INTO maturity_models (
name, description, level_count, status, version,
created_by, import_source, import_id, club_id
)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
RETURNING id
""",
(
(mrow.get("name") or "").strip() or "Importiertes Modell",
mrow.get("description"),
lc,
mrow.get("status") or "draft",
mrow.get("version") or "1.0",
profile_id,
mrow.get("import_source") or "matrix_stack_v1",
mrow.get("import_id") or f"stack:{data.get('bundle_export_id') or 'na'}:{src_mid}",
None,
),
)
new_mid = int(cur.fetchone()["id"])
model_id_map[src_mid] = new_mid
for fa in block.get("legacy_focus_areas") or []:
nm = (fa.get("name") or "").strip()
fid = fa_by_name.get(nm)
if fid is None:
warnings.append(f"Modell {mrow.get('name')}: Fokus „{nm}“ unbekannt")
continue
cur.execute(
"""
INSERT INTO maturity_model_focus_areas (maturity_model_id, focus_area_id, is_primary)
VALUES (%s, %s, %s)
ON CONFLICT (maturity_model_id, focus_area_id) DO NOTHING
""",
(new_mid, fid, bool(fa.get("is_primary"))),
)
for sd in block.get("legacy_style_directions") or []:
nm = (sd.get("name") or "").strip()
sid = sd_by_name.get(nm)
if sid is None:
warnings.append(f"Modell {mrow.get('name')}: Stilrichtung „{nm}“ unbekannt")
continue
cur.execute(
"""
INSERT INTO maturity_model_style_directions (maturity_model_id, style_direction_id, is_primary)
VALUES (%s, %s, %s)
ON CONFLICT (maturity_model_id, style_direction_id) DO NOTHING
""",
(new_mid, sid, bool(sd.get("is_primary"))),
)
for tg in block.get("legacy_target_groups") or []:
nm = (tg.get("name") or "").strip()
tid = tg_by_name.get(nm)
if tid is None:
warnings.append(f"Modell {mrow.get('name')}: Zielgruppe „{nm}“ unbekannt")
continue
cur.execute(
"""
INSERT INTO maturity_model_target_groups (maturity_model_id, target_group_id, is_primary)
VALUES (%s, %s, %s)
ON CONFLICT (maturity_model_id, target_group_id) DO NOTHING
""",
(new_mid, tid, bool(tg.get("is_primary"))),
)
for lev in block.get("levels") or []:
cur.execute(
"""
INSERT INTO model_levels (maturity_model_id, level_number, name, description, sort_order)
VALUES (%s, %s, %s, %s, %s)
""",
(
new_mid,
int(lev["level_number"]),
(lev.get("name") or f"Stufe {lev['level_number']}").strip(),
lev.get("description"),
int(lev.get("sort_order") or lev["level_number"]),
),
)
for ms in block.get("model_skills") or []:
old_sk = int(ms["skill_id"])
new_sk = skill_id_map.get(old_sk)
if not new_sk:
raise HTTPException(400, f"Modell {mrow.get('name')}: unbekannte skill_id {old_sk}")
cur.execute(
"""
INSERT INTO model_skills (maturity_model_id, skill_id, sort_order, relevance)
VALUES (%s, %s, %s, %s)
ON CONFLICT (maturity_model_id, skill_id) DO UPDATE SET
sort_order = EXCLUDED.sort_order,
relevance = EXCLUDED.relevance
""",
(new_mid, new_sk, int(ms.get("sort_order") or 0), ms.get("relevance")),
)
for sl in block.get("skill_levels") or []:
old_sk = int(sl["skill_id"])
new_sk = skill_id_map.get(old_sk)
if not new_sk:
continue
ln = int(sl["level_number"])
desc = (sl.get("description") or "").strip()
if not desc:
continue
cur.execute(
"""
INSERT INTO model_skill_levels (
maturity_model_id, skill_id, level_number,
description, observable_criteria, example_exercise_hints, ai_generated
)
VALUES (%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (maturity_model_id, skill_id, level_number)
DO UPDATE SET
description = EXCLUDED.description,
observable_criteria = EXCLUDED.observable_criteria,
example_exercise_hints = EXCLUDED.example_exercise_hints,
ai_generated = EXCLUDED.ai_generated,
updated_at = NOW()
""",
(
new_mid,
new_sk,
ln,
desc,
sl.get("observable_criteria"),
sl.get("example_exercise_hints"),
sl.get("ai_generated"),
),
)
for b in bind_rows:
src_m = int(b["maturity_model_source_id"])
new_m = model_id_map.get(src_m)
if not new_m:
warnings.append(f"Binding: Modell-Quell-ID {src_m} nicht gefunden, übersprungen")
continue
fa_n = (b.get("focus_area_name") or "").strip()
fa_id = fa_by_name.get(fa_n)
if fa_id is None:
warnings.append(f"Binding: Fokus „{fa_n}“ unbekannt")
continue
sd_n = b.get("style_direction_name")
sd_id = None
if sd_n:
sd_id = sd_by_name.get(str(sd_n).strip())
if sd_id is None:
warnings.append(f"Binding: Stil „{sd_n}“ unbekannt")
continue
tt_n = b.get("training_type_name")
tt_id = None
if tt_n:
tt_id = tt_by_name.get(str(tt_n).strip())
if tt_id is None:
warnings.append(f"Binding: Trainingsstil „{tt_n}“ unbekannt")
continue
if sd_id is None and tt_id is None:
cur.execute(
"""
DELETE FROM maturity_model_context_bindings
WHERE focus_area_id = %s AND style_direction_id IS NULL AND training_type_id IS NULL
""",
(fa_id,),
)
elif sd_id is not None and tt_id is None:
cur.execute(
"""
DELETE FROM maturity_model_context_bindings
WHERE focus_area_id = %s AND style_direction_id = %s AND training_type_id IS NULL
""",
(fa_id, sd_id),
)
elif sd_id is None and tt_id is not None:
cur.execute(
"""
DELETE FROM maturity_model_context_bindings
WHERE focus_area_id = %s AND style_direction_id IS NULL AND training_type_id = %s
""",
(fa_id, tt_id),
)
else:
cur.execute(
"""
DELETE FROM maturity_model_context_bindings
WHERE focus_area_id = %s AND style_direction_id = %s AND training_type_id = %s
""",
(fa_id, sd_id, tt_id),
)
cur.execute(
"""
INSERT INTO maturity_model_context_bindings (
maturity_model_id, focus_area_id, style_direction_id, training_type_id
)
VALUES (%s, %s, %s, %s)
""",
(new_m, fa_id, sd_id, tt_id),
)
return {
"ok": True,
"skill_id_map": {str(k): v for k, v in skill_id_map.items()},
"model_id_map": {str(k): v for k, v in model_id_map.items()},
"warnings": warnings,
}
router.add_api_route("/export", export_matrix_stack_v1, methods=["GET"])
router.add_api_route("/import", import_matrix_stack_v1, methods=["POST"])
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+97
View File
@@ -0,0 +1,97 @@
"""Superadmin: Speicherpfad-Konfiguration (§7.1 MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from club_tenancy import is_platform_admin
from db import get_db, get_cursor, r2d
from auth import require_auth
from media_storage import _default_media_root, get_effective_media_root, normalize_local_relative_root
router = APIRouter(prefix="/api/admin", tags=["admin", "media-storage"])
class PlatformMediaStorageUpdate(BaseModel):
local_relative_root: str = Field(
"",
description="Relativer Unterordner unter MEDIA_ROOT (z. B. nas/videos). Leer = nur MEDIA_ROOT.",
max_length=512,
)
class PlatformMediaStorageOut(BaseModel):
storage_backend: str
local_relative_root: str
media_root_env: str
effective_media_root: str
def _require_superadmin(session: dict) -> None:
role = (session.get("role") or "").strip().lower()
if role != "superadmin":
raise HTTPException(status_code=403, detail="Nur Superadmin")
@router.get("/platform-media-storage", response_model=PlatformMediaStorageOut)
def get_platform_media_storage(session: dict = Depends(require_auth)):
"""Lesen: Plattform-Admin (admin/superadmin) – Hilfe für Betrieb."""
role = (session.get("role") or "").strip().lower()
if not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT storage_backend, local_relative_root
FROM platform_media_storage WHERE id = 1""",
)
row = cur.fetchone()
if not row:
backend, rel = "local", ""
else:
d = r2d(row)
backend = d.get("storage_backend") or "local"
rel = str(d.get("local_relative_root") or "")
eff = get_effective_media_root(cur)
return PlatformMediaStorageOut(
storage_backend=backend,
local_relative_root=rel,
media_root_env=str(_default_media_root().resolve()),
effective_media_root=str(eff),
)
@router.put("/platform-media-storage", response_model=PlatformMediaStorageOut)
def put_platform_media_storage(
body: PlatformMediaStorageUpdate,
session: dict = Depends(require_auth),
):
"""Schreiben: nur superadmin."""
_require_superadmin(session)
profile_id = session["profile_id"]
try:
rel_norm = normalize_local_relative_root(body.local_relative_root)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""UPDATE platform_media_storage
SET local_relative_root = %s, updated_at = NOW(), updated_by_profile_id = %s
WHERE id = 1
RETURNING storage_backend, local_relative_root""",
(rel_norm, profile_id),
)
row = cur.fetchone()
conn.commit()
if not row:
raise HTTPException(status_code=500, detail="platform_media_storage fehlt")
d = r2d(row)
eff = get_effective_media_root(cur)
return PlatformMediaStorageOut(
storage_backend=str(d.get("storage_backend") or "local"),
local_relative_root=str(d.get("local_relative_root") or ""),
media_root_env=str(_default_media_root().resolve()),
effective_media_root=str(eff),
)
+349 -50
View File
@@ -3,86 +3,282 @@ Profile Management Endpoints for Mitai Jinkendo
Handles profile CRUD operations for both admin and current user.
"""
import uuid
import secrets
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Header, Depends
from psycopg2.extras import Json
from pydantic import BaseModel, Field, field_validator
from db import get_db, get_cursor, r2d
from auth import require_auth
from auth import require_auth, hash_pin
from club_tenancy import (
assert_club_member,
club_ids_for_profile_with_roles,
is_platform_admin,
is_superadmin,
memberships_with_roles,
)
from tenant_context import resolve_tenant_context, TenantContext, get_tenant_context
from models import ProfileCreate, ProfileUpdate
router = APIRouter(prefix="/api", tags=["profiles"])
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
# ── Helper ────────────────────────────────────────────────────────────────────
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
"""Get profile_id - from header for legacy endpoints."""
if x_profile_id:
return x_profile_id
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM profiles ORDER BY created LIMIT 1")
row = cur.fetchone()
if row: return row['id']
raise HTTPException(400, "Kein Profil gefunden")
class ManagementPasswordResetBody(BaseModel):
"""Optional: Nur Super-Admins dürfen `new_password` setzen — sonst E-Mail-Link (wie Passwort vergessen)."""
new_password: Optional[str] = Field(None, min_length=8, max_length=128)
@field_validator("new_password", mode="before")
@classmethod
def _empty_pw_none(cls, v):
if v is None:
return None
if isinstance(v, str) and not v.strip():
return None
return v
def _target_portal_role_lower(cur, target_pid: int) -> str:
cur.execute("SELECT lower(trim(COALESCE(role, ''))) AS r FROM profiles WHERE id = %s", (target_pid,))
row = cur.fetchone()
return (row.get("r") or "user") if row else "user"
def _assert_can_management_password_help(cur, tenant: TenantContext, target_pid: int, *, via_email: bool) -> None:
"""
Wer darf eines anderen Accounts Passwort-Helfer nutzen (E-Mail-Link oder — nur Superadmin — direktes Setzen)?
Superadmin / Portal-Admin global; Vereinsadmin nur für aktives Mitglied in gemeinsam verwaltetem Verein.
"""
viewer_pid = int(tenant.profile_id)
if target_pid == viewer_pid:
raise HTTPException(status_code=400, detail="Eigenes Passwort unter Einstellungen ändern")
role_raw = tenant.global_role or ""
if is_superadmin(role_raw):
return
if is_platform_admin(role_raw):
return
managed = club_ids_for_profile_with_roles(cur, viewer_pid, "club_admin")
if not managed:
raise HTTPException(status_code=403, detail="Keine Berechtigung")
cur.execute(
"""
SELECT 1 FROM club_members
WHERE profile_id = %s AND club_id = ANY(%s) AND status = 'active'
LIMIT 1
""",
(target_pid, list(managed)),
)
if not cur.fetchone():
raise HTTPException(
status_code=403,
detail="Nur für Nutzer, die in mindestens einem deiner Vereine (als Admin) aktiv sind",
)
if via_email and _target_portal_role_lower(cur, target_pid) in _CLUB_BLOCKED_PORTAL_TARGETS:
raise HTTPException(
status_code=403,
detail="Für Konten mit Portal-Administrator- oder Super-Administrator-Rolle ist das nur für Super-Admins möglich",
)
# ── Current User Profile ──────────────────────────────────────────────────────
@router.get("/profiles/me")
def get_current_profile(session=Depends(require_auth)):
"""Get current user's profile (for auth check on refresh)."""
profile_id = session['profile_id']
def get_current_profile(
session=Depends(require_auth),
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
):
"""Profil inkl. Vereinsmitgliedschaften (aktive und temporär deaktivierte Zugänge); effective_club_id nur bei aktivem Vereinszugang."""
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (profile_id,))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Profil nicht gefunden")
return r2d(row)
data = r2d(row)
data.pop("pin_hash", None)
clubs = memberships_with_roles(cur, profile_id, active_only=False)
data["clubs"] = clubs
ac_raw = data.get("active_club_id")
stored_ac = int(ac_raw) if ac_raw is not None and ac_raw != "" else None
tenant = resolve_tenant_context(
cur,
profile_id=int(profile_id),
global_role=session.get("role") or "",
header_raw=x_active_club_id,
memberships=clubs,
stored_active_club_id=stored_ac,
invalid_header_policy="ignore",
)
data["effective_club_id"] = tenant.effective_club_id
return data
# ── Admin Profile Management ──────────────────────────────────────────────────
@router.get("/profiles")
def list_profiles(session=Depends(require_auth)):
"""List all profiles (admin)."""
"""Liste aller Profile (nur Plattform-Admin)."""
role = (session.get("role") or "").lower()
if not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Nur Plattform-Administratoren dürfen alle Profile einsehen")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles ORDER BY created")
rows = cur.fetchall()
return [r2d(r) for r in rows]
out = []
for r in rows:
d = r2d(r)
d.pop("pin_hash", None)
out.append(d)
return out
@router.post("/profiles")
def create_profile(p: ProfileCreate, session=Depends(require_auth)):
"""Create new profile (admin)."""
pid = str(uuid.uuid4())
"""
Neues Profil anlegen — nur Plattform-Admin.
Nutzt gleiches Kernschema wie Registrierung (SERIAL id); PIN wird zufällig gesetzt — Nutzer
setzt das Passwort über „Passwort vergessen“ oder ein späteres Admin-Tool.
"""
role = session.get("role") or ""
if not is_platform_admin(role):
raise HTTPException(
status_code=403,
detail="Nur Plattform-Administratoren dürfen Profile anlegen",
)
email_norm = str(p.email).strip().lower()
name_s = (p.name or "").strip()
pin_hash = hash_pin(secrets.token_urlsafe(24))
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""INSERT INTO profiles (id,name,avatar_color,sex,dob,height,goal_weight,goal_bf_pct,created,updated)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)""",
(pid,p.name,p.avatar_color,p.sex,p.dob,p.height,p.goal_weight,p.goal_bf_pct))
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
return r2d(cur.fetchone())
cur.execute(
"SELECT id FROM profiles WHERE email IS NOT NULL AND lower(trim(email)) = %s",
(email_norm,),
)
if cur.fetchone():
raise HTTPException(status_code=409, detail="E-Mail bereits registriert")
cur.execute(
"""
INSERT INTO profiles (
name, email, pin_hash, auth_type, role, tier,
email_verified, created_at, updated_at
)
VALUES (%s, %s, %s, 'email', 'user', 'free', TRUE,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
RETURNING id
""",
(name_s, email_norm, pin_hash),
)
row = cur.fetchone()
new_id = row["id"] if row else None
if new_id is None:
raise HTTPException(status_code=500, detail="Profil konnte nicht angelegt werden")
return profile_document(str(new_id))
@router.get("/profiles/{pid}")
def get_profile(pid: str, session=Depends(require_auth)):
"""Get profile by ID."""
def profile_document(pid: str) -> dict:
"""Profil ohne PIN — für Routen und interne Aufrufe (z. B. /auth/me)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
row = cur.fetchone()
if not row: raise HTTPException(404, "Profil nicht gefunden")
return r2d(row)
if not row:
raise HTTPException(404, "Profil nicht gefunden")
d = r2d(row)
d.pop("pin_hash", None)
return d
@router.put("/profiles/{pid}")
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
"""Update profile by ID."""
@router.post("/profiles/{pid}/management-password-reset")
def management_password_reset(
pid: str,
body: ManagementPasswordResetBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Standard: E-Mail mit Reset-Link wie „Passwort vergessen“ — der PIN-Hash bleibt bis zur Bestätigung unverändert.
Nur Super-Admins können optional `new_password` setzen (Ausnahme).
"""
from routers.auth import send_email
from password_reset_mail import issue_password_reset_via_email
try:
target = int(pid)
except ValueError:
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
direct = body.new_password is not None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id, email, name FROM profiles WHERE id = %s", (target,))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
if direct:
role_raw = tenant.global_role or ""
if not is_superadmin(role_raw):
raise HTTPException(
status_code=403,
detail="Direktes Setzen eines Passworts ist nur Super-Admins vorbehalten. Bitte E-Mail-Link verwenden.",
)
_assert_can_management_password_help(cur, tenant, target, via_email=False)
new_hash = hash_pin(body.new_password)
cur.execute(
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
(new_hash, target),
)
return {"ok": True, "mode": "direct"}
_assert_can_management_password_help(cur, tenant, target, via_email=True)
email = (row.get("email") or "").strip()
if not email:
raise HTTPException(
status_code=400,
detail="Für dieses Profil ist keine E-Mail-Adresse hinterlegt; ein Reset-Link kann nicht versendet werden.",
)
name = row.get("name")
intro = "Ein Administrator hat für dein Konto einen sicheren Link zum Setzen eines neuen Passworts angefordert."
sent = issue_password_reset_via_email(
cur,
send_email,
profile_id=target,
email=email.lower(),
name=name,
intro=intro,
)
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
@router.get("/profiles/{pid}")
def get_profile(pid: str, session=Depends(require_auth)):
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
viewer = session["profile_id"]
role = session.get("role") or ""
if str(viewer) != str(pid) and not is_platform_admin(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung für dieses Profil")
return profile_document(pid)
def _run_profile_update(pid: str, p: ProfileUpdate, tenant: TenantContext) -> dict:
"""Gemeinsame PUT-Logik für /profiles/{id} und Legacy /profile."""
sess_pid = tenant.profile_id
role = tenant.global_role
if str(sess_pid) != str(pid) and role not in ("admin", "superadmin"):
raise HTTPException(403, "Keine Berechtigung für dieses Profil")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
@@ -95,6 +291,51 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
patch = p.model_dump(exclude_unset=True)
data = {}
if "role" in patch or "tier" in patch:
if not is_platform_admin(role):
raise HTTPException(
status_code=403,
detail="Nur Portal-Admins dürfen Rolle oder Tier ändern",
)
if "role" in patch:
new_role = (patch["role"] or "").strip().lower()
if new_role not in _ALLOWED_PORTAL_ROLES:
raise HTTPException(
status_code=400,
detail=f"Ungültige Portal-Rolle. Erlaubt: {', '.join(sorted(_ALLOWED_PORTAL_ROLES))}",
)
if new_role == "superadmin" and role != "superadmin":
raise HTTPException(
status_code=403,
detail="Nur Super-Admins dürfen die Rolle Super-Admin vergeben",
)
old_r = (rowd.get("role") or "user").strip().lower()
cur.execute(
"""
SELECT COUNT(*)::int AS c FROM profiles
WHERE lower(trim(role)) IN ('admin','superadmin')
"""
)
admin_cnt = int(cur.fetchone()["c"])
if old_r in ("admin", "superadmin") and new_role not in ("admin", "superadmin"):
if admin_cnt <= 1:
raise HTTPException(
status_code=400,
detail="Der letzte Portal-Administrator kann nicht zurückgestuft werden",
)
data["role"] = new_role
del patch["role"]
if "tier" in patch:
tv = patch["tier"]
if tv is None:
data["tier"] = "free"
else:
ts = str(tv).strip()
data["tier"] = (ts or "free")[:50]
del patch["tier"]
if "email" in patch:
ev = patch["email"]
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
@@ -122,49 +363,107 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
data["verification_token"] = None
data["verification_expires"] = None
if "active_club_id" in patch:
ac = patch["active_club_id"]
if ac is None:
data["active_club_id"] = None
else:
try:
cid = int(ac)
except (TypeError, ValueError):
raise HTTPException(400, "active_club_id ungültig")
assert_club_member(cur, int(pid), cid)
data["active_club_id"] = cid
if "exercise_list_prefs" in patch:
ep = patch.pop("exercise_list_prefs")
if ep is None:
data["exercise_list_prefs"] = Json({})
elif isinstance(ep, dict):
data["exercise_list_prefs"] = Json(ep)
else:
raise HTTPException(400, "exercise_list_prefs muss ein JSON-Objekt sein")
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
for k, v in patch.items():
if k == "email":
continue
if k == "active_club_id":
continue
if v is None and k in nullable_keys:
data[k] = None
elif v is not None:
data[k] = v
if not data:
return get_profile(pid, session)
return profile_document(pid)
data["updated"] = datetime.now().isoformat()
data["updated_at"] = datetime.now()
cols = ", ".join(f"{k}=%s" for k in data)
vals = list(data.values()) + [pid]
cur.execute(f"UPDATE profiles SET {cols} WHERE id=%s", vals)
return get_profile(pid, session)
return profile_document(pid)
@router.put("/profiles/{pid}")
def update_profile(pid: str, p: ProfileUpdate, tenant: TenantContext = Depends(get_tenant_context)):
"""Update profile — nur eigenes Profil oder Admin; TenantContext validiert X-Active-Club-Id."""
return _run_profile_update(pid, p, tenant)
@router.delete("/profiles/{pid}")
def delete_profile(pid: str, session=Depends(require_auth)):
"""Delete profile (admin)."""
"""Profil löschen — nur Plattform-Admin; letztes Profil wird geschützt."""
role = session.get("role") or ""
if not is_platform_admin(role):
raise HTTPException(
status_code=403,
detail="Nur Plattform-Administratoren dürfen Profile löschen",
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT COUNT(*) as count FROM profiles")
count = cur.fetchone()['count']
if count <= 1: raise HTTPException(400, "Letztes Profil kann nicht gelöscht werden")
for table in ['weight_log','circumference_log','caliper_log','nutrition_log','activity_log','ai_insights']:
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
# Mitai-Überbleibsel: nur löschen, wenn die Tabelle im Schema existiert (Shinkan-DB ohne diese Tabellen).
_optional_mitai_tables = (
"weight_log",
"circumference_log",
"caliper_log",
"nutrition_log",
"activity_log",
"ai_insights",
)
for table in _optional_mitai_tables:
cur.execute(
"""
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = %s
) AS t_exists
""",
(table,),
)
ex = cur.fetchone()
if ex and next(iter(ex.values())):
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
cur.execute("DELETE FROM profiles WHERE id=%s", (pid,))
return {"ok": True}
# ── Current User Profile ──────────────────────────────────────────────────────
@router.get("/profile")
def get_active_profile(x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
"""Legacy endpoint – returns active profile."""
pid = get_pid(x_profile_id)
return get_profile(pid, session)
def get_active_profile(session: dict = Depends(require_auth)):
"""Legacy-Alias für das eingeloggte Profil — immer Session, kein X-Profile-Id (SECURITY: kein IDOR)."""
pid = str(session["profile_id"])
return profile_document(pid)
@router.put("/profile")
def update_active_profile(p: ProfileUpdate, x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
"""Update current user's profile."""
pid = get_pid(x_profile_id)
return update_profile(pid, p, session)
def update_active_profile(
p: ProfileUpdate,
tenant: TenantContext = Depends(get_tenant_context),
):
"""Profil des eingeloggten Nutzers aktualisieren — dieselbe Quelle wie GET /profile."""
pid = str(tenant.profile_id)
return _run_profile_update(pid, p, tenant)
+156 -40
View File
@@ -5,8 +5,11 @@ Handles CRUD operations for skills and training methods.
Read access for all authenticated users.
Write access for admins only.
"""
from typing import Optional
import json
from typing import Any, Optional
from fastapi import APIRouter, HTTPException, Depends, Query
from psycopg2.extras import Json
from db import get_db, get_cursor, r2d
from auth import require_auth
@@ -14,6 +17,26 @@ from auth import require_auth
router = APIRouter(prefix="/api", tags=["skills"])
def _jsonb_param(val: Any) -> Any:
"""psycopg2 benötigt Json() oder String für JSONB — rohe dict/list sonst ProgrammingError."""
if val is None:
return None
if isinstance(val, (dict, list)):
return Json(val)
return val
def _main_id_for_category(cur, category_id: Optional[int]) -> Optional[int]:
if not category_id:
return None
cur.execute(
"SELECT main_category_id FROM skill_categories WHERE id = %s",
(category_id,),
)
row = cur.fetchone()
return row["main_category_id"] if row else None
# ── List Skills ───────────────────────────────────────────────────────
@router.get("/skills")
def list_skills(
@@ -40,11 +63,14 @@ def list_skills(
params.append(category)
if status:
where.append("status = %s")
params.append(status)
if status == "active":
where.append("(status = 'active' OR status IS NULL)")
else:
where.append("status = %s")
params.append(status)
else:
# Default: only active skills
where.append("status = 'active'")
# Default: nur aktive (NULL = Legacy, wie Kataloglisten)
where.append("(status = 'active' OR status IS NULL)")
if where:
query += " WHERE " + " AND ".join(where)
@@ -56,6 +82,57 @@ def list_skills(
return [r2d(r) for r in rows]
# ── Katalog-Ansicht (Hierarchie-Sortierung, Admin) ───────────────────────
@router.get("/skills/catalog")
def list_skills_catalog(
status: Optional[str] = Query(
default="active",
description="'active', 'inactive' oder 'all' (nur Admin)",
),
session=Depends(require_auth),
):
"""
Fähigkeiten für Admin-Katalog: sortiert nach Hauptgruppe → Kategorie → Sortierung → Name.
status=all nur für admin/superadmin.
"""
role = session.get("role")
admin = role in ("admin", "superadmin")
with get_db() as conn:
cur = get_cursor(conn)
q = """
SELECT s.*,
mc.name AS catalog_main_category_name,
mc.sort_order AS catalog_main_sort,
mc.slug AS catalog_main_slug,
sc.name AS catalog_category_name,
sc.sort_order AS catalog_category_sort,
sc.slug AS catalog_category_slug
FROM skills s
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
LEFT JOIN skill_categories sc ON s.category_id = sc.id
WHERE 1=1
"""
params: list[Any] = []
if status == "all":
if not admin:
raise HTTPException(403, "Nur Admins dürfen alle Status sehen")
elif status:
q += " AND s.status = %s"
params.append(status)
else:
q += " AND s.status = %s"
params.append("active")
q += """
ORDER BY mc.sort_order NULLS LAST,
sc.sort_order NULLS LAST,
s.sort_order NULLS LAST,
s.name
"""
cur.execute(q, params)
return [r2d(r) for r in cur.fetchall()]
# ── Get Skill ─────────────────────────────────────────────────────────
@router.get("/skills/{skill_id}")
def get_skill(skill_id: int, session=Depends(require_auth)):
@@ -84,24 +161,46 @@ def create_skill(data: dict, session=Depends(require_auth)):
if not name:
raise HTTPException(400, "Name ist Pflichtfeld")
cat_id = data.get("category_id")
if cat_id is not None:
cat_id = int(cat_id)
main_id = data.get("main_category_id")
if main_id is not None:
main_id = int(main_id)
focus = data.get("focus_areas")
if isinstance(focus, (list, dict)):
focus = json.dumps(focus)
with get_db() as conn:
cur = get_cursor(conn)
if cat_id and main_id is None:
main_id = _main_id_for_category(cur, cat_id)
cur.execute("""
INSERT INTO skills (name, category, description, importance, keywords, status)
VALUES (%s, %s, %s, %s, %s, %s)
cur.execute(
"""
INSERT INTO skills (
name, category, description, importance, keywords, status,
category_id, main_category_id, focus_areas, sort_order
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s)
RETURNING id
""", (
name,
data.get('category'),
data.get('description'),
data.get('importance'),
data.get('keywords'),
data.get('status', 'active')
))
""",
(
name,
data.get("category"),
data.get("description"),
data.get("importance"),
_jsonb_param(data.get("keywords")),
data.get("status", "active"),
cat_id,
main_id,
focus if focus is not None else "[]",
data.get("sort_order"),
),
)
skill_id = cur.fetchone()['id']
conn.commit()
skill_id = cur.fetchone()["id"]
return get_skill(skill_id, session)
@@ -122,28 +221,46 @@ def update_skill(skill_id: int, data: dict, session=Depends(require_auth)):
if not cur.fetchone():
raise HTTPException(404, "Fähigkeit nicht gefunden")
# Update
cur.execute("""
UPDATE skills SET
name = %s,
category = %s,
description = %s,
importance = %s,
keywords = %s,
status = %s,
updated_at = NOW()
WHERE id = %s
""", (
data.get('name'),
data.get('category'),
data.get('description'),
data.get('importance'),
data.get('keywords'),
data.get('status'),
skill_id
))
sets: list = []
vals: list = []
for key in (
"name",
"category",
"description",
"importance",
"status",
"category_id",
"main_category_id",
"sort_order",
):
if key in data:
sets.append(f"{key} = %s")
vals.append(data[key])
if "keywords" in data:
sets.append("keywords = %s")
vals.append(_jsonb_param(data["keywords"]))
if "focus_areas" in data:
fa = data["focus_areas"]
if isinstance(fa, (list, dict)):
fa = json.dumps(fa)
sets.append("focus_areas = %s::jsonb")
vals.append(fa if fa is not None else "[]")
conn.commit()
if sets:
sets.append("updated_at = NOW()")
vals.append(skill_id)
cur.execute(
f"UPDATE skills SET {', '.join(sets)} WHERE id = %s",
tuple(vals),
)
if "category_id" in data and "main_category_id" not in data:
mid = _main_id_for_category(cur, data.get("category_id"))
if mid is not None:
cur.execute(
"UPDATE skills SET main_category_id = %s WHERE id = %s",
(mid, skill_id),
)
return get_skill(skill_id, session)
@@ -166,7 +283,6 @@ def delete_skill(skill_id: int, session=Depends(require_auth)):
# Delete
cur.execute("DELETE FROM skills WHERE id = %s", (skill_id,))
conn.commit()
return {"ok": True}
@@ -0,0 +1,574 @@
"""
Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere Session-Slots.
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
nicht über group_id oder training_unit_id am Rahmen.
Lesen wie Übungen (official / private / club); Schreiben nur Ersteller oder Plattform-Admin.
"""
from typing import Any, Dict, List, Optional, Sequence
from fastapi import APIRouter, Depends, HTTPException
from club_tenancy import (
assert_valid_governance_visibility,
is_platform_admin,
library_content_visible_to_profile,
)
from db import get_db, get_cursor, r2d
from routers.training_planning import (
_has_planning_role,
_hydrate_training_unit_payload,
_optional_positive_int,
_insert_sections_from_legacy_exercises,
_replace_unit_sections,
_validate_variant_for_exercise,
)
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
router = APIRouter(prefix="/api", tags=["training_framework_programs"])
_VALID_VISIBILITY = frozenset({"private", "club", "official"})
def _fetch_framework_row(cur, framework_id: int) -> Dict[str, Any]:
cur.execute("SELECT * FROM training_framework_programs WHERE id = %s", (framework_id,))
r = cur.fetchone()
if not r:
raise HTTPException(status_code=404, detail="Trainingsrahmen nicht gefunden")
return r2d(r)
def _framework_assert_readable(
cur, row: Dict[str, Any], profile_id: int, role: Optional[str]
) -> None:
if is_platform_admin(role):
return
if not library_content_visible_to_profile(
cur,
profile_id,
row.get("visibility") or "private",
row.get("club_id"),
row.get("created_by"),
role,
):
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
def _framework_assert_writable(cur, row: Dict[str, Any], profile_id: int, role: Optional[str]) -> None:
if is_platform_admin(role):
return
if row.get("created_by") != profile_id:
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
row = _fetch_framework_row(cur, framework_id)
_framework_assert_readable(cur, row, profile_id, role)
return row
def _response_framework_detail(framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
"""Einzelabruf nach Schreiboperation (ohne FastAPI-Depends-Schleife)."""
with get_db() as conn:
cur = get_cursor(conn)
row = _framework_access(cur, framework_id, profile_id, role)
return _hydrate_framework(cur, row)
def _training_type_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT training_type_id
FROM training_framework_program_training_types
WHERE framework_program_id = %s
ORDER BY training_type_id
""",
(framework_id,),
)
return [r["training_type_id"] for r in cur.fetchall()]
def _target_group_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT target_group_id
FROM training_framework_program_target_groups
WHERE framework_program_id = %s
ORDER BY target_group_id
""",
(framework_id,),
)
return [r["target_group_id"] for r in cur.fetchall()]
def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
fid = row["id"]
cur.execute(
"""
SELECT id, framework_program_id, sort_order, title, notes
FROM training_framework_goals
WHERE framework_program_id = %s
ORDER BY sort_order
""",
(fid,),
)
row["goals"] = [r2d(g) for g in cur.fetchall()]
cur.execute(
"""
SELECT id, framework_program_id, sort_order, title, notes
FROM training_framework_slots
WHERE framework_program_id = %s
ORDER BY sort_order
""",
(fid,),
)
slots = [r2d(s) for s in cur.fetchall()]
for s in slots:
cur.execute(
"SELECT id FROM training_units WHERE framework_slot_id = %s",
(s["id"],),
)
row_b = cur.fetchone()
if not row_b:
s["blueprint_training_unit_id"] = None
s["sections"] = []
s["exercises"] = []
continue
uid = row_b["id"]
s["blueprint_training_unit_id"] = uid
unit_min: Dict[str, Any] = {"id": uid}
_hydrate_training_unit_payload(cur, unit_min)
s["sections"] = unit_min.get("sections", [])
s["exercises"] = unit_min.get("exercises", [])
row["slots"] = slots
row["training_type_ids"] = _training_type_ids(cur, fid)
row["target_group_ids"] = _target_group_ids(cur, fid)
return row
def _assert_visibility(val: Optional[str]) -> Optional[str]:
if val is None:
return None
if val not in _VALID_VISIBILITY:
raise HTTPException(
status_code=400,
detail="visibility muss private, club oder official sein",
)
return val
def _parse_positive_int_ids(raw: Any, label: str) -> List[int]:
if raw is None:
return []
if not isinstance(raw, list):
raise HTTPException(status_code=400, detail=f"{label} muss eine Liste von IDs sein")
out: List[int] = []
for item in raw:
if item in (None, ""):
continue
try:
n = int(item)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID") from None
if n <= 0:
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID")
if n not in out:
out.append(n)
return out
def _replace_training_types(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_training_types WHERE framework_program_id = %s",
(framework_id,),
)
for tid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_training_types (framework_program_id, training_type_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, tid),
)
def _replace_target_groups(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_target_groups WHERE framework_program_id = %s",
(framework_id,),
)
for gid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_target_groups (framework_program_id, target_group_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, gid),
)
def _insert_goal_rows(cur, framework_id: int, goals_in: List[Any]) -> None:
if not goals_in:
raise HTTPException(status_code=400, detail="Mindestens ein Entwicklungsziel (goals) ist erforderlich")
for gi, g in enumerate(goals_in):
title_g = (g.get("title") or "").strip()
if not title_g:
raise HTTPException(status_code=400, detail="Jedes Ziel braucht ein nicht-leeres title")
order_ix = g.get("sort_order")
if order_ix is None:
order_ix = gi
cur.execute(
"""
INSERT INTO training_framework_goals (
framework_program_id, sort_order, title, notes
) VALUES (%s, %s, %s, %s)
""",
(framework_id, int(order_ix), title_g[:500], g.get("notes")),
)
def _insert_default_blueprint_section(cur, blueprint_unit_id: int) -> None:
"""Leerer Ablauf, falls noch keine Sektionen existieren."""
cur.execute(
"SELECT 1 FROM training_unit_sections WHERE training_unit_id = %s",
(blueprint_unit_id,),
)
if cur.fetchone():
return
_replace_unit_sections(
cur,
blueprint_unit_id,
[{"title": "Ablauf", "order_index": 0, "guidance_notes": None, "items": []}],
)
def _insert_slots_and_blueprints(
cur,
framework_id: int,
slots_in: Optional[List[Any]],
profile_id: int,
) -> None:
if slots_in is None:
return
for si, slot in enumerate(slots_in):
order_ix = slot.get("sort_order")
if order_ix is None:
order_ix = si
title_s = slot.get("title")
if title_s is not None:
title_s = title_s.strip() or None
cur.execute(
"""
INSERT INTO training_framework_slots (
framework_program_id, sort_order, title, notes, training_unit_id
) VALUES (%s, %s, %s, %s, NULL)
RETURNING id
""",
(
framework_id,
int(order_ix),
title_s,
slot.get("notes"),
),
)
sid = cur.fetchone()["id"]
cur.execute(
"""
INSERT INTO training_units (
group_id, planned_date,
planned_time_start, planned_time_end, planned_focus,
status, notes, trainer_notes,
created_by, plan_template_id, framework_slot_id
) VALUES (
NULL, NULL,
NULL, NULL, NULL,
'planned', NULL, NULL,
%s, NULL, %s
)
RETURNING id
""",
(profile_id, sid),
)
bid = cur.fetchone()["id"]
sections_in = slot.get("sections")
exercises_in = slot.get("exercises")
if sections_in is not None:
if len(sections_in) == 0:
_insert_default_blueprint_section(cur, bid)
else:
_replace_unit_sections(cur, bid, sections_in)
elif exercises_in is not None and len(exercises_in) > 0:
for raw in exercises_in:
eid = raw.get("exercise_id")
if not eid:
continue
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
_validate_variant_for_exercise(cur, int(eid), vid)
_insert_sections_from_legacy_exercises(cur, bid, exercises_in)
else:
_insert_default_blueprint_section(cur, bid)
@router.get("/training-framework-programs")
def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
base_sel = """
SELECT fp.*,
fa.name AS focus_area_name,
sd.name AS style_direction_name,
(SELECT COUNT(*)::int FROM training_framework_goals g WHERE g.framework_program_id = fp.id)
AS goals_count,
(SELECT COUNT(*)::int FROM training_framework_slots s WHERE s.framework_program_id = fp.id)
AS slots_count,
(SELECT COUNT(*)::int FROM training_framework_program_training_types t
WHERE t.framework_program_id = fp.id) AS training_types_count,
(SELECT COUNT(*)::int FROM training_framework_program_target_groups tg
WHERE tg.framework_program_id = fp.id) AS target_groups_count,
(
SELECT STRING_AGG(typ.name::text, ', ' ORDER BY typ.sort_order NULLS LAST, typ.name)
FROM training_framework_program_training_types j
JOIN training_types typ ON typ.id = j.training_type_id
WHERE j.framework_program_id = fp.id
) AS training_type_names_agg,
(
SELECT STRING_AGG(tg.name::text, ', ' ORDER BY tg.name)
FROM training_framework_program_target_groups j
JOIN target_groups tg ON tg.id = j.target_group_id
WHERE j.framework_program_id = fp.id
) AS target_group_names_agg
FROM training_framework_programs fp
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
"""
vis_clause, vis_params = library_content_visibility_sql(
alias="fp",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
base_sel
+ f""" WHERE ({vis_clause})
ORDER BY fp.updated_at DESC NULLS LAST, fp.title""",
vis_params,
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/training-framework-programs/{framework_id}")
def get_training_framework_program(
framework_id: int, tenant: TenantContext = Depends(get_tenant_context)
):
profile_id = tenant.profile_id
role = tenant.global_role
return _response_framework_detail(framework_id, profile_id, role)
@router.post("/training-framework-programs")
def create_training_framework_program(
data: dict, tenant: TenantContext = Depends(get_tenant_context)
):
profile_id = tenant.profile_id
role = tenant.global_role
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Nur Planungsberechtigte dürfen Rahmenprogramme anlegen")
title = (data.get("title") or "").strip()
if not title:
raise HTTPException(status_code=400, detail="title ist Pflicht")
vis = data.get("visibility") or "private"
vis = _assert_visibility(vis)
club_id = data.get("club_id")
if club_id in ("", []):
club_id = None
if vis == "club" and club_id is None:
club_id = tenant.effective_club_id
goals_in = data.get("goals")
slots_in = data.get("slots")
if not isinstance(goals_in, list) or not goals_in:
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
fa_id = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
sd_id = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
with get_db() as conn:
cur = get_cursor(conn)
assert_valid_governance_visibility(cur, profile_id, role, vis, club_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
""",
(
title[:200],
data.get("description"),
data.get("planned_period_start"),
data.get("planned_period_end"),
vis,
club_id,
profile_id,
fa_id,
sd_id,
),
)
fid = cur.fetchone()["id"]
_insert_goal_rows(cur, fid, goals_in)
_insert_slots_and_blueprints(cur, fid, slots_in, profile_id)
_replace_training_types(cur, fid, tt_ids)
_replace_target_groups(cur, fid, tg_ids)
conn.commit()
return _response_framework_detail(fid, profile_id, role)
@router.put("/training-framework-programs/{framework_id}")
def update_training_framework_program(
framework_id: int, data: dict, tenant: TenantContext = Depends(get_tenant_context)
):
profile_id = tenant.profile_id
role = tenant.global_role
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung")
with get_db() as conn:
cur = get_cursor(conn)
row_prev = _fetch_framework_row(cur, framework_id)
_framework_assert_writable(cur, row_prev, profile_id, role)
merged_vis = row_prev.get("visibility") or "private"
merged_club = row_prev.get("club_id")
if "visibility" in data:
v_m = _assert_visibility(data.get("visibility"))
if v_m is None:
raise HTTPException(status_code=400, detail="visibility fehlt")
merged_vis = v_m
if "club_id" in data:
merged_club = data.get("club_id")
if merged_club in ("", []):
merged_club = None
if "visibility" in data or "club_id" in data:
assert_valid_governance_visibility(cur, profile_id, role, merged_vis, merged_club)
header_fields = []
header_params: List[Any] = []
if "title" in data:
tit = (data.get("title") or "").strip()
if not tit:
raise HTTPException(status_code=400, detail="title ist Pflicht")
header_fields.append("title = %s")
header_params.append(tit[:200])
if "description" in data:
header_fields.append("description = %s")
header_params.append(data.get("description"))
if "planned_period_start" in data:
header_fields.append("planned_period_start = %s")
header_params.append(data.get("planned_period_start"))
if "planned_period_end" in data:
header_fields.append("planned_period_end = %s")
header_params.append(data.get("planned_period_end"))
if "visibility" in data:
header_fields.append("visibility = %s")
header_params.append(merged_vis)
if "club_id" in data:
header_fields.append("club_id = %s")
header_params.append(merged_club)
if "focus_area_id" in data:
fidv = data.get("focus_area_id")
header_fields.append("focus_area_id = %s")
header_params.append(
None if fidv in (None, "") else _optional_positive_int(fidv, "focus_area_id")
)
if "style_direction_id" in data:
sidv = data.get("style_direction_id")
header_fields.append("style_direction_id = %s")
header_params.append(
None if sidv in (None, "") else _optional_positive_int(sidv, "style_direction_id")
)
if header_fields:
header_fields.append("updated_at = NOW()")
header_params.append(framework_id)
cur.execute(
f"""
UPDATE training_framework_programs
SET {", ".join(header_fields)}
WHERE id = %s
""",
tuple(header_params),
)
if "training_type_ids" in data:
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
_replace_training_types(cur, framework_id, tt_ids)
if "target_group_ids" in data:
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
_replace_target_groups(cur, framework_id, tg_ids)
if "goals" in data:
goals_in = data["goals"]
if not isinstance(goals_in, list) or not goals_in:
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
cur.execute(
"DELETE FROM training_framework_goals WHERE framework_program_id = %s",
(framework_id,),
)
_insert_goal_rows(cur, framework_id, goals_in)
if "slots" in data:
cur.execute(
"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)
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(
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
(framework_id,),
)
conn.commit()
return _response_framework_detail(framework_id, profile_id, role)
@router.delete("/training-framework-programs/{framework_id}")
def delete_training_framework_program(
framework_id: int, tenant: TenantContext = Depends(get_tenant_context)
):
profile_id = tenant.profile_id
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
row_fw = _fetch_framework_row(cur, framework_id)
_framework_assert_writable(cur, row_fw, profile_id, role)
cur.execute(
"DELETE FROM training_framework_programs WHERE id = %s",
(framework_id,),
)
conn.commit()
return {"ok": True}
File diff suppressed because it is too large. Load diff
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff. Show more